{"idx": 194963, "project": "ImageMagick6", "commit_id": "dc070da861a015d3c97488fdcca6063b44d47a7b", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/dc070da861a015d3c97488fdcca6063b44d47a7b", "commit_message": "https://github.com/ImageMagick/ImageMagick/pull/5034", "target": 1, "func": "static MagickBooleanType GetEXIFProperty(const Image *image,\n const char *property)\n{\n#define MaxDirectoryStack 16\n#define EXIF_DELIMITER \"\\n\"\n#define EXIF_NUM_FORMATS 12\n#define EXIF_FMT_BYTE 1\n#define EXIF_FMT_STRING 2\n#define EXIF_FMT_USHORT 3\n#define EXIF_FMT_ULONG 4\n#define EXIF_FMT_URATIONAL 5\n#define EXIF_FMT_SBYTE 6\n#define EXIF_FMT_UNDEFINED 7\n#define EXIF_FMT_SSHORT 8\n#define EXIF_FMT_SLONG 9\n#define EXIF_FMT_SRATIONAL 10\n#define EXIF_FMT_SINGLE 11\n#define EXIF_FMT_DOUBLE 12\n#define TAG_EXIF_OFFSET 0x8769\n#define TAG_GPS_OFFSET 0x8825\n#define TAG_INTEROP_OFFSET 0xa005\n\n#define EXIFMultipleValues(size,format,arg) \\\n{ \\\n ssize_t \\\n component; \\\n \\\n size_t \\\n length; \\\n \\\n unsigned char \\\n *p1; \\\n \\\n length=0; \\\n p1=p; \\\n for (component=0; component < components; component++) \\\n { \\\n length+=FormatLocaleString(buffer+length,MaxTextExtent-length, \\\n format\", \",arg); \\\n if (length >= (MaxTextExtent-1)) \\\n length=MaxTextExtent-1; \\\n p1+=size; \\\n } \\\n if (length > 1) \\\n buffer[length-2]='\\0'; \\\n value=AcquireString(buffer); \\\n}\n\n#define EXIFMultipleFractions(size,format,arg1,arg2) \\\n{ \\\n ssize_t \\\n component; \\\n \\\n size_t \\\n length; \\\n \\\n unsigned char \\\n *p1; \\\n \\\n length=0; \\\n p1=p; \\\n for (component=0; component < components; component++) \\\n { \\\n length+=FormatLocaleString(buffer+length,MaxTextExtent-length, \\\n format\", \",(arg1),(arg2)); \\\n if (length >= (MaxTextExtent-1)) \\\n length=MaxTextExtent-1; \\\n p1+=size; \\\n } \\\n if (length > 1) \\\n buffer[length-2]='\\0'; \\\n value=AcquireString(buffer); \\\n}\n\n typedef struct _DirectoryInfo\n {\n const unsigned char\n *directory;\n\n size_t\n entry;\n\n ssize_t\n offset;\n } DirectoryInfo;\n\n typedef struct _TagInfo\n {\n size_t\n tag;\n\n const char\n description[36];\n } TagInfo;\n\n static const TagInfo\n EXIFTag[] =\n {\n { 0x001, \"exif:InteroperabilityIndex\" },\n { 0x002, \"exif:InteroperabilityVersion\" },\n { 0x100, \"exif:ImageWidth\" },\n { 0x101, \"exif:ImageLength\" },\n { 0x102, \"exif:BitsPerSample\" },\n { 0x103, \"exif:Compression\" },\n { 0x106, \"exif:PhotometricInterpretation\" },\n { 0x10a, \"exif:FillOrder\" },\n { 0x10d, \"exif:DocumentName\" },\n { 0x10e, \"exif:ImageDescription\" },\n { 0x10f, \"exif:Make\" },\n { 0x110, \"exif:Model\" },\n { 0x111, \"exif:StripOffsets\" },\n { 0x112, \"exif:Orientation\" },\n { 0x115, \"exif:SamplesPerPixel\" },\n { 0x116, \"exif:RowsPerStrip\" },\n { 0x117, \"exif:StripByteCounts\" },\n { 0x11a, \"exif:XResolution\" },\n { 0x11b, \"exif:YResolution\" },\n { 0x11c, \"exif:PlanarConfiguration\" },\n { 0x11d, \"exif:PageName\" },\n { 0x11e, \"exif:XPosition\" },\n { 0x11f, \"exif:YPosition\" },\n { 0x118, \"exif:MinSampleValue\" },\n { 0x119, \"exif:MaxSampleValue\" },\n { 0x120, \"exif:FreeOffsets\" },\n { 0x121, \"exif:FreeByteCounts\" },\n { 0x122, \"exif:GrayResponseUnit\" },\n { 0x123, \"exif:GrayResponseCurve\" },\n { 0x124, \"exif:T4Options\" },\n { 0x125, \"exif:T6Options\" },\n { 0x128, \"exif:ResolutionUnit\" },\n { 0x12d, \"exif:TransferFunction\" },\n { 0x131, \"exif:Software\" },\n { 0x132, \"exif:DateTime\" },\n { 0x13b, \"exif:Artist\" },\n { 0x13e, \"exif:WhitePoint\" },\n { 0x13f, \"exif:PrimaryChromaticities\" },\n { 0x140, \"exif:ColorMap\" },\n { 0x141, \"exif:HalfToneHints\" },\n { 0x142, \"exif:TileWidth\" },\n { 0x143, \"exif:TileLength\" },\n { 0x144, \"exif:TileOffsets\" },\n { 0x145, \"exif:TileByteCounts\" },\n { 0x14a, \"exif:SubIFD\" },\n { 0x14c, \"exif:InkSet\" },\n { 0x14d, \"exif:InkNames\" },\n { 0x14e, \"exif:NumberOfInks\" },\n { 0x150, \"exif:DotRange\" },\n { 0x151, \"exif:TargetPrinter\" },\n { 0x152, \"exif:ExtraSample\" },\n { 0x153, \"exif:SampleFormat\" },\n { 0x154, \"exif:SMinSampleValue\" },\n { 0x155, \"exif:SMaxSampleValue\" },\n { 0x156, \"exif:TransferRange\" },\n { 0x157, \"exif:ClipPath\" },\n { 0x158, \"exif:XClipPathUnits\" },\n { 0x159, \"exif:YClipPathUnits\" },\n { 0x15a, \"exif:Indexed\" },\n { 0x15b, \"exif:JPEGTables\" },\n { 0x15f, \"exif:OPIProxy\" },\n { 0x200, \"exif:JPEGProc\" },\n { 0x201, \"exif:JPEGInterchangeFormat\" },\n { 0x202, \"exif:JPEGInterchangeFormatLength\" },\n { 0x203, \"exif:JPEGRestartInterval\" },\n { 0x205, \"exif:JPEGLosslessPredictors\" },\n { 0x206, \"exif:JPEGPointTransforms\" },\n { 0x207, \"exif:JPEGQTables\" },\n { 0x208, \"exif:JPEGDCTables\" },\n { 0x209, \"exif:JPEGACTables\" },\n { 0x211, \"exif:YCbCrCoefficients\" },\n { 0x212, \"exif:YCbCrSubSampling\" },\n { 0x213, \"exif:YCbCrPositioning\" },\n { 0x214, \"exif:ReferenceBlackWhite\" },\n { 0x2bc, \"exif:ExtensibleMetadataPlatform\" },\n { 0x301, \"exif:Gamma\" },\n { 0x302, \"exif:ICCProfileDescriptor\" },\n { 0x303, \"exif:SRGBRenderingIntent\" },\n { 0x320, \"exif:ImageTitle\" },\n { 0x5001, \"exif:ResolutionXUnit\" },\n { 0x5002, \"exif:ResolutionYUnit\" },\n { 0x5003, \"exif:ResolutionXLengthUnit\" },\n { 0x5004, \"exif:ResolutionYLengthUnit\" },\n { 0x5005, \"exif:PrintFlags\" },\n { 0x5006, \"exif:PrintFlagsVersion\" },\n { 0x5007, \"exif:PrintFlagsCrop\" },\n { 0x5008, \"exif:PrintFlagsBleedWidth\" },\n { 0x5009, \"exif:PrintFlagsBleedWidthScale\" },\n { 0x500A, \"exif:HalftoneLPI\" },\n { 0x500B, \"exif:HalftoneLPIUnit\" },\n { 0x500C, \"exif:HalftoneDegree\" },\n { 0x500D, \"exif:HalftoneShape\" },\n { 0x500E, \"exif:HalftoneMisc\" },\n { 0x500F, \"exif:HalftoneScreen\" },\n { 0x5010, \"exif:JPEGQuality\" },\n { 0x5011, \"exif:GridSize\" },\n { 0x5012, \"exif:ThumbnailFormat\" },\n { 0x5013, \"exif:ThumbnailWidth\" },\n { 0x5014, \"exif:ThumbnailHeight\" },\n { 0x5015, \"exif:ThumbnailColorDepth\" },\n { 0x5016, \"exif:ThumbnailPlanes\" },\n { 0x5017, \"exif:ThumbnailRawBytes\" },\n { 0x5018, \"exif:ThumbnailSize\" },\n { 0x5019, \"exif:ThumbnailCompressedSize\" },\n { 0x501a, \"exif:ColorTransferFunction\" },\n { 0x501b, \"exif:ThumbnailData\" },\n { 0x5020, \"exif:ThumbnailImageWidth\" },\n { 0x5021, \"exif:ThumbnailImageHeight\" },\n { 0x5022, \"exif:ThumbnailBitsPerSample\" },\n { 0x5023, \"exif:ThumbnailCompression\" },\n { 0x5024, \"exif:ThumbnailPhotometricInterp\" },\n { 0x5025, \"exif:ThumbnailImageDescription\" },\n { 0x5026, \"exif:ThumbnailEquipMake\" },\n { 0x5027, \"exif:ThumbnailEquipModel\" },\n { 0x5028, \"exif:ThumbnailStripOffsets\" },\n { 0x5029, \"exif:ThumbnailOrientation\" },\n { 0x502a, \"exif:ThumbnailSamplesPerPixel\" },\n { 0x502b, \"exif:ThumbnailRowsPerStrip\" },\n { 0x502c, \"exif:ThumbnailStripBytesCount\" },\n { 0x502d, \"exif:ThumbnailResolutionX\" },\n { 0x502e, \"exif:ThumbnailResolutionY\" },\n { 0x502f, \"exif:ThumbnailPlanarConfig\" },\n { 0x5030, \"exif:ThumbnailResolutionUnit\" },\n { 0x5031, \"exif:ThumbnailTransferFunction\" },\n { 0x5032, \"exif:ThumbnailSoftwareUsed\" },\n { 0x5033, \"exif:ThumbnailDateTime\" },\n { 0x5034, \"exif:ThumbnailArtist\" },\n { 0x5035, \"exif:ThumbnailWhitePoint\" },\n { 0x5036, \"exif:ThumbnailPrimaryChromaticities\" },\n { 0x5037, \"exif:ThumbnailYCbCrCoefficients\" },\n { 0x5038, \"exif:ThumbnailYCbCrSubsampling\" },\n { 0x5039, \"exif:ThumbnailYCbCrPositioning\" },\n { 0x503A, \"exif:ThumbnailRefBlackWhite\" },\n { 0x503B, \"exif:ThumbnailCopyRight\" },\n { 0x5090, \"exif:LuminanceTable\" },\n { 0x5091, \"exif:ChrominanceTable\" },\n { 0x5100, \"exif:FrameDelay\" },\n { 0x5101, \"exif:LoopCount\" },\n { 0x5110, \"exif:PixelUnit\" },\n { 0x5111, \"exif:PixelPerUnitX\" },\n { 0x5112, \"exif:PixelPerUnitY\" },\n { 0x5113, \"exif:PaletteHistogram\" },\n { 0x1000, \"exif:RelatedImageFileFormat\" },\n { 0x1001, \"exif:RelatedImageLength\" },\n { 0x1002, \"exif:RelatedImageWidth\" },\n { 0x800d, \"exif:ImageID\" },\n { 0x80e3, \"exif:Matteing\" },\n { 0x80e4, \"exif:DataType\" },\n { 0x80e5, \"exif:ImageDepth\" },\n { 0x80e6, \"exif:TileDepth\" },\n { 0x828d, \"exif:CFARepeatPatternDim\" },\n { 0x828e, \"exif:CFAPattern2\" },\n { 0x828f, \"exif:BatteryLevel\" },\n { 0x8298, \"exif:Copyright\" },\n { 0x829a, \"exif:ExposureTime\" },\n { 0x829d, \"exif:FNumber\" },\n { 0x83bb, \"exif:IPTC/NAA\" },\n { 0x84e3, \"exif:IT8RasterPadding\" },\n { 0x84e5, \"exif:IT8ColorTable\" },\n { 0x8649, \"exif:ImageResourceInformation\" },\n { 0x8769, \"exif:ExifOffset\" }, /* specs as \"Exif IFD Pointer\"? */\n { 0x8773, \"exif:InterColorProfile\" },\n { 0x8822, \"exif:ExposureProgram\" },\n { 0x8824, \"exif:SpectralSensitivity\" },\n { 0x8825, \"exif:GPSInfo\" }, /* specs as \"GPSInfo IFD Pointer\"? */\n { 0x8827, \"exif:PhotographicSensitivity\" },\n { 0x8828, \"exif:OECF\" },\n { 0x8829, \"exif:Interlace\" }, \n { 0x882a, \"exif:TimeZoneOffset\" },\n { 0x882b, \"exif:SelfTimerMode\" },\n { 0x8830, \"exif:SensitivityType\" },\n { 0x8831, \"exif:StandardOutputSensitivity\" },\n { 0x8832, \"exif:RecommendedExposureIndex\" },\n { 0x8833, \"exif:ISOSpeed\" },\n { 0x8834, \"exif:ISOSpeedLatitudeyyy\" },\n { 0x8835, \"exif:ISOSpeedLatitudezzz\" },\n { 0x9000, \"exif:ExifVersion\" },\n { 0x9003, \"exif:DateTimeOriginal\" },\n { 0x9004, \"exif:DateTimeDigitized\" },\n { 0x9010, \"exif:OffsetTime\" },\n { 0x9011, \"exif:OffsetTimeOriginal\" },\n { 0x9012, \"exif:OffsetTimeDigitized\" },\n { 0x9101, \"exif:ComponentsConfiguration\" },\n { 0x9102, \"exif:CompressedBitsPerPixel\" },\n { 0x9201, \"exif:ShutterSpeedValue\" },\n { 0x9202, \"exif:ApertureValue\" },\n { 0x9203, \"exif:BrightnessValue\" },\n { 0x9204, \"exif:ExposureBiasValue\" },\n { 0x9205, \"exif:MaxApertureValue\" },\n { 0x9206, \"exif:SubjectDistance\" },\n { 0x9207, \"exif:MeteringMode\" },\n { 0x9208, \"exif:LightSource\" },\n { 0x9209, \"exif:Flash\" },\n { 0x920a, \"exif:FocalLength\" },\n { 0x920b, \"exif:FlashEnergy\" },\n { 0x920c, \"exif:SpatialFrequencyResponse\" },\n { 0x920d, \"exif:Noise\" },\n { 0x9214, \"exif:SubjectArea\" },\n { 0x9290, \"exif:SubSecTime\" },\n { 0x9291, \"exif:SubSecTimeOriginal\" },\n { 0x9292, \"exif:SubSecTimeDigitized\" }, \n { 0x9211, \"exif:ImageNumber\" },\n { 0x9212, \"exif:SecurityClassification\" },\n { 0x9213, \"exif:ImageHistory\" },\n { 0x9214, \"exif:SubjectArea\" },\n { 0x9215, \"exif:ExposureIndex\" },\n { 0x9216, \"exif:TIFF-EPStandardID\" },\n { 0x927c, \"exif:MakerNote\" },\n { 0x9286, \"exif:UserComment\" },\n { 0x9290, \"exif:SubSecTime\" },\n { 0x9291, \"exif:SubSecTimeOriginal\" },\n { 0x9292, \"exif:SubSecTimeDigitized\" }, \n { 0x9400, \"exif:Temperature\" },\n { 0x9401, \"exif:Humidity\" },\n { 0x9402, \"exif:Pressure\" },\n { 0x9403, \"exif:WaterDepth\" },\n { 0x9404, \"exif:Acceleration\" },\n { 0x9405, \"exif:CameraElevationAngle\" }, \n { 0x9C9b, \"exif:WinXP-Title\" },\n { 0x9C9c, \"exif:WinXP-Comments\" },\n { 0x9C9d, \"exif:WinXP-Author\" },\n { 0x9C9e, \"exif:WinXP-Keywords\" },\n { 0x9C9f, \"exif:WinXP-Subject\" }, \n { 0xa000, \"exif:FlashPixVersion\" },\n { 0xa001, \"exif:ColorSpace\" },\n { 0xa002, \"exif:PixelXDimension\" },\n { 0xa003, \"exif:PixelYDimension\" },\n { 0xa004, \"exif:RelatedSoundFile\" },\n { 0xa005, \"exif:InteroperabilityOffset\" },\n { 0xa20b, \"exif:FlashEnergy\" },\n { 0xa20c, \"exif:SpatialFrequencyResponse\" },\n { 0xa20d, \"exif:Noise\" },\n { 0xa20e, \"exif:FocalPlaneXResolution\" },\n { 0xa20f, \"exif:FocalPlaneYResolution\" },\n { 0xa210, \"exif:FocalPlaneResolutionUnit\" },\n { 0xa214, \"exif:SubjectLocation\" },\n { 0xa215, \"exif:ExposureIndex\" },\n { 0xa216, \"exif:TIFF/EPStandardID\" },\n { 0xa217, \"exif:SensingMethod\" },\n { 0xa300, \"exif:FileSource\" },\n { 0xa301, \"exif:SceneType\" },\n { 0xa302, \"exif:CFAPattern\" },\n { 0xa401, \"exif:CustomRendered\" },\n { 0xa402, \"exif:ExposureMode\" },\n { 0xa403, \"exif:WhiteBalance\" },\n { 0xa404, \"exif:DigitalZoomRatio\" },\n { 0xa405, \"exif:FocalLengthIn35mmFilm\" },\n { 0xa406, \"exif:SceneCaptureType\" },\n { 0xa407, \"exif:GainControl\" },\n { 0xa408, \"exif:Contrast\" },\n { 0xa409, \"exif:Saturation\" },\n { 0xa40a, \"exif:Sharpness\" },\n { 0xa40b, \"exif:DeviceSettingDescription\" },\n { 0xa40c, \"exif:SubjectDistanceRange\" },\n { 0xa420, \"exif:ImageUniqueID\" },\n { 0xa430, \"exif:CameraOwnerName\" },\n { 0xa431, \"exif:BodySerialNumber\" },\n { 0xa432, \"exif:LensSpecification\" },\n { 0xa433, \"exif:LensMake\" },\n { 0xa434, \"exif:LensModel\" },\n { 0xa435, \"exif:LensSerialNumber\" },\n { 0xc4a5, \"exif:PrintImageMatching\" },\n { 0xa500, \"exif:Gamma\" },\n { 0xc640, \"exif:CR2Slice\" },\n { 0x10000, \"exif:GPSVersionID\" },\n { 0x10001, \"exif:GPSLatitudeRef\" },\n { 0x10002, \"exif:GPSLatitude\" },\n { 0x10003, \"exif:GPSLongitudeRef\" },\n { 0x10004, \"exif:GPSLongitude\" },\n { 0x10005, \"exif:GPSAltitudeRef\" },\n { 0x10006, \"exif:GPSAltitude\" },\n { 0x10007, \"exif:GPSTimeStamp\" },\n { 0x10008, \"exif:GPSSatellites\" },\n { 0x10009, \"exif:GPSStatus\" },\n { 0x1000a, \"exif:GPSMeasureMode\" },\n { 0x1000b, \"exif:GPSDop\" },\n { 0x1000c, \"exif:GPSSpeedRef\" },\n { 0x1000d, \"exif:GPSSpeed\" },\n { 0x1000e, \"exif:GPSTrackRef\" },\n { 0x1000f, \"exif:GPSTrack\" },\n { 0x10010, \"exif:GPSImgDirectionRef\" },\n { 0x10011, \"exif:GPSImgDirection\" },\n { 0x10012, \"exif:GPSMapDatum\" },\n { 0x10013, \"exif:GPSDestLatitudeRef\" },\n { 0x10014, \"exif:GPSDestLatitude\" },\n { 0x10015, \"exif:GPSDestLongitudeRef\" },\n { 0x10016, \"exif:GPSDestLongitude\" },\n { 0x10017, \"exif:GPSDestBearingRef\" },\n { 0x10018, \"exif:GPSDestBearing\" },\n { 0x10019, \"exif:GPSDestDistanceRef\" },\n { 0x1001a, \"exif:GPSDestDistance\" },\n { 0x1001b, \"exif:GPSProcessingMethod\" },\n { 0x1001c, \"exif:GPSAreaInformation\" },\n { 0x1001d, \"exif:GPSDateStamp\" },\n { 0x1001e, \"exif:GPSDifferential\" },\n { 0x1001f, \"exif:GPSHPositioningError\" },\n { 0x00000, \"\" }\n }; /* http://www.cipa.jp/std/documents/e/DC-008-Translation-2016-E.pdf */\n\n const StringInfo\n *profile;\n\n const unsigned char\n *directory,\n *exif;\n\n DirectoryInfo\n directory_stack[MaxDirectoryStack];\n\n EndianType\n endian;\n\n MagickBooleanType\n status;\n\n ssize_t\n i;\n\n size_t\n entry,\n length,\n number_entries,\n tag,\n tag_value;\n\n SplayTreeInfo\n *exif_resources;\n\n ssize_t\n all,\n id,\n level,\n offset,\n tag_offset;\n\n static int\n tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};\n\n /*\n If EXIF data exists, then try to parse the request for a tag.\n */\n profile=GetImageProfile(image,\"exif\");\n if (profile == (const StringInfo *) NULL)\n return(MagickFalse);\n if ((property == (const char *) NULL) || (*property == '\\0'))\n return(MagickFalse);\n while (isspace((int) ((unsigned char) *property)) != 0)\n property++;\n if (strlen(property) <= 5)\n return(MagickFalse);\n all=0;\n tag=(~0UL);\n switch (*(property+5))\n {\n case '*':\n {\n /*\n Caller has asked for all the tags in the EXIF data.\n */\n tag=0;\n all=1; /* return the data in description=value format */\n break;\n }\n case '!':\n {\n tag=0;\n all=2; /* return the data in tagid=value format */\n break;\n }\n case '#':\n case '@':\n {\n int\n c;\n\n size_t\n n;\n\n /*\n Check for a hex based tag specification first.\n */\n tag=(*(property+5) == '@') ? 1UL : 0UL;\n property+=6;\n n=strlen(property);\n if (n != 4)\n return(MagickFalse);\n /*\n Parse tag specification as a hex number.\n */\n n/=4;\n do\n {\n for (i=(ssize_t) n-1L; i >= 0; i--)\n {\n c=(*property++);\n tag<<=4;\n if ((c >= '0') && (c <= '9'))\n tag|=(c-'0');\n else\n if ((c >= 'A') && (c <= 'F'))\n tag|=(c-('A'-10));\n else\n if ((c >= 'a') && (c <= 'f'))\n tag|=(c-('a'-10));\n else\n return(MagickFalse);\n }\n } while (*property != '\\0');\n break;\n }\n default:\n {\n /*\n Try to match the text with a tag name instead.\n */\n for (i=0; ; i++)\n {\n if (EXIFTag[i].tag == 0)\n break;\n if (LocaleCompare(EXIFTag[i].description,property) == 0)\n {\n tag=(size_t) EXIFTag[i].tag;\n break;\n }\n }\n break;\n }\n }\n if (tag == (~0UL))\n return(MagickFalse);\n length=GetStringInfoLength(profile);\n if (length < 6)\n return(MagickFalse);\n exif=GetStringInfoDatum(profile);\n while (length != 0)\n {\n if (ReadPropertyByte(&exif,&length) != 0x45)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x78)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x69)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x66)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x00)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x00)\n continue;\n break;\n }\n if (length < 16)\n return(MagickFalse);\n id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif);\n endian=LSBEndian;\n if (id == 0x4949)\n endian=LSBEndian;\n else\n if (id == 0x4D4D)\n endian=MSBEndian;\n else\n return(MagickFalse);\n if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a)\n return(MagickFalse);\n /*\n This the offset to the first IFD.\n */\n offset=(ssize_t) ReadPropertySignedLong(endian,exif+4);\n if ((offset < 0) || (size_t) offset >= length)\n return(MagickFalse);\n /*\n Set the pointer to the first IFD and follow it were it leads.\n */\n status=MagickFalse;\n directory=exif+offset;\n level=0;\n entry=0;\n tag_offset=0;\n exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL,\n (void *(*)(void *)) NULL,(void *(*)(void *)) NULL);\n do\n {\n /*\n If there is anything on the stack then pop it off.\n */\n if (level > 0)\n {\n level--;\n directory=directory_stack[level].directory;\n entry=directory_stack[level].entry;\n tag_offset=directory_stack[level].offset;\n }\n if ((directory < exif) || (directory > (exif+length-2)))\n break;\n /*\n Determine how many entries there are in the current IFD.\n */\n number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory);\n for ( ; entry < number_entries; entry++)\n {\n unsigned char\n *p,\n *q;\n\n size_t\n format;\n\n ssize_t\n number_bytes,\n components;\n\n q=(unsigned char *) (directory+(12*entry)+2);\n if (q > (exif+length-12))\n break; /* corrupt EXIF */\n if (GetValueFromSplayTree(exif_resources,q) == q)\n break;\n (void) AddValueToSplayTree(exif_resources,q,q);\n tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset;\n format=(size_t) ReadPropertyUnsignedShort(endian,q+2);\n if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes)))\n break;\n if (format == 0)\n break; /* corrupt EXIF */\n components=(ssize_t) ReadPropertySignedLong(endian,q+4);\n if (components < 0)\n break; /* corrupt EXIF */\n number_bytes=(size_t) components*tag_bytes[format];\n if (number_bytes < components)\n break; /* prevent overflow */\n if (number_bytes <= 4)\n p=q+8;\n else\n {\n ssize_t\n dir_offset;\n\n /*\n The directory entry contains an offset.\n */\n dir_offset=(ssize_t) ReadPropertySignedLong(endian,q+8);\n if ((dir_offset < 0) || (size_t) dir_offset >= length)\n continue;\n if (((size_t) dir_offset+number_bytes) < (size_t) dir_offset)\n continue; /* prevent overflow */\n if (((size_t) dir_offset+number_bytes) > length)\n continue;\n p=(unsigned char *) (exif+dir_offset);\n }\n if ((all != 0) || (tag == (size_t) tag_value))\n {\n char\n buffer[MaxTextExtent],\n *value;\n\n if ((p < exif) || (p > (exif+length-tag_bytes[format])))\n break;\n value=(char *) NULL;\n *buffer='\\0';\n switch (format)\n {\n case EXIF_FMT_BYTE:\n case EXIF_FMT_UNDEFINED:\n {\n value=(char *) NULL;\n if (~((size_t) number_bytes) >= 1)\n value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL,\n sizeof(*value));\n if (value != (char *) NULL)\n {\n for (i=0; i < (ssize_t) number_bytes; i++)\n {\n value[i]='.';\n if (isprint((int) p[i]) != 0) \n value[i]=(char) p[i];\n }\n value[i]='\\0';\n }\n break;\n }\n case EXIF_FMT_SBYTE:\n {\n EXIFMultipleValues(1,\"%.20g\",(double) (*(signed char *) p1));\n break;\n }\n case EXIF_FMT_SSHORT:\n {\n EXIFMultipleValues(2,\"%hd\",ReadPropertySignedShort(endian,p1));\n break;\n }\n case EXIF_FMT_USHORT:\n {\n EXIFMultipleValues(2,\"%hu\",ReadPropertyUnsignedShort(endian,p1));\n break;\n }\n case EXIF_FMT_ULONG:\n {\n EXIFMultipleValues(4,\"%.20g\",(double)\n ReadPropertyUnsignedLong(endian,p1));\n break;\n }\n case EXIF_FMT_SLONG:\n {\n EXIFMultipleValues(4,\"%.20g\",(double)\n ReadPropertySignedLong(endian,p1));\n break;\n }\n case EXIF_FMT_URATIONAL:\n {\n EXIFMultipleFractions(8,\"%.20g/%.20g\",(double)\n ReadPropertyUnsignedLong(endian,p1),(double)\n ReadPropertyUnsignedLong(endian,p1+4));\n break;\n }\n case EXIF_FMT_SRATIONAL:\n {\n EXIFMultipleFractions(8,\"%.20g/%.20g\",(double)\n ReadPropertySignedLong(endian,p1),(double)\n ReadPropertySignedLong(endian,p1+4));\n break;\n }\n case EXIF_FMT_SINGLE:\n {\n EXIFMultipleValues(4,\"%f\",(double) *(float *) p1);\n break;\n }\n case EXIF_FMT_DOUBLE:\n {\n EXIFMultipleValues(8,\"%f\",*(double *) p1);\n break;\n }\n case EXIF_FMT_STRING:\n default:\n {\n if ((p < exif) || (p > (exif+length-number_bytes)))\n break;\n value=(char *) NULL;\n if (~((size_t) number_bytes) >= 1)\n value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL,\n sizeof(*value));\n if (value != (char *) NULL)\n {\n ssize_t\n i;\n\n for (i=0; i < (ssize_t) number_bytes; i++)\n {\n value[i]='.';\n if ((isprint((int) p[i]) != 0) || (p[i] == '\\0'))\n value[i]=(char) p[i];\n }\n value[i]='\\0';\n }\n break;\n }\n }\n if (value != (char *) NULL)\n {\n char\n *key;\n\n const char\n *p;\n\n key=AcquireString(property);\n switch (all)\n {\n case 1:\n {\n const char\n *description;\n\n ssize_t\n i;\n\n description=\"unknown\";\n for (i=0; ; i++)\n {\n if (EXIFTag[i].tag == 0)\n break;\n if (EXIFTag[i].tag == tag_value)\n {\n description=EXIFTag[i].description;\n break;\n }\n }\n (void) FormatLocaleString(key,MaxTextExtent,\"%s\",\n description);\n if (level == 2)\n (void) SubstituteString(&key,\"exif:\",\"exif:thumbnail:\");\n break;\n }\n case 2:\n {\n if (tag_value < 0x10000)\n (void) FormatLocaleString(key,MaxTextExtent,\"#%04lx\",\n (unsigned long) tag_value);\n else\n if (tag_value < 0x20000)\n (void) FormatLocaleString(key,MaxTextExtent,\"@%04lx\",\n (unsigned long) (tag_value & 0xffff));\n else\n (void) FormatLocaleString(key,MaxTextExtent,\"unknown\");\n break;\n }\n default:\n {\n if (level == 2)\n (void) SubstituteString(&key,\"exif:\",\"exif:thumbnail:\");\n }\n }\n p=(const char *) NULL;\n if (image->properties != (void *) NULL)\n p=(const char *) GetValueFromSplayTree((SplayTreeInfo *)\n image->properties,key);\n if (p == (const char *) NULL)\n (void) SetImageProperty((Image *) image,key,value);\n value=DestroyString(value);\n key=DestroyString(key);\n status=MagickTrue;\n }\n }\n if ((tag_value == TAG_EXIF_OFFSET) ||\n (tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET))\n {\n ssize_t\n offset;\n\n offset=(ssize_t) ReadPropertySignedLong(endian,p);\n if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))\n {\n ssize_t\n tag_offset1;\n\n tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 :\n 0);\n directory_stack[level].directory=directory;\n entry++;\n directory_stack[level].entry=entry;\n directory_stack[level].offset=tag_offset;\n level++;\n /*\n Check for duplicate tag.\n */\n for (i=0; i < level; i++)\n if (directory_stack[i].directory == (exif+tag_offset1))\n break;\n if (i < level)\n break; /* duplicate tag */\n directory_stack[level].directory=exif+offset;\n directory_stack[level].offset=tag_offset1;\n directory_stack[level].entry=0;\n level++;\n if ((directory+2+(12*number_entries)+4) > (exif+length))\n break;\n offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12*\n number_entries));\n if ((offset != 0) && ((size_t) offset < length) &&\n (level < (MaxDirectoryStack-2)))\n {\n directory_stack[level].directory=exif+offset;\n directory_stack[level].entry=0;\n directory_stack[level].offset=tag_offset1;\n level++;\n }\n }\n break;\n }\n }\n } while (level > 0);\n exif_resources=DestroySplayTree(exif_resources);\n return(status);\n}", "func_hash": 292096308156704952246887123009503225331, "file_name": "property.c", "file_hash": 122751008107964047346147343124174074065, "cwe": ["CWE-704"], "cve": "CVE-2022-32547", "cve_desc": "In ImageMagick, there is load of misaligned address for type 'double', which requires 8 byte alignment and for type 'float', which requires 4 byte alignment at MagickCore/property.c. Whenever crafted or untrusted input is processed by ImageMagick, this causes a negative impact to application availability or other problems related to undefined behavior.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32547"} {"idx": 217569, "project": "ImageMagick6", "commit_id": "dc070da861a015d3c97488fdcca6063b44d47a7b", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/dc070da861a015d3c97488fdcca6063b44d47a7b", "commit_message": "https://github.com/ImageMagick/ImageMagick/pull/5034", "target": 0, "func": "static MagickBooleanType GetEXIFProperty(const Image *image,\n const char *property)\n{\n#define MaxDirectoryStack 16\n#define EXIF_DELIMITER \"\\n\"\n#define EXIF_NUM_FORMATS 12\n#define EXIF_FMT_BYTE 1\n#define EXIF_FMT_STRING 2\n#define EXIF_FMT_USHORT 3\n#define EXIF_FMT_ULONG 4\n#define EXIF_FMT_URATIONAL 5\n#define EXIF_FMT_SBYTE 6\n#define EXIF_FMT_UNDEFINED 7\n#define EXIF_FMT_SSHORT 8\n#define EXIF_FMT_SLONG 9\n#define EXIF_FMT_SRATIONAL 10\n#define EXIF_FMT_SINGLE 11\n#define EXIF_FMT_DOUBLE 12\n#define TAG_EXIF_OFFSET 0x8769\n#define TAG_GPS_OFFSET 0x8825\n#define TAG_INTEROP_OFFSET 0xa005\n\n#define EXIFMultipleValues(size,format,arg) \\\n{ \\\n ssize_t \\\n component; \\\n \\\n size_t \\\n length; \\\n \\\n unsigned char \\\n *p1; \\\n \\\n length=0; \\\n p1=p; \\\n for (component=0; component < components; component++) \\\n { \\\n length+=FormatLocaleString(buffer+length,MaxTextExtent-length, \\\n format\", \",arg); \\\n if (length >= (MaxTextExtent-1)) \\\n length=MaxTextExtent-1; \\\n p1+=size; \\\n } \\\n if (length > 1) \\\n buffer[length-2]='\\0'; \\\n value=AcquireString(buffer); \\\n}\n\n#define EXIFMultipleFractions(size,format,arg1,arg2) \\\n{ \\\n ssize_t \\\n component; \\\n \\\n size_t \\\n length; \\\n \\\n unsigned char \\\n *p1; \\\n \\\n length=0; \\\n p1=p; \\\n for (component=0; component < components; component++) \\\n { \\\n length+=FormatLocaleString(buffer+length,MaxTextExtent-length, \\\n format\", \",(arg1),(arg2)); \\\n if (length >= (MaxTextExtent-1)) \\\n length=MaxTextExtent-1; \\\n p1+=size; \\\n } \\\n if (length > 1) \\\n buffer[length-2]='\\0'; \\\n value=AcquireString(buffer); \\\n}\n\n typedef struct _DirectoryInfo\n {\n const unsigned char\n *directory;\n\n size_t\n entry;\n\n ssize_t\n offset;\n } DirectoryInfo;\n\n typedef struct _TagInfo\n {\n size_t\n tag;\n\n const char\n description[36];\n } TagInfo;\n\n static const TagInfo\n EXIFTag[] =\n {\n { 0x001, \"exif:InteroperabilityIndex\" },\n { 0x002, \"exif:InteroperabilityVersion\" },\n { 0x100, \"exif:ImageWidth\" },\n { 0x101, \"exif:ImageLength\" },\n { 0x102, \"exif:BitsPerSample\" },\n { 0x103, \"exif:Compression\" },\n { 0x106, \"exif:PhotometricInterpretation\" },\n { 0x10a, \"exif:FillOrder\" },\n { 0x10d, \"exif:DocumentName\" },\n { 0x10e, \"exif:ImageDescription\" },\n { 0x10f, \"exif:Make\" },\n { 0x110, \"exif:Model\" },\n { 0x111, \"exif:StripOffsets\" },\n { 0x112, \"exif:Orientation\" },\n { 0x115, \"exif:SamplesPerPixel\" },\n { 0x116, \"exif:RowsPerStrip\" },\n { 0x117, \"exif:StripByteCounts\" },\n { 0x11a, \"exif:XResolution\" },\n { 0x11b, \"exif:YResolution\" },\n { 0x11c, \"exif:PlanarConfiguration\" },\n { 0x11d, \"exif:PageName\" },\n { 0x11e, \"exif:XPosition\" },\n { 0x11f, \"exif:YPosition\" },\n { 0x118, \"exif:MinSampleValue\" },\n { 0x119, \"exif:MaxSampleValue\" },\n { 0x120, \"exif:FreeOffsets\" },\n { 0x121, \"exif:FreeByteCounts\" },\n { 0x122, \"exif:GrayResponseUnit\" },\n { 0x123, \"exif:GrayResponseCurve\" },\n { 0x124, \"exif:T4Options\" },\n { 0x125, \"exif:T6Options\" },\n { 0x128, \"exif:ResolutionUnit\" },\n { 0x12d, \"exif:TransferFunction\" },\n { 0x131, \"exif:Software\" },\n { 0x132, \"exif:DateTime\" },\n { 0x13b, \"exif:Artist\" },\n { 0x13e, \"exif:WhitePoint\" },\n { 0x13f, \"exif:PrimaryChromaticities\" },\n { 0x140, \"exif:ColorMap\" },\n { 0x141, \"exif:HalfToneHints\" },\n { 0x142, \"exif:TileWidth\" },\n { 0x143, \"exif:TileLength\" },\n { 0x144, \"exif:TileOffsets\" },\n { 0x145, \"exif:TileByteCounts\" },\n { 0x14a, \"exif:SubIFD\" },\n { 0x14c, \"exif:InkSet\" },\n { 0x14d, \"exif:InkNames\" },\n { 0x14e, \"exif:NumberOfInks\" },\n { 0x150, \"exif:DotRange\" },\n { 0x151, \"exif:TargetPrinter\" },\n { 0x152, \"exif:ExtraSample\" },\n { 0x153, \"exif:SampleFormat\" },\n { 0x154, \"exif:SMinSampleValue\" },\n { 0x155, \"exif:SMaxSampleValue\" },\n { 0x156, \"exif:TransferRange\" },\n { 0x157, \"exif:ClipPath\" },\n { 0x158, \"exif:XClipPathUnits\" },\n { 0x159, \"exif:YClipPathUnits\" },\n { 0x15a, \"exif:Indexed\" },\n { 0x15b, \"exif:JPEGTables\" },\n { 0x15f, \"exif:OPIProxy\" },\n { 0x200, \"exif:JPEGProc\" },\n { 0x201, \"exif:JPEGInterchangeFormat\" },\n { 0x202, \"exif:JPEGInterchangeFormatLength\" },\n { 0x203, \"exif:JPEGRestartInterval\" },\n { 0x205, \"exif:JPEGLosslessPredictors\" },\n { 0x206, \"exif:JPEGPointTransforms\" },\n { 0x207, \"exif:JPEGQTables\" },\n { 0x208, \"exif:JPEGDCTables\" },\n { 0x209, \"exif:JPEGACTables\" },\n { 0x211, \"exif:YCbCrCoefficients\" },\n { 0x212, \"exif:YCbCrSubSampling\" },\n { 0x213, \"exif:YCbCrPositioning\" },\n { 0x214, \"exif:ReferenceBlackWhite\" },\n { 0x2bc, \"exif:ExtensibleMetadataPlatform\" },\n { 0x301, \"exif:Gamma\" },\n { 0x302, \"exif:ICCProfileDescriptor\" },\n { 0x303, \"exif:SRGBRenderingIntent\" },\n { 0x320, \"exif:ImageTitle\" },\n { 0x5001, \"exif:ResolutionXUnit\" },\n { 0x5002, \"exif:ResolutionYUnit\" },\n { 0x5003, \"exif:ResolutionXLengthUnit\" },\n { 0x5004, \"exif:ResolutionYLengthUnit\" },\n { 0x5005, \"exif:PrintFlags\" },\n { 0x5006, \"exif:PrintFlagsVersion\" },\n { 0x5007, \"exif:PrintFlagsCrop\" },\n { 0x5008, \"exif:PrintFlagsBleedWidth\" },\n { 0x5009, \"exif:PrintFlagsBleedWidthScale\" },\n { 0x500A, \"exif:HalftoneLPI\" },\n { 0x500B, \"exif:HalftoneLPIUnit\" },\n { 0x500C, \"exif:HalftoneDegree\" },\n { 0x500D, \"exif:HalftoneShape\" },\n { 0x500E, \"exif:HalftoneMisc\" },\n { 0x500F, \"exif:HalftoneScreen\" },\n { 0x5010, \"exif:JPEGQuality\" },\n { 0x5011, \"exif:GridSize\" },\n { 0x5012, \"exif:ThumbnailFormat\" },\n { 0x5013, \"exif:ThumbnailWidth\" },\n { 0x5014, \"exif:ThumbnailHeight\" },\n { 0x5015, \"exif:ThumbnailColorDepth\" },\n { 0x5016, \"exif:ThumbnailPlanes\" },\n { 0x5017, \"exif:ThumbnailRawBytes\" },\n { 0x5018, \"exif:ThumbnailSize\" },\n { 0x5019, \"exif:ThumbnailCompressedSize\" },\n { 0x501a, \"exif:ColorTransferFunction\" },\n { 0x501b, \"exif:ThumbnailData\" },\n { 0x5020, \"exif:ThumbnailImageWidth\" },\n { 0x5021, \"exif:ThumbnailImageHeight\" },\n { 0x5022, \"exif:ThumbnailBitsPerSample\" },\n { 0x5023, \"exif:ThumbnailCompression\" },\n { 0x5024, \"exif:ThumbnailPhotometricInterp\" },\n { 0x5025, \"exif:ThumbnailImageDescription\" },\n { 0x5026, \"exif:ThumbnailEquipMake\" },\n { 0x5027, \"exif:ThumbnailEquipModel\" },\n { 0x5028, \"exif:ThumbnailStripOffsets\" },\n { 0x5029, \"exif:ThumbnailOrientation\" },\n { 0x502a, \"exif:ThumbnailSamplesPerPixel\" },\n { 0x502b, \"exif:ThumbnailRowsPerStrip\" },\n { 0x502c, \"exif:ThumbnailStripBytesCount\" },\n { 0x502d, \"exif:ThumbnailResolutionX\" },\n { 0x502e, \"exif:ThumbnailResolutionY\" },\n { 0x502f, \"exif:ThumbnailPlanarConfig\" },\n { 0x5030, \"exif:ThumbnailResolutionUnit\" },\n { 0x5031, \"exif:ThumbnailTransferFunction\" },\n { 0x5032, \"exif:ThumbnailSoftwareUsed\" },\n { 0x5033, \"exif:ThumbnailDateTime\" },\n { 0x5034, \"exif:ThumbnailArtist\" },\n { 0x5035, \"exif:ThumbnailWhitePoint\" },\n { 0x5036, \"exif:ThumbnailPrimaryChromaticities\" },\n { 0x5037, \"exif:ThumbnailYCbCrCoefficients\" },\n { 0x5038, \"exif:ThumbnailYCbCrSubsampling\" },\n { 0x5039, \"exif:ThumbnailYCbCrPositioning\" },\n { 0x503A, \"exif:ThumbnailRefBlackWhite\" },\n { 0x503B, \"exif:ThumbnailCopyRight\" },\n { 0x5090, \"exif:LuminanceTable\" },\n { 0x5091, \"exif:ChrominanceTable\" },\n { 0x5100, \"exif:FrameDelay\" },\n { 0x5101, \"exif:LoopCount\" },\n { 0x5110, \"exif:PixelUnit\" },\n { 0x5111, \"exif:PixelPerUnitX\" },\n { 0x5112, \"exif:PixelPerUnitY\" },\n { 0x5113, \"exif:PaletteHistogram\" },\n { 0x1000, \"exif:RelatedImageFileFormat\" },\n { 0x1001, \"exif:RelatedImageLength\" },\n { 0x1002, \"exif:RelatedImageWidth\" },\n { 0x800d, \"exif:ImageID\" },\n { 0x80e3, \"exif:Matteing\" },\n { 0x80e4, \"exif:DataType\" },\n { 0x80e5, \"exif:ImageDepth\" },\n { 0x80e6, \"exif:TileDepth\" },\n { 0x828d, \"exif:CFARepeatPatternDim\" },\n { 0x828e, \"exif:CFAPattern2\" },\n { 0x828f, \"exif:BatteryLevel\" },\n { 0x8298, \"exif:Copyright\" },\n { 0x829a, \"exif:ExposureTime\" },\n { 0x829d, \"exif:FNumber\" },\n { 0x83bb, \"exif:IPTC/NAA\" },\n { 0x84e3, \"exif:IT8RasterPadding\" },\n { 0x84e5, \"exif:IT8ColorTable\" },\n { 0x8649, \"exif:ImageResourceInformation\" },\n { 0x8769, \"exif:ExifOffset\" }, /* specs as \"Exif IFD Pointer\"? */\n { 0x8773, \"exif:InterColorProfile\" },\n { 0x8822, \"exif:ExposureProgram\" },\n { 0x8824, \"exif:SpectralSensitivity\" },\n { 0x8825, \"exif:GPSInfo\" }, /* specs as \"GPSInfo IFD Pointer\"? */\n { 0x8827, \"exif:PhotographicSensitivity\" },\n { 0x8828, \"exif:OECF\" },\n { 0x8829, \"exif:Interlace\" }, \n { 0x882a, \"exif:TimeZoneOffset\" },\n { 0x882b, \"exif:SelfTimerMode\" },\n { 0x8830, \"exif:SensitivityType\" },\n { 0x8831, \"exif:StandardOutputSensitivity\" },\n { 0x8832, \"exif:RecommendedExposureIndex\" },\n { 0x8833, \"exif:ISOSpeed\" },\n { 0x8834, \"exif:ISOSpeedLatitudeyyy\" },\n { 0x8835, \"exif:ISOSpeedLatitudezzz\" },\n { 0x9000, \"exif:ExifVersion\" },\n { 0x9003, \"exif:DateTimeOriginal\" },\n { 0x9004, \"exif:DateTimeDigitized\" },\n { 0x9010, \"exif:OffsetTime\" },\n { 0x9011, \"exif:OffsetTimeOriginal\" },\n { 0x9012, \"exif:OffsetTimeDigitized\" },\n { 0x9101, \"exif:ComponentsConfiguration\" },\n { 0x9102, \"exif:CompressedBitsPerPixel\" },\n { 0x9201, \"exif:ShutterSpeedValue\" },\n { 0x9202, \"exif:ApertureValue\" },\n { 0x9203, \"exif:BrightnessValue\" },\n { 0x9204, \"exif:ExposureBiasValue\" },\n { 0x9205, \"exif:MaxApertureValue\" },\n { 0x9206, \"exif:SubjectDistance\" },\n { 0x9207, \"exif:MeteringMode\" },\n { 0x9208, \"exif:LightSource\" },\n { 0x9209, \"exif:Flash\" },\n { 0x920a, \"exif:FocalLength\" },\n { 0x920b, \"exif:FlashEnergy\" },\n { 0x920c, \"exif:SpatialFrequencyResponse\" },\n { 0x920d, \"exif:Noise\" },\n { 0x9214, \"exif:SubjectArea\" },\n { 0x9290, \"exif:SubSecTime\" },\n { 0x9291, \"exif:SubSecTimeOriginal\" },\n { 0x9292, \"exif:SubSecTimeDigitized\" }, \n { 0x9211, \"exif:ImageNumber\" },\n { 0x9212, \"exif:SecurityClassification\" },\n { 0x9213, \"exif:ImageHistory\" },\n { 0x9214, \"exif:SubjectArea\" },\n { 0x9215, \"exif:ExposureIndex\" },\n { 0x9216, \"exif:TIFF-EPStandardID\" },\n { 0x927c, \"exif:MakerNote\" },\n { 0x9286, \"exif:UserComment\" },\n { 0x9290, \"exif:SubSecTime\" },\n { 0x9291, \"exif:SubSecTimeOriginal\" },\n { 0x9292, \"exif:SubSecTimeDigitized\" }, \n { 0x9400, \"exif:Temperature\" },\n { 0x9401, \"exif:Humidity\" },\n { 0x9402, \"exif:Pressure\" },\n { 0x9403, \"exif:WaterDepth\" },\n { 0x9404, \"exif:Acceleration\" },\n { 0x9405, \"exif:CameraElevationAngle\" }, \n { 0x9C9b, \"exif:WinXP-Title\" },\n { 0x9C9c, \"exif:WinXP-Comments\" },\n { 0x9C9d, \"exif:WinXP-Author\" },\n { 0x9C9e, \"exif:WinXP-Keywords\" },\n { 0x9C9f, \"exif:WinXP-Subject\" }, \n { 0xa000, \"exif:FlashPixVersion\" },\n { 0xa001, \"exif:ColorSpace\" },\n { 0xa002, \"exif:PixelXDimension\" },\n { 0xa003, \"exif:PixelYDimension\" },\n { 0xa004, \"exif:RelatedSoundFile\" },\n { 0xa005, \"exif:InteroperabilityOffset\" },\n { 0xa20b, \"exif:FlashEnergy\" },\n { 0xa20c, \"exif:SpatialFrequencyResponse\" },\n { 0xa20d, \"exif:Noise\" },\n { 0xa20e, \"exif:FocalPlaneXResolution\" },\n { 0xa20f, \"exif:FocalPlaneYResolution\" },\n { 0xa210, \"exif:FocalPlaneResolutionUnit\" },\n { 0xa214, \"exif:SubjectLocation\" },\n { 0xa215, \"exif:ExposureIndex\" },\n { 0xa216, \"exif:TIFF/EPStandardID\" },\n { 0xa217, \"exif:SensingMethod\" },\n { 0xa300, \"exif:FileSource\" },\n { 0xa301, \"exif:SceneType\" },\n { 0xa302, \"exif:CFAPattern\" },\n { 0xa401, \"exif:CustomRendered\" },\n { 0xa402, \"exif:ExposureMode\" },\n { 0xa403, \"exif:WhiteBalance\" },\n { 0xa404, \"exif:DigitalZoomRatio\" },\n { 0xa405, \"exif:FocalLengthIn35mmFilm\" },\n { 0xa406, \"exif:SceneCaptureType\" },\n { 0xa407, \"exif:GainControl\" },\n { 0xa408, \"exif:Contrast\" },\n { 0xa409, \"exif:Saturation\" },\n { 0xa40a, \"exif:Sharpness\" },\n { 0xa40b, \"exif:DeviceSettingDescription\" },\n { 0xa40c, \"exif:SubjectDistanceRange\" },\n { 0xa420, \"exif:ImageUniqueID\" },\n { 0xa430, \"exif:CameraOwnerName\" },\n { 0xa431, \"exif:BodySerialNumber\" },\n { 0xa432, \"exif:LensSpecification\" },\n { 0xa433, \"exif:LensMake\" },\n { 0xa434, \"exif:LensModel\" },\n { 0xa435, \"exif:LensSerialNumber\" },\n { 0xc4a5, \"exif:PrintImageMatching\" },\n { 0xa500, \"exif:Gamma\" },\n { 0xc640, \"exif:CR2Slice\" },\n { 0x10000, \"exif:GPSVersionID\" },\n { 0x10001, \"exif:GPSLatitudeRef\" },\n { 0x10002, \"exif:GPSLatitude\" },\n { 0x10003, \"exif:GPSLongitudeRef\" },\n { 0x10004, \"exif:GPSLongitude\" },\n { 0x10005, \"exif:GPSAltitudeRef\" },\n { 0x10006, \"exif:GPSAltitude\" },\n { 0x10007, \"exif:GPSTimeStamp\" },\n { 0x10008, \"exif:GPSSatellites\" },\n { 0x10009, \"exif:GPSStatus\" },\n { 0x1000a, \"exif:GPSMeasureMode\" },\n { 0x1000b, \"exif:GPSDop\" },\n { 0x1000c, \"exif:GPSSpeedRef\" },\n { 0x1000d, \"exif:GPSSpeed\" },\n { 0x1000e, \"exif:GPSTrackRef\" },\n { 0x1000f, \"exif:GPSTrack\" },\n { 0x10010, \"exif:GPSImgDirectionRef\" },\n { 0x10011, \"exif:GPSImgDirection\" },\n { 0x10012, \"exif:GPSMapDatum\" },\n { 0x10013, \"exif:GPSDestLatitudeRef\" },\n { 0x10014, \"exif:GPSDestLatitude\" },\n { 0x10015, \"exif:GPSDestLongitudeRef\" },\n { 0x10016, \"exif:GPSDestLongitude\" },\n { 0x10017, \"exif:GPSDestBearingRef\" },\n { 0x10018, \"exif:GPSDestBearing\" },\n { 0x10019, \"exif:GPSDestDistanceRef\" },\n { 0x1001a, \"exif:GPSDestDistance\" },\n { 0x1001b, \"exif:GPSProcessingMethod\" },\n { 0x1001c, \"exif:GPSAreaInformation\" },\n { 0x1001d, \"exif:GPSDateStamp\" },\n { 0x1001e, \"exif:GPSDifferential\" },\n { 0x1001f, \"exif:GPSHPositioningError\" },\n { 0x00000, \"\" }\n }; /* http://www.cipa.jp/std/documents/e/DC-008-Translation-2016-E.pdf */\n\n const StringInfo\n *profile;\n\n const unsigned char\n *directory,\n *exif;\n\n DirectoryInfo\n directory_stack[MaxDirectoryStack];\n\n EndianType\n endian;\n\n MagickBooleanType\n status;\n\n ssize_t\n i;\n\n size_t\n entry,\n length,\n number_entries,\n tag,\n tag_value;\n\n SplayTreeInfo\n *exif_resources;\n\n ssize_t\n all,\n id,\n level,\n offset,\n tag_offset;\n\n static int\n tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};\n\n /*\n If EXIF data exists, then try to parse the request for a tag.\n */\n profile=GetImageProfile(image,\"exif\");\n if (profile == (const StringInfo *) NULL)\n return(MagickFalse);\n if ((property == (const char *) NULL) || (*property == '\\0'))\n return(MagickFalse);\n while (isspace((int) ((unsigned char) *property)) != 0)\n property++;\n if (strlen(property) <= 5)\n return(MagickFalse);\n all=0;\n tag=(~0UL);\n switch (*(property+5))\n {\n case '*':\n {\n /*\n Caller has asked for all the tags in the EXIF data.\n */\n tag=0;\n all=1; /* return the data in description=value format */\n break;\n }\n case '!':\n {\n tag=0;\n all=2; /* return the data in tagid=value format */\n break;\n }\n case '#':\n case '@':\n {\n int\n c;\n\n size_t\n n;\n\n /*\n Check for a hex based tag specification first.\n */\n tag=(*(property+5) == '@') ? 1UL : 0UL;\n property+=6;\n n=strlen(property);\n if (n != 4)\n return(MagickFalse);\n /*\n Parse tag specification as a hex number.\n */\n n/=4;\n do\n {\n for (i=(ssize_t) n-1L; i >= 0; i--)\n {\n c=(*property++);\n tag<<=4;\n if ((c >= '0') && (c <= '9'))\n tag|=(c-'0');\n else\n if ((c >= 'A') && (c <= 'F'))\n tag|=(c-('A'-10));\n else\n if ((c >= 'a') && (c <= 'f'))\n tag|=(c-('a'-10));\n else\n return(MagickFalse);\n }\n } while (*property != '\\0');\n break;\n }\n default:\n {\n /*\n Try to match the text with a tag name instead.\n */\n for (i=0; ; i++)\n {\n if (EXIFTag[i].tag == 0)\n break;\n if (LocaleCompare(EXIFTag[i].description,property) == 0)\n {\n tag=(size_t) EXIFTag[i].tag;\n break;\n }\n }\n break;\n }\n }\n if (tag == (~0UL))\n return(MagickFalse);\n length=GetStringInfoLength(profile);\n if (length < 6)\n return(MagickFalse);\n exif=GetStringInfoDatum(profile);\n while (length != 0)\n {\n if (ReadPropertyByte(&exif,&length) != 0x45)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x78)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x69)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x66)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x00)\n continue;\n if (ReadPropertyByte(&exif,&length) != 0x00)\n continue;\n break;\n }\n if (length < 16)\n return(MagickFalse);\n id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif);\n endian=LSBEndian;\n if (id == 0x4949)\n endian=LSBEndian;\n else\n if (id == 0x4D4D)\n endian=MSBEndian;\n else\n return(MagickFalse);\n if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a)\n return(MagickFalse);\n /*\n This the offset to the first IFD.\n */\n offset=(ssize_t) ReadPropertySignedLong(endian,exif+4);\n if ((offset < 0) || (size_t) offset >= length)\n return(MagickFalse);\n /*\n Set the pointer to the first IFD and follow it were it leads.\n */\n status=MagickFalse;\n directory=exif+offset;\n level=0;\n entry=0;\n tag_offset=0;\n exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL,\n (void *(*)(void *)) NULL,(void *(*)(void *)) NULL);\n do\n {\n /*\n If there is anything on the stack then pop it off.\n */\n if (level > 0)\n {\n level--;\n directory=directory_stack[level].directory;\n entry=directory_stack[level].entry;\n tag_offset=directory_stack[level].offset;\n }\n if ((directory < exif) || (directory > (exif+length-2)))\n break;\n /*\n Determine how many entries there are in the current IFD.\n */\n number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory);\n for ( ; entry < number_entries; entry++)\n {\n unsigned char\n *p,\n *q;\n\n size_t\n format;\n\n ssize_t\n number_bytes,\n components;\n\n q=(unsigned char *) (directory+(12*entry)+2);\n if (q > (exif+length-12))\n break; /* corrupt EXIF */\n if (GetValueFromSplayTree(exif_resources,q) == q)\n break;\n (void) AddValueToSplayTree(exif_resources,q,q);\n tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset;\n format=(size_t) ReadPropertyUnsignedShort(endian,q+2);\n if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes)))\n break;\n if (format == 0)\n break; /* corrupt EXIF */\n components=(ssize_t) ReadPropertySignedLong(endian,q+4);\n if (components < 0)\n break; /* corrupt EXIF */\n number_bytes=(size_t) components*tag_bytes[format];\n if (number_bytes < components)\n break; /* prevent overflow */\n if (number_bytes <= 4)\n p=q+8;\n else\n {\n ssize_t\n dir_offset;\n\n /*\n The directory entry contains an offset.\n */\n dir_offset=(ssize_t) ReadPropertySignedLong(endian,q+8);\n if ((dir_offset < 0) || (size_t) dir_offset >= length)\n continue;\n if (((size_t) dir_offset+number_bytes) < (size_t) dir_offset)\n continue; /* prevent overflow */\n if (((size_t) dir_offset+number_bytes) > length)\n continue;\n p=(unsigned char *) (exif+dir_offset);\n }\n if ((all != 0) || (tag == (size_t) tag_value))\n {\n char\n buffer[MaxTextExtent],\n *value;\n\n if ((p < exif) || (p > (exif+length-tag_bytes[format])))\n break;\n value=(char *) NULL;\n *buffer='\\0';\n switch (format)\n {\n case EXIF_FMT_BYTE:\n case EXIF_FMT_UNDEFINED:\n {\n value=(char *) NULL;\n if (~((size_t) number_bytes) >= 1)\n value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL,\n sizeof(*value));\n if (value != (char *) NULL)\n {\n for (i=0; i < (ssize_t) number_bytes; i++)\n {\n value[i]='.';\n if (isprint((int) p[i]) != 0) \n value[i]=(char) p[i];\n }\n value[i]='\\0';\n }\n break;\n }\n case EXIF_FMT_SBYTE:\n {\n EXIFMultipleValues(1,\"%.20g\",(double) (*(signed char *) p1));\n break;\n }\n case EXIF_FMT_SSHORT:\n {\n EXIFMultipleValues(2,\"%hd\",ReadPropertySignedShort(endian,p1));\n break;\n }\n case EXIF_FMT_USHORT:\n {\n EXIFMultipleValues(2,\"%hu\",ReadPropertyUnsignedShort(endian,p1));\n break;\n }\n case EXIF_FMT_ULONG:\n {\n EXIFMultipleValues(4,\"%.20g\",(double)\n ReadPropertyUnsignedLong(endian,p1));\n break;\n }\n case EXIF_FMT_SLONG:\n {\n EXIFMultipleValues(4,\"%.20g\",(double)\n ReadPropertySignedLong(endian,p1));\n break;\n }\n case EXIF_FMT_URATIONAL:\n {\n EXIFMultipleFractions(8,\"%.20g/%.20g\",(double)\n ReadPropertyUnsignedLong(endian,p1),(double)\n ReadPropertyUnsignedLong(endian,p1+4));\n break;\n }\n case EXIF_FMT_SRATIONAL:\n {\n EXIFMultipleFractions(8,\"%.20g/%.20g\",(double)\n ReadPropertySignedLong(endian,p1),(double)\n ReadPropertySignedLong(endian,p1+4));\n break;\n }\n case EXIF_FMT_SINGLE:\n {\n EXIFMultipleValues(4,\"%.20g\",(double)\n ReadPropertySignedLong(endian,p1));\n break;\n }\n case EXIF_FMT_DOUBLE:\n {\n EXIFMultipleValues(8,\"%.20g\",(double)\n ReadPropertySignedLong(endian,p1));\n break;\n }\n case EXIF_FMT_STRING:\n default:\n {\n if ((p < exif) || (p > (exif+length-number_bytes)))\n break;\n value=(char *) NULL;\n if (~((size_t) number_bytes) >= 1)\n value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL,\n sizeof(*value));\n if (value != (char *) NULL)\n {\n ssize_t\n i;\n\n for (i=0; i < (ssize_t) number_bytes; i++)\n {\n value[i]='.';\n if ((isprint((int) p[i]) != 0) || (p[i] == '\\0'))\n value[i]=(char) p[i];\n }\n value[i]='\\0';\n }\n break;\n }\n }\n if (value != (char *) NULL)\n {\n char\n *key;\n\n const char\n *p;\n\n key=AcquireString(property);\n switch (all)\n {\n case 1:\n {\n const char\n *description;\n\n ssize_t\n i;\n\n description=\"unknown\";\n for (i=0; ; i++)\n {\n if (EXIFTag[i].tag == 0)\n break;\n if (EXIFTag[i].tag == tag_value)\n {\n description=EXIFTag[i].description;\n break;\n }\n }\n (void) FormatLocaleString(key,MaxTextExtent,\"%s\",\n description);\n if (level == 2)\n (void) SubstituteString(&key,\"exif:\",\"exif:thumbnail:\");\n break;\n }\n case 2:\n {\n if (tag_value < 0x10000)\n (void) FormatLocaleString(key,MaxTextExtent,\"#%04lx\",\n (unsigned long) tag_value);\n else\n if (tag_value < 0x20000)\n (void) FormatLocaleString(key,MaxTextExtent,\"@%04lx\",\n (unsigned long) (tag_value & 0xffff));\n else\n (void) FormatLocaleString(key,MaxTextExtent,\"unknown\");\n break;\n }\n default:\n {\n if (level == 2)\n (void) SubstituteString(&key,\"exif:\",\"exif:thumbnail:\");\n }\n }\n p=(const char *) NULL;\n if (image->properties != (void *) NULL)\n p=(const char *) GetValueFromSplayTree((SplayTreeInfo *)\n image->properties,key);\n if (p == (const char *) NULL)\n (void) SetImageProperty((Image *) image,key,value);\n value=DestroyString(value);\n key=DestroyString(key);\n status=MagickTrue;\n }\n }\n if ((tag_value == TAG_EXIF_OFFSET) ||\n (tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET))\n {\n ssize_t\n offset;\n\n offset=(ssize_t) ReadPropertySignedLong(endian,p);\n if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))\n {\n ssize_t\n tag_offset1;\n\n tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 :\n 0);\n directory_stack[level].directory=directory;\n entry++;\n directory_stack[level].entry=entry;\n directory_stack[level].offset=tag_offset;\n level++;\n /*\n Check for duplicate tag.\n */\n for (i=0; i < level; i++)\n if (directory_stack[i].directory == (exif+tag_offset1))\n break;\n if (i < level)\n break; /* duplicate tag */\n directory_stack[level].directory=exif+offset;\n directory_stack[level].offset=tag_offset1;\n directory_stack[level].entry=0;\n level++;\n if ((directory+2+(12*number_entries)+4) > (exif+length))\n break;\n offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12*\n number_entries));\n if ((offset != 0) && ((size_t) offset < length) &&\n (level < (MaxDirectoryStack-2)))\n {\n directory_stack[level].directory=exif+offset;\n directory_stack[level].entry=0;\n directory_stack[level].offset=tag_offset1;\n level++;\n }\n }\n break;\n }\n }\n } while (level > 0);\n exif_resources=DestroySplayTree(exif_resources);\n return(status);\n}", "func_hash": 75422468811560646183620950160304672170, "file_name": "property.c", "file_hash": 320426917520707901134127411021604962567, "cwe": ["CWE-704"], "cve": "CVE-2022-32547", "cve_desc": "In ImageMagick, there is load of misaligned address for type 'double', which requires 8 byte alignment and for type 'float', which requires 4 byte alignment at MagickCore/property.c. Whenever crafted or untrusted input is processed by ImageMagick, this causes a negative impact to application availability or other problems related to undefined behavior.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32547"} {"idx": 194989, "project": "ImageMagick6", "commit_id": "450949ed017f009b399c937cf362f0058eacc5fa", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/450949ed017f009b399c937cf362f0058eacc5fa", "commit_message": "Pull request: https://github.com/ImageMagick/ImageMagick/pull/4963", "target": 1, "func": "static MagickBooleanType ReadPSDChannelPixels(Image *image,\n const size_t channels,const ssize_t row,const ssize_t type,\n const unsigned char *pixels,ExceptionInfo *exception)\n{\n Quantum\n pixel;\n\n const unsigned char\n *p;\n\n IndexPacket\n *indexes;\n\n PixelPacket\n *q;\n\n ssize_t\n x;\n\n size_t\n packet_size;\n\n unsigned short\n nibble;\n\n p=pixels;\n q=GetAuthenticPixels(image,0,row,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n return MagickFalse;\n indexes=GetAuthenticIndexQueue(image);\n packet_size=GetPSDPacketSize(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (packet_size == 1)\n pixel=ScaleCharToQuantum(*p++);\n else\n if (packet_size == 2)\n {\n p=PushShortPixel(MSBEndian,p,&nibble);\n pixel=ScaleShortToQuantum(nibble);\n }\n else\n {\n MagickFloatType\n nibble;\n\n p=PushFloatPixel(MSBEndian,p,&nibble);\n pixel=ClampToQuantum((MagickRealType)QuantumRange*nibble);\n }\n if (image->depth > 1)\n {\n SetPSDPixel(image,channels,type,packet_size,pixel,q,indexes,x);\n q++;\n }\n else\n {\n ssize_t\n bit,\n number_bits;\n\n number_bits=(ssize_t) image->columns-x;\n if (number_bits > 8)\n number_bits=8;\n for (bit=0; bit < number_bits; bit++)\n {\n SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)\n & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++);\n }\n if (x != (ssize_t) image->columns)\n x--;\n continue;\n }\n }\n return(SyncAuthenticPixels(image,exception));\n}", "func_hash": 50584299779312396054491404176852470969, "file_name": "psd.c", "file_hash": 159316916509494023086155162326374999236, "cwe": ["CWE-190"], "cve": "CVE-2022-32545", "cve_desc": "A vulnerability was found in ImageMagick, causing an outside the range of representable values of type 'unsigned char' at coders/psd.c, when crafted or untrusted input is processed. This leads to a negative impact to application availability or other problems related to undefined behavior.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32545"} {"idx": 218785, "project": "ImageMagick6", "commit_id": "450949ed017f009b399c937cf362f0058eacc5fa", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/450949ed017f009b399c937cf362f0058eacc5fa", "commit_message": "Pull request: https://github.com/ImageMagick/ImageMagick/pull/4963", "target": 0, "func": "static MagickBooleanType ReadPSDChannelPixels(Image *image,\n const size_t channels,const ssize_t row,const ssize_t type,\n const unsigned char *pixels,ExceptionInfo *exception)\n{\n Quantum\n pixel;\n\n const unsigned char\n *p;\n\n IndexPacket\n *indexes;\n\n PixelPacket\n *q;\n\n ssize_t\n x;\n\n size_t\n packet_size;\n\n unsigned short\n nibble;\n\n p=pixels;\n q=GetAuthenticPixels(image,0,row,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n return MagickFalse;\n indexes=GetAuthenticIndexQueue(image);\n packet_size=GetPSDPacketSize(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (packet_size == 1)\n pixel=ScaleCharToQuantum(*p++);\n else\n if (packet_size == 2)\n {\n p=PushShortPixel(MSBEndian,p,&nibble);\n pixel=ScaleShortToQuantum(nibble);\n }\n else\n {\n MagickFloatType\n nibble;\n\n p=PushFloatPixel(MSBEndian,p,&nibble);\n pixel=ClampToQuantum((MagickRealType)QuantumRange*nibble);\n }\n if (image->depth > 1)\n {\n SetPSDPixel(image,channels,type,packet_size,pixel,q,indexes,x);\n q++;\n }\n else\n {\n ssize_t\n bit,\n number_bits;\n\n number_bits=(ssize_t) image->columns-x;\n if (number_bits > 8)\n number_bits=8;\n for (bit=0; bit < number_bits; bit++)\n {\n SetPSDPixel(image,channels,type,packet_size,\n (((unsigned char) ((ssize_t) pixel)) & (0x01 << (7-bit))) != 0 ? 0 :\n QuantumRange,q++,indexes,x++);\n }\n if (x != (ssize_t) image->columns)\n x--;\n continue;\n }\n }\n return(SyncAuthenticPixels(image,exception));\n}", "func_hash": 177518249272594340059836567736761123364, "file_name": "psd.c", "file_hash": 226732625250511916284298083592366716300, "cwe": ["CWE-190"], "cve": "CVE-2022-32545", "cve_desc": "A vulnerability was found in ImageMagick, causing an outside the range of representable values of type 'unsigned char' at coders/psd.c, when crafted or untrusted input is processed. This leads to a negative impact to application availability or other problems related to undefined behavior.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32545"} {"idx": 194994, "project": "tensorflow", "commit_id": "c79ccba517dbb1a0ccb9b01ee3bd2a63748b60dd", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/c79ccba517dbb1a0ccb9b01ee3bd2a63748b60dd", "commit_message": "Fix memory leak when a graph node is invalid.\n\nIf a graph node is invalid but a kernel is created then we set the kernel back to `nullptr` but we forget to delete it. Hence, we get a memory leak.\n\nPiperOrigin-RevId: 408968108\nChange-Id: I1d8a9d0d8988ed5e08be8b9f2004ce1b4cd11b7c", "target": 1, "func": "Status ImmutableExecutorState::Initialize(const Graph& graph) {\n TF_RETURN_IF_ERROR(gview_.Initialize(&graph));\n\n // Build the information about frames in this subgraph.\n ControlFlowInfo cf_info;\n TF_RETURN_IF_ERROR(BuildControlFlowInfo(&graph, &cf_info));\n\n for (auto& it : cf_info.unique_frame_names) {\n EnsureFrameInfo(it)->nodes =\n absl::make_unique>();\n }\n root_frame_info_ = frame_info_[\"\"].get();\n\n pending_ids_.resize(gview_.num_nodes());\n\n // Preprocess every node in the graph to create an instance of op\n // kernel for each node.\n requires_control_flow_ = false;\n for (const Node* n : graph.nodes()) {\n if (IsSink(n)) continue;\n if (IsSwitch(n) || IsMerge(n) || IsEnter(n) || IsExit(n)) {\n requires_control_flow_ = true;\n } else if (IsRecv(n)) {\n // A Recv node from a different device may produce dead tensors from\n // non-local control-flow nodes.\n //\n // TODO(mrry): Track whether control flow was present in the\n // pre-partitioned graph, and enable the caller (e.g.\n // `DirectSession`) to relax this constraint.\n string send_device;\n string recv_device;\n TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), \"send_device\", &send_device));\n TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), \"recv_device\", &recv_device));\n if (send_device != recv_device) {\n requires_control_flow_ = true;\n }\n }\n\n const int id = n->id();\n const string& frame_name = cf_info.frame_names[id];\n FrameInfo* frame_info = EnsureFrameInfo(frame_name);\n\n NodeItem* item = gview_.node(id);\n item->node_id = id;\n\n item->input_start = frame_info->total_inputs;\n frame_info->total_inputs += n->num_inputs();\n\n Status s = params_.create_kernel(n->properties(), &item->kernel);\n if (!s.ok()) {\n item->kernel = nullptr;\n s = AttachDef(s, *n);\n return s;\n }\n CHECK(item->kernel);\n item->kernel_is_async = (item->kernel->AsAsync() != nullptr);\n item->is_merge = IsMerge(n);\n item->is_any_consumer_merge_or_control_trigger = false;\n for (const Node* consumer : n->out_nodes()) {\n if (IsMerge(consumer) || IsControlTrigger(consumer)) {\n item->is_any_consumer_merge_or_control_trigger = true;\n break;\n }\n }\n const Tensor* const_tensor = item->kernel->const_tensor();\n if (const_tensor) {\n // Hold onto a shallow copy of the constant tensor in `*this` so that the\n // reference count does not drop to 1. This prevents the constant tensor\n // from being forwarded, and its buffer reused.\n const_tensors_.emplace_back(*const_tensor);\n }\n item->const_tensor = const_tensor;\n item->is_noop = (item->kernel->type_string_view() == \"NoOp\");\n item->is_enter = IsEnter(n);\n if (item->is_enter) {\n bool is_constant_enter;\n TF_RETURN_IF_ERROR(\n GetNodeAttr(n->attrs(), \"is_constant\", &is_constant_enter));\n item->is_constant_enter = is_constant_enter;\n\n string frame_name;\n TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), \"frame_name\", &frame_name));\n FrameInfo* frame_info = frame_info_[frame_name].get();\n\n int parallel_iterations;\n TF_RETURN_IF_ERROR(\n GetNodeAttr(n->attrs(), \"parallel_iterations\", ¶llel_iterations));\n\n if (frame_info->parallel_iterations == -1) {\n frame_info->parallel_iterations = parallel_iterations;\n } else if (frame_info->parallel_iterations != parallel_iterations) {\n LOG(WARNING) << \"Loop frame \\\"\" << frame_name\n << \"\\\" had two different values for parallel_iterations: \"\n << frame_info->parallel_iterations << \" vs. \"\n << parallel_iterations << \".\";\n }\n\n if (enter_frame_info_.size() <= id) {\n enter_frame_info_.resize(id + 1);\n }\n enter_frame_info_[id] = frame_info;\n } else {\n item->is_constant_enter = false;\n }\n item->is_exit = IsExit(n);\n item->is_control_trigger = IsControlTrigger(n);\n item->is_source = IsSource(n);\n item->is_enter_exit_or_next_iter =\n (IsEnter(n) || IsExit(n) || IsNextIteration(n));\n item->is_transfer_node = IsTransferNode(n);\n item->is_initialization_op = IsInitializationOp(n);\n item->is_recv_or_switch = IsRecv(n) || IsSwitch(n);\n item->is_next_iteration = IsNextIteration(n);\n item->is_distributed_communication = IsDistributedCommunication(n);\n\n // Compute the maximum values we'll store for this node in the\n // pending counts data structure, and allocate a handle in\n // that frame's pending counts data structure that has enough\n // space to store these maximal count values.\n size_t max_pending, max_dead;\n GetMaxPendingCounts(n, &max_pending, &max_dead);\n pending_ids_[id] =\n frame_info->pending_counts_layout.CreateHandle(max_pending, max_dead);\n\n // See if this node is a root node, and if so, add item to root_nodes_.\n if (n->in_edges().empty()) {\n root_nodes_.push_back(item);\n }\n\n // Initialize static information about the frames in the graph.\n frame_info->nodes->push_back(item);\n if (item->is_enter) {\n string enter_name;\n TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), \"frame_name\", &enter_name));\n EnsureFrameInfo(enter_name)->input_count++;\n }\n\n // Record information about whether each output of the op is used.\n std::unique_ptr outputs_required(new bool[n->num_outputs()]);\n std::fill(&outputs_required[0], &outputs_required[n->num_outputs()], false);\n int32_t unused_outputs = n->num_outputs();\n for (const Edge* e : n->out_edges()) {\n if (IsSink(e->dst())) continue;\n if (e->src_output() >= 0) {\n if (!outputs_required[e->src_output()]) {\n --unused_outputs;\n outputs_required[e->src_output()] = true;\n }\n }\n }\n if (unused_outputs > 0) {\n for (int i = 0; i < n->num_outputs(); ++i) {\n if (!outputs_required[i]) {\n metrics::RecordUnusedOutput(n->type_string());\n }\n }\n item->outputs_required = std::move(outputs_required);\n }\n }\n\n // Rewrite each `EdgeInfo::input_slot` member to refer directly to the input\n // location.\n for (const Node* n : graph.nodes()) {\n if (IsSink(n)) continue;\n const int id = n->id();\n NodeItem* item = gview_.node(id);\n\n for (EdgeInfo& e : item->mutable_output_edges()) {\n const int dst_id = e.dst_id;\n NodeItem* dst_item = gview_.node(dst_id);\n e.input_slot += dst_item->input_start;\n }\n }\n\n // Initialize PendingCounts only after pending_ids_[node.id] is initialized\n // for all nodes.\n InitializePending(&graph, cf_info);\n return gview_.SetAllocAttrs(&graph, params_.device);\n}", "func_hash": 105248557138287586060572648585871722551, "file_name": "immutable_executor_state.cc", "file_hash": 234046012522402227954780787024760975669, "cwe": ["CWE-401"], "cve": "CVE-2022-23578", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. If a graph node is invalid, TensorFlow can leak memory in the implementation of `ImmutableExecutorState::Initialize`. Here, we set `item->kernel` to `nullptr` but it is a simple `OpKernel*` pointer so the memory that was previously allocated to it would leak. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23578"} {"idx": 218852, "project": "tensorflow", "commit_id": "c79ccba517dbb1a0ccb9b01ee3bd2a63748b60dd", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/c79ccba517dbb1a0ccb9b01ee3bd2a63748b60dd", "commit_message": "Fix memory leak when a graph node is invalid.\n\nIf a graph node is invalid but a kernel is created then we set the kernel back to `nullptr` but we forget to delete it. Hence, we get a memory leak.\n\nPiperOrigin-RevId: 408968108\nChange-Id: I1d8a9d0d8988ed5e08be8b9f2004ce1b4cd11b7c", "target": 0, "func": "Status ImmutableExecutorState::Initialize(const Graph& graph) {\n TF_RETURN_IF_ERROR(gview_.Initialize(&graph));\n\n // Build the information about frames in this subgraph.\n ControlFlowInfo cf_info;\n TF_RETURN_IF_ERROR(BuildControlFlowInfo(&graph, &cf_info));\n\n for (auto& it : cf_info.unique_frame_names) {\n EnsureFrameInfo(it)->nodes =\n absl::make_unique>();\n }\n root_frame_info_ = frame_info_[\"\"].get();\n\n pending_ids_.resize(gview_.num_nodes());\n\n // Preprocess every node in the graph to create an instance of op\n // kernel for each node.\n requires_control_flow_ = false;\n for (const Node* n : graph.nodes()) {\n if (IsSink(n)) continue;\n if (IsSwitch(n) || IsMerge(n) || IsEnter(n) || IsExit(n)) {\n requires_control_flow_ = true;\n } else if (IsRecv(n)) {\n // A Recv node from a different device may produce dead tensors from\n // non-local control-flow nodes.\n //\n // TODO(mrry): Track whether control flow was present in the\n // pre-partitioned graph, and enable the caller (e.g.\n // `DirectSession`) to relax this constraint.\n string send_device;\n string recv_device;\n TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), \"send_device\", &send_device));\n TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), \"recv_device\", &recv_device));\n if (send_device != recv_device) {\n requires_control_flow_ = true;\n }\n }\n\n const int id = n->id();\n const string& frame_name = cf_info.frame_names[id];\n FrameInfo* frame_info = EnsureFrameInfo(frame_name);\n\n NodeItem* item = gview_.node(id);\n item->node_id = id;\n\n item->input_start = frame_info->total_inputs;\n frame_info->total_inputs += n->num_inputs();\n\n Status s = params_.create_kernel(n->properties(), &item->kernel);\n if (!s.ok()) {\n params_.delete_kernel(item->kernel);\n item->kernel = nullptr;\n s = AttachDef(s, *n);\n return s;\n }\n CHECK(item->kernel);\n item->kernel_is_async = (item->kernel->AsAsync() != nullptr);\n item->is_merge = IsMerge(n);\n item->is_any_consumer_merge_or_control_trigger = false;\n for (const Node* consumer : n->out_nodes()) {\n if (IsMerge(consumer) || IsControlTrigger(consumer)) {\n item->is_any_consumer_merge_or_control_trigger = true;\n break;\n }\n }\n const Tensor* const_tensor = item->kernel->const_tensor();\n if (const_tensor) {\n // Hold onto a shallow copy of the constant tensor in `*this` so that the\n // reference count does not drop to 1. This prevents the constant tensor\n // from being forwarded, and its buffer reused.\n const_tensors_.emplace_back(*const_tensor);\n }\n item->const_tensor = const_tensor;\n item->is_noop = (item->kernel->type_string_view() == \"NoOp\");\n item->is_enter = IsEnter(n);\n if (item->is_enter) {\n bool is_constant_enter;\n TF_RETURN_IF_ERROR(\n GetNodeAttr(n->attrs(), \"is_constant\", &is_constant_enter));\n item->is_constant_enter = is_constant_enter;\n\n string frame_name;\n TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), \"frame_name\", &frame_name));\n FrameInfo* frame_info = frame_info_[frame_name].get();\n\n int parallel_iterations;\n TF_RETURN_IF_ERROR(\n GetNodeAttr(n->attrs(), \"parallel_iterations\", ¶llel_iterations));\n\n if (frame_info->parallel_iterations == -1) {\n frame_info->parallel_iterations = parallel_iterations;\n } else if (frame_info->parallel_iterations != parallel_iterations) {\n LOG(WARNING) << \"Loop frame \\\"\" << frame_name\n << \"\\\" had two different values for parallel_iterations: \"\n << frame_info->parallel_iterations << \" vs. \"\n << parallel_iterations << \".\";\n }\n\n if (enter_frame_info_.size() <= id) {\n enter_frame_info_.resize(id + 1);\n }\n enter_frame_info_[id] = frame_info;\n } else {\n item->is_constant_enter = false;\n }\n item->is_exit = IsExit(n);\n item->is_control_trigger = IsControlTrigger(n);\n item->is_source = IsSource(n);\n item->is_enter_exit_or_next_iter =\n (IsEnter(n) || IsExit(n) || IsNextIteration(n));\n item->is_transfer_node = IsTransferNode(n);\n item->is_initialization_op = IsInitializationOp(n);\n item->is_recv_or_switch = IsRecv(n) || IsSwitch(n);\n item->is_next_iteration = IsNextIteration(n);\n item->is_distributed_communication = IsDistributedCommunication(n);\n\n // Compute the maximum values we'll store for this node in the\n // pending counts data structure, and allocate a handle in\n // that frame's pending counts data structure that has enough\n // space to store these maximal count values.\n size_t max_pending, max_dead;\n GetMaxPendingCounts(n, &max_pending, &max_dead);\n pending_ids_[id] =\n frame_info->pending_counts_layout.CreateHandle(max_pending, max_dead);\n\n // See if this node is a root node, and if so, add item to root_nodes_.\n if (n->in_edges().empty()) {\n root_nodes_.push_back(item);\n }\n\n // Initialize static information about the frames in the graph.\n frame_info->nodes->push_back(item);\n if (item->is_enter) {\n string enter_name;\n TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), \"frame_name\", &enter_name));\n EnsureFrameInfo(enter_name)->input_count++;\n }\n\n // Record information about whether each output of the op is used.\n std::unique_ptr outputs_required(new bool[n->num_outputs()]);\n std::fill(&outputs_required[0], &outputs_required[n->num_outputs()], false);\n int32_t unused_outputs = n->num_outputs();\n for (const Edge* e : n->out_edges()) {\n if (IsSink(e->dst())) continue;\n if (e->src_output() >= 0) {\n if (!outputs_required[e->src_output()]) {\n --unused_outputs;\n outputs_required[e->src_output()] = true;\n }\n }\n }\n if (unused_outputs > 0) {\n for (int i = 0; i < n->num_outputs(); ++i) {\n if (!outputs_required[i]) {\n metrics::RecordUnusedOutput(n->type_string());\n }\n }\n item->outputs_required = std::move(outputs_required);\n }\n }\n\n // Rewrite each `EdgeInfo::input_slot` member to refer directly to the input\n // location.\n for (const Node* n : graph.nodes()) {\n if (IsSink(n)) continue;\n const int id = n->id();\n NodeItem* item = gview_.node(id);\n\n for (EdgeInfo& e : item->mutable_output_edges()) {\n const int dst_id = e.dst_id;\n NodeItem* dst_item = gview_.node(dst_id);\n e.input_slot += dst_item->input_start;\n }\n }\n\n // Initialize PendingCounts only after pending_ids_[node.id] is initialized\n // for all nodes.\n InitializePending(&graph, cf_info);\n return gview_.SetAllocAttrs(&graph, params_.device);\n}", "func_hash": 156764801773187472412077288460661715117, "file_name": "immutable_executor_state.cc", "file_hash": 208458315060777566057381971058447382110, "cwe": ["CWE-401"], "cve": "CVE-2022-23578", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. If a graph node is invalid, TensorFlow can leak memory in the implementation of `ImmutableExecutorState::Initialize`. Here, we set `item->kernel` to `nullptr` but it is a simple `OpKernel*` pointer so the memory that was previously allocated to it would leak. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23578"} {"idx": 194996, "project": "tensorflow", "commit_id": "4f38b1ac8e42727e18a2f0bde06d3bee8e77b250", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4f38b1ac8e42727e18a2f0bde06d3bee8e77b250", "commit_message": "Prevent null dereference read in `GetInitOp`.\n\nWe have a map of maps. We test that the key exists in the first map but then we don't have any validation that this also means the second map has the needed key. In the scenarios where this is not the case, we'll dereference a nullptr, if we don't have this check\n\nPiperOrigin-RevId: 408739325\nChange-Id: If9bb7ed759aba1f3b56a34913f209508dbaf65ce", "target": 1, "func": "Status GetInitOp(const string& export_dir, const MetaGraphDef& meta_graph_def,\n string* init_op_name) {\n const auto& sig_def_map = meta_graph_def.signature_def();\n const auto& init_op_sig_it =\n meta_graph_def.signature_def().find(kSavedModelInitOpSignatureKey);\n if (init_op_sig_it != sig_def_map.end()) {\n *init_op_name = init_op_sig_it->second.outputs()\n .find(kSavedModelInitOpSignatureKey)\n ->second.name();\n return Status::OK();\n }\n\n const auto& collection_def_map = meta_graph_def.collection_def();\n string init_op_collection_key;\n if (collection_def_map.find(kSavedModelMainOpKey) !=\n collection_def_map.end()) {\n init_op_collection_key = kSavedModelMainOpKey;\n } else {\n init_op_collection_key = kSavedModelLegacyInitOpKey;\n }\n\n const auto init_op_it = collection_def_map.find(init_op_collection_key);\n if (init_op_it != collection_def_map.end()) {\n if (init_op_it->second.node_list().value_size() != 1) {\n return errors::FailedPrecondition(\n strings::StrCat(\"Expected exactly one main op in : \", export_dir));\n }\n *init_op_name = init_op_it->second.node_list().value(0);\n }\n return Status::OK();\n}", "func_hash": 90320046309155279319769139363770698236, "file_name": "loader_util.cc", "file_hash": 223638670651747648145854147173893848422, "cwe": ["CWE-476"], "cve": "CVE-2022-23577", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `GetInitOp` is vulnerable to a crash caused by dereferencing a null pointer. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23577"} {"idx": 218933, "project": "tensorflow", "commit_id": "4f38b1ac8e42727e18a2f0bde06d3bee8e77b250", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4f38b1ac8e42727e18a2f0bde06d3bee8e77b250", "commit_message": "Prevent null dereference read in `GetInitOp`.\n\nWe have a map of maps. We test that the key exists in the first map but then we don't have any validation that this also means the second map has the needed key. In the scenarios where this is not the case, we'll dereference a nullptr, if we don't have this check\n\nPiperOrigin-RevId: 408739325\nChange-Id: If9bb7ed759aba1f3b56a34913f209508dbaf65ce", "target": 0, "func": "Status GetInitOp(const string& export_dir, const MetaGraphDef& meta_graph_def,\n string* init_op_name) {\n const auto& sig_def_map = meta_graph_def.signature_def();\n const auto& init_op_sig_it =\n meta_graph_def.signature_def().find(kSavedModelInitOpSignatureKey);\n if (init_op_sig_it != sig_def_map.end()) {\n const auto& sig_def_outputs = init_op_sig_it->second.outputs();\n const auto& sig_def_outputs_it =\n sig_def_outputs.find(kSavedModelInitOpSignatureKey);\n if (sig_def_outputs_it == sig_def_outputs.end()) {\n return errors::FailedPrecondition(\"Could not find output \",\n kSavedModelInitOpSignatureKey);\n }\n *init_op_name = sig_def_outputs_it->second.name();\n return Status::OK();\n }\n\n const auto& collection_def_map = meta_graph_def.collection_def();\n string init_op_collection_key;\n if (collection_def_map.find(kSavedModelMainOpKey) !=\n collection_def_map.end()) {\n init_op_collection_key = kSavedModelMainOpKey;\n } else {\n init_op_collection_key = kSavedModelLegacyInitOpKey;\n }\n\n const auto init_op_it = collection_def_map.find(init_op_collection_key);\n if (init_op_it != collection_def_map.end()) {\n if (init_op_it->second.node_list().value_size() != 1) {\n return errors::FailedPrecondition(\n strings::StrCat(\"Expected exactly one main op in : \", export_dir));\n }\n *init_op_name = init_op_it->second.node_list().value(0);\n }\n return Status::OK();\n}", "func_hash": 120370294428908534368713689048437773064, "file_name": "loader_util.cc", "file_hash": 225205642200693417259460288987767726126, "cwe": ["CWE-476"], "cve": "CVE-2022-23577", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `GetInitOp` is vulnerable to a crash caused by dereferencing a null pointer. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23577"} {"idx": 194998, "project": "tensorflow", "commit_id": "240655511cd3e701155f944a972db71b6c0b1bb6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/240655511cd3e701155f944a972db71b6c0b1bb6", "commit_message": "Eliminate `CHECK`-fails from `IsSimplifiableReshape` via `MakeShape()`\n\nPiperOrigin-RevId: 409166738\nChange-Id: I7f0a3590b8acae3f3e3e2fe636e1f5ef285693cf", "target": 1, "func": "Status ConstantFolding::IsSimplifiableReshape(\n const NodeDef& node, const GraphProperties& properties) const {\n if (!IsReshape(node)) {\n return errors::Internal(\"Node \", node.name(), \" is not a Reshape node\");\n }\n if (2 > node.input_size()) {\n return errors::Internal(\"Node \", node.name(),\n \" must have at most 2 inputs but has \",\n node.input_size());\n }\n const NodeDef* new_shape = node_map_->GetNode(node.input(1));\n if (!IsReallyConstant(*new_shape)) {\n return errors::Internal(\"Node \", node.name(), \" has shape \",\n new_shape->DebugString(),\n \" which is not a constant\");\n }\n TensorVector outputs;\n auto outputs_cleanup = gtl::MakeCleanup([&outputs] {\n for (const auto& output : outputs) {\n delete output.tensor;\n }\n });\n\n Status s = EvaluateNode(*new_shape, TensorVector(), &outputs);\n if (!s.ok()) {\n return errors::Internal(\"Could not evaluate node \", node.name());\n }\n if (outputs.size() != 1) {\n return errors::Internal(\"Node \", node.name(),\n \" must have exactly 1 output but has \",\n outputs.size());\n }\n\n const std::vector& props =\n properties.GetInputProperties(node.name());\n if (props.empty()) {\n return errors::Internal(\"Node \", node.name(), \" has no properties\");\n }\n const OpInfo::TensorProperties& prop = props[0];\n if (prop.dtype() == DT_INVALID) {\n return errors::Internal(\"Node \", node.name(), \" has property \",\n prop.DebugString(), \" with invalid dtype\");\n }\n const PartialTensorShape shape(prop.shape());\n if (!shape.IsFullyDefined()) {\n return errors::Internal(\"Node \", node.name(), \" has property \",\n prop.DebugString(), \" with shape \",\n shape.DebugString(), \" which is not fully defined\");\n }\n\n PartialTensorShape new_dims;\n if (outputs[0]->dtype() == DT_INT32) {\n std::vector shp;\n for (int i = 0; i < outputs[0]->NumElements(); ++i) {\n int32_t dim = outputs[0]->flat()(i);\n shp.push_back(dim);\n }\n TF_CHECK_OK(TensorShapeUtils::MakeShape(shp, &new_dims));\n } else {\n std::vector shp;\n for (int i = 0; i < outputs[0]->NumElements(); ++i) {\n int64_t dim = outputs[0]->flat()(i);\n shp.push_back(dim);\n }\n TF_CHECK_OK(TensorShapeUtils::MakeShape(shp, &new_dims));\n }\n\n if (!shape.IsCompatibleWith(new_dims)) {\n return errors::Internal(\"Expected shape \", shape.DebugString(),\n \"to be compatible with \", new_dims.DebugString());\n }\n\n return Status::OK();\n}", "func_hash": 122664089420988233915419567191040959656, "file_name": "constant_folding.cc", "file_hash": 35061507297230918846503076104140700863, "cwe": ["CWE-617"], "cve": "CVE-2022-23581", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The Grappler optimizer in TensorFlow can be used to cause a denial of service by altering a `SavedModel` such that `IsSimplifiableReshape` would trigger `CHECK` failures. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23581"} {"idx": 219032, "project": "tensorflow", "commit_id": "240655511cd3e701155f944a972db71b6c0b1bb6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/240655511cd3e701155f944a972db71b6c0b1bb6", "commit_message": "Eliminate `CHECK`-fails from `IsSimplifiableReshape` via `MakeShape()`\n\nPiperOrigin-RevId: 409166738\nChange-Id: I7f0a3590b8acae3f3e3e2fe636e1f5ef285693cf", "target": 0, "func": "Status ConstantFolding::IsSimplifiableReshape(\n const NodeDef& node, const GraphProperties& properties) const {\n if (!IsReshape(node)) {\n return errors::Internal(\"Node \", node.name(), \" is not a Reshape node\");\n }\n if (2 > node.input_size()) {\n return errors::Internal(\"Node \", node.name(),\n \" must have at most 2 inputs but has \",\n node.input_size());\n }\n const NodeDef* new_shape = node_map_->GetNode(node.input(1));\n if (!IsReallyConstant(*new_shape)) {\n return errors::Internal(\"Node \", node.name(), \" has shape \",\n new_shape->DebugString(),\n \" which is not a constant\");\n }\n TensorVector outputs;\n auto outputs_cleanup = gtl::MakeCleanup([&outputs] {\n for (const auto& output : outputs) {\n delete output.tensor;\n }\n });\n\n Status s = EvaluateNode(*new_shape, TensorVector(), &outputs);\n if (!s.ok()) {\n return errors::Internal(\"Could not evaluate node \", node.name());\n }\n if (outputs.size() != 1) {\n return errors::Internal(\"Node \", node.name(),\n \" must have exactly 1 output but has \",\n outputs.size());\n }\n\n const std::vector& props =\n properties.GetInputProperties(node.name());\n if (props.empty()) {\n return errors::Internal(\"Node \", node.name(), \" has no properties\");\n }\n const OpInfo::TensorProperties& prop = props[0];\n if (prop.dtype() == DT_INVALID) {\n return errors::Internal(\"Node \", node.name(), \" has property \",\n prop.DebugString(), \" with invalid dtype\");\n }\n const PartialTensorShape shape(prop.shape());\n if (!shape.IsFullyDefined()) {\n return errors::Internal(\"Node \", node.name(), \" has property \",\n prop.DebugString(), \" with shape \",\n shape.DebugString(), \" which is not fully defined\");\n }\n\n PartialTensorShape new_dims;\n if (outputs[0]->dtype() == DT_INT32) {\n std::vector shp;\n for (int i = 0; i < outputs[0]->NumElements(); ++i) {\n int32_t dim = outputs[0]->flat()(i);\n shp.push_back(dim);\n }\n s = TensorShapeUtils::MakeShape(shp, &new_dims);\n if (!s.ok()) return s;\n } else {\n std::vector shp;\n for (int i = 0; i < outputs[0]->NumElements(); ++i) {\n int64_t dim = outputs[0]->flat()(i);\n shp.push_back(dim);\n }\n s = TensorShapeUtils::MakeShape(shp, &new_dims);\n if (!s.ok()) return s;\n }\n\n if (!shape.IsCompatibleWith(new_dims)) {\n return errors::Internal(\"Expected shape \", shape.DebugString(),\n \"to be compatible with \", new_dims.DebugString());\n }\n\n return Status::OK();\n}", "func_hash": 262760907526734396914090099303096262406, "file_name": "constant_folding.cc", "file_hash": 271606694375277711450004865336349725435, "cwe": ["CWE-617"], "cve": "CVE-2022-23581", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The Grappler optimizer in TensorFlow can be used to cause a denial of service by altering a `SavedModel` such that `IsSimplifiableReshape` would trigger `CHECK` failures. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23581"} {"idx": 195017, "project": "gpac", "commit_id": "ad18ece95fa064efc0995c4ab2c985f77fb166ec", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/ad18ece95fa064efc0995c4ab2c985f77fb166ec", "commit_message": "fixed #1904", "target": 1, "func": "u32 GetHintFormat(GF_TrackBox *trak)\n{\n\tGF_HintMediaHeaderBox *hmhd = (GF_HintMediaHeaderBox *)trak->Media->information->InfoHeader;\n\tif (hmhd->type != GF_ISOM_BOX_TYPE_HMHD)\n\t\treturn 0;\n\t\t\n\tif (!hmhd || !hmhd->subType) {\n\t\tGF_Box *a = (GF_Box *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->child_boxes, 0);\n\t\tif (!hmhd) return a ? a->type : 0;\n\t\tif (a) hmhd->subType = a->type;\n\t\treturn hmhd->subType;\n\t}\n\treturn hmhd->subType;\n}", "func_hash": 91218268849686441388880855658517990203, "file_name": "hint_track.c", "file_hash": 60176895274654779679144452624639678766, "cwe": ["CWE-476"], "cve": "CVE-2021-40576", "cve_desc": "The binary MP4Box in Gpac 1.0.1 has a null pointer dereference vulnerability in the gf_isom_get_payt_count function in hint_track.c, which allows attackers to cause a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40576"} {"idx": 219912, "project": "gpac", "commit_id": "ad18ece95fa064efc0995c4ab2c985f77fb166ec", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/ad18ece95fa064efc0995c4ab2c985f77fb166ec", "commit_message": "fixed #1904", "target": 0, "func": "u32 GetHintFormat(GF_TrackBox *trak)\n{\n\tGF_HintMediaHeaderBox *hmhd = (GF_HintMediaHeaderBox *)trak->Media->information->InfoHeader;\n\tif (!hmhd || (hmhd->type != GF_ISOM_BOX_TYPE_HMHD))\n\t\treturn 0;\n\t\t\n\tif (!hmhd || !hmhd->subType) {\n\t\tGF_Box *a = (GF_Box *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->child_boxes, 0);\n\t\tif (!hmhd) return a ? a->type : 0;\n\t\tif (a) hmhd->subType = a->type;\n\t\treturn hmhd->subType;\n\t}\n\treturn hmhd->subType;\n}", "func_hash": 240641657114030682383886931707833033482, "file_name": "hint_track.c", "file_hash": 28976036322661795345788739460485147148, "cwe": ["CWE-476"], "cve": "CVE-2021-40576", "cve_desc": "The binary MP4Box in Gpac 1.0.1 has a null pointer dereference vulnerability in the gf_isom_get_payt_count function in hint_track.c, which allows attackers to cause a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40576"} {"idx": 195019, "project": "tensorflow", "commit_id": "6b5adc0877de832b2a7c189532dbbbc64622eeb6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/6b5adc0877de832b2a7c189532dbbbc64622eeb6", "commit_message": "Prevent `CHECK`-fail when building reference tensor.\n\nThe tensor constructor does not allow reference dtypes, as these should not show up explicitly. However, when passed these invalid types instead of building an invalid object the constructor crashes via a `CHECK`-fail. We have a static builder that properly handles this case but is not applicable given current usage.\n\nInstead, before calling the constructor, we can check that the dtype is not a reference type and return an error otherwise, given that the dtype is user controlled so malicious users can trigger denial of service.\n\nPiperOrigin-RevId: 409662503\nChange-Id: I5892f831fde7f276cd7ab34519cf6b8061c71a59", "target": 1, "func": "Status ConstantFolding::EvaluateOneFoldable(const NodeDef& node,\n std::vector* outputs,\n bool* result_too_large) {\n TensorVector inputs;\n TensorVector output_tensors;\n auto inputs_cleanup = gtl::MakeCleanup([&inputs, &output_tensors] {\n for (const auto& input : inputs) {\n delete input.tensor;\n }\n for (const auto& output : output_tensors) {\n if (output.tensor) {\n delete output.tensor;\n }\n }\n });\n\n size_t total_inputs_size = 0;\n for (const auto& input : node.input()) {\n const TensorId input_tensor = ParseTensorName(input);\n if (input_tensor.index() < 0) {\n // Control dependency\n break;\n }\n const NodeDef* input_node = node_map_->GetNode(input);\n if (!IsReallyConstant(*input_node)) {\n return Status(error::INVALID_ARGUMENT,\n strings::StrCat(\"Can't fold \", node.name(), \", its \", input,\n \" isn't constant\"));\n }\n TF_RETURN_IF_ERROR(CheckAttrExists(*input_node, \"value\"));\n const TensorProto& raw_val = input_node->attr().at(\"value\").tensor();\n if (raw_val.dtype() == DT_INVALID) {\n return Status(\n error::INVALID_ARGUMENT,\n strings::StrCat(\"A tensor in the input node, with TensorId of \",\n input_tensor.ToString(),\n \" has a dtype of DT_INVALID.\"));\n }\n Tensor* value = new Tensor(raw_val.dtype(), raw_val.tensor_shape());\n if (!value->FromProto(raw_val)) {\n delete (value);\n return errors::InvalidArgument(\"Unable to make Tensor from proto for \",\n node.name(), \" with shape \",\n raw_val.tensor_shape().DebugString());\n }\n inputs.emplace_back(value);\n total_inputs_size += value->TotalBytes();\n }\n\n TF_RETURN_IF_ERROR(EvaluateNode(node, inputs, &output_tensors));\n if (output_tensors.empty()) {\n return Status(error::INVALID_ARGUMENT, \"Expected at least one output.\");\n }\n\n outputs->resize(output_tensors.size());\n for (size_t i = 0; i < output_tensors.size(); i++) {\n string node_name = OptimizedNodeName(node, \"-folded\");\n if (output_tensors.size() > 1) {\n node_name = strings::StrCat(node_name, \"-\", i);\n }\n if (output_tensors[i].tensor) {\n Status s = CreateNodeDef(node_name, output_tensors[i], &outputs->at(i),\n total_inputs_size);\n if (!s.ok()) {\n *result_too_large = true;\n return s;\n }\n } else {\n // Create an empty NodeDef to identify dead outputs (e.g. the output of a\n // switch that's not selected by the switch predicate).\n outputs->at(i) = NodeDef();\n }\n }\n return Status::OK();\n}", "func_hash": 33937240667530924395323323412961833143, "file_name": "constant_folding.cc", "file_hash": 221573695858123615640237954647315751120, "cwe": ["CWE-617"], "cve": "CVE-2022-23588", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. A malicious user can cause a denial of service by altering a `SavedModel` such that Grappler optimizer would attempt to build a tensor using a reference `dtype`. This would result in a crash due to a `CHECK`-fail in the `Tensor` constructor as reference types are not allowed. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23588"} {"idx": 219931, "project": "tensorflow", "commit_id": "6b5adc0877de832b2a7c189532dbbbc64622eeb6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/6b5adc0877de832b2a7c189532dbbbc64622eeb6", "commit_message": "Prevent `CHECK`-fail when building reference tensor.\n\nThe tensor constructor does not allow reference dtypes, as these should not show up explicitly. However, when passed these invalid types instead of building an invalid object the constructor crashes via a `CHECK`-fail. We have a static builder that properly handles this case but is not applicable given current usage.\n\nInstead, before calling the constructor, we can check that the dtype is not a reference type and return an error otherwise, given that the dtype is user controlled so malicious users can trigger denial of service.\n\nPiperOrigin-RevId: 409662503\nChange-Id: I5892f831fde7f276cd7ab34519cf6b8061c71a59", "target": 0, "func": "Status ConstantFolding::EvaluateOneFoldable(const NodeDef& node,\n std::vector* outputs,\n bool* result_too_large) {\n TensorVector inputs;\n TensorVector output_tensors;\n auto inputs_cleanup = gtl::MakeCleanup([&inputs, &output_tensors] {\n for (const auto& input : inputs) {\n delete input.tensor;\n }\n for (const auto& output : output_tensors) {\n if (output.tensor) {\n delete output.tensor;\n }\n }\n });\n\n size_t total_inputs_size = 0;\n for (const auto& input : node.input()) {\n const TensorId input_tensor = ParseTensorName(input);\n if (input_tensor.index() < 0) {\n // Control dependency\n break;\n }\n const NodeDef* input_node = node_map_->GetNode(input);\n if (!IsReallyConstant(*input_node)) {\n return Status(error::INVALID_ARGUMENT,\n strings::StrCat(\"Can't fold \", node.name(), \", its \", input,\n \" isn't constant\"));\n }\n TF_RETURN_IF_ERROR(CheckAttrExists(*input_node, \"value\"));\n const TensorProto& raw_val = input_node->attr().at(\"value\").tensor();\n if (raw_val.dtype() == DT_INVALID) {\n return Status(\n error::INVALID_ARGUMENT,\n strings::StrCat(\"A tensor in the input node, with TensorId of \",\n input_tensor.ToString(),\n \" has a dtype of DT_INVALID.\"));\n }\n if (IsRefType(raw_val.dtype())) {\n return errors::InvalidArgument(\n \"Not allowed to construct a tensor with reference dtype, got \",\n DataTypeString(raw_val.dtype()));\n }\n Tensor* value = new Tensor(raw_val.dtype(), raw_val.tensor_shape());\n if (!value->FromProto(raw_val)) {\n delete (value);\n return errors::InvalidArgument(\"Unable to make Tensor from proto for \",\n node.name(), \" with shape \",\n raw_val.tensor_shape().DebugString());\n }\n inputs.emplace_back(value);\n total_inputs_size += value->TotalBytes();\n }\n\n TF_RETURN_IF_ERROR(EvaluateNode(node, inputs, &output_tensors));\n if (output_tensors.empty()) {\n return Status(error::INVALID_ARGUMENT, \"Expected at least one output.\");\n }\n\n outputs->resize(output_tensors.size());\n for (size_t i = 0; i < output_tensors.size(); i++) {\n string node_name = OptimizedNodeName(node, \"-folded\");\n if (output_tensors.size() > 1) {\n node_name = strings::StrCat(node_name, \"-\", i);\n }\n if (output_tensors[i].tensor) {\n Status s = CreateNodeDef(node_name, output_tensors[i], &outputs->at(i),\n total_inputs_size);\n if (!s.ok()) {\n *result_too_large = true;\n return s;\n }\n } else {\n // Create an empty NodeDef to identify dead outputs (e.g. the output of a\n // switch that's not selected by the switch predicate).\n outputs->at(i) = NodeDef();\n }\n }\n return Status::OK();\n}", "func_hash": 111779981092160670584101984885423453823, "file_name": "constant_folding.cc", "file_hash": 271606694375277711450004865336349725435, "cwe": ["CWE-617"], "cve": "CVE-2022-23588", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. A malicious user can cause a denial of service by altering a `SavedModel` such that Grappler optimizer would attempt to build a tensor using a reference `dtype`. This would result in a crash due to a `CHECK`-fail in the `Tensor` constructor as reference types are not allowed. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23588"} {"idx": 195022, "project": "glewlwyd", "commit_id": "125281f1c0d4b6a8b49f7e55a757205a2ef01fbe", "project_url": "https://github.com/babelouest/glewlwyd", "commit_url": "https://github.com/babelouest/glewlwyd/commit/125281f1c0d4b6a8b49f7e55a757205a2ef01fbe", "commit_message": "Fix update session when auth fail", "target": 1, "func": "int callback_glewlwyd_user_auth (const struct _u_request * request, struct _u_response * response, void * user_data) {\n struct config_elements * config = (struct config_elements *)user_data;\n json_t * j_param = ulfius_get_json_body_request(request, NULL), * j_result = NULL;\n const char * ip_source = get_ip_source(request);\n char * issued_for = get_client_hostname(request);\n char * session_uid, expires[129];\n time_t now;\n struct tm ts;\n \n time(&now);\n now += GLEWLWYD_DEFAULT_SESSION_EXPIRATION_COOKIE;\n gmtime_r(&now, &ts);\n strftime(expires, 128, \"%a, %d %b %Y %T %Z\", &ts);\n if (j_param != NULL) {\n if (json_string_length(json_object_get(j_param, \"username\"))) {\n if (json_object_get(j_param, \"scheme_type\") == NULL || 0 == o_strcmp(json_string_value(json_object_get(j_param, \"scheme_type\")), \"password\")) {\n if (json_string_length(json_object_get(j_param, \"password\"))) {\n j_result = auth_check_user_credentials(config, json_string_value(json_object_get(j_param, \"username\")), json_string_value(json_object_get(j_param, \"password\")));\n if (check_result_value(j_result, G_OK)) {\n if ((session_uid = get_session_id(config, request)) == NULL) {\n session_uid = generate_session_id();\n }\n if (user_session_update(config, session_uid, u_map_get_case(request->map_header, \"user-agent\"), issued_for, json_string_value(json_object_get(j_param, \"username\")), NULL, 1) != G_OK) {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error user_session_update (1)\");\n response->status = 500;\n } else {\n ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, \"/\", config->cookie_secure, 0);\n y_log_message(Y_LOG_LEVEL_INFO, \"Event - User '%s' authenticated with password\", json_string_value(json_object_get(j_param, \"username\")));\n }\n o_free(session_uid);\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID, 1, NULL);\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID_SCHEME, 1, \"scheme_type\", \"password\", NULL);\n } else {\n if (check_result_value(j_result, G_ERROR_UNAUTHORIZED)) {\n y_log_message(Y_LOG_LEVEL_WARNING, \"Security - Authorization invalid for username %s at IP Address %s\", json_string_value(json_object_get(j_param, \"username\")), ip_source);\n }\n if ((session_uid = get_session_id(config, request)) != NULL && user_session_update(config, session_uid, u_map_get_case(request->map_header, \"user-agent\"), issued_for, json_string_value(json_object_get(j_param, \"username\")), NULL, 1) != G_OK) {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error user_session_update (2)\");\n }\n o_free(session_uid);\n response->status = 401;\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID, 1, NULL);\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID_SCHEME, 1, \"scheme_type\", \"password\", NULL);\n }\n json_decref(j_result);\n } else if (json_object_get(j_param, \"password\") != NULL && !json_is_string(json_object_get(j_param, \"password\"))) {\n ulfius_set_string_body_response(response, 400, \"password must be a string\");\n } else {\n session_uid = get_session_id(config, request);\n j_result = get_users_for_session(config, session_uid);\n if (check_result_value(j_result, G_OK)) {\n // Refresh username to set as default\n if (user_session_update(config, u_map_get(request->map_cookie, config->session_key), u_map_get_case(request->map_header, \"user-agent\"), issued_for, json_string_value(json_object_get(j_param, \"username\")), NULL, 0) != G_OK) {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error user_session_update (3)\");\n response->status = 500;\n } else {\n ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, \"/\", config->cookie_secure, 0);\n }\n } else if (check_result_value(j_result, G_ERROR_NOT_FOUND)) {\n response->status = 401;\n } else {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error get_users_for_session\");\n response->status = 500;\n }\n o_free(session_uid);\n json_decref(j_result);\n }\n } else {\n if (json_string_length(json_object_get(j_param, \"scheme_type\")) && json_string_length(json_object_get(j_param, \"scheme_name\")) && json_is_object(json_object_get(j_param, \"value\"))) {\n j_result = auth_check_user_scheme(config, json_string_value(json_object_get(j_param, \"scheme_type\")), json_string_value(json_object_get(j_param, \"scheme_name\")), json_string_value(json_object_get(j_param, \"username\")), json_object_get(j_param, \"value\"), request);\n if (check_result_value(j_result, G_ERROR_PARAM)) {\n ulfius_set_string_body_response(response, 400, \"bad scheme response\");\n } else if (check_result_value(j_result, G_ERROR_UNAUTHORIZED)) {\n y_log_message(Y_LOG_LEVEL_WARNING, \"Security - Authorization invalid for username %s at IP Address %s\", json_string_value(json_object_get(j_param, \"username\")), ip_source);\n response->status = 401;\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID, 1, NULL);\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID_SCHEME, 1, \"scheme_type\", json_string_value(json_object_get(j_param, \"scheme_type\")), \"scheme_name\", json_string_value(json_object_get(j_param, \"scheme_name\")), NULL);\n } else if (check_result_value(j_result, G_ERROR_NOT_FOUND)) {\n response->status = 404;\n } else if (check_result_value(j_result, G_OK)) {\n if ((session_uid = get_session_id(config, request)) == NULL) {\n session_uid = generate_session_id();\n }\n if (user_session_update(config, session_uid, u_map_get_case(request->map_header, \"user-agent\"), issued_for, json_string_value(json_object_get(j_param, \"username\")), json_string_value(json_object_get(j_param, \"scheme_name\")), 1) != G_OK) {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error user_session_update (4)\");\n response->status = 500;\n } else {\n ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, \"/\", config->cookie_secure, 0);\n y_log_message(Y_LOG_LEVEL_INFO, \"Event - User '%s' authenticated with scheme '%s/%s'\", json_string_value(json_object_get(j_param, \"username\")), json_string_value(json_object_get(j_param, \"scheme_type\")), json_string_value(json_object_get(j_param, \"scheme_name\")));\n }\n o_free(session_uid);\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID, 1, NULL);\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID_SCHEME, 1, \"scheme_type\", json_string_value(json_object_get(j_param, \"scheme_type\")), \"scheme_name\", json_string_value(json_object_get(j_param, \"scheme_name\")), NULL);\n } else {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error auth_check_user_scheme\");\n response->status = 500;\n }\n json_decref(j_result);\n } else {\n ulfius_set_string_body_response(response, 400, \"scheme_type, scheme_name and value are mandatory\");\n }\n }\n } else {\n if (json_string_length(json_object_get(j_param, \"scheme_type\")) && json_string_length(json_object_get(j_param, \"scheme_name\")) && json_is_object(json_object_get(j_param, \"value\"))) {\n j_result = auth_check_identify_scheme(config, json_string_value(json_object_get(j_param, \"scheme_type\")), json_string_value(json_object_get(j_param, \"scheme_name\")), json_object_get(j_param, \"value\"), request);\n if (check_result_value(j_result, G_ERROR_PARAM)) {\n ulfius_set_string_body_response(response, 400, \"bad scheme response\");\n } else if (check_result_value(j_result, G_ERROR_UNAUTHORIZED)) {\n y_log_message(Y_LOG_LEVEL_WARNING, \"Security - Authorization invalid for username at IP Address %s\", ip_source);\n response->status = 401;\n } else if (check_result_value(j_result, G_ERROR_NOT_FOUND)) {\n response->status = 404;\n } else if (check_result_value(j_result, G_OK)) {\n if ((session_uid = get_session_id(config, request)) == NULL) {\n session_uid = generate_session_id();\n }\n if (user_session_update(config, session_uid, u_map_get_case(request->map_header, \"user-agent\"), issued_for, json_string_value(json_object_get(j_result, \"username\")), json_string_value(json_object_get(j_param, \"scheme_name\")), 1) != G_OK) {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error user_session_update (4)\");\n response->status = 500;\n } else {\n ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, \"/\", config->cookie_secure, 0);\n y_log_message(Y_LOG_LEVEL_INFO, \"Event - User '%s' authenticated with scheme '%s/%s'\", json_string_value(json_object_get(j_result, \"username\")), json_string_value(json_object_get(j_param, \"scheme_type\")), json_string_value(json_object_get(j_param, \"scheme_name\")));\n }\n o_free(session_uid);\n } else {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error auth_check_user_scheme\");\n response->status = 500;\n }\n json_decref(j_result);\n } else {\n ulfius_set_string_body_response(response, 400, \"username is mandatory\");\n }\n }\n } else {\n ulfius_set_string_body_response(response, 400, \"Input parameters must be in JSON format\");\n }\n json_decref(j_param);\n o_free(issued_for);\n\n return U_CALLBACK_CONTINUE;\n}", "func_hash": 236114269060053642565806917047085397848, "file_name": "webservice.c", "file_hash": 249878395356016662912854745569339968395, "cwe": ["CWE-287"], "cve": "CVE-2021-45379", "cve_desc": "Glewlwyd 2.0.0, fixed in 2.6.1 is affected by an incorrect access control vulnerability. One user can attempt to log in as another user without its password.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-45379"} {"idx": 219947, "project": "glewlwyd", "commit_id": "125281f1c0d4b6a8b49f7e55a757205a2ef01fbe", "project_url": "https://github.com/babelouest/glewlwyd", "commit_url": "https://github.com/babelouest/glewlwyd/commit/125281f1c0d4b6a8b49f7e55a757205a2ef01fbe", "commit_message": "Fix update session when auth fail", "target": 0, "func": "int callback_glewlwyd_user_auth (const struct _u_request * request, struct _u_response * response, void * user_data) {\n struct config_elements * config = (struct config_elements *)user_data;\n json_t * j_param = ulfius_get_json_body_request(request, NULL), * j_result = NULL;\n const char * ip_source = get_ip_source(request);\n char * issued_for = get_client_hostname(request);\n char * session_uid, expires[129];\n time_t now;\n struct tm ts;\n \n time(&now);\n now += GLEWLWYD_DEFAULT_SESSION_EXPIRATION_COOKIE;\n gmtime_r(&now, &ts);\n strftime(expires, 128, \"%a, %d %b %Y %T %Z\", &ts);\n if (j_param != NULL) {\n if (json_string_length(json_object_get(j_param, \"username\"))) {\n if (json_object_get(j_param, \"scheme_type\") == NULL || 0 == o_strcmp(json_string_value(json_object_get(j_param, \"scheme_type\")), \"password\")) {\n if (json_string_length(json_object_get(j_param, \"password\"))) {\n j_result = auth_check_user_credentials(config, json_string_value(json_object_get(j_param, \"username\")), json_string_value(json_object_get(j_param, \"password\")));\n if (check_result_value(j_result, G_OK)) {\n if ((session_uid = get_session_id(config, request)) == NULL) {\n session_uid = generate_session_id();\n }\n if (user_session_update(config, session_uid, u_map_get_case(request->map_header, \"user-agent\"), issued_for, json_string_value(json_object_get(j_param, \"username\")), NULL, 1) != G_OK) {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error user_session_update (1)\");\n response->status = 500;\n } else {\n ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, \"/\", config->cookie_secure, 0);\n y_log_message(Y_LOG_LEVEL_INFO, \"Event - User '%s' authenticated with password\", json_string_value(json_object_get(j_param, \"username\")));\n }\n o_free(session_uid);\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID, 1, NULL);\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID_SCHEME, 1, \"scheme_type\", \"password\", NULL);\n } else {\n if (check_result_value(j_result, G_ERROR_UNAUTHORIZED)) {\n y_log_message(Y_LOG_LEVEL_WARNING, \"Security - Authorization invalid for username %s at IP Address %s\", json_string_value(json_object_get(j_param, \"username\")), ip_source);\n }\n response->status = 401;\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID, 1, NULL);\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID_SCHEME, 1, \"scheme_type\", \"password\", NULL);\n }\n json_decref(j_result);\n } else if (json_object_get(j_param, \"password\") != NULL && !json_is_string(json_object_get(j_param, \"password\"))) {\n ulfius_set_string_body_response(response, 400, \"password must be a string\");\n } else {\n session_uid = get_session_id(config, request);\n j_result = get_users_for_session(config, session_uid);\n if (check_result_value(j_result, G_OK)) {\n // Refresh username to set as default\n if (user_session_update(config, u_map_get(request->map_cookie, config->session_key), u_map_get_case(request->map_header, \"user-agent\"), issued_for, json_string_value(json_object_get(j_param, \"username\")), NULL, 0) != G_OK) {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error user_session_update (3)\");\n response->status = 500;\n } else {\n ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, \"/\", config->cookie_secure, 0);\n }\n } else if (check_result_value(j_result, G_ERROR_NOT_FOUND)) {\n response->status = 401;\n } else {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error get_users_for_session\");\n response->status = 500;\n }\n o_free(session_uid);\n json_decref(j_result);\n }\n } else {\n if (json_string_length(json_object_get(j_param, \"scheme_type\")) && json_string_length(json_object_get(j_param, \"scheme_name\")) && json_is_object(json_object_get(j_param, \"value\"))) {\n j_result = auth_check_user_scheme(config, json_string_value(json_object_get(j_param, \"scheme_type\")), json_string_value(json_object_get(j_param, \"scheme_name\")), json_string_value(json_object_get(j_param, \"username\")), json_object_get(j_param, \"value\"), request);\n if (check_result_value(j_result, G_ERROR_PARAM)) {\n ulfius_set_string_body_response(response, 400, \"bad scheme response\");\n } else if (check_result_value(j_result, G_ERROR_UNAUTHORIZED)) {\n y_log_message(Y_LOG_LEVEL_WARNING, \"Security - Authorization invalid for username %s at IP Address %s\", json_string_value(json_object_get(j_param, \"username\")), ip_source);\n response->status = 401;\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID, 1, NULL);\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID_SCHEME, 1, \"scheme_type\", json_string_value(json_object_get(j_param, \"scheme_type\")), \"scheme_name\", json_string_value(json_object_get(j_param, \"scheme_name\")), NULL);\n } else if (check_result_value(j_result, G_ERROR_NOT_FOUND)) {\n response->status = 404;\n } else if (check_result_value(j_result, G_OK)) {\n if ((session_uid = get_session_id(config, request)) == NULL) {\n session_uid = generate_session_id();\n }\n if (user_session_update(config, session_uid, u_map_get_case(request->map_header, \"user-agent\"), issued_for, json_string_value(json_object_get(j_param, \"username\")), json_string_value(json_object_get(j_param, \"scheme_name\")), 1) != G_OK) {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error user_session_update (4)\");\n response->status = 500;\n } else {\n ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, \"/\", config->cookie_secure, 0);\n y_log_message(Y_LOG_LEVEL_INFO, \"Event - User '%s' authenticated with scheme '%s/%s'\", json_string_value(json_object_get(j_param, \"username\")), json_string_value(json_object_get(j_param, \"scheme_type\")), json_string_value(json_object_get(j_param, \"scheme_name\")));\n }\n o_free(session_uid);\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID, 1, NULL);\n glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID_SCHEME, 1, \"scheme_type\", json_string_value(json_object_get(j_param, \"scheme_type\")), \"scheme_name\", json_string_value(json_object_get(j_param, \"scheme_name\")), NULL);\n } else {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error auth_check_user_scheme\");\n response->status = 500;\n }\n json_decref(j_result);\n } else {\n ulfius_set_string_body_response(response, 400, \"scheme_type, scheme_name and value are mandatory\");\n }\n }\n } else {\n if (json_string_length(json_object_get(j_param, \"scheme_type\")) && json_string_length(json_object_get(j_param, \"scheme_name\")) && json_is_object(json_object_get(j_param, \"value\"))) {\n j_result = auth_check_identify_scheme(config, json_string_value(json_object_get(j_param, \"scheme_type\")), json_string_value(json_object_get(j_param, \"scheme_name\")), json_object_get(j_param, \"value\"), request);\n if (check_result_value(j_result, G_ERROR_PARAM)) {\n ulfius_set_string_body_response(response, 400, \"bad scheme response\");\n } else if (check_result_value(j_result, G_ERROR_UNAUTHORIZED)) {\n y_log_message(Y_LOG_LEVEL_WARNING, \"Security - Authorization invalid for username at IP Address %s\", ip_source);\n response->status = 401;\n } else if (check_result_value(j_result, G_ERROR_NOT_FOUND)) {\n response->status = 404;\n } else if (check_result_value(j_result, G_OK)) {\n if ((session_uid = get_session_id(config, request)) == NULL) {\n session_uid = generate_session_id();\n }\n if (user_session_update(config, session_uid, u_map_get_case(request->map_header, \"user-agent\"), issued_for, json_string_value(json_object_get(j_result, \"username\")), json_string_value(json_object_get(j_param, \"scheme_name\")), 1) != G_OK) {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error user_session_update (4)\");\n response->status = 500;\n } else {\n ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, \"/\", config->cookie_secure, 0);\n y_log_message(Y_LOG_LEVEL_INFO, \"Event - User '%s' authenticated with scheme '%s/%s'\", json_string_value(json_object_get(j_result, \"username\")), json_string_value(json_object_get(j_param, \"scheme_type\")), json_string_value(json_object_get(j_param, \"scheme_name\")));\n }\n o_free(session_uid);\n } else {\n y_log_message(Y_LOG_LEVEL_ERROR, \"callback_glewlwyd_user_auth - Error auth_check_user_scheme\");\n response->status = 500;\n }\n json_decref(j_result);\n } else {\n ulfius_set_string_body_response(response, 400, \"username is mandatory\");\n }\n }\n } else {\n ulfius_set_string_body_response(response, 400, \"Input parameters must be in JSON format\");\n }\n json_decref(j_param);\n o_free(issued_for);\n\n return U_CALLBACK_CONTINUE;\n}", "func_hash": 155113792370707223407331204609439430532, "file_name": "webservice.c", "file_hash": 287798817606377336444620654835011177393, "cwe": ["CWE-287"], "cve": "CVE-2021-45379", "cve_desc": "Glewlwyd 2.0.0, fixed in 2.6.1 is affected by an incorrect access control vulnerability. One user can attempt to log in as another user without its password.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-45379"} {"idx": 195023, "project": "tensorflow", "commit_id": "a68f68061e263a88321c104a6c911fe5598050a8", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a68f68061e263a88321c104a6c911fe5598050a8", "commit_message": "Replace faulty overflow check with a builder for `TensorShape`.\n\nPrevents an integer overflow that was not caught before.\n\nPiperOrigin-RevId: 415381595\nChange-Id: I76585ddedc912bd9f4a390aeafa8e2ced1a28863", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const Tensor* input_indices;\n const Tensor* input_values;\n const Tensor* input_shape;\n SparseTensorsMap* map;\n\n OP_REQUIRES_OK(context, context->input(\"sparse_indices\", &input_indices));\n OP_REQUIRES_OK(context, context->input(\"sparse_values\", &input_values));\n OP_REQUIRES_OK(context, context->input(\"sparse_shape\", &input_shape));\n OP_REQUIRES_OK(context, GetMap(context, true /* is_writing */, &map));\n\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be a matrix but received shape \",\n input_indices->shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values->shape()),\n errors::InvalidArgument(\n \"Input values should be a vector but received shape \",\n input_values->shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape->shape()),\n errors::InvalidArgument(\n \"Input shape should be a vector but received shape \",\n input_shape->shape().DebugString()));\n OP_REQUIRES(\n context,\n input_values->shape().dim_size(0) == input_indices->shape().dim_size(0),\n errors::InvalidArgument(\n \"Number of values must match first dimension of indices. \", \"Got \",\n input_values->shape().dim_size(0),\n \" values, indices shape: \", input_indices->shape().DebugString()));\n OP_REQUIRES(\n context,\n input_shape->shape().dim_size(0) == input_indices->shape().dim_size(1),\n errors::InvalidArgument(\n \"Number of dimensions must match second dimension of indices. \",\n \"Got \", input_shape->shape().dim_size(0),\n \" dimensions, indices shape: \",\n input_indices->shape().DebugString()));\n\n int rank = input_shape->NumElements();\n\n OP_REQUIRES(\n context, rank > 1,\n errors::InvalidArgument(\n \"Rank of input SparseTensor should be > 1, but saw rank: \", rank));\n\n auto input_shape_vec = input_shape->vec();\n int new_num_elements = 1;\n bool overflow_ocurred = false;\n for (int i = 0; i < input_shape_vec.size(); i++) {\n new_num_elements =\n MultiplyWithoutOverflow(new_num_elements, input_shape_vec(i));\n if (new_num_elements < 0) {\n overflow_ocurred = true;\n break;\n }\n }\n\n OP_REQUIRES(\n context, !overflow_ocurred,\n errors::Internal(\"Encountered overflow from large input shape.\"));\n\n TensorShape tensor_input_shape(input_shape_vec);\n gtl::InlinedVector std_order(rank);\n std::iota(std_order.begin(), std_order.end(), 0);\n SparseTensor input_st;\n OP_REQUIRES_OK(context, SparseTensor::Create(*input_indices, *input_values,\n tensor_input_shape, std_order,\n &input_st));\n\n const int64_t N = input_shape_vec(0);\n\n Tensor sparse_handles(DT_INT64, TensorShape({N}));\n auto sparse_handles_t = sparse_handles.vec();\n\n OP_REQUIRES_OK(context, input_st.IndicesValid());\n\n // We can generate the output shape proto string now, for all\n // minibatch entries.\n TensorShape output_shape;\n OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(\n input_shape_vec.data() + 1,\n input_shape->NumElements() - 1, &output_shape));\n\n // Get groups by minibatch dimension\n std::unordered_set visited;\n sparse::GroupIterable minibatch = input_st.group({0});\n for (const auto& subset : minibatch) {\n const int64_t b = subset.group()[0];\n visited.insert(b);\n OP_REQUIRES(\n context, b > -1 && b < N,\n errors::InvalidArgument(\n \"Received unexpected column 0 value in input SparseTensor: \", b,\n \" < 0 or >= N (= \", N, \")\"));\n\n const auto indices = subset.indices();\n const auto values = subset.values();\n const int64_t num_entries = values.size();\n\n Tensor output_indices = Tensor(DT_INT64, {num_entries, rank - 1});\n Tensor output_values = Tensor(DataTypeToEnum::value, {num_entries});\n\n auto output_indices_t = output_indices.matrix();\n auto output_values_t = output_values.vec();\n\n for (int i = 0; i < num_entries; ++i) {\n for (int d = 1; d < rank; ++d) {\n output_indices_t(i, d - 1) = indices(i, d);\n }\n output_values_t(i) = values(i);\n }\n\n SparseTensor st_i;\n OP_REQUIRES_OK(context,\n SparseTensor::Create(output_indices, output_values,\n output_shape, &st_i));\n int64_t handle;\n OP_REQUIRES_OK(context, map->AddSparseTensor(context, st_i, &handle));\n sparse_handles_t(b) = handle;\n }\n\n // Fill in any gaps; we must provide an empty ST for batch entries\n // the grouper didn't find.\n if (visited.size() < N) {\n Tensor empty_indices(DT_INT64, {0, rank - 1});\n Tensor empty_values(DataTypeToEnum::value, {0});\n SparseTensor empty_st;\n OP_REQUIRES_OK(context, SparseTensor::Create(empty_indices, empty_values,\n output_shape, &empty_st));\n\n for (int64_t b = 0; b < N; ++b) {\n // We skipped this batch entry.\n if (visited.find(b) == visited.end()) {\n int64_t handle;\n OP_REQUIRES_OK(context,\n map->AddSparseTensor(context, empty_st, &handle));\n sparse_handles_t(b) = handle;\n }\n }\n }\n\n context->set_output(0, sparse_handles);\n }", "func_hash": 160387063214720131730960354923232758630, "file_name": "sparse_tensors_map_ops.cc", "file_hash": 224775123349374780251651202891389866533, "cwe": ["CWE-190"], "cve": "CVE-2022-23568", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `AddManySparseToTensorsMap` is vulnerable to an integer overflow which results in a `CHECK`-fail when building new `TensorShape` objects (so, an assert failure based denial of service). We are missing some validation on the shapes of the input tensors as well as directly constructing a large `TensorShape` with user-provided dimensions. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23568"} {"idx": 220021, "project": "tensorflow", "commit_id": "a68f68061e263a88321c104a6c911fe5598050a8", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a68f68061e263a88321c104a6c911fe5598050a8", "commit_message": "Replace faulty overflow check with a builder for `TensorShape`.\n\nPrevents an integer overflow that was not caught before.\n\nPiperOrigin-RevId: 415381595\nChange-Id: I76585ddedc912bd9f4a390aeafa8e2ced1a28863", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const Tensor* input_indices;\n const Tensor* input_values;\n const Tensor* input_shape;\n SparseTensorsMap* map;\n\n OP_REQUIRES_OK(context, context->input(\"sparse_indices\", &input_indices));\n OP_REQUIRES_OK(context, context->input(\"sparse_values\", &input_values));\n OP_REQUIRES_OK(context, context->input(\"sparse_shape\", &input_shape));\n OP_REQUIRES_OK(context, GetMap(context, true /* is_writing */, &map));\n\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be a matrix but received shape \",\n input_indices->shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values->shape()),\n errors::InvalidArgument(\n \"Input values should be a vector but received shape \",\n input_values->shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape->shape()),\n errors::InvalidArgument(\n \"Input shape should be a vector but received shape \",\n input_shape->shape().DebugString()));\n OP_REQUIRES(\n context,\n input_values->shape().dim_size(0) == input_indices->shape().dim_size(0),\n errors::InvalidArgument(\n \"Number of values must match first dimension of indices. \", \"Got \",\n input_values->shape().dim_size(0),\n \" values, indices shape: \", input_indices->shape().DebugString()));\n OP_REQUIRES(\n context,\n input_shape->shape().dim_size(0) == input_indices->shape().dim_size(1),\n errors::InvalidArgument(\n \"Number of dimensions must match second dimension of indices. \",\n \"Got \", input_shape->shape().dim_size(0),\n \" dimensions, indices shape: \",\n input_indices->shape().DebugString()));\n\n int rank = input_shape->NumElements();\n\n OP_REQUIRES(\n context, rank > 1,\n errors::InvalidArgument(\n \"Rank of input SparseTensor should be > 1, but saw rank: \", rank));\n\n auto input_shape_vec = input_shape->vec();\n\n TensorShape tensor_input_shape;\n OP_REQUIRES_OK(context, TensorShape::BuildTensorShape(input_shape_vec,\n &tensor_input_shape));\n gtl::InlinedVector std_order(rank);\n std::iota(std_order.begin(), std_order.end(), 0);\n SparseTensor input_st;\n OP_REQUIRES_OK(context, SparseTensor::Create(*input_indices, *input_values,\n tensor_input_shape, std_order,\n &input_st));\n\n const int64_t N = input_shape_vec(0);\n\n Tensor sparse_handles(DT_INT64, TensorShape({N}));\n auto sparse_handles_t = sparse_handles.vec();\n\n OP_REQUIRES_OK(context, input_st.IndicesValid());\n\n // We can generate the output shape proto string now, for all\n // minibatch entries.\n TensorShape output_shape;\n OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(\n input_shape_vec.data() + 1,\n input_shape->NumElements() - 1, &output_shape));\n\n // Get groups by minibatch dimension\n std::unordered_set visited;\n sparse::GroupIterable minibatch = input_st.group({0});\n for (const auto& subset : minibatch) {\n const int64_t b = subset.group()[0];\n visited.insert(b);\n OP_REQUIRES(\n context, b > -1 && b < N,\n errors::InvalidArgument(\n \"Received unexpected column 0 value in input SparseTensor: \", b,\n \" < 0 or >= N (= \", N, \")\"));\n\n const auto indices = subset.indices();\n const auto values = subset.values();\n const int64_t num_entries = values.size();\n\n Tensor output_indices = Tensor(DT_INT64, {num_entries, rank - 1});\n Tensor output_values = Tensor(DataTypeToEnum::value, {num_entries});\n\n auto output_indices_t = output_indices.matrix();\n auto output_values_t = output_values.vec();\n\n for (int i = 0; i < num_entries; ++i) {\n for (int d = 1; d < rank; ++d) {\n output_indices_t(i, d - 1) = indices(i, d);\n }\n output_values_t(i) = values(i);\n }\n\n SparseTensor st_i;\n OP_REQUIRES_OK(context,\n SparseTensor::Create(output_indices, output_values,\n output_shape, &st_i));\n int64_t handle;\n OP_REQUIRES_OK(context, map->AddSparseTensor(context, st_i, &handle));\n sparse_handles_t(b) = handle;\n }\n\n // Fill in any gaps; we must provide an empty ST for batch entries\n // the grouper didn't find.\n if (visited.size() < N) {\n Tensor empty_indices(DT_INT64, {0, rank - 1});\n Tensor empty_values(DataTypeToEnum::value, {0});\n SparseTensor empty_st;\n OP_REQUIRES_OK(context, SparseTensor::Create(empty_indices, empty_values,\n output_shape, &empty_st));\n\n for (int64_t b = 0; b < N; ++b) {\n // We skipped this batch entry.\n if (visited.find(b) == visited.end()) {\n int64_t handle;\n OP_REQUIRES_OK(context,\n map->AddSparseTensor(context, empty_st, &handle));\n sparse_handles_t(b) = handle;\n }\n }\n }\n\n context->set_output(0, sparse_handles);\n }", "func_hash": 294930600730557371611113946400120075396, "file_name": "sparse_tensors_map_ops.cc", "file_hash": 5591389034837291700501932002893322459, "cwe": ["CWE-190"], "cve": "CVE-2022-23568", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `AddManySparseToTensorsMap` is vulnerable to an integer overflow which results in a `CHECK`-fail when building new `TensorShape` objects (so, an assert failure based denial of service). We are missing some validation on the shapes of the input tensors as well as directly constructing a large `TensorShape` with user-provided dimensions. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23568"} {"idx": 195026, "project": "linux", "commit_id": "ab0fc21bc7105b54bafd85bd8b82742f9e68898a", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/ab0fc21bc7105b54bafd85bd8b82742f9e68898a", "commit_message": "Revert \"NFSv4: Handle the special Linux file open access mode\"\n\nThis reverts commit 44942b4e457beda00981f616402a1a791e8c616e.\n\nAfter secondly opening a file with O_ACCMODE|O_DIRECT flags,\nnfs4_valid_open_stateid() will dereference NULL nfs4_state when lseek().\n\nReproducer:\n 1. mount -t nfs -o vers=4.2 $server_ip:/ /mnt/\n 2. fd = open(\"/mnt/file\", O_ACCMODE|O_DIRECT|O_CREAT)\n 3. close(fd)\n 4. fd = open(\"/mnt/file\", O_ACCMODE|O_DIRECT)\n 5. lseek(fd)\n\nReported-by: Lyu Tao \nSigned-off-by: ChenXiaoSong \nSigned-off-by: Trond Myklebust ", "target": 1, "func": "nfs4_file_open(struct inode *inode, struct file *filp)\n{\n\tstruct nfs_open_context *ctx;\n\tstruct dentry *dentry = file_dentry(filp);\n\tstruct dentry *parent = NULL;\n\tstruct inode *dir;\n\tunsigned openflags = filp->f_flags;\n\tstruct iattr attr;\n\tint err;\n\n\t/*\n\t * If no cached dentry exists or if it's negative, NFSv4 handled the\n\t * opens in ->lookup() or ->create().\n\t *\n\t * We only get this far for a cached positive dentry. We skipped\n\t * revalidation, so handle it here by dropping the dentry and returning\n\t * -EOPENSTALE. The VFS will retry the lookup/create/open.\n\t */\n\n\tdprintk(\"NFS: open file(%pd2)\\n\", dentry);\n\n\terr = nfs_check_flags(openflags);\n\tif (err)\n\t\treturn err;\n\n\tif ((openflags & O_ACCMODE) == 3)\n\t\treturn nfs_open(inode, filp);\n\n\t/* We can't create new files here */\n\topenflags &= ~(O_CREAT|O_EXCL);\n\n\tparent = dget_parent(dentry);\n\tdir = d_inode(parent);\n\n\tctx = alloc_nfs_open_context(file_dentry(filp), filp->f_mode, filp);\n\terr = PTR_ERR(ctx);\n\tif (IS_ERR(ctx))\n\t\tgoto out;\n\n\tattr.ia_valid = ATTR_OPEN;\n\tif (openflags & O_TRUNC) {\n\t\tattr.ia_valid |= ATTR_SIZE;\n\t\tattr.ia_size = 0;\n\t\tfilemap_write_and_wait(inode->i_mapping);\n\t}\n\n\tinode = NFS_PROTO(dir)->open_context(dir, ctx, openflags, &attr, NULL);\n\tif (IS_ERR(inode)) {\n\t\terr = PTR_ERR(inode);\n\t\tswitch (err) {\n\t\tdefault:\n\t\t\tgoto out_put_ctx;\n\t\tcase -ENOENT:\n\t\tcase -ESTALE:\n\t\tcase -EISDIR:\n\t\tcase -ENOTDIR:\n\t\tcase -ELOOP:\n\t\t\tgoto out_drop;\n\t\t}\n\t}\n\tif (inode != d_inode(dentry))\n\t\tgoto out_drop;\n\n\tnfs_file_set_open_context(filp, ctx);\n\tnfs_fscache_open_file(inode, filp);\n\terr = 0;\n\nout_put_ctx:\n\tput_nfs_open_context(ctx);\nout:\n\tdput(parent);\n\treturn err;\n\nout_drop:\n\td_drop(dentry);\n\terr = -EOPENSTALE;\n\tgoto out_put_ctx;\n}", "func_hash": 67846125552854891508125900978071958871, "file_name": "nfs4file.c", "file_hash": 109456154040292488452120321326967957719, "cwe": ["CWE-909"], "cve": "CVE-2022-24448", "cve_desc": "An issue was discovered in fs/nfs/dir.c in the Linux kernel before 5.16.5. If an application sets the O_DIRECTORY flag, and tries to open a regular file, nfs_atomic_open() performs a regular lookup. If a regular file is found, ENOTDIR should occur, but the server instead returns uninitialized data in the file descriptor.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24448"} {"idx": 220100, "project": "linux", "commit_id": "ab0fc21bc7105b54bafd85bd8b82742f9e68898a", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/ab0fc21bc7105b54bafd85bd8b82742f9e68898a", "commit_message": "Revert \"NFSv4: Handle the special Linux file open access mode\"\n\nThis reverts commit 44942b4e457beda00981f616402a1a791e8c616e.\n\nAfter secondly opening a file with O_ACCMODE|O_DIRECT flags,\nnfs4_valid_open_stateid() will dereference NULL nfs4_state when lseek().\n\nReproducer:\n 1. mount -t nfs -o vers=4.2 $server_ip:/ /mnt/\n 2. fd = open(\"/mnt/file\", O_ACCMODE|O_DIRECT|O_CREAT)\n 3. close(fd)\n 4. fd = open(\"/mnt/file\", O_ACCMODE|O_DIRECT)\n 5. lseek(fd)\n\nReported-by: Lyu Tao \nSigned-off-by: ChenXiaoSong \nSigned-off-by: Trond Myklebust ", "target": 0, "func": "nfs4_file_open(struct inode *inode, struct file *filp)\n{\n\tstruct nfs_open_context *ctx;\n\tstruct dentry *dentry = file_dentry(filp);\n\tstruct dentry *parent = NULL;\n\tstruct inode *dir;\n\tunsigned openflags = filp->f_flags;\n\tstruct iattr attr;\n\tint err;\n\n\t/*\n\t * If no cached dentry exists or if it's negative, NFSv4 handled the\n\t * opens in ->lookup() or ->create().\n\t *\n\t * We only get this far for a cached positive dentry. We skipped\n\t * revalidation, so handle it here by dropping the dentry and returning\n\t * -EOPENSTALE. The VFS will retry the lookup/create/open.\n\t */\n\n\tdprintk(\"NFS: open file(%pd2)\\n\", dentry);\n\n\terr = nfs_check_flags(openflags);\n\tif (err)\n\t\treturn err;\n\n\tif ((openflags & O_ACCMODE) == 3)\n\t\topenflags--;\n\n\t/* We can't create new files here */\n\topenflags &= ~(O_CREAT|O_EXCL);\n\n\tparent = dget_parent(dentry);\n\tdir = d_inode(parent);\n\n\tctx = alloc_nfs_open_context(file_dentry(filp), filp->f_mode, filp);\n\terr = PTR_ERR(ctx);\n\tif (IS_ERR(ctx))\n\t\tgoto out;\n\n\tattr.ia_valid = ATTR_OPEN;\n\tif (openflags & O_TRUNC) {\n\t\tattr.ia_valid |= ATTR_SIZE;\n\t\tattr.ia_size = 0;\n\t\tfilemap_write_and_wait(inode->i_mapping);\n\t}\n\n\tinode = NFS_PROTO(dir)->open_context(dir, ctx, openflags, &attr, NULL);\n\tif (IS_ERR(inode)) {\n\t\terr = PTR_ERR(inode);\n\t\tswitch (err) {\n\t\tdefault:\n\t\t\tgoto out_put_ctx;\n\t\tcase -ENOENT:\n\t\tcase -ESTALE:\n\t\tcase -EISDIR:\n\t\tcase -ENOTDIR:\n\t\tcase -ELOOP:\n\t\t\tgoto out_drop;\n\t\t}\n\t}\n\tif (inode != d_inode(dentry))\n\t\tgoto out_drop;\n\n\tnfs_file_set_open_context(filp, ctx);\n\tnfs_fscache_open_file(inode, filp);\n\terr = 0;\n\nout_put_ctx:\n\tput_nfs_open_context(ctx);\nout:\n\tdput(parent);\n\treturn err;\n\nout_drop:\n\td_drop(dentry);\n\terr = -EOPENSTALE;\n\tgoto out_put_ctx;\n}", "func_hash": 272987829557105540879962051296017178836, "file_name": "nfs4file.c", "file_hash": 19160442996144037090827134285929888626, "cwe": ["CWE-909"], "cve": "CVE-2022-24448", "cve_desc": "An issue was discovered in fs/nfs/dir.c in the Linux kernel before 5.16.5. If an application sets the O_DIRECTORY flag, and tries to open a regular file, nfs_atomic_open() performs a regular lookup. If a regular file is found, ENOTDIR should occur, but the server instead returns uninitialized data in the file descriptor.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24448"} {"idx": 195028, "project": "tensorflow", "commit_id": "ab51e5b813573dc9f51efa335aebcf2994125ee9", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/ab51e5b813573dc9f51efa335aebcf2994125ee9", "commit_message": "Prevent memory leak in decoding PNG images.\n\nPiperOrigin-RevId: 409300653\nChange-Id: I6182124c545989cef80cefd439b659095920763b", "target": 1, "func": " void DecodePngV2(OpKernelContext* context, StringPiece input) {\n int channel_bits = (data_type_ == DataType::DT_UINT8) ? 8 : 16;\n png::DecodeContext decode;\n OP_REQUIRES(\n context, png::CommonInitDecode(input, channels_, channel_bits, &decode),\n errors::InvalidArgument(\"Invalid PNG. Failed to initialize decoder.\"));\n\n // Verify that width and height are not too large:\n // - verify width and height don't overflow int.\n // - width can later be multiplied by channels_ and sizeof(uint16), so\n // verify single dimension is not too large.\n // - verify when width and height are multiplied together, there are a few\n // bits to spare as well.\n const int width = static_cast(decode.width);\n const int height = static_cast(decode.height);\n const int64_t total_size =\n static_cast(width) * static_cast(height);\n if (width != static_cast(decode.width) || width <= 0 ||\n width >= (1LL << 27) || height != static_cast(decode.height) ||\n height <= 0 || height >= (1LL << 27) || total_size >= (1LL << 29)) {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\"PNG size too large for int: \",\n decode.width, \" by \", decode.height));\n }\n\n Tensor* output = nullptr;\n // By the existing API, we support decoding PNG with `DecodeGif` op.\n // We need to make sure to return 4-D shapes when using `DecodeGif`.\n if (op_type_ == \"DecodeGif\") {\n OP_REQUIRES_OK(\n context,\n context->allocate_output(\n 0, TensorShape({1, height, width, decode.channels}), &output));\n } else {\n OP_REQUIRES_OK(\n context,\n context->allocate_output(\n 0, TensorShape({height, width, decode.channels}), &output));\n }\n\n if (op_type_ == \"DecodeBmp\") {\n // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here\n // because currently `decode_(jpeg|png|gif)` ops can decode any one of\n // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode\n // anything but bmp formats. This behavior needs to be revisited. For more\n // details, please refer to the bug.\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Trying to decode PNG format using DecodeBmp op. Use \"\n \"`decode_png` or `decode_image` instead.\"));\n } else if (op_type_ == \"DecodeAndCropJpeg\") {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"DecodeAndCropJpeg operation can run on JPEG only, but \"\n \"detected PNG.\"));\n }\n\n if (data_type_ == DataType::DT_UINT8) {\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(\n reinterpret_cast(output->flat().data()),\n decode.channels * width * sizeof(uint8), &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n } else if (data_type_ == DataType::DT_UINT16) {\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(\n reinterpret_cast(output->flat().data()),\n decode.channels * width * sizeof(uint16), &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n } else if (data_type_ == DataType::DT_FLOAT) {\n // `png::CommonFinishDecode` does not support `float`. First allocate\n // uint16 buffer for the image and decode in uint16 (lossless). Wrap the\n // buffer in `unique_ptr` so that we don't forget to delete the buffer.\n std::unique_ptr buffer(\n new uint16[height * width * decode.channels]);\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(reinterpret_cast(buffer.get()),\n decode.channels * width * sizeof(uint16),\n &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n\n // Convert uint16 image data to desired data type.\n // Use eigen threadpooling to speed up the copy operation.\n const auto& device = context->eigen_device();\n TTypes::UnalignedConstTensor buf(buffer.get(), height, width,\n decode.channels);\n float scale = 1. / std::numeric_limits::max();\n // Fill output tensor with desired dtype.\n output->tensor().device(device) = buf.cast() * scale;\n }\n }", "func_hash": 67814436772398534036630434647873886403, "file_name": "decode_image_op.cc", "file_hash": 283519422605879710361255065504339887165, "cwe": ["CWE-401"], "cve": "CVE-2022-23585", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. When decoding PNG images TensorFlow can produce a memory leak if the image is invalid. After calling `png::CommonInitDecode(..., &decode)`, the `decode` value contains allocated buffers which can only be freed by calling `png::CommonFreeDecode(&decode)`. However, several error case in the function implementation invoke the `OP_REQUIRES` macro which immediately terminates the execution of the function, without allowing for the memory free to occur. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23585"} {"idx": 220168, "project": "tensorflow", "commit_id": "ab51e5b813573dc9f51efa335aebcf2994125ee9", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/ab51e5b813573dc9f51efa335aebcf2994125ee9", "commit_message": "Prevent memory leak in decoding PNG images.\n\nPiperOrigin-RevId: 409300653\nChange-Id: I6182124c545989cef80cefd439b659095920763b", "target": 0, "func": " void DecodePngV2(OpKernelContext* context, StringPiece input) {\n int channel_bits = (data_type_ == DataType::DT_UINT8) ? 8 : 16;\n png::DecodeContext decode;\n OP_REQUIRES(\n context, png::CommonInitDecode(input, channels_, channel_bits, &decode),\n errors::InvalidArgument(\"Invalid PNG. Failed to initialize decoder.\"));\n\n // If we reach this point, then there is data in `decode` which must be\n // freed by the time we end execution in this function. We cannot call\n // `png::CommonFreeDecode()` before an `OP_REQUIRES` because if\n // `OP_REQUIRES` constraint is satisfied then the data would be freed\n // prematurely. Instead, let's use a `Cleanup` object.\n auto cleanup = gtl::MakeCleanup([&decode]() {\n std::cerr << \"Cleanup called...\\n\";\n png::CommonFreeDecode(&decode);\n });\n\n // Verify that width and height are not too large:\n // - verify width and height don't overflow int.\n // - width can later be multiplied by channels_ and sizeof(uint16), so\n // verify single dimension is not too large.\n // - verify when width and height are multiplied together, there are a few\n // bits to spare as well.\n const int width = static_cast(decode.width);\n const int height = static_cast(decode.height);\n const int64_t total_size =\n static_cast(width) * static_cast(height);\n if (width != static_cast(decode.width) || width <= 0 ||\n width >= (1LL << 27) || height != static_cast(decode.height) ||\n height <= 0 || height >= (1LL << 27) || total_size >= (1LL << 29)) {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\"PNG size too large for int: \",\n decode.width, \" by \", decode.height));\n }\n\n Tensor* output = nullptr;\n // By the existing API, we support decoding PNG with `DecodeGif` op.\n // We need to make sure to return 4-D shapes when using `DecodeGif`.\n if (op_type_ == \"DecodeGif\") {\n OP_REQUIRES_OK(\n context,\n context->allocate_output(\n 0, TensorShape({1, height, width, decode.channels}), &output));\n } else {\n OP_REQUIRES_OK(\n context,\n context->allocate_output(\n 0, TensorShape({height, width, decode.channels}), &output));\n }\n\n if (op_type_ == \"DecodeBmp\") {\n // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here\n // because currently `decode_(jpeg|png|gif)` ops can decode any one of\n // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode\n // anything but bmp formats. This behavior needs to be revisited. For more\n // details, please refer to the bug.\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Trying to decode PNG format using DecodeBmp op. Use \"\n \"`decode_png` or `decode_image` instead.\"));\n } else if (op_type_ == \"DecodeAndCropJpeg\") {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"DecodeAndCropJpeg operation can run on JPEG only, but \"\n \"detected PNG.\"));\n }\n\n if (data_type_ == DataType::DT_UINT8) {\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(\n reinterpret_cast(output->flat().data()),\n decode.channels * width * sizeof(uint8), &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n } else if (data_type_ == DataType::DT_UINT16) {\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(\n reinterpret_cast(output->flat().data()),\n decode.channels * width * sizeof(uint16), &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n } else if (data_type_ == DataType::DT_FLOAT) {\n // `png::CommonFinishDecode` does not support `float`. First allocate\n // uint16 buffer for the image and decode in uint16 (lossless). Wrap the\n // buffer in `unique_ptr` so that we don't forget to delete the buffer.\n std::unique_ptr buffer(\n new uint16[height * width * decode.channels]);\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(reinterpret_cast(buffer.get()),\n decode.channels * width * sizeof(uint16),\n &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n\n // Convert uint16 image data to desired data type.\n // Use eigen threadpooling to speed up the copy operation.\n const auto& device = context->eigen_device();\n TTypes::UnalignedConstTensor buf(buffer.get(), height, width,\n decode.channels);\n float scale = 1. / std::numeric_limits::max();\n // Fill output tensor with desired dtype.\n output->tensor().device(device) = buf.cast() * scale;\n }\n }", "func_hash": 183944225263640230240348550837981668390, "file_name": "decode_image_op.cc", "file_hash": 140340118421060830961361158847913918052, "cwe": ["CWE-401"], "cve": "CVE-2022-23585", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. When decoding PNG images TensorFlow can produce a memory leak if the image is invalid. After calling `png::CommonInitDecode(..., &decode)`, the `decode` value contains allocated buffers which can only be freed by calling `png::CommonFreeDecode(&decode)`. However, several error case in the function implementation invoke the `OP_REQUIRES` macro which immediately terminates the execution of the function, without allowing for the memory free to occur. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23585"} {"idx": 195029, "project": "tensorflow", "commit_id": "c99d98cd189839dcf51aee94e7437b54b31f8abd", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/c99d98cd189839dcf51aee94e7437b54b31f8abd", "commit_message": "Handle invalid inputs instead of crashing.\n\nPiperOrigin-RevId: 409549744\nChange-Id: I7f5935b34b53f7e426a5462fcc027bdbf5dcda24", "target": 1, "func": "void Node::RunForwardTypeInference() {\n VLOG(4) << \"Forward type inference: \" << props_->node_def.DebugString();\n\n if (props_->fwd_type_fn == nullptr) {\n return;\n }\n\n std::vector input_nodes(props_->input_types.size(), nullptr);\n std::vector input_idx(props_->input_types.size(), 0);\n for (const auto& edge : in_edges_) {\n if (edge->IsControlEdge()) {\n continue;\n }\n DCHECK(edge->dst_input() < input_nodes.size()) << DebugString();\n int i = edge->dst_input();\n input_nodes.at(i) = edge->src();\n input_idx.at(i) = edge->src_output();\n }\n\n // Note: technically, we could use a very generic type when some of the inputs\n // are unknown. But there is an expectation that a node will have complete\n // inputs soon, so updating intermediate types is largely unnecessary.\n\n for (const auto* node : input_nodes) {\n if (node == nullptr) {\n // Incomplete inputs, bail.\n ClearTypeInfo();\n return;\n }\n }\n\n static FullTypeDef* no_type = new FullTypeDef();\n\n std::vector> input_types;\n for (int i = 0; i < input_nodes.size(); i++) {\n const auto* node = input_nodes[i];\n if (node->def().has_experimental_type()) {\n const auto& node_t = node->def().experimental_type();\n if (node_t.type_id() != TFT_UNSET) {\n int ix = input_idx[i];\n DCHECK(ix < node_t.args_size())\n << \"input \" << i << \" should have an output \" << ix\n << \" but instead only has \" << node_t.args_size()\n << \" outputs: \" << node_t.DebugString();\n input_types.emplace_back(node_t.args(ix));\n } else {\n input_types.emplace_back(*no_type);\n }\n } else {\n // Incomplete inputs, bail.\n ClearTypeInfo();\n return;\n }\n }\n\n const auto infer_type = props_->fwd_type_fn(input_types);\n const FullTypeDef infer_typedef = infer_type.ValueOrDie();\n if (infer_typedef.type_id() != TFT_UNSET) {\n MaybeCopyOnWrite();\n *(props_->node_def.mutable_experimental_type()) = infer_typedef;\n }\n}", "func_hash": 285691869172413131662679092330979772991, "file_name": "graph.cc", "file_hash": 172099243927919341591512227523808328051, "cwe": ["CWE-125"], "cve": "CVE-2022-23592", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. TensorFlow's type inference can cause a heap out of bounds read as the bounds checking is done in a `DCHECK` (which is a no-op during production). An attacker can control the `input_idx` variable such that `ix` would be larger than the number of values in `node_t.args`. The fix will be included in TensorFlow 2.8.0. This is the only affected version.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23592"} {"idx": 220201, "project": "tensorflow", "commit_id": "c99d98cd189839dcf51aee94e7437b54b31f8abd", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/c99d98cd189839dcf51aee94e7437b54b31f8abd", "commit_message": "Handle invalid inputs instead of crashing.\n\nPiperOrigin-RevId: 409549744\nChange-Id: I7f5935b34b53f7e426a5462fcc027bdbf5dcda24", "target": 0, "func": "void Node::RunForwardTypeInference() {\n VLOG(4) << \"Forward type inference: \" << props_->node_def.DebugString();\n\n if (props_->fwd_type_fn == nullptr) {\n return;\n }\n\n std::vector input_nodes(props_->input_types.size(), nullptr);\n std::vector input_idx(props_->input_types.size(), 0);\n for (const auto& edge : in_edges_) {\n if (edge->IsControlEdge()) {\n continue;\n }\n DCHECK(edge->dst_input() < input_nodes.size()) << DebugString();\n int i = edge->dst_input();\n input_nodes.at(i) = edge->src();\n input_idx.at(i) = edge->src_output();\n }\n\n // Note: technically, we could use a very generic type when some of the inputs\n // are unknown. But there is an expectation that a node will have complete\n // inputs soon, so updating intermediate types is largely unnecessary.\n\n for (const auto* node : input_nodes) {\n if (node == nullptr) {\n // Incomplete inputs, bail.\n ClearTypeInfo();\n return;\n }\n }\n\n static FullTypeDef* no_type = new FullTypeDef();\n\n std::vector> input_types;\n for (int i = 0; i < input_nodes.size(); i++) {\n const auto* node = input_nodes[i];\n if (node->def().has_experimental_type()) {\n const auto& node_t = node->def().experimental_type();\n if (node_t.type_id() != TFT_UNSET) {\n int ix = input_idx[i];\n if (ix >= node_t.args_size()) {\n LOG(WARNING) << name() << \" has bad type information: input \" << i\n << \" should have an output \" << ix\n << \" but instead only has \" << node_t.args_size()\n << \" outputs: \" << node_t.DebugString()\n << \"\\nThis indicates either \"\n \"a bug in op registration or a corrupted graph.\";\n ClearTypeInfo();\n return;\n }\n input_types.emplace_back(node_t.args(ix));\n } else {\n input_types.emplace_back(*no_type);\n }\n } else {\n // Incomplete inputs, bail.\n ClearTypeInfo();\n return;\n }\n }\n\n const auto infer_type = props_->fwd_type_fn(input_types);\n const FullTypeDef infer_typedef = infer_type.ValueOrDie();\n if (infer_typedef.type_id() != TFT_UNSET) {\n MaybeCopyOnWrite();\n *(props_->node_def.mutable_experimental_type()) = infer_typedef;\n }\n}", "func_hash": 208747443072046126472677622190312892089, "file_name": "graph.cc", "file_hash": 252683577168046425270820661985512954953, "cwe": ["CWE-125"], "cve": "CVE-2022-23592", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. TensorFlow's type inference can cause a heap out of bounds read as the bounds checking is done in a `DCHECK` (which is a no-op during production). An attacker can control the `input_idx` variable such that `ix` would be larger than the number of values in `node_t.args`. The fix will be included in TensorFlow 2.8.0. This is the only affected version.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23592"} {"idx": 195038, "project": "mruby", "commit_id": "27d1e0132a0804581dca28df042e7047fd27eaa8", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/27d1e0132a0804581dca28df042e7047fd27eaa8", "commit_message": "array.c: fix `mrb_ary_shift_m` initialization bug.\n\nThe `ARY_PTR` and `ARY_LEN` may be modified in `mrb_get_args`.", "target": 1, "func": "mrb_ary_shift_m(mrb_state *mrb, mrb_value self)\n{\n struct RArray *a = mrb_ary_ptr(self);\n mrb_int len = ARY_LEN(a);\n mrb_int n;\n mrb_value val;\n\n if (mrb_get_args(mrb, \"|i\", &n) == 0) {\n return mrb_ary_shift(mrb, self);\n };\n ary_modify_check(mrb, a);\n if (len == 0 || n == 0) return mrb_ary_new(mrb);\n if (n < 0) mrb_raise(mrb, E_ARGUMENT_ERROR, \"negative array shift\");\n if (n > len) n = len;\n val = mrb_ary_new_from_values(mrb, n, ARY_PTR(a));\n if (ARY_SHARED_P(a)) {\n L_SHIFT:\n a->as.heap.ptr+=n;\n a->as.heap.len-=n;\n return val;\n }\n if (len > ARY_SHIFT_SHARED_MIN) {\n ary_make_shared(mrb, a);\n goto L_SHIFT;\n }\n else if (len == n) {\n ARY_SET_LEN(a, 0);\n }\n else {\n mrb_value *ptr = ARY_PTR(a);\n mrb_int size = len-n;\n\n while (size--) {\n *ptr = *(ptr+n);\n ++ptr;\n }\n ARY_SET_LEN(a, len-n);\n }\n return val;\n}", "func_hash": 88987793594626442814152795226896894437, "file_name": "array.c", "file_hash": 131985777969528154957566525214352537878, "cwe": ["CWE-476"], "cve": "CVE-2021-4188", "cve_desc": "mruby is vulnerable to NULL Pointer Dereference", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-4188"} {"idx": 220442, "project": "mruby", "commit_id": "27d1e0132a0804581dca28df042e7047fd27eaa8", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/27d1e0132a0804581dca28df042e7047fd27eaa8", "commit_message": "array.c: fix `mrb_ary_shift_m` initialization bug.\n\nThe `ARY_PTR` and `ARY_LEN` may be modified in `mrb_get_args`.", "target": 0, "func": "mrb_ary_shift_m(mrb_state *mrb, mrb_value self)\n{\n mrb_int n;\n\n if (mrb_get_args(mrb, \"|i\", &n) == 0) {\n return mrb_ary_shift(mrb, self);\n }\n\n struct RArray *a = mrb_ary_ptr(self);\n mrb_int len = ARY_LEN(a);\n mrb_value val;\n\n ary_modify_check(mrb, a);\n if (len == 0 || n == 0) return mrb_ary_new(mrb);\n if (n < 0) mrb_raise(mrb, E_ARGUMENT_ERROR, \"negative array shift\");\n if (n > len) n = len;\n val = mrb_ary_new_from_values(mrb, n, ARY_PTR(a));\n if (ARY_SHARED_P(a)) {\n L_SHIFT:\n a->as.heap.ptr+=n;\n a->as.heap.len-=n;\n return val;\n }\n if (len > ARY_SHIFT_SHARED_MIN) {\n ary_make_shared(mrb, a);\n goto L_SHIFT;\n }\n else if (len == n) {\n ARY_SET_LEN(a, 0);\n }\n else {\n mrb_value *ptr = ARY_PTR(a);\n mrb_int size = len-n;\n\n while (size--) {\n *ptr = *(ptr+n);\n ++ptr;\n }\n ARY_SET_LEN(a, len-n);\n }\n return val;\n}", "func_hash": 336824346603495353101799104649854425750, "file_name": "array.c", "file_hash": 295526445825727607536544634773604768998, "cwe": ["CWE-476"], "cve": "CVE-2021-4188", "cve_desc": "mruby is vulnerable to NULL Pointer Dereference", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-4188"} {"idx": 195039, "project": "tensorflow", "commit_id": "e7f497570abb6b4ae5af4970620cd880e4c0c904", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e7f497570abb6b4ae5af4970620cd880e4c0c904", "commit_message": "Fix segfault on OOM in Conv2D.\n\nPiperOrigin-RevId: 404655317\nChange-Id: I33588dbd3f5d0fef980e3c908bf5515a9ee09ce7", "target": 1, "func": " void operator()(OpKernelContext* ctx, const Tensor& input,\n const Tensor& filter, int row_stride, int col_stride,\n int row_dilation, int col_dilation, const Padding& padding,\n const std::vector& explicit_paddings, Tensor* output,\n TensorFormat data_format) {\n DCHECK(data_format == FORMAT_NHWC)\n << \"Grouped conv implementation only \"\n \"supports NHWC tensor format for now.\";\n\n const int64_t in_depth = input.dim_size(3);\n const int64_t patch_depth = filter.dim_size(2);\n const int64_t num_groups = in_depth / patch_depth;\n\n // Shuffle input/filter tensors to have group as a leading dimension.\n std::array shuffle({3, 0, 1, 2, 4});\n\n // Compute pre shuffle dimemnsions.\n auto pre_shuffle = [&](const Tensor& tensor) -> std::array {\n return {tensor.dim_size(0), tensor.dim_size(1), tensor.dim_size(2),\n num_groups, tensor.dim_size(3) / num_groups};\n };\n\n // Compute post shuffle dimemnsions.\n auto post_shuffle = [&](const Tensor& tensor) -> std::array {\n return {num_groups, tensor.dim_size(0), tensor.dim_size(1),\n tensor.dim_size(2), tensor.dim_size(3) / num_groups};\n };\n\n auto& device = ctx->eigen_device();\n\n absl::BlockingCounter shuffles_completed(2);\n auto on_shuffled = [&]() { shuffles_completed.DecrementCount(); };\n\n // Shuffle input into temporary tensor.\n Tensor input_shuffled(input.dtype(), TensorShape(post_shuffle(input)));\n input_shuffled.tensor().device(device, on_shuffled) =\n input.shaped(pre_shuffle(input)).shuffle(shuffle);\n\n // Shuffle filter into temporary tensor.\n Tensor filter_shuffled(filter.dtype(), TensorShape(post_shuffle(filter)));\n filter_shuffled.tensor().device(device, on_shuffled) =\n filter.shaped(pre_shuffle(filter)).shuffle(shuffle);\n\n // Wait for the completion of input/filter shuffles.\n shuffles_completed.Wait();\n\n // Write group convolution results into temporary output tensor.\n Tensor output_shuffled(output->dtype(), TensorShape(post_shuffle(*output)));\n\n for (int64_t i = 0; i < num_groups; ++i) {\n // TODO(ezhulenev): Run this loop using `parallelFor` (regular parallelFor\n // will lead to deadlock, SpatialConvolution has to use async Eigen\n // assignment). This requires small changes to Eigen to support async\n // exeuction for tensor chipping operation.\n\n // TODO(ezhulenev): Grouped convolution should also support 1x1 filter\n // optimization.\n\n auto input_slice = input_shuffled.tensor().template chip<0>(i);\n auto filter_slice = filter_shuffled.tensor().template chip<0>(i);\n auto output_slice = output_shuffled.tensor().template chip<0>(i);\n\n if (padding == EXPLICIT) {\n functor::SpatialConvolution()(\n ctx->eigen_device(), output_slice, input_slice,\n filter_slice, row_stride, col_stride, row_dilation, col_dilation,\n static_cast(explicit_paddings[2]),\n static_cast(explicit_paddings[3]),\n static_cast(explicit_paddings[4]),\n static_cast(explicit_paddings[5]));\n } else {\n functor::SpatialConvolution()(\n ctx->eigen_device(), output_slice, input_slice,\n filter_slice, row_stride, col_stride, row_dilation, col_dilation,\n BrainPadding2EigenPadding(padding));\n }\n }\n\n // Shuffle temporary output back into pre-shuffled shape.\n std::array rev_shuffle({1, 2, 3, 0, 4});\n output->shaped(pre_shuffle(*output)).device(device) =\n output_shuffled.tensor().shuffle(rev_shuffle);\n }", "func_hash": 257618220779157714024325768166416151732, "file_name": "conv_ops.cc", "file_hash": 252300068611383622428481854806618645318, "cwe": ["CWE-354"], "cve": "CVE-2021-41206", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions several TensorFlow operations are missing validation for the shapes of the tensor arguments involved in the call. Depending on the API, this can result in undefined behavior and segfault or `CHECK`-fail related crashes but in some scenarios writes and reads from heap populated arrays are also possible. We have discovered these issues internally via tooling while working on improving/testing GPU op determinism. As such, we don't have reproducers and there will be multiple fixes for these issues. These fixes will be included in TensorFlow 2.7.0. We will also cherrypick these commits on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41206"} {"idx": 220449, "project": "tensorflow", "commit_id": "e7f497570abb6b4ae5af4970620cd880e4c0c904", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e7f497570abb6b4ae5af4970620cd880e4c0c904", "commit_message": "Fix segfault on OOM in Conv2D.\n\nPiperOrigin-RevId: 404655317\nChange-Id: I33588dbd3f5d0fef980e3c908bf5515a9ee09ce7", "target": 0, "func": " void operator()(OpKernelContext* ctx, const Tensor& input,\n const Tensor& filter, int row_stride, int col_stride,\n int row_dilation, int col_dilation, const Padding& padding,\n const std::vector& explicit_paddings, Tensor* output,\n TensorFormat data_format) {\n DCHECK(data_format == FORMAT_NHWC)\n << \"Grouped conv implementation only \"\n \"supports NHWC tensor format for now.\";\n\n const int64_t in_depth = input.dim_size(3);\n const int64_t patch_depth = filter.dim_size(2);\n const int64_t num_groups = in_depth / patch_depth;\n\n // Shuffle input/filter tensors to have group as a leading dimension.\n std::array shuffle({3, 0, 1, 2, 4});\n\n // Compute pre shuffle dimemnsions.\n auto pre_shuffle = [&](const Tensor& tensor) -> std::array {\n return {tensor.dim_size(0), tensor.dim_size(1), tensor.dim_size(2),\n num_groups, tensor.dim_size(3) / num_groups};\n };\n\n // Compute post shuffle dimemnsions.\n auto post_shuffle = [&](const Tensor& tensor) -> std::array {\n return {num_groups, tensor.dim_size(0), tensor.dim_size(1),\n tensor.dim_size(2), tensor.dim_size(3) / num_groups};\n };\n\n auto& device = ctx->eigen_device();\n\n absl::BlockingCounter shuffles_completed(2);\n auto on_shuffled = [&]() { shuffles_completed.DecrementCount(); };\n\n // Shuffle input into temporary tensor.\n Tensor input_shuffled;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_temp(input.dtype(), TensorShape(post_shuffle(input)),\n &input_shuffled));\n input_shuffled.tensor().device(device, on_shuffled) =\n input.shaped(pre_shuffle(input)).shuffle(shuffle);\n\n // Shuffle filter into temporary tensor.\n Tensor filter_shuffled;\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(filter.dtype(),\n TensorShape(post_shuffle(filter)),\n &filter_shuffled));\n filter_shuffled.tensor().device(device, on_shuffled) =\n filter.shaped(pre_shuffle(filter)).shuffle(shuffle);\n\n // Wait for the completion of input/filter shuffles.\n shuffles_completed.Wait();\n\n // Write group convolution results into temporary output tensor.\n Tensor output_shuffled;\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(output->dtype(),\n TensorShape(post_shuffle(*output)),\n &output_shuffled));\n\n for (int64_t i = 0; i < num_groups; ++i) {\n // TODO(ezhulenev): Run this loop using `parallelFor` (regular parallelFor\n // will lead to deadlock, SpatialConvolution has to use async Eigen\n // assignment). This requires small changes to Eigen to support async\n // exeuction for tensor chipping operation.\n\n // TODO(ezhulenev): Grouped convolution should also support 1x1 filter\n // optimization.\n\n auto input_slice = input_shuffled.tensor().template chip<0>(i);\n auto filter_slice = filter_shuffled.tensor().template chip<0>(i);\n auto output_slice = output_shuffled.tensor().template chip<0>(i);\n\n if (padding == EXPLICIT) {\n functor::SpatialConvolution()(\n ctx->eigen_device(), output_slice, input_slice,\n filter_slice, row_stride, col_stride, row_dilation, col_dilation,\n static_cast(explicit_paddings[2]),\n static_cast(explicit_paddings[3]),\n static_cast(explicit_paddings[4]),\n static_cast(explicit_paddings[5]));\n } else {\n functor::SpatialConvolution()(\n ctx->eigen_device(), output_slice, input_slice,\n filter_slice, row_stride, col_stride, row_dilation, col_dilation,\n BrainPadding2EigenPadding(padding));\n }\n }\n\n // Shuffle temporary output back into pre-shuffled shape.\n std::array rev_shuffle({1, 2, 3, 0, 4});\n output->shaped(pre_shuffle(*output)).device(device) =\n output_shuffled.tensor().shuffle(rev_shuffle);\n }", "func_hash": 52476148530312265483336987277784785500, "file_name": "conv_ops.cc", "file_hash": 162425470101834995272420301327894414264, "cwe": ["CWE-354"], "cve": "CVE-2021-41206", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions several TensorFlow operations are missing validation for the shapes of the tensor arguments involved in the call. Depending on the API, this can result in undefined behavior and segfault or `CHECK`-fail related crashes but in some scenarios writes and reads from heap populated arrays are also possible. We have discovered these issues internally via tooling while working on improving/testing GPU op determinism. As such, we don't have reproducers and there will be multiple fixes for these issues. These fixes will be included in TensorFlow 2.7.0. We will also cherrypick these commits on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41206"} {"idx": 195040, "project": "tensorflow", "commit_id": "e21af685e1828f7ca65038307df5cc06de4479e8", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e21af685e1828f7ca65038307df5cc06de4479e8", "commit_message": "Fix Null-pointer dereference in BuildXlaCompilationCache\n\nIf ConfigProto is not used, then use the default settings which is to allow all devices.\n\nPiperOrigin-RevId: 420391800\nChange-Id: I88161ad7042990aef678e77b597a2fb2c8f815be", "target": 1, "func": "Status BuildXlaCompilationCache(DeviceBase* device, FunctionLibraryRuntime* flr,\n const XlaPlatformInfo& platform_info,\n XlaCompilationCache** cache) {\n if (platform_info.xla_device_metadata()) {\n *cache = new XlaCompilationCache(\n platform_info.xla_device_metadata()->client(),\n platform_info.xla_device_metadata()->jit_device_type());\n return Status::OK();\n }\n\n auto platform =\n se::MultiPlatformManager::PlatformWithId(platform_info.platform_id());\n if (!platform.ok()) {\n return platform.status();\n }\n\n StatusOr compiler_for_platform =\n xla::Compiler::GetForPlatform(platform.ValueOrDie());\n if (!compiler_for_platform.ok()) {\n // In some rare cases (usually in unit tests with very small clusters) we\n // may end up transforming an XLA cluster with at least one GPU operation\n // (which would normally force the cluster to be compiled using XLA:GPU)\n // into an XLA cluster with no GPU operations (i.e. containing only CPU\n // operations). Such a cluster can fail compilation (in way that\n // MarkForCompilation could not have detected) if the CPU JIT is not linked\n // in.\n //\n // So bail out of _XlaCompile in this case, and let the executor handle the\n // situation for us.\n const Status& status = compiler_for_platform.status();\n if (status.code() == error::NOT_FOUND) {\n return errors::Unimplemented(\"Could not find compiler for platform \",\n platform.ValueOrDie()->Name(), \": \",\n status.ToString());\n }\n }\n\n xla::LocalClientOptions client_options;\n client_options.set_platform(platform.ValueOrDie());\n client_options.set_intra_op_parallelism_threads(\n device->tensorflow_cpu_worker_threads()->num_threads);\n\n string allowed_gpus =\n flr->config_proto()->gpu_options().visible_device_list();\n TF_ASSIGN_OR_RETURN(absl::optional> gpu_ids,\n ParseVisibleDeviceList(allowed_gpus));\n client_options.set_allowed_devices(gpu_ids);\n\n auto client = xla::ClientLibrary::GetOrCreateLocalClient(client_options);\n if (!client.ok()) {\n return client.status();\n }\n const XlaOpRegistry::DeviceRegistration* registration;\n if (!XlaOpRegistry::GetCompilationDevice(platform_info.device_type().type(),\n ®istration)) {\n return errors::InvalidArgument(\"No JIT device registered for \",\n platform_info.device_type().type());\n }\n *cache = new XlaCompilationCache(\n client.ValueOrDie(), DeviceType(registration->compilation_device_name));\n return Status::OK();\n}", "func_hash": 179065639871904945359341382009364285020, "file_name": "xla_platform_info.cc", "file_hash": 171804916137745205288117058026592469555, "cwe": ["CWE-476"], "cve": "CVE-2022-23595", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. When building an XLA compilation cache, if default settings are used, TensorFlow triggers a null pointer dereference. In the default scenario, all devices are allowed, so `flr->config_proto` is `nullptr`. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23595"} {"idx": 220463, "project": "tensorflow", "commit_id": "e21af685e1828f7ca65038307df5cc06de4479e8", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e21af685e1828f7ca65038307df5cc06de4479e8", "commit_message": "Fix Null-pointer dereference in BuildXlaCompilationCache\n\nIf ConfigProto is not used, then use the default settings which is to allow all devices.\n\nPiperOrigin-RevId: 420391800\nChange-Id: I88161ad7042990aef678e77b597a2fb2c8f815be", "target": 0, "func": "Status BuildXlaCompilationCache(DeviceBase* device, FunctionLibraryRuntime* flr,\n const XlaPlatformInfo& platform_info,\n XlaCompilationCache** cache) {\n if (platform_info.xla_device_metadata()) {\n *cache = new XlaCompilationCache(\n platform_info.xla_device_metadata()->client(),\n platform_info.xla_device_metadata()->jit_device_type());\n return Status::OK();\n }\n\n auto platform =\n se::MultiPlatformManager::PlatformWithId(platform_info.platform_id());\n if (!platform.ok()) {\n return platform.status();\n }\n\n StatusOr compiler_for_platform =\n xla::Compiler::GetForPlatform(platform.ValueOrDie());\n if (!compiler_for_platform.ok()) {\n // In some rare cases (usually in unit tests with very small clusters) we\n // may end up transforming an XLA cluster with at least one GPU operation\n // (which would normally force the cluster to be compiled using XLA:GPU)\n // into an XLA cluster with no GPU operations (i.e. containing only CPU\n // operations). Such a cluster can fail compilation (in way that\n // MarkForCompilation could not have detected) if the CPU JIT is not linked\n // in.\n //\n // So bail out of _XlaCompile in this case, and let the executor handle the\n // situation for us.\n const Status& status = compiler_for_platform.status();\n if (status.code() == error::NOT_FOUND) {\n return errors::Unimplemented(\"Could not find compiler for platform \",\n platform.ValueOrDie()->Name(), \": \",\n status.ToString());\n }\n }\n\n xla::LocalClientOptions client_options;\n client_options.set_platform(platform.ValueOrDie());\n client_options.set_intra_op_parallelism_threads(\n device->tensorflow_cpu_worker_threads()->num_threads);\n\n if (flr->config_proto()) {\n string allowed_gpus =\n flr->config_proto()->gpu_options().visible_device_list();\n TF_ASSIGN_OR_RETURN(absl::optional> gpu_ids,\n ParseVisibleDeviceList(allowed_gpus));\n client_options.set_allowed_devices(gpu_ids);\n }\n\n auto client = xla::ClientLibrary::GetOrCreateLocalClient(client_options);\n if (!client.ok()) {\n return client.status();\n }\n const XlaOpRegistry::DeviceRegistration* registration;\n if (!XlaOpRegistry::GetCompilationDevice(platform_info.device_type().type(),\n ®istration)) {\n return errors::InvalidArgument(\"No JIT device registered for \",\n platform_info.device_type().type());\n }\n *cache = new XlaCompilationCache(\n client.ValueOrDie(), DeviceType(registration->compilation_device_name));\n return Status::OK();\n}", "func_hash": 150487232572114145456611052017035566512, "file_name": "xla_platform_info.cc", "file_hash": 318276067980065095571736754899104138947, "cwe": ["CWE-476"], "cve": "CVE-2022-23595", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. When building an XLA compilation cache, if default settings are used, TensorFlow triggers a null pointer dereference. In the default scenario, all devices are allowed, so `flr->config_proto` is `nullptr`. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23595"} {"idx": 195055, "project": "tensorflow", "commit_id": "2b7100d6cdff36aa21010a82269bc05a6d1cc74a", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/2b7100d6cdff36aa21010a82269bc05a6d1cc74a", "commit_message": "Cleanup and remove duplicate validation in `SparseCount`.\n\nWe have valdiation that is duplicated, checking different conditions, in different formats and failing to capture all cases. This should fix all the previous bugs.\n\nPiperOrigin-RevId: 414886981\nChange-Id: Ibf0bba0beb057b76d505324bb9487565daf95f01", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& indices = context->input(0);\n const Tensor& values = context->input(1);\n const Tensor& shape = context->input(2);\n const Tensor& weights = context->input(3);\n bool use_weights = weights.NumElements() > 0;\n\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices.shape()),\n errors::InvalidArgument(\n \"Input indices must be a 2-dimensional tensor. Got: \",\n indices.shape().DebugString()));\n\n if (use_weights) {\n OP_REQUIRES(\n context, weights.shape() == values.shape(),\n errors::InvalidArgument(\n \"Weights and values must have the same shape. Weight shape: \",\n weights.shape().DebugString(),\n \"; values shape: \", values.shape().DebugString()));\n }\n\n OP_REQUIRES(context, shape.NumElements() != 0,\n errors::InvalidArgument(\n \"The shape argument requires at least one element.\"));\n\n bool is_1d = shape.NumElements() == 1;\n auto shape_vector = shape.flat();\n int num_batches = is_1d ? 1 : shape_vector(0);\n int num_values = values.NumElements();\n\n for (int b = 0; b < shape_vector.size(); b++) {\n OP_REQUIRES(context, shape_vector(b) >= 0,\n errors::InvalidArgument(\n \"Elements in dense_shape must be >= 0. Instead got:\",\n shape.DebugString()));\n }\n\n OP_REQUIRES(context, num_values == indices.shape().dim_size(0),\n errors::InvalidArgument(\n \"Number of values must match first dimension of indices.\",\n \"Got \", num_values,\n \" values, indices shape: \", indices.shape().DebugString()));\n\n const auto indices_values = indices.matrix();\n const auto values_values = values.flat();\n const auto weight_values = weights.flat();\n\n auto per_batch_counts = BatchedMap(num_batches);\n\n T max_value = 0;\n\n OP_REQUIRES(context, num_values <= indices.shape().dim_size(0),\n errors::InvalidArgument(\n \"The first dimension of indices must be equal to or \"\n \"greather than number of values. ( \",\n indices.shape().dim_size(0), \" vs. \", num_values, \" )\"));\n OP_REQUIRES(context, indices.shape().dim_size(1) > 0,\n errors::InvalidArgument(\"The second dimension of indices must \"\n \"be greater than 0. Received: \",\n indices.shape().dim_size(1)));\n\n for (int idx = 0; idx < num_values; ++idx) {\n int batch = is_1d ? 0 : indices_values(idx, 0);\n if (batch >= num_batches) {\n OP_REQUIRES(context, batch < num_batches,\n errors::InvalidArgument(\n \"Indices value along the first dimension must be \",\n \"lower than the first index of the shape.\", \"Got \",\n batch, \" as batch and \", num_batches,\n \" as the first dimension of the shape.\"));\n }\n const auto& value = values_values(idx);\n if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) {\n if (binary_output_) {\n per_batch_counts[batch][value] = 1;\n } else if (use_weights) {\n per_batch_counts[batch][value] += weight_values(idx);\n } else {\n per_batch_counts[batch][value]++;\n }\n if (value > max_value) {\n max_value = value;\n }\n }\n }\n\n int num_output_values = GetOutputSize(max_value, maxlength_, minlength_);\n OP_REQUIRES_OK(context, OutputSparse(per_batch_counts, num_output_values,\n is_1d, context));\n }", "func_hash": 115744370413617881150207979427400512016, "file_name": "count_ops.cc", "file_hash": 290832582717285970119064032382621433475, "cwe": ["CWE-787"], "cve": "CVE-2022-21740", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `SparseCountSparseOutput` is vulnerable to a heap overflow. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21740"} {"idx": 220804, "project": "tensorflow", "commit_id": "2b7100d6cdff36aa21010a82269bc05a6d1cc74a", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/2b7100d6cdff36aa21010a82269bc05a6d1cc74a", "commit_message": "Cleanup and remove duplicate validation in `SparseCount`.\n\nWe have valdiation that is duplicated, checking different conditions, in different formats and failing to capture all cases. This should fix all the previous bugs.\n\nPiperOrigin-RevId: 414886981\nChange-Id: Ibf0bba0beb057b76d505324bb9487565daf95f01", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& splits = context->input(0);\n const Tensor& values = context->input(1);\n const Tensor& weights = context->input(2);\n bool use_weights = weights.NumElements() > 0;\n bool is_1d = false;\n\n if (use_weights) {\n OP_REQUIRES(\n context, weights.shape() == values.shape(),\n errors::InvalidArgument(\n \"Weights and values must have the same shape. Weight shape: \",\n weights.shape().DebugString(),\n \"; values shape: \", values.shape().DebugString()));\n }\n\n const auto splits_values = splits.flat();\n const auto values_values = values.flat();\n const auto weight_values = weights.flat();\n int num_batches = splits.NumElements() - 1;\n int num_values = values.NumElements();\n\n OP_REQUIRES(\n context, num_batches > 0,\n errors::InvalidArgument(\n \"Must provide at least 2 elements for the splits argument\"));\n OP_REQUIRES(context, splits_values(0) == 0,\n errors::InvalidArgument(\"Splits must start with 0, not with \",\n splits_values(0)));\n OP_REQUIRES(context, splits_values(num_batches) == num_values,\n errors::InvalidArgument(\n \"Splits must end with the number of values, got \",\n splits_values(num_batches), \" instead of \", num_values));\n\n auto per_batch_counts = BatchedMap(num_batches);\n T max_value = 0;\n int batch_idx = 0;\n\n for (int idx = 0; idx < num_values; ++idx) {\n while (idx >= splits_values(batch_idx)) {\n batch_idx++;\n }\n const auto& value = values_values(idx);\n if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) {\n if (binary_output_) {\n per_batch_counts[batch_idx - 1][value] = 1;\n } else if (use_weights) {\n per_batch_counts[batch_idx - 1][value] += weight_values(idx);\n } else {\n per_batch_counts[batch_idx - 1][value]++;\n }\n if (value > max_value) {\n max_value = value;\n }\n }\n }\n\n int num_output_values = GetOutputSize(max_value, maxlength_, minlength_);\n OP_REQUIRES_OK(context, OutputSparse(per_batch_counts, num_output_values,\n is_1d, context));\n }", "func_hash": 321329284400462468105618833406255634390, "file_name": "count_ops.cc", "file_hash": 221778566959720819887290009238961995785, "cwe": ["CWE-787"], "cve": "CVE-2022-21740", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `SparseCountSparseOutput` is vulnerable to a heap overflow. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21740"} {"idx": 195056, "project": "tensorflow", "commit_id": "8c6f391a2282684a25cbfec7687bd5d35261a209", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/8c6f391a2282684a25cbfec7687bd5d35261a209", "commit_message": "[lite] Add check for bias_size is zero to avoid division by zero. This shouldn't happen for properly converted models. Just safety check\n\nPiperOrigin-RevId: 416383645\nChange-Id: If8e508bf696ae8ecfb927e69c139a8ccf7fe60cb", "target": 1, "func": "inline void BiasAndClamp(float clamp_min, float clamp_max, int bias_size,\n const float* bias_data, int array_size,\n float* array_data) {\n // Note: see b/132215220: in May 2019 we thought it would be OK to replace\n // this with the Eigen one-liner:\n // return (array.colwise() + bias).cwiseMin(clamp_max).cwiseMin(clamp_max).\n // This turned out to severely regress performance: +4ms (i.e. 8%) on\n // MobileNet v2 / 1.0 / 224. So we keep custom NEON code for now.\n TFLITE_DCHECK_EQ((array_size % bias_size), 0);\n#ifdef USE_NEON\n float* array_ptr = array_data;\n float* array_end_ptr = array_ptr + array_size;\n const auto clamp_min_vec = vdupq_n_f32(clamp_min);\n const auto clamp_max_vec = vdupq_n_f32(clamp_max);\n for (; array_ptr != array_end_ptr; array_ptr += bias_size) {\n int i = 0;\n for (; i <= bias_size - 16; i += 16) {\n auto b0 = vld1q_f32(bias_data + i);\n auto b1 = vld1q_f32(bias_data + i + 4);\n auto b2 = vld1q_f32(bias_data + i + 8);\n auto b3 = vld1q_f32(bias_data + i + 12);\n auto a0 = vld1q_f32(array_ptr + i);\n auto a1 = vld1q_f32(array_ptr + i + 4);\n auto a2 = vld1q_f32(array_ptr + i + 8);\n auto a3 = vld1q_f32(array_ptr + i + 12);\n auto x0 = vaddq_f32(a0, b0);\n auto x1 = vaddq_f32(a1, b1);\n auto x2 = vaddq_f32(a2, b2);\n auto x3 = vaddq_f32(a3, b3);\n x0 = vmaxq_f32(clamp_min_vec, x0);\n x1 = vmaxq_f32(clamp_min_vec, x1);\n x2 = vmaxq_f32(clamp_min_vec, x2);\n x3 = vmaxq_f32(clamp_min_vec, x3);\n x0 = vminq_f32(clamp_max_vec, x0);\n x1 = vminq_f32(clamp_max_vec, x1);\n x2 = vminq_f32(clamp_max_vec, x2);\n x3 = vminq_f32(clamp_max_vec, x3);\n vst1q_f32(array_ptr + i, x0);\n vst1q_f32(array_ptr + i + 4, x1);\n vst1q_f32(array_ptr + i + 8, x2);\n vst1q_f32(array_ptr + i + 12, x3);\n }\n for (; i <= bias_size - 4; i += 4) {\n auto b = vld1q_f32(bias_data + i);\n auto a = vld1q_f32(array_ptr + i);\n auto x = vaddq_f32(a, b);\n x = vmaxq_f32(clamp_min_vec, x);\n x = vminq_f32(clamp_max_vec, x);\n vst1q_f32(array_ptr + i, x);\n }\n for (; i < bias_size; i++) {\n array_ptr[i] = ActivationFunctionWithMinMax(array_ptr[i] + bias_data[i],\n clamp_min, clamp_max);\n }\n }\n#else // not NEON\n for (int array_offset = 0; array_offset < array_size;\n array_offset += bias_size) {\n for (int i = 0; i < bias_size; i++) {\n array_data[array_offset + i] = ActivationFunctionWithMinMax(\n array_data[array_offset + i] + bias_data[i], clamp_min, clamp_max);\n }\n }\n#endif\n}", "func_hash": 154263320578941255259441922880599149557, "file_name": "common.h", "file_hash": 11373796702176609664888229687660280569, "cwe": ["CWE-369"], "cve": "CVE-2022-23557", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. An attacker can craft a TFLite model that would trigger a division by zero in `BiasAndClamp` implementation. There is no check that the `bias_size` is non zero. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23557"} {"idx": 220841, "project": "tensorflow", "commit_id": "8c6f391a2282684a25cbfec7687bd5d35261a209", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/8c6f391a2282684a25cbfec7687bd5d35261a209", "commit_message": "[lite] Add check for bias_size is zero to avoid division by zero. This shouldn't happen for properly converted models. Just safety check\n\nPiperOrigin-RevId: 416383645\nChange-Id: If8e508bf696ae8ecfb927e69c139a8ccf7fe60cb", "target": 0, "func": "inline void BiasAndClamp(float clamp_min, float clamp_max, int bias_size,\n const float* bias_data, int array_size,\n float* array_data) {\n if (bias_size == 0) return;\n // Note: see b/132215220: in May 2019 we thought it would be OK to replace\n // this with the Eigen one-liner:\n // return (array.colwise() + bias).cwiseMin(clamp_max).cwiseMin(clamp_max).\n // This turned out to severely regress performance: +4ms (i.e. 8%) on\n // MobileNet v2 / 1.0 / 224. So we keep custom NEON code for now.\n TFLITE_DCHECK_EQ((array_size % bias_size), 0);\n#ifdef USE_NEON\n float* array_ptr = array_data;\n float* array_end_ptr = array_ptr + array_size;\n const auto clamp_min_vec = vdupq_n_f32(clamp_min);\n const auto clamp_max_vec = vdupq_n_f32(clamp_max);\n for (; array_ptr != array_end_ptr; array_ptr += bias_size) {\n int i = 0;\n for (; i <= bias_size - 16; i += 16) {\n auto b0 = vld1q_f32(bias_data + i);\n auto b1 = vld1q_f32(bias_data + i + 4);\n auto b2 = vld1q_f32(bias_data + i + 8);\n auto b3 = vld1q_f32(bias_data + i + 12);\n auto a0 = vld1q_f32(array_ptr + i);\n auto a1 = vld1q_f32(array_ptr + i + 4);\n auto a2 = vld1q_f32(array_ptr + i + 8);\n auto a3 = vld1q_f32(array_ptr + i + 12);\n auto x0 = vaddq_f32(a0, b0);\n auto x1 = vaddq_f32(a1, b1);\n auto x2 = vaddq_f32(a2, b2);\n auto x3 = vaddq_f32(a3, b3);\n x0 = vmaxq_f32(clamp_min_vec, x0);\n x1 = vmaxq_f32(clamp_min_vec, x1);\n x2 = vmaxq_f32(clamp_min_vec, x2);\n x3 = vmaxq_f32(clamp_min_vec, x3);\n x0 = vminq_f32(clamp_max_vec, x0);\n x1 = vminq_f32(clamp_max_vec, x1);\n x2 = vminq_f32(clamp_max_vec, x2);\n x3 = vminq_f32(clamp_max_vec, x3);\n vst1q_f32(array_ptr + i, x0);\n vst1q_f32(array_ptr + i + 4, x1);\n vst1q_f32(array_ptr + i + 8, x2);\n vst1q_f32(array_ptr + i + 12, x3);\n }\n for (; i <= bias_size - 4; i += 4) {\n auto b = vld1q_f32(bias_data + i);\n auto a = vld1q_f32(array_ptr + i);\n auto x = vaddq_f32(a, b);\n x = vmaxq_f32(clamp_min_vec, x);\n x = vminq_f32(clamp_max_vec, x);\n vst1q_f32(array_ptr + i, x);\n }\n for (; i < bias_size; i++) {\n array_ptr[i] = ActivationFunctionWithMinMax(array_ptr[i] + bias_data[i],\n clamp_min, clamp_max);\n }\n }\n#else // not NEON\n for (int array_offset = 0; array_offset < array_size;\n array_offset += bias_size) {\n for (int i = 0; i < bias_size; i++) {\n array_data[array_offset + i] = ActivationFunctionWithMinMax(\n array_data[array_offset + i] + bias_data[i], clamp_min, clamp_max);\n }\n }\n#endif\n}", "func_hash": 163406073569204971648641083480315438791, "file_name": "common.h", "file_hash": 206010119069068373550820723284960883967, "cwe": ["CWE-369"], "cve": "CVE-2022-23557", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. An attacker can craft a TFLite model that would trigger a division by zero in `BiasAndClamp` implementation. There is no check that the `bias_size` is non zero. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23557"} {"idx": 195059, "project": "tensorflow", "commit_id": "92dba16749fae36c246bec3f9ba474d9ddeb7662", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/92dba16749fae36c246bec3f9ba474d9ddeb7662", "commit_message": "Prevent a null-pointer dereference / `CHECK`-fail in grappler.\n\nPiperOrigin-RevId: 409187354\nChange-Id: I369c249cca32e6c56ec193f0ebbf2f2768fc7d43", "target": 1, "func": "bool DependencyOptimizer::SafeToRemoveIdentity(const NodeDef& node) const {\n if (!IsIdentity(node) && !IsIdentityN(node)) {\n return true;\n }\n\n if (nodes_to_preserve_.find(node.name()) != nodes_to_preserve_.end()) {\n return false;\n }\n if (!fetch_nodes_known_) {\n // The output values of this node may be needed.\n return false;\n }\n\n if (node.input_size() < 1) {\n // Node lacks input, is invalid\n return false;\n }\n\n const NodeDef* input = node_map_->GetNode(NodeName(node.input(0)));\n CHECK(input != nullptr) << \"node = \" << node.name()\n << \" input = \" << node.input(0);\n // Don't remove Identity nodes corresponding to Variable reads or following\n // Recv.\n if (IsVariable(*input) || IsRecv(*input)) {\n return false;\n }\n for (const auto& consumer : node_map_->GetOutputs(node.name())) {\n if (node.input_size() > 1 && (IsRetval(*consumer) || IsMerge(*consumer))) {\n return false;\n }\n if (IsSwitch(*input)) {\n for (const string& consumer_input : consumer->input()) {\n if (consumer_input == AsControlDependency(node.name())) {\n return false;\n }\n }\n }\n }\n return true;\n}", "func_hash": 61147310262209694276783937154772465535, "file_name": "dependency_optimizer.cc", "file_hash": 98916752340112642333125918775752240620, "cwe": ["CWE-617"], "cve": "CVE-2022-23579", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The Grappler optimizer in TensorFlow can be used to cause a denial of service by altering a `SavedModel` such that `SafeToRemoveIdentity` would trigger `CHECK` failures. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23579"} {"idx": 220909, "project": "tensorflow", "commit_id": "92dba16749fae36c246bec3f9ba474d9ddeb7662", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/92dba16749fae36c246bec3f9ba474d9ddeb7662", "commit_message": "Prevent a null-pointer dereference / `CHECK`-fail in grappler.\n\nPiperOrigin-RevId: 409187354\nChange-Id: I369c249cca32e6c56ec193f0ebbf2f2768fc7d43", "target": 0, "func": "bool DependencyOptimizer::SafeToRemoveIdentity(const NodeDef& node) const {\n if (!IsIdentity(node) && !IsIdentityN(node)) {\n return true;\n }\n\n if (nodes_to_preserve_.find(node.name()) != nodes_to_preserve_.end()) {\n return false;\n }\n if (!fetch_nodes_known_) {\n // The output values of this node may be needed.\n return false;\n }\n\n if (node.input_size() < 1) {\n // Node lacks input, is invalid\n return false;\n }\n\n const NodeDef* input = node_map_->GetNode(NodeName(node.input(0)));\n if (input == nullptr) {\n VLOG(1) << \"node = \" << node.name() << \" input = \" << node.input(0);\n return false;\n }\n // Don't remove Identity nodes corresponding to Variable reads or following\n // Recv.\n if (IsVariable(*input) || IsRecv(*input)) {\n return false;\n }\n for (const auto& consumer : node_map_->GetOutputs(node.name())) {\n if (node.input_size() > 1 && (IsRetval(*consumer) || IsMerge(*consumer))) {\n return false;\n }\n if (IsSwitch(*input)) {\n for (const string& consumer_input : consumer->input()) {\n if (consumer_input == AsControlDependency(node.name())) {\n return false;\n }\n }\n }\n }\n return true;\n}", "func_hash": 223351651745564626611627672045490996261, "file_name": "None", "file_hash": null, "cwe": ["CWE-617"], "cve": "CVE-2022-23579", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The Grappler optimizer in TensorFlow can be used to cause a denial of service by altering a `SavedModel` such that `SafeToRemoveIdentity` would trigger `CHECK` failures. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23579"} {"idx": 195063, "project": "gpac", "commit_id": "5f2c2a16d30229b6241f02fa28e3d6b810d64858", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/5f2c2a16d30229b6241f02fa28e3d6b810d64858", "commit_message": "fixed #1905", "target": 1, "func": "GF_Err mpgviddmx_process(GF_Filter *filter)\n{\n\tGF_MPGVidDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck, *dst_pck;\n\tu64 byte_offset;\n\ts64 vosh_start = -1;\n\ts64 vosh_end = -1;\n\tGF_Err e;\n\tchar *data;\n\tu8 *start;\n\tu32 pck_size;\n\ts32 remain;\n\n\t//always reparse duration\n\tif (!ctx->duration.num)\n\t\tmpgviddmx_check_dur(filter, ctx);\n\n\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tmpgviddmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE, GF_TRUE);\n\t\t\tif (ctx->opid)\n\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\tctx->src_pck = NULL;\n\t\t\treturn GF_EOS;\n\t\t}\n\t\treturn GF_OK;\n\t}\n\n\tdata = (char *) gf_filter_pck_get_data(pck, &pck_size);\n\tbyte_offset = gf_filter_pck_get_byte_offset(pck);\n\n\tstart = data;\n\tremain = pck_size;\n\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (!ctx->resume_from && ctx->timescale) {\n\t\tu64 ts = gf_filter_pck_get_cts(pck);\n\t\tif (ts != GF_FILTER_NO_TS) {\n\t\t\tif (!ctx->cts || !ctx->recompute_cts)\n\t\t\t\tctx->cts = ts;\n\t\t}\n\t\tts = gf_filter_pck_get_dts(pck);\n\t\tif (ts != GF_FILTER_NO_TS) {\n\t\t\tif (!ctx->dts || !ctx->recompute_cts)\n\t\t\t\tctx->dts = ts;\n\n\t\t\tif (!ctx->prev_dts) ctx->prev_dts = ts;\n\t\t\telse if (ctx->prev_dts != ts) {\n\t\t\t\tu64 diff = ts;\n\t\t\t\tdiff -= ctx->prev_dts;\n\t\t\t\tif (!ctx->cur_fps.den) ctx->cur_fps.den = (u32) diff;\n\t\t\t\telse if (ctx->cur_fps.den > diff)\n\t\t\t\t\tctx->cur_fps.den = (u32) diff;\n\t\t\t}\n\t\t}\n\t\tgf_filter_pck_get_framing(pck, &ctx->input_is_au_start, &ctx->input_is_au_end);\n\t\t//this will force CTS recomput of each frame\n\t\tif (ctx->recompute_cts) ctx->input_is_au_start = GF_FALSE;\n\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\tctx->src_pck = pck;\n\t\tgf_filter_pck_ref_props(&ctx->src_pck);\n\t}\n\n\t//we stored some data to find the complete vosh, aggregate this packet with current one\n\tif (!ctx->resume_from && ctx->hdr_store_size) {\n\t\tif (ctx->hdr_store_alloc < ctx->hdr_store_size + pck_size) {\n\t\t\tctx->hdr_store_alloc = ctx->hdr_store_size + pck_size;\n\t\t\tctx->hdr_store = gf_realloc(ctx->hdr_store, sizeof(char)*ctx->hdr_store_alloc);\n\t\t}\n\t\tmemcpy(ctx->hdr_store + ctx->hdr_store_size, data, sizeof(char)*pck_size);\n\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\tif (byte_offset >= ctx->hdr_store_size)\n\t\t\t\tbyte_offset -= ctx->hdr_store_size;\n\t\t\telse\n\t\t\t\tbyte_offset = GF_FILTER_NO_BO;\n\t\t}\n\t\tctx->hdr_store_size += pck_size;\n\t\tstart = data = ctx->hdr_store;\n\t\tremain = pck_size = ctx->hdr_store_size;\n\t}\n\n\tif (ctx->resume_from) {\n\t\tif (gf_filter_pid_would_block(ctx->opid))\n\t\t\treturn GF_OK;\n\n\t\t//resume from data copied internally\n\t\tif (ctx->hdr_store_size) {\n\t\t\tassert(ctx->resume_from <= ctx->hdr_store_size);\n\t\t\tstart = data = ctx->hdr_store + ctx->resume_from;\n\t\t\tremain = pck_size = ctx->hdr_store_size - ctx->resume_from;\n\t\t} else {\n\t\t\tassert(remain >= (s32) ctx->resume_from);\n\t\t\tstart += ctx->resume_from;\n\t\t\tremain -= ctx->resume_from;\n\t\t}\n\t\tctx->resume_from = 0;\n\t}\n\n\tif (!ctx->bs) {\n\t\tctx->bs = gf_bs_new(start, remain, GF_BITSTREAM_READ);\n\t} else {\n\t\tgf_bs_reassign_buffer(ctx->bs, start, remain);\n\t}\n\tif (!ctx->vparser) {\n\t\tctx->vparser = gf_m4v_parser_bs_new(ctx->bs, ctx->is_mpg12);\n\t}\n\n\n\twhile (remain) {\n\t\tBool full_frame;\n\t\tu8 *pck_data;\n\t\ts32 current;\n\t\tu8 sc_type, forced_sc_type=0;\n\t\tBool sc_type_forced = GF_FALSE;\n\t\tBool skip_pck = GF_FALSE;\n\t\tu8 ftype;\n\t\tu32 tinc;\n\t\tu64 size=0;\n\t\tu64 fstart;\n\t\tBool is_coded;\n\t\tu32 bytes_from_store = 0;\n\t\tu32 hdr_offset = 0;\n\t\tBool copy_last_bytes = GF_FALSE;\n\n\t\t//not enough bytes to parse start code\n\t\tif (remain<5) {\n\t\t\tmemcpy(ctx->hdr_store, start, remain);\n\t\t\tctx->bytes_in_header = remain;\n\t\t\tbreak;\n\t\t}\n\t\tcurrent = -1;\n\n\t\t//we have some potential bytes of a start code in the store, copy some more bytes and check if valid start code.\n\t\t//if not, dispatch these bytes as continuation of the data\n\t\tif (ctx->bytes_in_header) {\n\n\t\t\tmemcpy(ctx->hdr_store + ctx->bytes_in_header, start, 8 - ctx->bytes_in_header);\n\t\t\tcurrent = mpgviddmx_next_start_code(ctx->hdr_store, 8);\n\n\t\t\t//no start code in stored buffer\n\t\t\tif ((current<0) || (current >= (s32) ctx->bytes_in_header) ) {\n\t\t\t\tif (ctx->opid) {\n\t\t\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, ctx->bytes_in_header, &pck_data);\n\t\t\t\t\tif (!dst_pck) return GF_OUT_OF_MEM;\n\n\t\t\t\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);\n\t\t\t\t\tgf_filter_pck_set_cts(dst_pck, GF_FILTER_NO_TS);\n\t\t\t\t\tgf_filter_pck_set_dts(dst_pck, GF_FILTER_NO_TS);\n\t\t\t\t\tmemcpy(pck_data, ctx->hdr_store, ctx->bytes_in_header);\n\t\t\t\t\tgf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_FALSE);\n\n\t\t\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, byte_offset - ctx->bytes_in_header);\n\t\t\t\t\t}\n\n\t\t\t\t\tmpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE);\n\t\t\t\t}\n\n\t\t\t\tif (current<0) current = -1;\n\t\t\t\telse current -= ctx->bytes_in_header;\n\t\t\t\tctx->bytes_in_header = 0;\n\t\t\t} else {\n\t\t\t\t//we have a valid start code, check which byte in our store or in the packet payload is the start code type\n\t\t\t\t//and remember its location to reinit the parser from there\n\t\t\t\thdr_offset = 4 - ctx->bytes_in_header + current;\n\t\t\t\t//bytes still to dispatch\n\t\t\t\tbytes_from_store = ctx->bytes_in_header;\n\t\t\t\tctx->bytes_in_header = 0;\n\t\t\t\tif (!hdr_offset) {\n\t\t\t\t\tforced_sc_type = ctx->hdr_store[current+3];\n\t\t\t\t} else {\n\t\t\t\t\tforced_sc_type = start[hdr_offset-1];\n\t\t\t\t}\n\t\t\t\tsc_type_forced = GF_TRUE;\n\t\t\t}\n\t\t}\n\t\t//no starcode in store, look for startcode in packet\n\t\tif (current == -1) {\n\t\t\t//locate next start code\n\t\t\tcurrent = mpgviddmx_next_start_code(start, remain);\n\t\t\t//no start code, dispatch the block\n\t\t\tif (current<0) {\n\t\t\t\tu8 b3, b2, b1;\n\t\t\t\tif (! ctx->frame_started) {\n\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_MEDIA, (\"[MPGVid] no start code in block and no frame started, discarding data\\n\" ));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsize = remain;\n\t\t\t\tb3 = start[remain-3];\n\t\t\t\tb2 = start[remain-2];\n\t\t\t\tb1 = start[remain-1];\n\t\t\t\t//we may have a startcode at the end of the packet, store it and don't dispatch the last 3 bytes !\n\t\t\t\tif (!b1 || !b2 || !b3) {\n\t\t\t\t\tcopy_last_bytes = GF_TRUE;\n\t\t\t\t\tassert(size >= 3);\n\t\t\t\t\tsize -= 3;\n\t\t\t\t\tctx->bytes_in_header = 3;\n\t\t\t\t}\n\n\t\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, (u32) size, &pck_data);\n\t\t\t\tif (!dst_pck) return GF_OUT_OF_MEM;\n\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);\n\t\t\t\tmemcpy(pck_data, start, (size_t) size);\n\t\t\t\tgf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_FALSE);\n\t\t\t\tgf_filter_pck_set_cts(dst_pck, GF_FILTER_NO_TS);\n\t\t\t\tgf_filter_pck_set_dts(dst_pck, GF_FILTER_NO_TS);\n\n\t\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, byte_offset);\n\t\t\t\t}\n\n\t\t\t\tmpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE);\n\t\t\t\tif (copy_last_bytes) {\n\t\t\t\t\tmemcpy(ctx->hdr_store, start+remain-3, 3);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tassert(current>=0);\n\n\t\t//if we are in the middle of parsing the vosh, skip over bytes remaining from previous obj not parsed\n\t\tif ((vosh_start>=0) && current) {\n\t\t\tassert(remain>=current);\n\t\t\tstart += current;\n\t\t\tremain -= current;\n\t\t\tcurrent = 0;\n\t\t}\n\t\t//also skip if no output pid\n\t\tif (!ctx->opid && current) {\n\t\t\tassert(remain>=current);\n\t\t\tstart += current;\n\t\t\tremain -= current;\n\t\t\tcurrent = 0;\n\t\t}\n\t\t//dispatch remaining bytes\n\t\tif (current>0) {\n\t\t\t//flush remaining\n\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, current, &pck_data);\n\t\t\tif (!dst_pck) return GF_OUT_OF_MEM;\n\n\t\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);\n\t\t\tgf_filter_pck_set_cts(dst_pck, GF_FILTER_NO_TS);\n\t\t\tgf_filter_pck_set_dts(dst_pck, GF_FILTER_NO_TS);\n\t\t\tgf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_TRUE);\n\t\t\t//bytes were partly in store, partly in packet\n\t\t\tif (bytes_from_store) {\n\t\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, byte_offset - bytes_from_store);\n\t\t\t\t}\n\t\t\t\tassert(bytes_from_store>=(u32) current);\n\t\t\t\tbytes_from_store -= current;\n\t\t\t\tmemcpy(pck_data, ctx->hdr_store, current);\n\t\t\t} else {\n\t\t\t\t//bytes were only in packet\n\t\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, byte_offset);\n\t\t\t\t}\n\t\t\t\tmemcpy(pck_data, start, current);\n\t\t\t\tassert(remain>=current);\n\t\t\t\tstart += current;\n\t\t\t\tremain -= current;\n\t\t\t\tcurrent = 0;\n\t\t\t}\n\t\t\tgf_filter_pck_set_carousel_version(dst_pck, 1);\n\n\t\t\tmpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE);\n\t\t}\n\n\t\t//parse headers\n\n\t\t//we have a start code loaded, eg the data packet does not have a full start code at the beginning\n\t\tif (sc_type_forced) {\n\t\t\tgf_bs_reassign_buffer(ctx->bs, start + hdr_offset, remain - hdr_offset);\n\t\t\tsc_type = forced_sc_type;\n\t\t} else {\n\t\t\tgf_bs_reassign_buffer(ctx->bs, start, remain);\n\t\t\tgf_bs_read_int(ctx->bs, 24);\n\t\t\tsc_type = gf_bs_read_int(ctx->bs, 8);\n\t\t}\n\n\t\tif (ctx->is_mpg12) {\n\t\t\tswitch (sc_type) {\n\t\t\tcase M2V_SEQ_START_CODE:\n\t\t\tcase M2V_EXT_START_CODE:\n\t\t\t\tgf_bs_reassign_buffer(ctx->bs, start, remain);\n\t\t\t\te = gf_m4v_parse_config(ctx->vparser, &ctx->dsi);\n\t\t\t\t//not enough data, accumulate until we can parse the full header\n\t\t\t\tif (e==GF_EOS) {\n\t\t\t\t\tif (vosh_start<0) vosh_start = 0;\n\t\t\t\t\tif (data == ctx->hdr_store) {\n\t\t\t\t\t\tmemmove(ctx->hdr_store, start, remain);\n\t\t\t\t\t\tctx->hdr_store_size = remain;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (ctx->hdr_store_alloc < ctx->hdr_store_size + pck_size - vosh_start) {\n\t\t\t\t\t\t\tctx->hdr_store_alloc = (u32) (ctx->hdr_store_size + pck_size - vosh_start);\n\t\t\t\t\t\t\tctx->hdr_store = gf_realloc(ctx->hdr_store, sizeof(char)*ctx->hdr_store_alloc);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmemcpy(ctx->hdr_store + ctx->hdr_store_size, data + vosh_start, (size_t) (pck_size - vosh_start) );\n\t\t\t\t\t\tctx->hdr_store_size += pck_size - (u32) vosh_start;\n\t\t\t\t\t}\n\t\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t} else if (e != GF_OK) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_MEDIA, (\"[MPGVid] Failed to parse VOS header: %s\\n\", gf_error_to_string(e) ));\n\t\t\t\t} else {\n\t\t\t\t\tmpgviddmx_check_pid(filter, ctx, 0, NULL);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase M2V_PIC_START_CODE:\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t} else {\n\t\t\tu8 PL;\n\t\t\tswitch (sc_type) {\n\t\t\tcase M4V_VOS_START_CODE:\n\t\t\t\tctx->dsi.VideoPL = (u8) gf_bs_read_u8(ctx->bs);\n\t\t\t\tvosh_start = start - (u8 *)data;\n\t\t\t\tskip_pck = GF_TRUE;\n\t\t\t\tassert(remain>=5);\n\t\t\t\tstart += 5;\n\t\t\t\tremain -= 5;\n\t\t\t\tbreak;\n\t\t\tcase M4V_VOL_START_CODE:\n\t\t\t\tgf_bs_reassign_buffer(ctx->bs, start, remain);\n\t\t\t\tPL = ctx->dsi.VideoPL;\n\t\t\t\te = gf_m4v_parse_config(ctx->vparser, &ctx->dsi);\n\t\t\t\tctx->dsi.VideoPL = PL;\n\t\t\t\t//not enough data, accumulate until we can parse the full header\n\t\t\t\tif (e==GF_EOS) {\n\t\t\t\t\tif (vosh_start<0) vosh_start = 0;\n\t\t\t\t\tif (data == ctx->hdr_store) {\n\t\t\t\t\t\tmemmove(ctx->hdr_store, start, remain);\n\t\t\t\t\t\tctx->hdr_store_size = remain;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (ctx->hdr_store_alloc < ctx->hdr_store_size + pck_size - vosh_start) {\n\t\t\t\t\t\t\tctx->hdr_store_alloc = (u32) (ctx->hdr_store_size + pck_size - (u32) vosh_start);\n\t\t\t\t\t\t\tctx->hdr_store = gf_realloc(ctx->hdr_store, sizeof(char)*ctx->hdr_store_alloc);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmemcpy(ctx->hdr_store + ctx->hdr_store_size, data + vosh_start, (size_t) (pck_size - vosh_start) );\n\t\t\t\t\t\tctx->hdr_store_size += pck_size - (u32) vosh_start;\n\t\t\t\t\t}\n\t\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t} else if (e != GF_OK) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_MEDIA, (\"[MPGVid] Failed to parse VOS header: %s\\n\", gf_error_to_string(e) ));\n\t\t\t\t} else {\n\t\t\t\t\tu32 obj_size = (u32) gf_m4v_get_object_start(ctx->vparser);\n\t\t\t\t\tif (vosh_start<0) vosh_start = 0;\n\t\t\t\t\tvosh_end = start - (u8 *)data + obj_size;\n\t\t\t\t\tvosh_end -= vosh_start;\n\t\t\t\t\tmpgviddmx_check_pid(filter, ctx,(u32) vosh_end, data+vosh_start);\n\t\t\t\t\tskip_pck = GF_TRUE;\n\t\t\t\t\tassert(remain>=(s32) obj_size);\n\t\t\t\t\tstart += obj_size;\n\t\t\t\t\tremain -= obj_size;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase M4V_VOP_START_CODE:\n\t\t\tcase M4V_GOV_START_CODE:\n\t\t\t\tbreak;\n\n\t\t\tcase M4V_VO_START_CODE:\n\t\t\tcase M4V_VISOBJ_START_CODE:\n\t\t\tdefault:\n\t\t\t\tif (vosh_start>=0) {\n\t\t\t\t\tskip_pck = GF_TRUE;\n\t\t\t\t\tassert(remain>=4);\n\t\t\t\t\tstart += 4;\n\t\t\t\t\tremain -= 4;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (skip_pck) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!ctx->opid) {\n\t\t\tassert(remain>=4);\n\t\t\tstart += 4;\n\t\t\tremain -= 4;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!ctx->is_playing) {\n\t\t\tctx->resume_from = (u32) ((char *)start - (char *)data);\n\t\t\treturn GF_OK;\n\t\t}\n\t\t//at this point, we no longer reaggregate packets\n\t\tctx->hdr_store_size = 0;\n\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_frames_at_seek = (u64) (ctx->start_range * ctx->cur_fps.num);\n\t\t\tif (ctx->cts + ctx->cur_fps.den >= nb_frames_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + ctx->dts_inc) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}\n\t\t//may happen that after all our checks, only 4 bytes are left, continue to store these 4 bytes\n\t\tif (remain<5)\n\t\t\tcontinue;\n\n\t\t//good to go\n\t\tgf_m4v_parser_reset(ctx->vparser, sc_type_forced ? forced_sc_type + 1 : 0);\n\t\tsize = 0;\n\t\te = gf_m4v_parse_frame(ctx->vparser, &ctx->dsi, &ftype, &tinc, &size, &fstart, &is_coded);\n\t\t//true if we strip VO and VISOBJ assert(!fstart);\n\n\t\t//we skipped bytes already in store + end of start code present in packet, so the size of the first object\n\t\t//needs adjustement\n\t\tif (bytes_from_store) {\n\t\t\tsize += bytes_from_store + hdr_offset;\n\t\t}\n\n\t\tif ((e == GF_EOS) && !ctx->input_is_au_end) {\n\t\t\tu8 b3 = start[remain-3];\n\t\t\tu8 b2 = start[remain-2];\n\t\t\tu8 b1 = start[remain-1];\n\n\t\t\t//we may have a startcode at the end of the packet, store it and don't dispatch the last 3 bytes !\n\t\t\tif (!b1 || !b2 || !b3) {\n\t\t\t\tcopy_last_bytes = GF_TRUE;\n\t\t\t\tassert(size >= 3);\n\t\t\t\tsize -= 3;\n\t\t\t\tctx->bytes_in_header = 3;\n\t\t\t}\n\t\t\tfull_frame = GF_FALSE;\n\t\t} else {\n\t\t\tfull_frame = GF_TRUE;\n\t\t}\n\n\t\tif (!is_coded) {\n\t\t\t/*if prev is B and we're parsing a packed bitstream discard n-vop*/\n\t\t\tif (ctx->forced_packed && ctx->b_frames) {\n\t\t\t\tctx->is_packed = GF_TRUE;\n\t\t\t\tassert(remain>=size);\n\t\t\t\tstart += size;\n\t\t\t\tremain -= (s32) size;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t/*policy is to import at variable frame rate, skip*/\n\t\t\tif (ctx->vfr) {\n\t\t\t\tctx->is_vfr = GF_TRUE;\n\t\t\t\tmpgviddmx_update_time(ctx);\n\t\t\t\tassert(remain>=size);\n\t\t\t\tstart += size;\n\t\t\t\tremain -= (s32) size;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t/*policy is to keep non coded frame (constant frame rate), add*/\n\t\t}\n\n\t\tif (ftype==2) {\n\t\t\t//count number of B-frames since last ref\n\t\t\tctx->b_frames++;\n\t\t\tctx->nb_b++;\n\t\t} else {\n\t\t\t//flush all pending packets\n\t\t\tmpgviddmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE, GF_FALSE);\n\t\t\t//remeber the CTS of the last ref\n\t\t\tctx->last_ref_cts = ctx->cts;\n\t\t\tif (ctx->max_b < ctx->b_frames) ctx->max_b = ctx->b_frames;\n\t\t\t\n\t\t\tctx->b_frames = 0;\n\t\t\tif (ftype)\n\t\t\t\tctx->nb_p++;\n\t\t\telse\n\t\t\t\tctx->nb_i++;\n\t\t}\n\t\tctx->nb_frames++;\n\n\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, (u32) size, &pck_data);\n\t\tif (!dst_pck) return GF_OUT_OF_MEM;\n\n\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);\n\t\t//bytes come from both our store and the data packet\n\t\tif (bytes_from_store) {\n\t\t\tmemcpy(pck_data, ctx->hdr_store+current, bytes_from_store);\n\t\t\tassert(size >= bytes_from_store);\n\t\t\tsize -= bytes_from_store;\n\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, byte_offset - bytes_from_store);\n\t\t\t}\n\t\t\tmemcpy(pck_data + bytes_from_store, start, (size_t) size);\n\t\t} else {\n\t\t\t//bytes only come the data packet\n\t\t\tmemcpy(pck_data, start, (size_t) size);\n\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, byte_offset + start - (u8 *) data);\n\t\t\t}\n\t\t}\n\t\tassert(pck_data[0] == 0);\n\t\tassert(pck_data[1] == 0);\n\t\tassert(pck_data[2] == 0x01);\n\n\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, (full_frame || ctx->input_is_au_end) ? GF_TRUE : GF_FALSE);\n\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\tgf_filter_pck_set_dts(dst_pck, ctx->dts);\n\t\tif (ctx->input_is_au_start) {\n\t\t\tctx->input_is_au_start = GF_FALSE;\n\t\t} else {\n\t\t\t//we use the carousel flag temporarly to indicate the cts must be recomputed\n\t\t\tgf_filter_pck_set_carousel_version(dst_pck, 1);\n\t\t}\n\t\tgf_filter_pck_set_sap(dst_pck, ftype ? GF_FILTER_SAP_NONE : GF_FILTER_SAP_1);\n\t\tgf_filter_pck_set_duration(dst_pck, ctx->cur_fps.den);\n\t\tif (ctx->in_seek) gf_filter_pck_set_seek_flag(dst_pck, GF_TRUE);\n\t\tctx->frame_started = GF_TRUE;\n\n\t\tmpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE);\n\n\t\tmpgviddmx_update_time(ctx);\n\n\t\tif (!full_frame) {\n\t\t\tif (copy_last_bytes) {\n\t\t\t\tmemcpy(ctx->hdr_store, start+remain-3, 3);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tassert(remain>=size);\n\t\tstart += size;\n\t\tremain -= (s32) size;\n\t}\n\tgf_filter_pid_drop_packet(ctx->ipid);\n\n\treturn GF_OK;\n}", "func_hash": 49630978088913986571244550780083545600, "file_name": "reframe_mpgvid.c", "file_hash": 148306570807841160156662867455353144265, "cwe": ["CWE-476"], "cve": "CVE-2021-40575", "cve_desc": "The binary MP4Box in Gpac 1.0.1 has a null pointer dereference vulnerability in the mpgviddmx_process function in reframe_mpgvid.c, which allows attackers to cause a denial of service. This vulnerability is possibly due to an incomplete fix for CVE-2021-40566.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40575"} {"idx": 220924, "project": "gpac", "commit_id": "5f2c2a16d30229b6241f02fa28e3d6b810d64858", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/5f2c2a16d30229b6241f02fa28e3d6b810d64858", "commit_message": "fixed #1905", "target": 0, "func": "GF_Err mpgviddmx_process(GF_Filter *filter)\n{\n\tGF_MPGVidDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck, *dst_pck;\n\tu64 byte_offset;\n\ts64 vosh_start = -1;\n\ts64 vosh_end = -1;\n\tGF_Err e;\n\tchar *data;\n\tu8 *start;\n\tu32 pck_size;\n\ts32 remain;\n\n\t//always reparse duration\n\tif (!ctx->duration.num)\n\t\tmpgviddmx_check_dur(filter, ctx);\n\n\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tmpgviddmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE, GF_TRUE);\n\t\t\tif (ctx->opid)\n\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\tctx->src_pck = NULL;\n\t\t\treturn GF_EOS;\n\t\t}\n\t\treturn GF_OK;\n\t}\n\n\tdata = (char *) gf_filter_pck_get_data(pck, &pck_size);\n\tbyte_offset = gf_filter_pck_get_byte_offset(pck);\n\n\tstart = data;\n\tremain = pck_size;\n\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (!ctx->resume_from && ctx->timescale) {\n\t\tu64 ts = gf_filter_pck_get_cts(pck);\n\t\tif (ts != GF_FILTER_NO_TS) {\n\t\t\tif (!ctx->cts || !ctx->recompute_cts)\n\t\t\t\tctx->cts = ts;\n\t\t}\n\t\tts = gf_filter_pck_get_dts(pck);\n\t\tif (ts != GF_FILTER_NO_TS) {\n\t\t\tif (!ctx->dts || !ctx->recompute_cts)\n\t\t\t\tctx->dts = ts;\n\n\t\t\tif (!ctx->prev_dts) ctx->prev_dts = ts;\n\t\t\telse if (ctx->prev_dts != ts) {\n\t\t\t\tu64 diff = ts;\n\t\t\t\tdiff -= ctx->prev_dts;\n\t\t\t\tif (!ctx->cur_fps.den) ctx->cur_fps.den = (u32) diff;\n\t\t\t\telse if (ctx->cur_fps.den > diff)\n\t\t\t\t\tctx->cur_fps.den = (u32) diff;\n\t\t\t}\n\t\t}\n\t\tgf_filter_pck_get_framing(pck, &ctx->input_is_au_start, &ctx->input_is_au_end);\n\t\t//this will force CTS recomput of each frame\n\t\tif (ctx->recompute_cts) ctx->input_is_au_start = GF_FALSE;\n\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\tctx->src_pck = pck;\n\t\tgf_filter_pck_ref_props(&ctx->src_pck);\n\t}\n\n\t//we stored some data to find the complete vosh, aggregate this packet with current one\n\tif (!ctx->resume_from && ctx->hdr_store_size) {\n\t\tif (ctx->hdr_store_alloc < ctx->hdr_store_size + pck_size) {\n\t\t\tctx->hdr_store_alloc = ctx->hdr_store_size + pck_size;\n\t\t\tctx->hdr_store = gf_realloc(ctx->hdr_store, sizeof(char)*ctx->hdr_store_alloc);\n\t\t}\n\t\tmemcpy(ctx->hdr_store + ctx->hdr_store_size, data, sizeof(char)*pck_size);\n\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\tif (byte_offset >= ctx->hdr_store_size)\n\t\t\t\tbyte_offset -= ctx->hdr_store_size;\n\t\t\telse\n\t\t\t\tbyte_offset = GF_FILTER_NO_BO;\n\t\t}\n\t\tctx->hdr_store_size += pck_size;\n\t\tstart = data = ctx->hdr_store;\n\t\tremain = pck_size = ctx->hdr_store_size;\n\t}\n\n\tif (ctx->resume_from) {\n\t\tif (gf_filter_pid_would_block(ctx->opid))\n\t\t\treturn GF_OK;\n\n\t\t//resume from data copied internally\n\t\tif (ctx->hdr_store_size) {\n\t\t\tassert(ctx->resume_from <= ctx->hdr_store_size);\n\t\t\tstart = data = ctx->hdr_store + ctx->resume_from;\n\t\t\tremain = pck_size = ctx->hdr_store_size - ctx->resume_from;\n\t\t} else {\n\t\t\tassert(remain >= (s32) ctx->resume_from);\n\t\t\tstart += ctx->resume_from;\n\t\t\tremain -= ctx->resume_from;\n\t\t}\n\t\tctx->resume_from = 0;\n\t}\n\n\tif (!ctx->bs) {\n\t\tctx->bs = gf_bs_new(start, remain, GF_BITSTREAM_READ);\n\t} else {\n\t\tgf_bs_reassign_buffer(ctx->bs, start, remain);\n\t}\n\tif (!ctx->vparser) {\n\t\tctx->vparser = gf_m4v_parser_bs_new(ctx->bs, ctx->is_mpg12);\n\t}\n\n\n\twhile (remain) {\n\t\tBool full_frame;\n\t\tu8 *pck_data;\n\t\ts32 current;\n\t\tu8 sc_type, forced_sc_type=0;\n\t\tBool sc_type_forced = GF_FALSE;\n\t\tBool skip_pck = GF_FALSE;\n\t\tu8 ftype;\n\t\tu32 tinc;\n\t\tu64 size=0;\n\t\tu64 fstart;\n\t\tBool is_coded;\n\t\tu32 bytes_from_store = 0;\n\t\tu32 hdr_offset = 0;\n\t\tBool copy_last_bytes = GF_FALSE;\n\n\t\t//not enough bytes to parse start code\n\t\tif (remain<5) {\n\t\t\tmemcpy(ctx->hdr_store, start, remain);\n\t\t\tctx->bytes_in_header = remain;\n\t\t\tbreak;\n\t\t}\n\t\tcurrent = -1;\n\n\t\t//we have some potential bytes of a start code in the store, copy some more bytes and check if valid start code.\n\t\t//if not, dispatch these bytes as continuation of the data\n\t\tif (ctx->bytes_in_header) {\n\n\t\t\tmemcpy(ctx->hdr_store + ctx->bytes_in_header, start, 8 - ctx->bytes_in_header);\n\t\t\tcurrent = mpgviddmx_next_start_code(ctx->hdr_store, 8);\n\n\t\t\t//no start code in stored buffer\n\t\t\tif ((current<0) || (current >= (s32) ctx->bytes_in_header) ) {\n\t\t\t\tif (ctx->opid) {\n\t\t\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, ctx->bytes_in_header, &pck_data);\n\t\t\t\t\tif (!dst_pck) return GF_OUT_OF_MEM;\n\n\t\t\t\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);\n\t\t\t\t\tgf_filter_pck_set_cts(dst_pck, GF_FILTER_NO_TS);\n\t\t\t\t\tgf_filter_pck_set_dts(dst_pck, GF_FILTER_NO_TS);\n\t\t\t\t\tmemcpy(pck_data, ctx->hdr_store, ctx->bytes_in_header);\n\t\t\t\t\tgf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_FALSE);\n\n\t\t\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, byte_offset - ctx->bytes_in_header);\n\t\t\t\t\t}\n\n\t\t\t\t\tmpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE);\n\t\t\t\t}\n\n\t\t\t\tif (current<0) current = -1;\n\t\t\t\telse current -= ctx->bytes_in_header;\n\t\t\t\tctx->bytes_in_header = 0;\n\t\t\t} else {\n\t\t\t\t//we have a valid start code, check which byte in our store or in the packet payload is the start code type\n\t\t\t\t//and remember its location to reinit the parser from there\n\t\t\t\thdr_offset = 4 - ctx->bytes_in_header + current;\n\t\t\t\t//bytes still to dispatch\n\t\t\t\tbytes_from_store = ctx->bytes_in_header;\n\t\t\t\tctx->bytes_in_header = 0;\n\t\t\t\tif (!hdr_offset) {\n\t\t\t\t\tforced_sc_type = ctx->hdr_store[current+3];\n\t\t\t\t} else {\n\t\t\t\t\tforced_sc_type = start[hdr_offset-1];\n\t\t\t\t}\n\t\t\t\tsc_type_forced = GF_TRUE;\n\t\t\t}\n\t\t}\n\t\t//no starcode in store, look for startcode in packet\n\t\tif (current == -1) {\n\t\t\t//locate next start code\n\t\t\tcurrent = mpgviddmx_next_start_code(start, remain);\n\t\t\t//no start code, dispatch the block\n\t\t\tif (current<0) {\n\t\t\t\tu8 b3, b2, b1;\n\t\t\t\tif (! ctx->frame_started) {\n\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_MEDIA, (\"[MPGVid] no start code in block and no frame started, discarding data\\n\" ));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsize = remain;\n\t\t\t\tb3 = start[remain-3];\n\t\t\t\tb2 = start[remain-2];\n\t\t\t\tb1 = start[remain-1];\n\t\t\t\t//we may have a startcode at the end of the packet, store it and don't dispatch the last 3 bytes !\n\t\t\t\tif (!b1 || !b2 || !b3) {\n\t\t\t\t\tcopy_last_bytes = GF_TRUE;\n\t\t\t\t\tassert(size >= 3);\n\t\t\t\t\tsize -= 3;\n\t\t\t\t\tctx->bytes_in_header = 3;\n\t\t\t\t}\n\n\t\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, (u32) size, &pck_data);\n\t\t\t\tif (!dst_pck) return GF_OUT_OF_MEM;\n\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);\n\t\t\t\tmemcpy(pck_data, start, (size_t) size);\n\t\t\t\tgf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_FALSE);\n\t\t\t\tgf_filter_pck_set_cts(dst_pck, GF_FILTER_NO_TS);\n\t\t\t\tgf_filter_pck_set_dts(dst_pck, GF_FILTER_NO_TS);\n\n\t\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, byte_offset);\n\t\t\t\t}\n\n\t\t\t\tmpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE);\n\t\t\t\tif (copy_last_bytes) {\n\t\t\t\t\tmemcpy(ctx->hdr_store, start+remain-3, 3);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tassert(current>=0);\n\n\t\t//if we are in the middle of parsing the vosh, skip over bytes remaining from previous obj not parsed\n\t\tif ((vosh_start>=0) && current) {\n\t\t\tassert(remain>=current);\n\t\t\tstart += current;\n\t\t\tremain -= current;\n\t\t\tcurrent = 0;\n\t\t}\n\t\t//also skip if no output pid\n\t\tif (!ctx->opid && current) {\n\t\t\tassert(remain>=current);\n\t\t\tstart += current;\n\t\t\tremain -= current;\n\t\t\tcurrent = 0;\n\t\t}\n\t\t//dispatch remaining bytes\n\t\tif (current>0) {\n\t\t\t//flush remaining\n\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, current, &pck_data);\n\t\t\tif (!dst_pck) return GF_OUT_OF_MEM;\n\n\t\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);\n\t\t\tgf_filter_pck_set_cts(dst_pck, GF_FILTER_NO_TS);\n\t\t\tgf_filter_pck_set_dts(dst_pck, GF_FILTER_NO_TS);\n\t\t\tgf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_TRUE);\n\t\t\t//bytes were partly in store, partly in packet\n\t\t\tif (bytes_from_store) {\n\t\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, byte_offset - bytes_from_store);\n\t\t\t\t}\n\t\t\t\tassert(bytes_from_store>=(u32) current);\n\t\t\t\tbytes_from_store -= current;\n\t\t\t\tmemcpy(pck_data, ctx->hdr_store, current);\n\t\t\t} else {\n\t\t\t\t//bytes were only in packet\n\t\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, byte_offset);\n\t\t\t\t}\n\t\t\t\tmemcpy(pck_data, start, current);\n\t\t\t\tassert(remain>=current);\n\t\t\t\tstart += current;\n\t\t\t\tremain -= current;\n\t\t\t\tcurrent = 0;\n\t\t\t}\n\t\t\tgf_filter_pck_set_carousel_version(dst_pck, 1);\n\n\t\t\tmpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE);\n\t\t}\n\n\t\t//not enough bytes to parse start code\n\t\tif (remain<5) {\n\t\t\tmemcpy(ctx->hdr_store, start, remain);\n\t\t\tctx->bytes_in_header = remain;\n\t\t\tbreak;\n\t\t}\n\n\t\t//parse headers\n\t\t//we have a start code loaded, eg the data packet does not have a full start code at the beginning\n\t\tif (sc_type_forced) {\n\t\t\tgf_bs_reassign_buffer(ctx->bs, start + hdr_offset, remain - hdr_offset);\n\t\t\tsc_type = forced_sc_type;\n\t\t} else {\n\t\t\tgf_bs_reassign_buffer(ctx->bs, start, remain);\n\t\t\tgf_bs_read_int(ctx->bs, 24);\n\t\t\tsc_type = gf_bs_read_int(ctx->bs, 8);\n\t\t}\n\n\t\tif (ctx->is_mpg12) {\n\t\t\tswitch (sc_type) {\n\t\t\tcase M2V_SEQ_START_CODE:\n\t\t\tcase M2V_EXT_START_CODE:\n\t\t\t\tgf_bs_reassign_buffer(ctx->bs, start, remain);\n\t\t\t\te = gf_m4v_parse_config(ctx->vparser, &ctx->dsi);\n\t\t\t\t//not enough data, accumulate until we can parse the full header\n\t\t\t\tif (e==GF_EOS) {\n\t\t\t\t\tif (vosh_start<0) vosh_start = 0;\n\t\t\t\t\tif (data == ctx->hdr_store) {\n\t\t\t\t\t\tmemmove(ctx->hdr_store, start, remain);\n\t\t\t\t\t\tctx->hdr_store_size = remain;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (ctx->hdr_store_alloc < ctx->hdr_store_size + pck_size - vosh_start) {\n\t\t\t\t\t\t\tctx->hdr_store_alloc = (u32) (ctx->hdr_store_size + pck_size - vosh_start);\n\t\t\t\t\t\t\tctx->hdr_store = gf_realloc(ctx->hdr_store, sizeof(char)*ctx->hdr_store_alloc);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmemcpy(ctx->hdr_store + ctx->hdr_store_size, data + vosh_start, (size_t) (pck_size - vosh_start) );\n\t\t\t\t\t\tctx->hdr_store_size += pck_size - (u32) vosh_start;\n\t\t\t\t\t}\n\t\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t} else if (e != GF_OK) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_MEDIA, (\"[MPGVid] Failed to parse VOS header: %s\\n\", gf_error_to_string(e) ));\n\t\t\t\t} else {\n\t\t\t\t\tmpgviddmx_check_pid(filter, ctx, 0, NULL);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase M2V_PIC_START_CODE:\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t} else {\n\t\t\tu8 PL;\n\t\t\tswitch (sc_type) {\n\t\t\tcase M4V_VOS_START_CODE:\n\t\t\t\tctx->dsi.VideoPL = (u8) gf_bs_read_u8(ctx->bs);\n\t\t\t\tvosh_start = start - (u8 *)data;\n\t\t\t\tskip_pck = GF_TRUE;\n\t\t\t\tassert(remain>=5);\n\t\t\t\tstart += 5;\n\t\t\t\tremain -= 5;\n\t\t\t\tbreak;\n\t\t\tcase M4V_VOL_START_CODE:\n\t\t\t\tgf_bs_reassign_buffer(ctx->bs, start, remain);\n\t\t\t\tPL = ctx->dsi.VideoPL;\n\t\t\t\te = gf_m4v_parse_config(ctx->vparser, &ctx->dsi);\n\t\t\t\tctx->dsi.VideoPL = PL;\n\t\t\t\t//not enough data, accumulate until we can parse the full header\n\t\t\t\tif (e==GF_EOS) {\n\t\t\t\t\tif (vosh_start<0) vosh_start = 0;\n\t\t\t\t\tif (data == ctx->hdr_store) {\n\t\t\t\t\t\tmemmove(ctx->hdr_store, start, remain);\n\t\t\t\t\t\tctx->hdr_store_size = remain;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (ctx->hdr_store_alloc < ctx->hdr_store_size + pck_size - vosh_start) {\n\t\t\t\t\t\t\tctx->hdr_store_alloc = (u32) (ctx->hdr_store_size + pck_size - (u32) vosh_start);\n\t\t\t\t\t\t\tctx->hdr_store = gf_realloc(ctx->hdr_store, sizeof(char)*ctx->hdr_store_alloc);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmemcpy(ctx->hdr_store + ctx->hdr_store_size, data + vosh_start, (size_t) (pck_size - vosh_start) );\n\t\t\t\t\t\tctx->hdr_store_size += pck_size - (u32) vosh_start;\n\t\t\t\t\t}\n\t\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t} else if (e != GF_OK) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_MEDIA, (\"[MPGVid] Failed to parse VOS header: %s\\n\", gf_error_to_string(e) ));\n\t\t\t\t} else {\n\t\t\t\t\tu32 obj_size = (u32) gf_m4v_get_object_start(ctx->vparser);\n\t\t\t\t\tif (vosh_start<0) vosh_start = 0;\n\t\t\t\t\tvosh_end = start - (u8 *)data + obj_size;\n\t\t\t\t\tvosh_end -= vosh_start;\n\t\t\t\t\tmpgviddmx_check_pid(filter, ctx,(u32) vosh_end, data+vosh_start);\n\t\t\t\t\tskip_pck = GF_TRUE;\n\t\t\t\t\tassert(remain>=(s32) obj_size);\n\t\t\t\t\tstart += obj_size;\n\t\t\t\t\tremain -= obj_size;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase M4V_VOP_START_CODE:\n\t\t\tcase M4V_GOV_START_CODE:\n\t\t\t\tbreak;\n\n\t\t\tcase M4V_VO_START_CODE:\n\t\t\tcase M4V_VISOBJ_START_CODE:\n\t\t\tdefault:\n\t\t\t\tif (vosh_start>=0) {\n\t\t\t\t\tskip_pck = GF_TRUE;\n\t\t\t\t\tassert(remain>=4);\n\t\t\t\t\tstart += 4;\n\t\t\t\t\tremain -= 4;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (skip_pck) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!ctx->opid) {\n\t\t\tassert(remain>=4);\n\t\t\tstart += 4;\n\t\t\tremain -= 4;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!ctx->is_playing) {\n\t\t\tctx->resume_from = (u32) ((char *)start - (char *)data);\n\t\t\treturn GF_OK;\n\t\t}\n\t\t//at this point, we no longer reaggregate packets\n\t\tctx->hdr_store_size = 0;\n\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_frames_at_seek = (u64) (ctx->start_range * ctx->cur_fps.num);\n\t\t\tif (ctx->cts + ctx->cur_fps.den >= nb_frames_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + ctx->dts_inc) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}\n\t\t//may happen that after all our checks, only 4 bytes are left, continue to store these 4 bytes\n\t\tif (remain<5)\n\t\t\tcontinue;\n\n\t\t//good to go\n\t\tgf_m4v_parser_reset(ctx->vparser, sc_type_forced ? forced_sc_type + 1 : 0);\n\t\tsize = 0;\n\t\te = gf_m4v_parse_frame(ctx->vparser, &ctx->dsi, &ftype, &tinc, &size, &fstart, &is_coded);\n\t\t//true if we strip VO and VISOBJ assert(!fstart);\n\n\t\t//we skipped bytes already in store + end of start code present in packet, so the size of the first object\n\t\t//needs adjustement\n\t\tif (bytes_from_store) {\n\t\t\tsize += bytes_from_store + hdr_offset;\n\t\t}\n\n\t\tif ((e == GF_EOS) && !ctx->input_is_au_end) {\n\t\t\tu8 b3 = start[remain-3];\n\t\t\tu8 b2 = start[remain-2];\n\t\t\tu8 b1 = start[remain-1];\n\n\t\t\t//we may have a startcode at the end of the packet, store it and don't dispatch the last 3 bytes !\n\t\t\tif (!b1 || !b2 || !b3) {\n\t\t\t\tcopy_last_bytes = GF_TRUE;\n\t\t\t\tassert(size >= 3);\n\t\t\t\tsize -= 3;\n\t\t\t\tctx->bytes_in_header = 3;\n\t\t\t}\n\t\t\tfull_frame = GF_FALSE;\n\t\t} else {\n\t\t\tfull_frame = GF_TRUE;\n\t\t}\n\n\t\tif (!is_coded) {\n\t\t\t/*if prev is B and we're parsing a packed bitstream discard n-vop*/\n\t\t\tif (ctx->forced_packed && ctx->b_frames) {\n\t\t\t\tctx->is_packed = GF_TRUE;\n\t\t\t\tassert(remain>=size);\n\t\t\t\tstart += size;\n\t\t\t\tremain -= (s32) size;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t/*policy is to import at variable frame rate, skip*/\n\t\t\tif (ctx->vfr) {\n\t\t\t\tctx->is_vfr = GF_TRUE;\n\t\t\t\tmpgviddmx_update_time(ctx);\n\t\t\t\tassert(remain>=size);\n\t\t\t\tstart += size;\n\t\t\t\tremain -= (s32) size;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t/*policy is to keep non coded frame (constant frame rate), add*/\n\t\t}\n\n\t\tif (ftype==2) {\n\t\t\t//count number of B-frames since last ref\n\t\t\tctx->b_frames++;\n\t\t\tctx->nb_b++;\n\t\t} else {\n\t\t\t//flush all pending packets\n\t\t\tmpgviddmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE, GF_FALSE);\n\t\t\t//remeber the CTS of the last ref\n\t\t\tctx->last_ref_cts = ctx->cts;\n\t\t\tif (ctx->max_b < ctx->b_frames) ctx->max_b = ctx->b_frames;\n\t\t\t\n\t\t\tctx->b_frames = 0;\n\t\t\tif (ftype)\n\t\t\t\tctx->nb_p++;\n\t\t\telse\n\t\t\t\tctx->nb_i++;\n\t\t}\n\t\tctx->nb_frames++;\n\n\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, (u32) size, &pck_data);\n\t\tif (!dst_pck) return GF_OUT_OF_MEM;\n\n\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);\n\t\t//bytes come from both our store and the data packet\n\t\tif (bytes_from_store) {\n\t\t\tmemcpy(pck_data, ctx->hdr_store+current, bytes_from_store);\n\t\t\tassert(size >= bytes_from_store);\n\t\t\tsize -= bytes_from_store;\n\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, byte_offset - bytes_from_store);\n\t\t\t}\n\t\t\tmemcpy(pck_data + bytes_from_store, start, (size_t) size);\n\t\t} else {\n\t\t\t//bytes only come the data packet\n\t\t\tmemcpy(pck_data, start, (size_t) size);\n\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, byte_offset + start - (u8 *) data);\n\t\t\t}\n\t\t}\n\t\tassert(pck_data[0] == 0);\n\t\tassert(pck_data[1] == 0);\n\t\tassert(pck_data[2] == 0x01);\n\n\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, (full_frame || ctx->input_is_au_end) ? GF_TRUE : GF_FALSE);\n\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\tgf_filter_pck_set_dts(dst_pck, ctx->dts);\n\t\tif (ctx->input_is_au_start) {\n\t\t\tctx->input_is_au_start = GF_FALSE;\n\t\t} else {\n\t\t\t//we use the carousel flag temporarly to indicate the cts must be recomputed\n\t\t\tgf_filter_pck_set_carousel_version(dst_pck, 1);\n\t\t}\n\t\tgf_filter_pck_set_sap(dst_pck, ftype ? GF_FILTER_SAP_NONE : GF_FILTER_SAP_1);\n\t\tgf_filter_pck_set_duration(dst_pck, ctx->cur_fps.den);\n\t\tif (ctx->in_seek) gf_filter_pck_set_seek_flag(dst_pck, GF_TRUE);\n\t\tctx->frame_started = GF_TRUE;\n\n\t\tmpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE);\n\n\t\tmpgviddmx_update_time(ctx);\n\n\t\tif (!full_frame) {\n\t\t\tif (copy_last_bytes) {\n\t\t\t\tmemcpy(ctx->hdr_store, start+remain-3, 3);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tassert(remain>=size);\n\t\tstart += size;\n\t\tremain -= (s32) size;\n\t}\n\tgf_filter_pid_drop_packet(ctx->ipid);\n\n\treturn GF_OK;\n}", "func_hash": 313423902312193703310274340114212883369, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2021-40575", "cve_desc": "The binary MP4Box in Gpac 1.0.1 has a null pointer dereference vulnerability in the mpgviddmx_process function in reframe_mpgvid.c, which allows attackers to cause a denial of service. This vulnerability is possibly due to an incomplete fix for CVE-2021-40566.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40575"} {"idx": 195069, "project": "gpac", "commit_id": "f1ae01d745200a258cdf62622f71754c37cb6c30", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/f1ae01d745200a258cdf62622f71754c37cb6c30", "commit_message": "fixed #1900", "target": 1, "func": "static s32 svc_parse_slice(GF_BitStream *bs, AVCState *avc, AVCSliceInfo *si)\n{\n\ts32 pps_id;\n\n\t/*s->current_picture.reference= h->nal_ref_idc != 0;*/\n\tgf_bs_read_ue_log(bs, \"first_mb_in_slice\");\n\tsi->slice_type = gf_bs_read_ue_log(bs, \"slice_type\");\n\tif (si->slice_type > 9) return -1;\n\n\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n\tif (pps_id > 255)\n\t\treturn -1;\n\tsi->pps = &avc->pps[pps_id];\n\tsi->pps->id = pps_id;\n\tif (!si->pps->slice_group_count)\n\t\treturn -2;\n\tsi->sps = &avc->sps[si->pps->sps_id + GF_SVC_SSPS_ID_SHIFT];\n\tif (!si->sps->log2_max_frame_num)\n\t\treturn -2;\n\n\tsi->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, \"frame_num\");\n\n\tsi->field_pic_flag = 0;\n\tif (si->sps->frame_mbs_only_flag) {\n\t\t/*s->picture_structure= PICT_FRAME;*/\n\t}\n\telse {\n\t\tsi->field_pic_flag = gf_bs_read_int_log(bs, 1, \"field_pic_flag\");\n\t\tif (si->field_pic_flag) si->bottom_field_flag = gf_bs_read_int_log(bs, 1, \"bottom_field_flag\");\n\t}\n\tif (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE || si->NalHeader.idr_pic_flag)\n\t\tsi->idr_pic_id = gf_bs_read_ue_log(bs, \"idr_pic_id\");\n\n\tif (si->sps->poc_type == 0) {\n\t\tsi->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, \"poc_lsb\");\n\t\tif (si->pps->pic_order_present && !si->field_pic_flag) {\n\t\t\tsi->delta_poc_bottom = gf_bs_read_se_log(bs, \"delta_poc_bottom\");\n\t\t}\n\t}\n\telse if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) {\n\t\tsi->delta_poc[0] = gf_bs_read_se_log(bs, \"delta_poc0\");\n\t\tif ((si->pps->pic_order_present == 1) && !si->field_pic_flag)\n\t\t\tsi->delta_poc[1] = gf_bs_read_se_log(bs, \"delta_poc1\");\n\t}\n\tif (si->pps->redundant_pic_cnt_present) {\n\t\tsi->redundant_pic_cnt = gf_bs_read_ue_log(bs, \"redundant_pic_cnt\");\n\t}\n\treturn 0;\n}", "func_hash": 32918828304584753556059241288811637938, "file_name": "av_parsers.c", "file_hash": 168517587328341017594269375399465893964, "cwe": ["CWE-120"], "cve": "CVE-2021-40568", "cve_desc": "A buffer overflow vulnerability exists in Gpac through 1.0.1 via a malformed MP4 file in the svc_parse_slice function in av_parsers.c, which allows attackers to cause a denial of service, even code execution and escalation of privileges.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40568"} {"idx": 221079, "project": "gpac", "commit_id": "f1ae01d745200a258cdf62622f71754c37cb6c30", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/f1ae01d745200a258cdf62622f71754c37cb6c30", "commit_message": "fixed #1900", "target": 0, "func": "static s32 svc_parse_slice(GF_BitStream *bs, AVCState *avc, AVCSliceInfo *si)\n{\n\ts32 pps_id;\n\n\t/*s->current_picture.reference= h->nal_ref_idc != 0;*/\n\tgf_bs_read_ue_log(bs, \"first_mb_in_slice\");\n\tsi->slice_type = gf_bs_read_ue_log(bs, \"slice_type\");\n\tif (si->slice_type > 9) return -1;\n\n\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n\tif ((pps_id<0) || (pps_id > 255))\n\t\treturn -1;\n\tsi->pps = &avc->pps[pps_id];\n\tsi->pps->id = pps_id;\n\tif (!si->pps->slice_group_count)\n\t\treturn -2;\n\tsi->sps = &avc->sps[si->pps->sps_id + GF_SVC_SSPS_ID_SHIFT];\n\tif (!si->sps->log2_max_frame_num)\n\t\treturn -2;\n\n\tsi->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, \"frame_num\");\n\n\tsi->field_pic_flag = 0;\n\tif (si->sps->frame_mbs_only_flag) {\n\t\t/*s->picture_structure= PICT_FRAME;*/\n\t}\n\telse {\n\t\tsi->field_pic_flag = gf_bs_read_int_log(bs, 1, \"field_pic_flag\");\n\t\tif (si->field_pic_flag) si->bottom_field_flag = gf_bs_read_int_log(bs, 1, \"bottom_field_flag\");\n\t}\n\tif (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE || si->NalHeader.idr_pic_flag)\n\t\tsi->idr_pic_id = gf_bs_read_ue_log(bs, \"idr_pic_id\");\n\n\tif (si->sps->poc_type == 0) {\n\t\tsi->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, \"poc_lsb\");\n\t\tif (si->pps->pic_order_present && !si->field_pic_flag) {\n\t\t\tsi->delta_poc_bottom = gf_bs_read_se_log(bs, \"delta_poc_bottom\");\n\t\t}\n\t}\n\telse if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) {\n\t\tsi->delta_poc[0] = gf_bs_read_se_log(bs, \"delta_poc0\");\n\t\tif ((si->pps->pic_order_present == 1) && !si->field_pic_flag)\n\t\t\tsi->delta_poc[1] = gf_bs_read_se_log(bs, \"delta_poc1\");\n\t}\n\tif (si->pps->redundant_pic_cnt_present) {\n\t\tsi->redundant_pic_cnt = gf_bs_read_ue_log(bs, \"redundant_pic_cnt\");\n\t}\n\treturn 0;\n}", "func_hash": 185903137648833315964702797768717766367, "file_name": "av_parsers.c", "file_hash": 336095072032702615903888752582747164805, "cwe": ["CWE-120"], "cve": "CVE-2021-40568", "cve_desc": "A buffer overflow vulnerability exists in Gpac through 1.0.1 via a malformed MP4 file in the svc_parse_slice function in av_parsers.c, which allows attackers to cause a denial of service, even code execution and escalation of privileges.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40568"} {"idx": 195073, "project": "tensorflow", "commit_id": "e746adbfcfee15e9cfdb391ff746c765b99bdf9b", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e746adbfcfee15e9cfdb391ff746c765b99bdf9b", "commit_message": "Prevent use after free in `DecodePng` kernel.\n\nWe are cleaning up the memory in `decode` and then we are using an `OP_REQUIRES` to check an invariant on the `decode` data.\n\nPiperOrigin-RevId: 409299145\nChange-Id: I4eb93aaca52483eb202e89b78df07fbb2f6cb254", "target": 1, "func": " void DecodePngV2(OpKernelContext* context, StringPiece input) {\n int channel_bits = (data_type_ == DataType::DT_UINT8) ? 8 : 16;\n png::DecodeContext decode;\n OP_REQUIRES(\n context, png::CommonInitDecode(input, channels_, channel_bits, &decode),\n errors::InvalidArgument(\"Invalid PNG. Failed to initialize decoder.\"));\n\n // Verify that width and height are not too large:\n // - verify width and height don't overflow int.\n // - width can later be multiplied by channels_ and sizeof(uint16), so\n // verify single dimension is not too large.\n // - verify when width and height are multiplied together, there are a few\n // bits to spare as well.\n const int width = static_cast(decode.width);\n const int height = static_cast(decode.height);\n const int64_t total_size =\n static_cast(width) * static_cast(height);\n if (width != static_cast(decode.width) || width <= 0 ||\n width >= (1LL << 27) || height != static_cast(decode.height) ||\n height <= 0 || height >= (1LL << 27) || total_size >= (1LL << 29)) {\n png::CommonFreeDecode(&decode);\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\"PNG size too large for int: \",\n decode.width, \" by \", decode.height));\n }\n\n Tensor* output = nullptr;\n Status status;\n // By the existing API, we support decoding PNG with `DecodeGif` op.\n // We need to make sure to return 4-D shapes when using `DecodeGif`.\n if (op_type_ == \"DecodeGif\") {\n status = context->allocate_output(\n 0, TensorShape({1, height, width, decode.channels}), &output);\n } else {\n status = context->allocate_output(\n 0, TensorShape({height, width, decode.channels}), &output);\n }\n\n if (op_type_ == \"DecodeBmp\") {\n // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here\n // because currently `decode_(jpeg|png|gif)` ops can decode any one of\n // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode\n // anything but bmp formats. This behavior needs to be revisited. For more\n // details, please refer to the bug.\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Trying to decode PNG format using DecodeBmp op. Use \"\n \"`decode_png` or `decode_image` instead.\"));\n } else if (op_type_ == \"DecodeAndCropJpeg\") {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"DecodeAndCropJpeg operation can run on JPEG only, but \"\n \"detected PNG.\"));\n }\n\n if (!status.ok()) png::CommonFreeDecode(&decode);\n OP_REQUIRES_OK(context, status);\n\n if (data_type_ == DataType::DT_UINT8) {\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(\n reinterpret_cast(output->flat().data()),\n decode.channels * width * sizeof(uint8), &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n } else if (data_type_ == DataType::DT_UINT16) {\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(\n reinterpret_cast(output->flat().data()),\n decode.channels * width * sizeof(uint16), &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n } else if (data_type_ == DataType::DT_FLOAT) {\n // `png::CommonFinishDecode` does not support `float`. First allocate\n // uint16 buffer for the image and decode in uint16 (lossless). Wrap the\n // buffer in `unique_ptr` so that we don't forget to delete the buffer.\n std::unique_ptr buffer(\n new uint16[height * width * decode.channels]);\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(reinterpret_cast(buffer.get()),\n decode.channels * width * sizeof(uint16),\n &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n\n // Convert uint16 image data to desired data type.\n // Use eigen threadpooling to speed up the copy operation.\n const auto& device = context->eigen_device();\n TTypes::UnalignedConstTensor buf(buffer.get(), height, width,\n decode.channels);\n float scale = 1. / std::numeric_limits::max();\n // Fill output tensor with desired dtype.\n output->tensor().device(device) = buf.cast() * scale;\n }\n }", "func_hash": 20785520030401878119367159260444796492, "file_name": "decode_image_op.cc", "file_hash": 250237771010213788823348212493793467085, "cwe": ["CWE-416"], "cve": "CVE-2022-23584", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. A malicious user can cause a use after free behavior when decoding PNG images. After `png::CommonFreeDecode(&decode)` gets called, the values of `decode.width` and `decode.height` are in an unspecified state. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23584"} {"idx": 221123, "project": "tensorflow", "commit_id": "e746adbfcfee15e9cfdb391ff746c765b99bdf9b", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e746adbfcfee15e9cfdb391ff746c765b99bdf9b", "commit_message": "Prevent use after free in `DecodePng` kernel.\n\nWe are cleaning up the memory in `decode` and then we are using an `OP_REQUIRES` to check an invariant on the `decode` data.\n\nPiperOrigin-RevId: 409299145\nChange-Id: I4eb93aaca52483eb202e89b78df07fbb2f6cb254", "target": 0, "func": " void DecodePngV2(OpKernelContext* context, StringPiece input) {\n int channel_bits = (data_type_ == DataType::DT_UINT8) ? 8 : 16;\n png::DecodeContext decode;\n OP_REQUIRES(\n context, png::CommonInitDecode(input, channels_, channel_bits, &decode),\n errors::InvalidArgument(\"Invalid PNG. Failed to initialize decoder.\"));\n\n // Verify that width and height are not too large:\n // - verify width and height don't overflow int.\n // - width can later be multiplied by channels_ and sizeof(uint16), so\n // verify single dimension is not too large.\n // - verify when width and height are multiplied together, there are a few\n // bits to spare as well.\n const int width = static_cast(decode.width);\n const int height = static_cast(decode.height);\n const int64_t total_size =\n static_cast(width) * static_cast(height);\n if (width != static_cast(decode.width) || width <= 0 ||\n width >= (1LL << 27) || height != static_cast(decode.height) ||\n height <= 0 || height >= (1LL << 27) || total_size >= (1LL << 29)) {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\"PNG size too large for int: \",\n decode.width, \" by \", decode.height));\n }\n\n Tensor* output = nullptr;\n Status status;\n // By the existing API, we support decoding PNG with `DecodeGif` op.\n // We need to make sure to return 4-D shapes when using `DecodeGif`.\n if (op_type_ == \"DecodeGif\") {\n status = context->allocate_output(\n 0, TensorShape({1, height, width, decode.channels}), &output);\n } else {\n status = context->allocate_output(\n 0, TensorShape({height, width, decode.channels}), &output);\n }\n\n if (op_type_ == \"DecodeBmp\") {\n // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here\n // because currently `decode_(jpeg|png|gif)` ops can decode any one of\n // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode\n // anything but bmp formats. This behavior needs to be revisited. For more\n // details, please refer to the bug.\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Trying to decode PNG format using DecodeBmp op. Use \"\n \"`decode_png` or `decode_image` instead.\"));\n } else if (op_type_ == \"DecodeAndCropJpeg\") {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"DecodeAndCropJpeg operation can run on JPEG only, but \"\n \"detected PNG.\"));\n }\n\n if (!status.ok()) png::CommonFreeDecode(&decode);\n OP_REQUIRES_OK(context, status);\n\n if (data_type_ == DataType::DT_UINT8) {\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(\n reinterpret_cast(output->flat().data()),\n decode.channels * width * sizeof(uint8), &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n } else if (data_type_ == DataType::DT_UINT16) {\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(\n reinterpret_cast(output->flat().data()),\n decode.channels * width * sizeof(uint16), &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n } else if (data_type_ == DataType::DT_FLOAT) {\n // `png::CommonFinishDecode` does not support `float`. First allocate\n // uint16 buffer for the image and decode in uint16 (lossless). Wrap the\n // buffer in `unique_ptr` so that we don't forget to delete the buffer.\n std::unique_ptr buffer(\n new uint16[height * width * decode.channels]);\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(reinterpret_cast(buffer.get()),\n decode.channels * width * sizeof(uint16),\n &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n\n // Convert uint16 image data to desired data type.\n // Use eigen threadpooling to speed up the copy operation.\n const auto& device = context->eigen_device();\n TTypes::UnalignedConstTensor buf(buffer.get(), height, width,\n decode.channels);\n float scale = 1. / std::numeric_limits::max();\n // Fill output tensor with desired dtype.\n output->tensor().device(device) = buf.cast() * scale;\n }\n }", "func_hash": 197194550974667972193999280383190029027, "file_name": "decode_image_op.cc", "file_hash": 250371192243587827698671199962137663449, "cwe": ["CWE-416"], "cve": "CVE-2022-23584", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. A malicious user can cause a use after free behavior when decoding PNG images. After `png::CommonFreeDecode(&decode)` gets called, the values of `decode.width` and `decode.height` are in an unspecified state. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23584"} {"idx": 195074, "project": "gpac", "commit_id": "a69b567b8c95c72f9560c873c5ab348be058f340", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/a69b567b8c95c72f9560c873c5ab348be058f340", "commit_message": "fixed #1895", "target": 1, "func": "GF_AV1Config *gf_odf_av1_cfg_read_bs_size(GF_BitStream *bs, u32 size)\n{\n#ifndef GPAC_DISABLE_AV_PARSERS\n\tAV1State state;\n\tu8 reserved;\n\tGF_AV1Config *cfg;\n\n\tif (!size) size = (u32) gf_bs_available(bs);\n\tif (!size) return NULL;\n\n\tcfg = gf_odf_av1_cfg_new();\n\tgf_av1_init_state(&state);\n\tstate.config = cfg;\n\n\tcfg->marker = gf_bs_read_int(bs, 1);\n\tcfg->version = gf_bs_read_int(bs, 7);\n\tcfg->seq_profile = gf_bs_read_int(bs, 3);\n\tcfg->seq_level_idx_0 = gf_bs_read_int(bs, 5);\n\tcfg->seq_tier_0 = gf_bs_read_int(bs, 1);\n\tcfg->high_bitdepth = gf_bs_read_int(bs, 1);\n\tcfg->twelve_bit = gf_bs_read_int(bs, 1);\n\tcfg->monochrome = gf_bs_read_int(bs, 1);\n\tcfg->chroma_subsampling_x = gf_bs_read_int(bs, 1);\n\tcfg->chroma_subsampling_y = gf_bs_read_int(bs, 1);\n\tcfg->chroma_sample_position = gf_bs_read_int(bs, 2);\n\n\treserved = gf_bs_read_int(bs, 3);\n\tif (reserved != 0 || cfg->marker != 1 || cfg->version != 1) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] wrong avcC reserved %d / marker %d / version %d expecting 0 1 1\\n\", reserved, cfg->marker, cfg->version));\n\t\tgf_odf_av1_cfg_del(cfg);\n\t\treturn NULL;\n\t}\n\tcfg->initial_presentation_delay_present = gf_bs_read_int(bs, 1);\n\tif (cfg->initial_presentation_delay_present) {\n\t\tcfg->initial_presentation_delay_minus_one = gf_bs_read_int(bs, 4);\n\t} else {\n\t\t/*reserved = */gf_bs_read_int(bs, 4);\n\t\tcfg->initial_presentation_delay_minus_one = 0;\n\t}\n\tsize -= 4;\n\n\twhile (size) {\n\t\tu64 pos, obu_size;\n\t\tObuType obu_type;\n\t\tGF_AV1_OBUArrayEntry *a;\n\n\t\tpos = gf_bs_get_position(bs);\n\t\tobu_size = 0;\n\t\tif (gf_av1_parse_obu(bs, &obu_type, &obu_size, NULL, &state) != GF_OK) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[AV1] could not parse AV1 OBU at position \"LLU\". Leaving parsing.\\n\", pos));\n\t\t\tbreak;\n\t\t}\n\t\tassert(obu_size == gf_bs_get_position(bs) - pos);\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] parsed AV1 OBU type=%u size=\"LLU\" at position \"LLU\".\\n\", obu_type, obu_size, pos));\n\n\t\tif (!av1_is_obu_header(obu_type)) {\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] AV1 unexpected OBU type=%u size=\"LLU\" found at position \"LLU\". Forwarding.\\n\", pos));\n\t\t}\n\t\tGF_SAFEALLOC(a, GF_AV1_OBUArrayEntry);\n\t\tif (!a) break;\n\t\ta->obu = gf_malloc((size_t)obu_size);\n\t\tif (!a->obu) {\n\t\t\tgf_free(a);\n\t\t\tbreak;\n\t\t}\n\t\tgf_bs_seek(bs, pos);\n\t\tgf_bs_read_data(bs, (char *) a->obu, (u32)obu_size);\n\t\ta->obu_length = obu_size;\n\t\ta->obu_type = obu_type;\n\t\tgf_list_add(cfg->obu_array, a);\n\n\t\tif (sizemarker = gf_bs_read_int(bs, 1);\n\tcfg->version = gf_bs_read_int(bs, 7);\n\tcfg->seq_profile = gf_bs_read_int(bs, 3);\n\tcfg->seq_level_idx_0 = gf_bs_read_int(bs, 5);\n\tcfg->seq_tier_0 = gf_bs_read_int(bs, 1);\n\tcfg->high_bitdepth = gf_bs_read_int(bs, 1);\n\tcfg->twelve_bit = gf_bs_read_int(bs, 1);\n\tcfg->monochrome = gf_bs_read_int(bs, 1);\n\tcfg->chroma_subsampling_x = gf_bs_read_int(bs, 1);\n\tcfg->chroma_subsampling_y = gf_bs_read_int(bs, 1);\n\tcfg->chroma_sample_position = gf_bs_read_int(bs, 2);\n\n\treserved = gf_bs_read_int(bs, 3);\n\tif (reserved != 0 || cfg->marker != 1 || cfg->version != 1) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] wrong avcC reserved %d / marker %d / version %d expecting 0 1 1\\n\", reserved, cfg->marker, cfg->version));\n\t\tgf_odf_av1_cfg_del(cfg);\n\t\treturn NULL;\n\t}\n\tcfg->initial_presentation_delay_present = gf_bs_read_int(bs, 1);\n\tif (cfg->initial_presentation_delay_present) {\n\t\tcfg->initial_presentation_delay_minus_one = gf_bs_read_int(bs, 4);\n\t} else {\n\t\t/*reserved = */gf_bs_read_int(bs, 4);\n\t\tcfg->initial_presentation_delay_minus_one = 0;\n\t}\n\tsize -= 4;\n\n\twhile (size) {\n\t\tu64 pos, obu_size;\n\t\tObuType obu_type;\n\t\tGF_AV1_OBUArrayEntry *a;\n\n\t\tpos = gf_bs_get_position(bs);\n\t\tobu_size = 0;\n\t\tif (gf_av1_parse_obu(bs, &obu_type, &obu_size, NULL, &state) != GF_OK) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[AV1] could not parse AV1 OBU at position \"LLU\". Leaving parsing.\\n\", pos));\n\t\t\tbreak;\n\t\t}\n\t\tassert(obu_size == gf_bs_get_position(bs) - pos);\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] parsed AV1 OBU type=%u size=\"LLU\" at position \"LLU\".\\n\", obu_type, obu_size, pos));\n\n\t\tif (!av1_is_obu_header(obu_type)) {\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] AV1 unexpected OBU type=%u size=\"LLU\" found at position \"LLU\". Forwarding.\\n\", pos));\n\t\t}\n\t\tGF_SAFEALLOC(a, GF_AV1_OBUArrayEntry);\n\t\tif (!a) break;\n\t\ta->obu = gf_malloc((size_t)obu_size);\n\t\tif (!a->obu) {\n\t\t\tgf_free(a);\n\t\t\tbreak;\n\t\t}\n\t\tgf_bs_seek(bs, pos);\n\t\tgf_bs_read_data(bs, (char *) a->obu, (u32)obu_size);\n\t\ta->obu_length = obu_size;\n\t\ta->obu_type = obu_type;\n\t\tgf_list_add(cfg->obu_array, a);\n\n\t\tif (size\nSigned-off-by: Maxim Levitsky \nSigned-off-by: Paolo Bonzini ", "target": 1, "func": "void recalc_intercepts(struct vcpu_svm *svm)\n{\n\tstruct vmcb_control_area *c, *h, *g;\n\tunsigned int i;\n\n\tvmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);\n\n\tif (!is_guest_mode(&svm->vcpu))\n\t\treturn;\n\n\tc = &svm->vmcb->control;\n\th = &svm->vmcb01.ptr->control;\n\tg = &svm->nested.ctl;\n\n\tfor (i = 0; i < MAX_INTERCEPT; i++)\n\t\tc->intercepts[i] = h->intercepts[i];\n\n\tif (g->int_ctl & V_INTR_MASKING_MASK) {\n\t\t/* We only want the cr8 intercept bits of L1 */\n\t\tvmcb_clr_intercept(c, INTERCEPT_CR8_READ);\n\t\tvmcb_clr_intercept(c, INTERCEPT_CR8_WRITE);\n\n\t\t/*\n\t\t * Once running L2 with HF_VINTR_MASK, EFLAGS.IF does not\n\t\t * affect any interrupt we may want to inject; therefore,\n\t\t * interrupt window vmexits are irrelevant to L0.\n\t\t */\n\t\tvmcb_clr_intercept(c, INTERCEPT_VINTR);\n\t}\n\n\t/* We don't want to see VMMCALLs from a nested guest */\n\tvmcb_clr_intercept(c, INTERCEPT_VMMCALL);\n\n\tfor (i = 0; i < MAX_INTERCEPT; i++)\n\t\tc->intercepts[i] |= g->intercepts[i];\n\n\t/* If SMI is not intercepted, ignore guest SMI intercept as well */\n\tif (!intercept_smi)\n\t\tvmcb_clr_intercept(c, INTERCEPT_SMI);\n}", "func_hash": 308018010909685377463219146239861290533, "file_name": "None", "file_hash": null, "cwe": ["CWE-862"], "cve": "CVE-2021-3656", "cve_desc": "A flaw was found in the KVM's AMD code for supporting SVM nested virtualization. The flaw occurs when processing the VMCB (virtual machine control block) provided by the L1 guest to spawn/handle a nested guest (L2). Due to improper validation of the \"virt_ext\" field, this issue could allow a malicious L1 to disable both VMLOAD/VMSAVE intercepts and VLS (Virtual VMLOAD/VMSAVE) for the L2 guest. As a result, the L2 guest would be allowed to read/write physical pages of the host, resulting in a crash of the entire system, leak of sensitive data or potential guest-to-host escape.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3656"} {"idx": 221413, "project": "linux", "commit_id": "c7dfa4009965a9b2d7b329ee970eb8da0d32f0bc", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/c7dfa4009965a9b2d7b329ee970eb8da0d32f0bc", "commit_message": "KVM: nSVM: always intercept VMLOAD/VMSAVE when nested (CVE-2021-3656)\n\nIf L1 disables VMLOAD/VMSAVE intercepts, and doesn't enable\nVirtual VMLOAD/VMSAVE (currently not supported for the nested hypervisor),\nthen VMLOAD/VMSAVE must operate on the L1 physical memory, which is only\npossible by making L0 intercept these instructions.\n\nFailure to do so allowed the nested guest to run VMLOAD/VMSAVE unintercepted,\nand thus read/write portions of the host physical memory.\n\nFixes: 89c8a4984fc9 (\"KVM: SVM: Enable Virtual VMLOAD VMSAVE feature\")\n\nSuggested-by: Paolo Bonzini \nSigned-off-by: Maxim Levitsky \nSigned-off-by: Paolo Bonzini ", "target": 0, "func": "void recalc_intercepts(struct vcpu_svm *svm)\n{\n\tstruct vmcb_control_area *c, *h, *g;\n\tunsigned int i;\n\n\tvmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);\n\n\tif (!is_guest_mode(&svm->vcpu))\n\t\treturn;\n\n\tc = &svm->vmcb->control;\n\th = &svm->vmcb01.ptr->control;\n\tg = &svm->nested.ctl;\n\n\tfor (i = 0; i < MAX_INTERCEPT; i++)\n\t\tc->intercepts[i] = h->intercepts[i];\n\n\tif (g->int_ctl & V_INTR_MASKING_MASK) {\n\t\t/* We only want the cr8 intercept bits of L1 */\n\t\tvmcb_clr_intercept(c, INTERCEPT_CR8_READ);\n\t\tvmcb_clr_intercept(c, INTERCEPT_CR8_WRITE);\n\n\t\t/*\n\t\t * Once running L2 with HF_VINTR_MASK, EFLAGS.IF does not\n\t\t * affect any interrupt we may want to inject; therefore,\n\t\t * interrupt window vmexits are irrelevant to L0.\n\t\t */\n\t\tvmcb_clr_intercept(c, INTERCEPT_VINTR);\n\t}\n\n\t/* We don't want to see VMMCALLs from a nested guest */\n\tvmcb_clr_intercept(c, INTERCEPT_VMMCALL);\n\n\tfor (i = 0; i < MAX_INTERCEPT; i++)\n\t\tc->intercepts[i] |= g->intercepts[i];\n\n\t/* If SMI is not intercepted, ignore guest SMI intercept as well */\n\tif (!intercept_smi)\n\t\tvmcb_clr_intercept(c, INTERCEPT_SMI);\n\n\tvmcb_set_intercept(c, INTERCEPT_VMLOAD);\n\tvmcb_set_intercept(c, INTERCEPT_VMSAVE);\n}", "func_hash": 61346983903340748153155985789359366401, "file_name": "None", "file_hash": null, "cwe": ["CWE-862"], "cve": "CVE-2021-3656", "cve_desc": "A flaw was found in the KVM's AMD code for supporting SVM nested virtualization. The flaw occurs when processing the VMCB (virtual machine control block) provided by the L1 guest to spawn/handle a nested guest (L2). Due to improper validation of the \"virt_ext\" field, this issue could allow a malicious L1 to disable both VMLOAD/VMSAVE intercepts and VLS (Virtual VMLOAD/VMSAVE) for the L2 guest. As a result, the L2 guest would be allowed to read/write physical pages of the host, resulting in a crash of the entire system, leak of sensitive data or potential guest-to-host escape.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3656"} {"idx": 195083, "project": "tensorflow", "commit_id": "5b491cd5e41ad63735161cec9c2a568172c8b6a3", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/5b491cd5e41ad63735161cec9c2a568172c8b6a3", "commit_message": "Validate `proto.dtype()` before calling `set_dtype()`.\n\nThis prevents a `DCHECK`-fail when the proto contains an invalid dtype for a tensor shape with 0 elements or for an incomplete tensor shape.\n\nPiperOrigin-RevId: 408369083\nChange-Id: Ia21a3e3d62a90d642a4561f08f3b543e5ad00c46", "target": 1, "func": "bool Tensor::FromProto(Allocator* a, const TensorProto& proto) {\n CHECK_NOTNULL(a);\n TensorBuffer* p = nullptr;\n if (!TensorShape::IsValid(proto.tensor_shape())) return false;\n if (proto.dtype() == DT_INVALID) return false;\n TensorShape shape(proto.tensor_shape());\n const int64_t N = shape.num_elements();\n if (N > 0 && proto.dtype()) {\n bool dtype_error = false;\n if (!proto.tensor_content().empty()) {\n const auto& content = proto.tensor_content();\n CASES_WITH_DEFAULT(proto.dtype(), p = Helper::Decode(a, content, N),\n dtype_error = true, dtype_error = true);\n } else {\n CASES_WITH_DEFAULT(proto.dtype(), p = FromProtoField(a, proto, N),\n dtype_error = true, dtype_error = true);\n }\n if (dtype_error || p == nullptr) return false;\n }\n shape_ = shape;\n set_dtype(proto.dtype());\n UnrefIfNonNull(buf_);\n buf_ = p;\n // TODO(misard) add tracking of which kernels and steps are calling\n // FromProto.\n if (MemoryLoggingEnabled() && buf_ != nullptr && buf_->data() != nullptr) {\n LogMemory::RecordTensorAllocation(\"Unknown (from Proto)\",\n LogMemory::UNKNOWN_STEP_ID, *this);\n }\n return true;\n}", "func_hash": 112719252128622113589892906952570683457, "file_name": "tensor.cc", "file_hash": 289613009517546867193769314060658742037, "cwe": ["CWE-617"], "cve": "CVE-2022-23571", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. When decoding a tensor from protobuf, a TensorFlow process can encounter cases where a `CHECK` assertion is invalidated based on user controlled arguments, if the tensors have an invalid `dtype` and 0 elements or an invalid shape. This allows attackers to cause denial of services in TensorFlow processes. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23571"} {"idx": 221428, "project": "tensorflow", "commit_id": "5b491cd5e41ad63735161cec9c2a568172c8b6a3", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/5b491cd5e41ad63735161cec9c2a568172c8b6a3", "commit_message": "Validate `proto.dtype()` before calling `set_dtype()`.\n\nThis prevents a `DCHECK`-fail when the proto contains an invalid dtype for a tensor shape with 0 elements or for an incomplete tensor shape.\n\nPiperOrigin-RevId: 408369083\nChange-Id: Ia21a3e3d62a90d642a4561f08f3b543e5ad00c46", "target": 0, "func": "bool Tensor::FromProto(Allocator* a, const TensorProto& proto) {\n CHECK_NOTNULL(a);\n TensorBuffer* p = nullptr;\n if (!TensorShape::IsValid(proto.tensor_shape())) return false;\n if (proto.dtype() == DT_INVALID) return false;\n TensorShape shape(proto.tensor_shape());\n const int64_t N = shape.num_elements();\n if (N > 0 && proto.dtype()) {\n bool dtype_error = false;\n if (!proto.tensor_content().empty()) {\n const auto& content = proto.tensor_content();\n CASES_WITH_DEFAULT(proto.dtype(), p = Helper::Decode(a, content, N),\n dtype_error = true, dtype_error = true);\n } else {\n CASES_WITH_DEFAULT(proto.dtype(), p = FromProtoField(a, proto, N),\n dtype_error = true, dtype_error = true);\n }\n if (dtype_error || p == nullptr) return false;\n } else {\n // Handle the case of empty tensors (N = 0) or tensors with incomplete shape\n // (N = -1). All other values of `shape.num_elements()` should be invalid by\n // construction.\n // Here, we just need to validate that the `proto.dtype()` value is valid.\n bool dtype_error = false;\n CASES_WITH_DEFAULT(proto.dtype(), break, dtype_error = true,\n dtype_error = true);\n if (dtype_error) return false;\n }\n shape_ = shape;\n set_dtype(proto.dtype());\n UnrefIfNonNull(buf_);\n buf_ = p;\n // TODO(misard) add tracking of which kernels and steps are calling\n // FromProto.\n if (MemoryLoggingEnabled() && buf_ != nullptr && buf_->data() != nullptr) {\n LogMemory::RecordTensorAllocation(\"Unknown (from Proto)\",\n LogMemory::UNKNOWN_STEP_ID, *this);\n }\n return true;\n}", "func_hash": 12020279702191708342972381802829194549, "file_name": "tensor.cc", "file_hash": 303884711858139014412460575672580480868, "cwe": ["CWE-617"], "cve": "CVE-2022-23571", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. When decoding a tensor from protobuf, a TensorFlow process can encounter cases where a `CHECK` assertion is invalidated based on user controlled arguments, if the tensors have an invalid `dtype` and 0 elements or an invalid shape. This allows attackers to cause denial of services in TensorFlow processes. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23571"} {"idx": 195091, "project": "tensorflow", "commit_id": "35f0fabb4c178253a964d7aabdbb15c6a398b69a", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/35f0fabb4c178253a964d7aabdbb15c6a398b69a", "commit_message": "Avoid Segfault for scalar shapes.\n\nCalling tensor::FromElementsOp with an empty vector of elements and no type\ncauses a segfault. We need to let the FromElementsOp know which scalar type it\nshould have.\nAlso add back the DynamicBroadcastInDimOp canonicalization patterns, which\npreviously prevented this bug from happening.\nAdd a regression test that demonstrates the bug.\n\nPiperOrigin-RevId: 417561444\nChange-Id: I6d1d6cfb71aabbad6102422625a00bbe253ac95a", "target": 1, "func": "llvm::Optional simplifyBroadcast(ShapeComponentAnalysis& analysis,\n ValueRange shapes, Location loc,\n OpBuilder* builder) {\n // First find the input shape with the largest rank.\n SmallVector> shapes_found;\n size_t maxRank = 0;\n for (const auto &shape : llvm::enumerate(shapes)) {\n auto found_shape = analysis.GetValueInfo(shape.value());\n if (!found_shape) return {};\n shapes_found.push_back(*found_shape);\n maxRank = std::max(maxRank, found_shape->size());\n }\n\n SmallVector joined_dimensions(\n maxRank);\n SmallVector> shape_and_rank_for_dim(maxRank);\n for (const auto &shape : llvm::enumerate(shapes_found)) {\n for (const auto &dim : llvm::enumerate(llvm::reverse(shape.value()))) {\n // 1 dimensions don't contribute to the final result.\n if (dim.value().isConstant(1)) continue;\n // If it's not a 1 dimension it will be present in the result. Remember\n // where it came from.\n auto index = maxRank - dim.index() - 1;\n if (!joined_dimensions[index]) {\n joined_dimensions[index] = &dim.value();\n shape_and_rank_for_dim[index] =\n std::make_pair(shapes[shape.index()], shape.value().size());\n continue;\n }\n // Bail if the dimensions are neither equal nor 1.\n if (*joined_dimensions[index] != dim.value()) return {};\n }\n }\n // If the output is the same as one of the inputs just return that.\n if (llvm::is_splat(shape_and_rank_for_dim) &&\n shape_and_rank_for_dim[0].first) {\n return shape_and_rank_for_dim[0].first;\n }\n // Otherwise rematerialize the shape from the pieces we have.\n SmallVector elements;\n for (int i = 0; i != maxRank; ++i) {\n // 1 dimensions are filtered above, recreate the constant.\n if (!shape_and_rank_for_dim[i].first) {\n auto one = builder->getIntegerAttr(\n shapes[0].getType().cast().getElementType(), 1);\n elements.push_back(builder->create(loc, one));\n continue;\n }\n // Extract from one of the shapes, accounting for the reverse indexing\n // performed by broadcast.\n Value index = builder->create(\n loc, i - maxRank + shape_and_rank_for_dim[i].second);\n elements.push_back(builder->create(\n loc, shape_and_rank_for_dim[i].first, index));\n }\n return Value(builder->create(loc, elements));\n}", "func_hash": 84683486121098934971147990908524528886, "file_name": "tf_cpurt_symbolic_shape_optimization.cc", "file_hash": 183860206963562900623001205261417288221, "cwe": ["CWE-754"], "cve": "CVE-2022-23593", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The `simplifyBroadcast` function in the MLIR-TFRT infrastructure in TensorFlow is vulnerable to a segfault (hence, denial of service), if called with scalar shapes. If all shapes are scalar, then `maxRank` is 0, so we build an empty `SmallVector`. The fix will be included in TensorFlow 2.8.0. This is the only affected version.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23593"} {"idx": 221631, "project": "tensorflow", "commit_id": "35f0fabb4c178253a964d7aabdbb15c6a398b69a", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/35f0fabb4c178253a964d7aabdbb15c6a398b69a", "commit_message": "Avoid Segfault for scalar shapes.\n\nCalling tensor::FromElementsOp with an empty vector of elements and no type\ncauses a segfault. We need to let the FromElementsOp know which scalar type it\nshould have.\nAlso add back the DynamicBroadcastInDimOp canonicalization patterns, which\npreviously prevented this bug from happening.\nAdd a regression test that demonstrates the bug.\n\nPiperOrigin-RevId: 417561444\nChange-Id: I6d1d6cfb71aabbad6102422625a00bbe253ac95a", "target": 0, "func": "llvm::Optional simplifyBroadcast(ShapeComponentAnalysis& analysis,\n ValueRange shapes, Location loc,\n OpBuilder* builder) {\n // First find the input shape with the largest rank.\n SmallVector> shapes_found;\n size_t maxRank = 0;\n for (const auto &shape : llvm::enumerate(shapes)) {\n auto found_shape = analysis.GetValueInfo(shape.value());\n if (!found_shape) return {};\n shapes_found.push_back(*found_shape);\n maxRank = std::max(maxRank, found_shape->size());\n }\n if (maxRank == 0) {\n return Value(builder->create(\n loc, shapes[0].getType(), SmallVector()));\n }\n\n SmallVector joined_dimensions(\n maxRank);\n SmallVector> shape_and_rank_for_dim(maxRank);\n for (const auto &shape : llvm::enumerate(shapes_found)) {\n for (const auto &dim : llvm::enumerate(llvm::reverse(shape.value()))) {\n // 1 dimensions don't contribute to the final result.\n if (dim.value().isConstant(1)) continue;\n // If it's not a 1 dimension it will be present in the result. Remember\n // where it came from.\n auto index = maxRank - dim.index() - 1;\n if (!joined_dimensions[index]) {\n joined_dimensions[index] = &dim.value();\n shape_and_rank_for_dim[index] =\n std::make_pair(shapes[shape.index()], shape.value().size());\n continue;\n }\n // Bail if the dimensions are neither equal nor 1.\n if (*joined_dimensions[index] != dim.value()) return {};\n }\n }\n // If the output is the same as one of the inputs just return that.\n if (llvm::is_splat(shape_and_rank_for_dim) &&\n shape_and_rank_for_dim[0].first) {\n return shape_and_rank_for_dim[0].first;\n }\n // Otherwise rematerialize the shape from the pieces we have.\n SmallVector elements;\n for (int i = 0; i != maxRank; ++i) {\n // 1 dimensions are filtered above, recreate the constant.\n if (!shape_and_rank_for_dim[i].first) {\n auto one = builder->getIntegerAttr(\n shapes[0].getType().cast().getElementType(), 1);\n elements.push_back(builder->create(loc, one));\n continue;\n }\n // Extract from one of the shapes, accounting for the reverse indexing\n // performed by broadcast.\n Value index = builder->create(\n loc, i - maxRank + shape_and_rank_for_dim[i].second);\n elements.push_back(builder->create(\n loc, shape_and_rank_for_dim[i].first, index));\n }\n return Value(builder->create(loc, elements));\n}", "func_hash": 131837408517580503230068988683463768929, "file_name": "tf_cpurt_symbolic_shape_optimization.cc", "file_hash": 61127670286277963749447708912499557476, "cwe": ["CWE-754"], "cve": "CVE-2022-23593", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The `simplifyBroadcast` function in the MLIR-TFRT infrastructure in TensorFlow is vulnerable to a segfault (hence, denial of service), if called with scalar shapes. If all shapes are scalar, then `maxRank` is 0, so we build an empty `SmallVector`. The fix will be included in TensorFlow 2.8.0. This is the only affected version.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23593"} {"idx": 195092, "project": "hermes", "commit_id": "55e1b2343f4deb1a1b5726cfe1e23b2068217ff2", "project_url": "https://github.com/facebook/hermes", "commit_url": "https://github.com/facebook/hermes/commit/55e1b2343f4deb1a1b5726cfe1e23b2068217ff2", "commit_message": "Handle typeof applied to empty in InstSimplify\n\nSummary:\nDo not simplify `typeof` if it is applied to an invalid type. This\nhandles a case like the one in the added test, where `typeof` is called\non a literal empty in unreachable code.\n\nReviewed By: kodafb\n\nDifferential Revision: D31000173\n\nfbshipit-source-id: 2d7f69cbcc9c1bb0a916585c07171089444c85dc", "target": 1, "func": "Literal *hermes::evalUnaryOperator(\n UnaryOperatorInst::OpKind kind,\n IRBuilder &builder,\n Literal *operand) {\n switch (kind) {\n case UnaryOperatorInst::OpKind::MinusKind:\n // Negate constant integers.\n switch (operand->getKind()) {\n case ValueKind::LiteralNumberKind:\n if (auto *literalNum = llvh::dyn_cast(operand)) {\n auto V = -literalNum->getValue();\n return builder.getLiteralNumber(V);\n }\n break;\n case ValueKind::LiteralUndefinedKind:\n return builder.getLiteralNaN();\n case ValueKind::LiteralBoolKind:\n if (evalIsTrue(builder, operand)) {\n return builder.getLiteralNumber(-1);\n } else { // evalIsFalse(operand)\n return builder.getLiteralNegativeZero();\n }\n case ValueKind::LiteralNullKind:\n return builder.getLiteralNegativeZero();\n default:\n break;\n }\n break;\n case UnaryOperatorInst::OpKind::TypeofKind:\n switch (operand->getKind()) {\n case ValueKind::GlobalObjectKind:\n case ValueKind::LiteralNullKind:\n return builder.getLiteralString(\"object\");\n case ValueKind::LiteralUndefinedKind:\n return builder.getLiteralString(\"undefined\");\n case ValueKind::LiteralBoolKind:\n return builder.getLiteralString(\"boolean\");\n case ValueKind::LiteralNumberKind:\n return builder.getLiteralString(\"number\");\n case ValueKind::LiteralStringKind:\n return builder.getLiteralString(\"string\");\n default:\n llvm_unreachable(\"Invalid literal kind.\");\n }\n break;\n\n case UnaryOperatorInst::OpKind::BangKind:\n if (evalIsTrue(builder, operand)) {\n return builder.getLiteralBool(false);\n }\n if (evalIsFalse(builder, operand)) {\n return builder.getLiteralBool(true);\n }\n break;\n\n case UnaryOperatorInst::OpKind::VoidKind:\n return builder.getLiteralUndefined();\n\n default:\n break;\n }\n\n return nullptr;\n}", "func_hash": 318397569222892175642900890058916302083, "file_name": "IREval.cpp", "file_hash": 25640608993938735880507555687030796129, "cwe": ["CWE-843"], "cve": "CVE-2021-24045", "cve_desc": "A type confusion vulnerability could be triggered when resolving the \"typeof\" unary operator in Facebook Hermes prior to v0.10.0. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-24045"} {"idx": 221651, "project": "hermes", "commit_id": "55e1b2343f4deb1a1b5726cfe1e23b2068217ff2", "project_url": "https://github.com/facebook/hermes", "commit_url": "https://github.com/facebook/hermes/commit/55e1b2343f4deb1a1b5726cfe1e23b2068217ff2", "commit_message": "Handle typeof applied to empty in InstSimplify\n\nSummary:\nDo not simplify `typeof` if it is applied to an invalid type. This\nhandles a case like the one in the added test, where `typeof` is called\non a literal empty in unreachable code.\n\nReviewed By: kodafb\n\nDifferential Revision: D31000173\n\nfbshipit-source-id: 2d7f69cbcc9c1bb0a916585c07171089444c85dc", "target": 0, "func": "Literal *hermes::evalUnaryOperator(\n UnaryOperatorInst::OpKind kind,\n IRBuilder &builder,\n Literal *operand) {\n switch (kind) {\n case UnaryOperatorInst::OpKind::MinusKind:\n // Negate constant integers.\n switch (operand->getKind()) {\n case ValueKind::LiteralNumberKind:\n if (auto *literalNum = llvh::dyn_cast(operand)) {\n auto V = -literalNum->getValue();\n return builder.getLiteralNumber(V);\n }\n break;\n case ValueKind::LiteralUndefinedKind:\n return builder.getLiteralNaN();\n case ValueKind::LiteralBoolKind:\n if (evalIsTrue(builder, operand)) {\n return builder.getLiteralNumber(-1);\n } else { // evalIsFalse(operand)\n return builder.getLiteralNegativeZero();\n }\n case ValueKind::LiteralNullKind:\n return builder.getLiteralNegativeZero();\n default:\n break;\n }\n break;\n case UnaryOperatorInst::OpKind::TypeofKind:\n switch (operand->getKind()) {\n case ValueKind::GlobalObjectKind:\n case ValueKind::LiteralNullKind:\n return builder.getLiteralString(\"object\");\n case ValueKind::LiteralUndefinedKind:\n return builder.getLiteralString(\"undefined\");\n case ValueKind::LiteralBoolKind:\n return builder.getLiteralString(\"boolean\");\n case ValueKind::LiteralNumberKind:\n return builder.getLiteralString(\"number\");\n case ValueKind::LiteralStringKind:\n return builder.getLiteralString(\"string\");\n default:\n break;\n }\n break;\n\n case UnaryOperatorInst::OpKind::BangKind:\n if (evalIsTrue(builder, operand)) {\n return builder.getLiteralBool(false);\n }\n if (evalIsFalse(builder, operand)) {\n return builder.getLiteralBool(true);\n }\n break;\n\n case UnaryOperatorInst::OpKind::VoidKind:\n return builder.getLiteralUndefined();\n\n default:\n break;\n }\n\n return nullptr;\n}", "func_hash": 123137692006195986808828639392289766950, "file_name": "IREval.cpp", "file_hash": 42961914778696217563735135747458181955, "cwe": ["CWE-843"], "cve": "CVE-2021-24045", "cve_desc": "A type confusion vulnerability could be triggered when resolving the \"typeof\" unary operator in Facebook Hermes prior to v0.10.0. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-24045"} {"idx": 195095, "project": "e2guardian", "commit_id": "eae46a7e2a57103aadca903c4a24cca94dc502a2", "project_url": "https://github.com/e2guardian/e2guardian", "commit_url": "https://github.com/e2guardian/e2guardian/commit/eae46a7e2a57103aadca903c4a24cca94dc502a2", "commit_message": "Fix bug #707 cert hostnames not being checked\n- only happened when openssl v1.1 is used", "target": 1, "func": "int Socket::startSslClient(const std::string &certificate_path, String hostname)\n{\n if (isssl) {\n stopSsl();\n }\n\n ERR_clear_error();\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n ctx = SSL_CTX_new(SSLv23_client_method());\n#else\n ctx = SSL_CTX_new(TLS_client_method());\n#endif\n\n if (ctx == NULL) {\n#ifdef NETDEBUG\n std::cout << thread_id << \"Error ssl context is null (check that openssl has been inited)\" << std::endl;\n#endif\n log_ssl_errors(\"Error ssl context is null for %s\", hostname.c_str());\n return -1;\n }\n\n //set the timeout for the ssl session\n if (SSL_CTX_set_timeout(ctx, 130l) < 1) {\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -1;\n }\n\n //load certs\n ERR_clear_error();\n if (certificate_path.length()) {\n if (!SSL_CTX_load_verify_locations(ctx, NULL, certificate_path.c_str())) {\n#ifdef NETDEBUG\n std::cout << thread_id << \"couldnt load certificates\" << std::endl;\n#endif\n log_ssl_errors(\"couldnt load certificates from %s\", certificate_path.c_str());\n //tidy up\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -2;\n }\n } else if (!SSL_CTX_set_default_verify_paths(ctx)) //use default if no certPpath given\n {\n#ifdef NETDEBUG\n std::cout << thread_id << \"couldnt load certificates\" << std::endl;\n#endif\n log_ssl_errors(\"couldnt load default certificates for %s\", hostname.c_str());\n //tidy up\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -2;\n }\n\n // add validation params\n ERR_clear_error();\n X509_VERIFY_PARAM *x509_param = X509_VERIFY_PARAM_new();\n if (!x509_param) {\n log_ssl_errors(\"couldnt add validation params for %s\", hostname.c_str());\n //X509_VERIFY_PARAM_free(x509_param);\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -2;\n }\n\n ERR_clear_error();\n if (!X509_VERIFY_PARAM_set_flags(x509_param, X509_V_FLAG_TRUSTED_FIRST)) {\n log_ssl_errors(\"couldnt add validation params for %s\", hostname.c_str());\n X509_VERIFY_PARAM_free(x509_param);\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -2;\n }\n\n ERR_clear_error();\n if (!SSL_CTX_set1_param(ctx, x509_param)) {\n log_ssl_errors(\"couldnt add validation params for %s\", hostname.c_str());\n X509_VERIFY_PARAM_free(x509_param);\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -2;\n }\n\n X509_VERIFY_PARAM_free(x509_param); // try not freeing this as SSL_CTX_free seems to be ring to free it\n\n //hand socket over to ssl lib\n ERR_clear_error();\n ssl = SSL_new(ctx);\n SSL_set_options(ssl, SSL_OP_ALL);\n SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);\n SSL_set_connect_state(ssl);\n\n //fcntl(this->getFD() ,F_SETFL, O_NONBLOCK); // blocking mode used currently\n SSL_set_fd(ssl, this->getFD());\n SSL_set_tlsext_host_name(ssl, hostname.c_str());\n\n //make io non blocking as select wont tell us if we can do a read without blocking\n //BIO_set_nbio(SSL_get_rbio(ssl),1l); // blocking mode used currently\n //BIO_set_nbio(SSL_get_wbio(ssl),1l); // blocking mode used currently\n ERR_clear_error();\n int rc = SSL_connect(ssl);\n if (rc < 0) {\n log_ssl_errors(\"ssl_connect failed to %s\", hostname.c_str());\n#ifdef NETDEBUG\n std::cout << thread_id << \"ssl_connect failed with error \" << SSL_get_error(ssl, rc) << std::endl;\n#endif\n // tidy up\n SSL_free(ssl);\n ssl = NULL;\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -3;\n }\n\n //should be safer to do this last as nothing will ever try to use a ssl socket that isnt fully setup\n isssl = true;\n issslserver = false;\n return 0;\n}", "func_hash": 285364534121786496260977042144971081331, "file_name": "Socket.cpp", "file_hash": 283084154597152068392957992825637904487, "cwe": ["CWE-295"], "cve": "CVE-2021-44273", "cve_desc": "e2guardian v5.4.x <= v5.4.3r is affected by missing SSL certificate validation in the SSL MITM engine. In standalone mode (i.e., acting as a proxy or a transparent proxy), with SSL MITM enabled, e2guardian, if built with OpenSSL v1.1.x, did not validate hostnames in certificates of the web servers that it connected to, and thus was itself vulnerable to MITM attacks.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-44273"} {"idx": 221678, "project": "e2guardian", "commit_id": "eae46a7e2a57103aadca903c4a24cca94dc502a2", "project_url": "https://github.com/e2guardian/e2guardian", "commit_url": "https://github.com/e2guardian/e2guardian/commit/eae46a7e2a57103aadca903c4a24cca94dc502a2", "commit_message": "Fix bug #707 cert hostnames not being checked\n- only happened when openssl v1.1 is used", "target": 0, "func": "int Socket::startSslClient(const std::string &certificate_path, String hostname)\n{\n if (isssl) {\n stopSsl();\n }\n\n ERR_clear_error();\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n ctx = SSL_CTX_new(SSLv23_client_method());\n#else\n ctx = SSL_CTX_new(TLS_client_method());\n#endif\n\n if (ctx == NULL) {\n#ifdef NETDEBUG\n std::cout << thread_id << \"Error ssl context is null (check that openssl has been inited)\" << std::endl;\n#endif\n log_ssl_errors(\"Error ssl context is null for %s\", hostname.c_str());\n return -1;\n }\n\n //set the timeout for the ssl session\n if (SSL_CTX_set_timeout(ctx, 130l) < 1) {\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -1;\n }\n\n //load certs\n ERR_clear_error();\n if (certificate_path.length()) {\n if (!SSL_CTX_load_verify_locations(ctx, NULL, certificate_path.c_str())) {\n#ifdef NETDEBUG\n std::cout << thread_id << \"couldnt load certificates\" << std::endl;\n#endif\n log_ssl_errors(\"couldnt load certificates from %s\", certificate_path.c_str());\n //tidy up\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -2;\n }\n } else if (!SSL_CTX_set_default_verify_paths(ctx)) //use default if no certPpath given\n {\n#ifdef NETDEBUG\n std::cout << thread_id << \"couldnt load certificates\" << std::endl;\n#endif\n log_ssl_errors(\"couldnt load default certificates for %s\", hostname.c_str());\n //tidy up\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -2;\n }\n\n // add validation params\n ERR_clear_error();\n X509_VERIFY_PARAM *x509_param = X509_VERIFY_PARAM_new();\n if (!x509_param) {\n log_ssl_errors(\"couldnt add validation params for %s\", hostname.c_str());\n //X509_VERIFY_PARAM_free(x509_param);\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -2;\n }\n\n ERR_clear_error();\n if (!X509_VERIFY_PARAM_set_flags(x509_param, X509_V_FLAG_TRUSTED_FIRST)) {\n log_ssl_errors(\"couldnt add validation params for %s\", hostname.c_str());\n X509_VERIFY_PARAM_free(x509_param);\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -2;\n }\n\n ERR_clear_error();\n if (!SSL_CTX_set1_param(ctx, x509_param)) {\n log_ssl_errors(\"couldnt add validation params for %s\", hostname.c_str());\n X509_VERIFY_PARAM_free(x509_param);\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -2;\n }\n\n X509_VERIFY_PARAM_free(x509_param); // try not freeing this as SSL_CTX_free seems to be ring to free it\n\n //hand socket over to ssl lib\n ERR_clear_error();\n ssl = SSL_new(ctx);\n SSL_set_options(ssl, SSL_OP_ALL);\n SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);\n SSL_set_connect_state(ssl);\n\n //fcntl(this->getFD() ,F_SETFL, O_NONBLOCK); // blocking mode used currently\n SSL_set_fd(ssl, this->getFD());\n SSL_set_tlsext_host_name(ssl, hostname.c_str());\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n#else\n X509_VERIFY_PARAM_set1_host(SSL_get0_param(ssl),hostname.c_str(),0);\n#endif\n\n //make io non blocking as select wont tell us if we can do a read without blocking\n //BIO_set_nbio(SSL_get_rbio(ssl),1l); // blocking mode used currently\n //BIO_set_nbio(SSL_get_wbio(ssl),1l); // blocking mode used currently\n ERR_clear_error();\n int rc = SSL_connect(ssl);\n if (rc < 0) {\n log_ssl_errors(\"ssl_connect failed to %s\", hostname.c_str());\n#ifdef NETDEBUG\n std::cout << thread_id << \"ssl_connect failed with error \" << SSL_get_error(ssl, rc) << std::endl;\n#endif\n // tidy up\n SSL_free(ssl);\n ssl = NULL;\n SSL_CTX_free(ctx);\n ctx = NULL;\n return -3;\n }\n\n //should be safer to do this last as nothing will ever try to use a ssl socket that isnt fully setup\n isssl = true;\n issslserver = false;\n return 0;\n}", "func_hash": 137664252347139284732164058213112105028, "file_name": "Socket.cpp", "file_hash": 316707147744091371767800459911917453562, "cwe": ["CWE-295"], "cve": "CVE-2021-44273", "cve_desc": "e2guardian v5.4.x <= v5.4.3r is affected by missing SSL certificate validation in the SSL MITM engine. In standalone mode (i.e., acting as a proxy or a transparent proxy), with SSL MITM enabled, e2guardian, if built with OpenSSL v1.1.x, did not validate hostnames in certificates of the web servers that it connected to, and thus was itself vulnerable to MITM attacks.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-44273"} {"idx": 195220, "project": "tmate-ssh-server", "commit_id": "1c020d1f5ca462f5b150b46a027aaa1bbe3c9596", "project_url": "https://github.com/tmate-io/tmate-ssh-server", "commit_url": "https://github.com/tmate-io/tmate-ssh-server/commit/1c020d1f5ca462f5b150b46a027aaa1bbe3c9596", "commit_message": "Harden /tmp/tmate directory\n\nSuggested by Matthias Gerstner", "target": 1, "func": "int main(int argc, char **argv, char **envp)\n{\n\tint opt;\n\n\twhile ((opt = getopt(argc, argv, \"b:h:k:p:q:w:z:xv\")) != -1) {\n\t\tswitch (opt) {\n\t\tcase 'b':\n\t\t\ttmate_settings->bind_addr = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\ttmate_settings->tmate_host = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'k':\n\t\t\ttmate_settings->keys_dir = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'p':\n\t\t\ttmate_settings->ssh_port = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\ttmate_settings->ssh_port_advertized = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'w':\n\t\t\ttmate_settings->websocket_hostname = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'z':\n\t\t\ttmate_settings->websocket_port = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'x':\n\t\t\ttmate_settings->use_proxy_protocol = true;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\ttmate_settings->log_level++;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage();\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tinit_logging(tmate_settings->log_level);\n\n\tsetup_locale();\n\n\tif (!tmate_settings->tmate_host)\n\t\ttmate_settings->tmate_host = get_full_hostname();\n\n\tcmdline = *argv;\n\tcmdline_end = *envp;\n\n\ttmate_preload_trace_lib();\n\ttmate_catch_sigsegv();\n\ttmate_init_rand();\n\n\tif ((mkdir(TMATE_WORKDIR, 0701) < 0 && errno != EEXIST) ||\n\t (mkdir(TMATE_WORKDIR \"/sessions\", 0703) < 0 && errno != EEXIST) ||\n\t (mkdir(TMATE_WORKDIR \"/jail\", 0700) < 0 && errno != EEXIST))\n\t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n\n\t/* The websocket server needs to access the /session dir to rename sockets */\n\tif ((chmod(TMATE_WORKDIR, 0701) < 0) ||\n\t (chmod(TMATE_WORKDIR \"/sessions\", 0703) < 0) ||\n\t (chmod(TMATE_WORKDIR \"/jail\", 0700) < 0))\n\t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n\n\ttmate_ssh_server_main(tmate_session,\n\t\t\t tmate_settings->keys_dir, tmate_settings->bind_addr, tmate_settings->ssh_port);\n\treturn 0;\n}", "func_hash": 154027151645284385944526585123822701001, "file_name": "tmate-main.c", "file_hash": 280350825550794138629823084137678566150, "cwe": ["CWE-362"], "cve": "CVE-2021-44512", "cve_desc": "World-writable permissions on the /tmp/tmate/sessions directory in tmate-ssh-server 2.3.0 allow a local attacker to compromise the integrity of session handling, or obtain the read-write session ID from a read-only session symlink in this directory.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-44512"} {"idx": 222666, "project": "tmate-ssh-server", "commit_id": "1c020d1f5ca462f5b150b46a027aaa1bbe3c9596", "project_url": "https://github.com/tmate-io/tmate-ssh-server", "commit_url": "https://github.com/tmate-io/tmate-ssh-server/commit/1c020d1f5ca462f5b150b46a027aaa1bbe3c9596", "commit_message": "Harden /tmp/tmate directory\n\nSuggested by Matthias Gerstner", "target": 0, "func": "int main(int argc, char **argv, char **envp)\n{\n\tint opt;\n\n\twhile ((opt = getopt(argc, argv, \"b:h:k:p:q:w:z:xv\")) != -1) {\n\t\tswitch (opt) {\n\t\tcase 'b':\n\t\t\ttmate_settings->bind_addr = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\ttmate_settings->tmate_host = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'k':\n\t\t\ttmate_settings->keys_dir = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'p':\n\t\t\ttmate_settings->ssh_port = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\ttmate_settings->ssh_port_advertized = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'w':\n\t\t\ttmate_settings->websocket_hostname = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'z':\n\t\t\ttmate_settings->websocket_port = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'x':\n\t\t\ttmate_settings->use_proxy_protocol = true;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\ttmate_settings->log_level++;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage();\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tinit_logging(tmate_settings->log_level);\n\n\tsetup_locale();\n\n\tif (!tmate_settings->tmate_host)\n\t\ttmate_settings->tmate_host = get_full_hostname();\n\n\tcmdline = *argv;\n\tcmdline_end = *envp;\n\n\ttmate_preload_trace_lib();\n\ttmate_catch_sigsegv();\n\ttmate_init_rand();\n\n\tif ((mkdir(TMATE_WORKDIR, 0700) < 0 && errno != EEXIST) ||\n\t (mkdir(TMATE_WORKDIR \"/sessions\", 0700) < 0 && errno != EEXIST) ||\n\t (mkdir(TMATE_WORKDIR \"/jail\", 0700) < 0 && errno != EEXIST))\n\t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n\n\tif ((chmod(TMATE_WORKDIR, 0700) < 0) ||\n\t (chmod(TMATE_WORKDIR \"/sessions\", 0700) < 0) ||\n\t (chmod(TMATE_WORKDIR \"/jail\", 0700) < 0))\n\t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n\n\tif (check_owned_directory_mode(TMATE_WORKDIR, 0700) ||\n\t check_owned_directory_mode(TMATE_WORKDIR \"/sessions\", 0700) ||\n\t check_owned_directory_mode(TMATE_WORKDIR \"/jail\", 0700))\n\t\ttmate_fatal(TMATE_WORKDIR \" and subdirectories has incorrect ownership/mode. \"\n\t\t\t \"Try deleting \" TMATE_WORKDIR \" and try again\");\n\n\ttmate_ssh_server_main(tmate_session,\n\t\t\t tmate_settings->keys_dir, tmate_settings->bind_addr, tmate_settings->ssh_port);\n\treturn 0;\n}", "func_hash": 271664953315961811306024013861867052587, "file_name": "tmate-main.c", "file_hash": 90810006588409733709876992634170493502, "cwe": ["CWE-362"], "cve": "CVE-2021-44512", "cve_desc": "World-writable permissions on the /tmp/tmate/sessions directory in tmate-ssh-server 2.3.0 allow a local attacker to compromise the integrity of session handling, or obtain the read-write session ID from a read-only session symlink in this directory.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-44512"} {"idx": 195230, "project": "pjproject", "commit_id": "f74c1fc22b760d2a24369aa72c74c4a9ab985859", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/f74c1fc22b760d2a24369aa72c74c4a9ab985859", "commit_message": "Merge pull request from GHSA-r374-qrwv-86hh", "target": 1, "func": "void pjmedia_rtcp_xr_rx_rtcp_xr( pjmedia_rtcp_xr_session *sess,\n\t\t\t\t const void *pkt,\n\t\t\t\t pj_size_t size)\n{\n const pjmedia_rtcp_xr_pkt\t *rtcp_xr = (pjmedia_rtcp_xr_pkt*) pkt;\n const pjmedia_rtcp_xr_rb_rr_time *rb_rr_time = NULL;\n const pjmedia_rtcp_xr_rb_dlrr *rb_dlrr = NULL;\n const pjmedia_rtcp_xr_rb_stats *rb_stats = NULL;\n const pjmedia_rtcp_xr_rb_voip_mtc *rb_voip_mtc = NULL;\n const pjmedia_rtcp_xr_rb_header *rb_hdr = (pjmedia_rtcp_xr_rb_header*) \n\t\t\t\t\t\trtcp_xr->buf;\n unsigned pkt_len, rb_len;\n\n if (rtcp_xr->common.pt != RTCP_XR)\n\treturn;\n\n pkt_len = pj_ntohs((pj_uint16_t)rtcp_xr->common.length);\n\n if ((pkt_len + 1) > (size / 4))\n\treturn;\n\n /* Parse report rpt_types */\n while ((pj_int32_t*)rb_hdr < (pj_int32_t*)pkt + pkt_len)\n {\t\n\trb_len = pj_ntohs((pj_uint16_t)rb_hdr->length);\n\n\t/* Just skip any block with length == 0 (no report content) */\n\tif (rb_len) {\n\t switch (rb_hdr->bt) {\n\t\tcase BT_RR_TIME:\n\t\t rb_rr_time = (pjmedia_rtcp_xr_rb_rr_time*) rb_hdr;\n\t\t break;\n\t\tcase BT_DLRR:\n\t\t rb_dlrr = (pjmedia_rtcp_xr_rb_dlrr*) rb_hdr;\n\t\t break;\n\t\tcase BT_STATS:\n\t\t rb_stats = (pjmedia_rtcp_xr_rb_stats*) rb_hdr;\n\t\t break;\n\t\tcase BT_VOIP_METRICS:\n\t\t rb_voip_mtc = (pjmedia_rtcp_xr_rb_voip_mtc*) rb_hdr;\n\t\t break;\n\t\tdefault:\n\t\t break;\n\t }\n\t}\n\trb_hdr = (pjmedia_rtcp_xr_rb_header*)\n\t\t ((pj_int32_t*)rb_hdr + rb_len + 1);\n }\n\n /* Receiving RR Time */\n if (rb_rr_time) {\n\t/* Save LRR from NTP timestamp of the RR time block report */\n\tsess->rx_lrr = ((pj_ntohl(rb_rr_time->ntp_sec) & 0x0000FFFF) << 16) | \n\t\t ((pj_ntohl(rb_rr_time->ntp_frac) >> 16) & 0xFFFF);\n\n\t/* Calculate RR arrival time for DLRR */\n\tpj_get_timestamp(&sess->rx_lrr_time);\n\n\tTRACE_((sess->name, \"Rx RTCP SR: ntp_ts=%p\", sess->rx_lrr,\n\t (pj_uint32_t)(sess->rx_lrr_time.u64*65536/\n\t\t\t sess->rtcp_session->ts_freq.u64)));\n }\n\n /* Receiving DLRR */\n if (rb_dlrr) {\n\tpj_uint32_t lrr, now, dlrr;\n\tpj_uint64_t eedelay;\n\tpjmedia_rtcp_ntp_rec ntp;\n\n\t/* LRR is the middle 32bit of NTP. It has 1/65536 second \n\t * resolution \n\t */\n\tlrr = pj_ntohl(rb_dlrr->item.lrr);\n\n\t/* DLRR is delay since LRR, also in 1/65536 resolution */\n\tdlrr = pj_ntohl(rb_dlrr->item.dlrr);\n\n\t/* Get current time, and convert to 1/65536 resolution */\n\tpjmedia_rtcp_get_ntp_time(sess->rtcp_session, &ntp);\n\tnow = ((ntp.hi & 0xFFFF) << 16) + (ntp.lo >> 16);\n\n\t/* End-to-end delay is (now-lrr-dlrr) */\n\teedelay = now - lrr - dlrr;\n\n\t/* Convert end to end delay to usec (keeping the calculation in\n * 64bit space)::\n\t * sess->ee_delay = (eedelay * 1000) / 65536;\n\t */\n\tif (eedelay < 4294) {\n\t eedelay = (eedelay * 1000000) >> 16;\n\t} else {\n\t eedelay = (eedelay * 1000) >> 16;\n\t eedelay *= 1000;\n\t}\n\n\tTRACE_((sess->name, \"Rx RTCP XR DLRR: lrr=%p, dlrr=%p (%d:%03dms), \"\n\t\t\t \"now=%p, rtt=%p\",\n\t\tlrr, dlrr, dlrr/65536, (dlrr%65536)*1000/65536,\n\t\tnow, (pj_uint32_t)eedelay));\n\t\n\t/* Only save calculation if \"now\" is greater than lrr, or\n\t * otherwise rtt will be invalid \n\t */\n\tif (now-dlrr >= lrr) {\n\t unsigned rtt = (pj_uint32_t)eedelay;\n\t \n\t /* Check that eedelay value really makes sense. \n\t * We allow up to 30 seconds RTT!\n\t */\n\t if (eedelay <= 30 * 1000 * 1000UL) {\n\t\t/* \"Normalize\" rtt value that is exceptionally high.\n\t\t * For such values, \"normalize\" the rtt to be three times\n\t\t * the average value.\n\t\t */\n\t\tif (rtt>((unsigned)sess->stat.rtt.mean*3) && sess->stat.rtt.n!=0)\n\t\t{\n\t\t unsigned orig_rtt = rtt;\n\t\t rtt = (unsigned)sess->stat.rtt.mean*3;\n\t\t PJ_LOG(5,(sess->name, \n\t\t\t \"RTT value %d usec is normalized to %d usec\",\n\t\t\t orig_rtt, rtt));\n\t\t}\n \t\n\t\tTRACE_((sess->name, \"RTCP RTT is set to %d usec\", rtt));\n\t\tpj_math_stat_update(&sess->stat.rtt, rtt);\n\t }\n\t} else {\n\t PJ_LOG(5, (sess->name, \"Internal RTCP NTP clock skew detected: \"\n\t\t\t\t \"lrr=%p, now=%p, dlrr=%p (%d:%03dms), \"\n\t\t\t\t \"diff=%d\",\n\t\t\t\t lrr, now, dlrr, dlrr/65536,\n\t\t\t\t (dlrr%65536)*1000/65536,\n\t\t\t\t dlrr-(now-lrr)));\n\t}\n }\n\n /* Receiving Statistics Summary */\n if (rb_stats) {\n\tpj_uint8_t flags = rb_stats->header.specific;\n\n\tpj_bzero(&sess->stat.tx.stat_sum, sizeof(sess->stat.tx.stat_sum));\n\n\t/* Range of packets sequence reported in this blocks */\n\tsess->stat.tx.stat_sum.begin_seq = pj_ntohs(rb_stats->begin_seq);\n\tsess->stat.tx.stat_sum.end_seq = pj_ntohs(rb_stats->end_seq);\n\n\t/* Get flags of valid fields */\n\tsess->stat.tx.stat_sum.l = (flags & (1 << 7)) != 0;\n\tsess->stat.tx.stat_sum.d = (flags & (1 << 6)) != 0;\n\tsess->stat.tx.stat_sum.j = (flags & (1 << 5)) != 0;\n\tsess->stat.tx.stat_sum.t = (flags & (3 << 3)) != 0;\n\n\t/* Fetch the reports info */\n\tif (sess->stat.tx.stat_sum.l) {\n\t sess->stat.tx.stat_sum.lost = pj_ntohl(rb_stats->lost);\n\t}\n\n\tif (sess->stat.tx.stat_sum.d) {\n\t sess->stat.tx.stat_sum.dup = pj_ntohl(rb_stats->dup);\n\t}\n\n\tif (sess->stat.tx.stat_sum.j) {\n\t sess->stat.tx.stat_sum.jitter.min = pj_ntohl(rb_stats->jitter_min);\n\t sess->stat.tx.stat_sum.jitter.max = pj_ntohl(rb_stats->jitter_max);\n\t sess->stat.tx.stat_sum.jitter.mean= pj_ntohl(rb_stats->jitter_mean);\n\t pj_math_stat_set_stddev(&sess->stat.tx.stat_sum.jitter, \n\t\t\t\t pj_ntohl(rb_stats->jitter_dev));\n\t}\n\n\tif (sess->stat.tx.stat_sum.t) {\n\t sess->stat.tx.stat_sum.toh.min = rb_stats->toh_min;\n\t sess->stat.tx.stat_sum.toh.max = rb_stats->toh_max;\n\t sess->stat.tx.stat_sum.toh.mean= rb_stats->toh_mean;\n\t pj_math_stat_set_stddev(&sess->stat.tx.stat_sum.toh, \n\t\t\t\t pj_ntohl(rb_stats->toh_dev));\n\t}\n\n\tpj_gettimeofday(&sess->stat.tx.stat_sum.update);\n }\n\n /* Receiving VoIP Metrics */\n if (rb_voip_mtc) {\n\tsess->stat.tx.voip_mtc.loss_rate = rb_voip_mtc->loss_rate;\n\tsess->stat.tx.voip_mtc.discard_rate = rb_voip_mtc->discard_rate;\n\tsess->stat.tx.voip_mtc.burst_den = rb_voip_mtc->burst_den;\n\tsess->stat.tx.voip_mtc.gap_den = rb_voip_mtc->gap_den;\n\tsess->stat.tx.voip_mtc.burst_dur = pj_ntohs(rb_voip_mtc->burst_dur);\n\tsess->stat.tx.voip_mtc.gap_dur = pj_ntohs(rb_voip_mtc->gap_dur);\n\tsess->stat.tx.voip_mtc.rnd_trip_delay = \n\t\t\t\t\tpj_ntohs(rb_voip_mtc->rnd_trip_delay);\n\tsess->stat.tx.voip_mtc.end_sys_delay = \n\t\t\t\t\tpj_ntohs(rb_voip_mtc->end_sys_delay);\n\t/* signal & noise level encoded in two's complement form */\n\tsess->stat.tx.voip_mtc.signal_lvl = (pj_int8_t)\n\t\t\t\t ((rb_voip_mtc->signal_lvl > 127)?\n\t\t\t\t ((int)rb_voip_mtc->signal_lvl - 256) : \n\t\t\t\t rb_voip_mtc->signal_lvl);\n\tsess->stat.tx.voip_mtc.noise_lvl = (pj_int8_t)\n\t\t\t\t ((rb_voip_mtc->noise_lvl > 127)?\n\t\t\t\t ((int)rb_voip_mtc->noise_lvl - 256) : \n\t\t\t\t rb_voip_mtc->noise_lvl);\n\tsess->stat.tx.voip_mtc.rerl = rb_voip_mtc->rerl;\n\tsess->stat.tx.voip_mtc.gmin = rb_voip_mtc->gmin;\n\tsess->stat.tx.voip_mtc.r_factor = rb_voip_mtc->r_factor;\n\tsess->stat.tx.voip_mtc.ext_r_factor = rb_voip_mtc->ext_r_factor;\n\tsess->stat.tx.voip_mtc.mos_lq = rb_voip_mtc->mos_lq;\n\tsess->stat.tx.voip_mtc.mos_cq = rb_voip_mtc->mos_cq;\n\tsess->stat.tx.voip_mtc.rx_config = rb_voip_mtc->rx_config;\n\tsess->stat.tx.voip_mtc.jb_nom = pj_ntohs(rb_voip_mtc->jb_nom);\n\tsess->stat.tx.voip_mtc.jb_max = pj_ntohs(rb_voip_mtc->jb_max);\n\tsess->stat.tx.voip_mtc.jb_abs_max = pj_ntohs(rb_voip_mtc->jb_abs_max);\n\n\tpj_gettimeofday(&sess->stat.tx.voip_mtc.update);\n }\n}", "func_hash": 128531615202269817130665554219664776865, "file_name": "rtcp_xr.c", "file_hash": 114410540091951766279707779044798368853, "cwe": ["CWE-125"], "cve": "CVE-2021-43845", "cve_desc": "PJSIP is a free and open source multimedia communication library. In version 2.11.1 and prior, if incoming RTCP XR message contain block, the data field is not checked against the received packet size, potentially resulting in an out-of-bound read access. This affects all users that use PJMEDIA and RTCP XR. A malicious actor can send a RTCP XR message with an invalid packet size.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43845"} {"idx": 222737, "project": "pjproject", "commit_id": "f74c1fc22b760d2a24369aa72c74c4a9ab985859", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/f74c1fc22b760d2a24369aa72c74c4a9ab985859", "commit_message": "Merge pull request from GHSA-r374-qrwv-86hh", "target": 0, "func": "void pjmedia_rtcp_xr_rx_rtcp_xr( pjmedia_rtcp_xr_session *sess,\n\t\t\t\t const void *pkt,\n\t\t\t\t pj_size_t size)\n{\n const pjmedia_rtcp_xr_pkt\t *rtcp_xr = (pjmedia_rtcp_xr_pkt*) pkt;\n const pjmedia_rtcp_xr_rb_rr_time *rb_rr_time = NULL;\n const pjmedia_rtcp_xr_rb_dlrr *rb_dlrr = NULL;\n const pjmedia_rtcp_xr_rb_stats *rb_stats = NULL;\n const pjmedia_rtcp_xr_rb_voip_mtc *rb_voip_mtc = NULL;\n const pjmedia_rtcp_xr_rb_header *rb_hdr = (pjmedia_rtcp_xr_rb_header*) \n\t\t\t\t\t\trtcp_xr->buf;\n unsigned pkt_len, rb_len;\n\n if (rtcp_xr->common.pt != RTCP_XR)\n\treturn;\n\n pkt_len = pj_ntohs((pj_uint16_t)rtcp_xr->common.length);\n\n if ((pkt_len + 1) > (size / 4))\n\treturn;\n\n /* Parse report rpt_types */\n while ((pj_int32_t*)rb_hdr < (pj_int32_t*)pkt + pkt_len)\n {\t\n\trb_len = pj_ntohs((pj_uint16_t)rb_hdr->length);\n\n\t/* Just skip any block with length == 0 (no report content) */\n\tif (rb_len) {\n\t switch (rb_hdr->bt) {\n\t\tcase BT_RR_TIME:\n\t\t if ((char*)rb_hdr + sizeof(*rb_rr_time) <=\n\t\t\t(char*)pkt + size) \n\t\t {\n\t\t\trb_rr_time = (pjmedia_rtcp_xr_rb_rr_time*)rb_hdr;\n\t\t }\n\t\t break;\n\t\tcase BT_DLRR:\n\t\t if ((char*)rb_hdr + sizeof(*rb_dlrr) <=\n\t\t\t(char*)pkt + size)\n\t\t {\n\t\t\trb_dlrr = (pjmedia_rtcp_xr_rb_dlrr*)rb_hdr;\n\t\t }\n\t\t break;\n\t\tcase BT_STATS:\n\t\t if ((char*)rb_hdr + sizeof(*rb_stats) <=\n\t\t\t(char*)pkt + size)\n\t\t {\n\t\t\trb_stats = (pjmedia_rtcp_xr_rb_stats*)rb_hdr;\n\t\t }\n\t\t break;\n\t\tcase BT_VOIP_METRICS:\n\t\t if ((char*)rb_hdr + sizeof(*rb_voip_mtc) <=\n\t\t\t(char*)pkt + size)\n\t\t {\n\t\t\trb_voip_mtc = (pjmedia_rtcp_xr_rb_voip_mtc*)rb_hdr;\n\t\t }\n\t\t break;\n\t\tdefault:\n\t\t break;\n\t }\n\t}\n\trb_hdr = (pjmedia_rtcp_xr_rb_header*)\n\t\t ((pj_int32_t*)rb_hdr + rb_len + 1);\n }\n\n /* Receiving RR Time */\n if (rb_rr_time) {\n\t/* Save LRR from NTP timestamp of the RR time block report */\n\tsess->rx_lrr = ((pj_ntohl(rb_rr_time->ntp_sec) & 0x0000FFFF) << 16) | \n\t\t ((pj_ntohl(rb_rr_time->ntp_frac) >> 16) & 0xFFFF);\n\n\t/* Calculate RR arrival time for DLRR */\n\tpj_get_timestamp(&sess->rx_lrr_time);\n\n\tTRACE_((sess->name, \"Rx RTCP SR: ntp_ts=%p\", sess->rx_lrr,\n\t (pj_uint32_t)(sess->rx_lrr_time.u64*65536/\n\t\t\t sess->rtcp_session->ts_freq.u64)));\n }\n\n /* Receiving DLRR */\n if (rb_dlrr) {\n\tpj_uint32_t lrr, now, dlrr;\n\tpj_uint64_t eedelay;\n\tpjmedia_rtcp_ntp_rec ntp;\n\n\t/* LRR is the middle 32bit of NTP. It has 1/65536 second \n\t * resolution \n\t */\n\tlrr = pj_ntohl(rb_dlrr->item.lrr);\n\n\t/* DLRR is delay since LRR, also in 1/65536 resolution */\n\tdlrr = pj_ntohl(rb_dlrr->item.dlrr);\n\n\t/* Get current time, and convert to 1/65536 resolution */\n\tpjmedia_rtcp_get_ntp_time(sess->rtcp_session, &ntp);\n\tnow = ((ntp.hi & 0xFFFF) << 16) + (ntp.lo >> 16);\n\n\t/* End-to-end delay is (now-lrr-dlrr) */\n\teedelay = now - lrr - dlrr;\n\n\t/* Convert end to end delay to usec (keeping the calculation in\n * 64bit space)::\n\t * sess->ee_delay = (eedelay * 1000) / 65536;\n\t */\n\tif (eedelay < 4294) {\n\t eedelay = (eedelay * 1000000) >> 16;\n\t} else {\n\t eedelay = (eedelay * 1000) >> 16;\n\t eedelay *= 1000;\n\t}\n\n\tTRACE_((sess->name, \"Rx RTCP XR DLRR: lrr=%p, dlrr=%p (%d:%03dms), \"\n\t\t\t \"now=%p, rtt=%p\",\n\t\tlrr, dlrr, dlrr/65536, (dlrr%65536)*1000/65536,\n\t\tnow, (pj_uint32_t)eedelay));\n\t\n\t/* Only save calculation if \"now\" is greater than lrr, or\n\t * otherwise rtt will be invalid \n\t */\n\tif (now-dlrr >= lrr) {\n\t unsigned rtt = (pj_uint32_t)eedelay;\n\t \n\t /* Check that eedelay value really makes sense. \n\t * We allow up to 30 seconds RTT!\n\t */\n\t if (eedelay <= 30 * 1000 * 1000UL) {\n\t\t/* \"Normalize\" rtt value that is exceptionally high.\n\t\t * For such values, \"normalize\" the rtt to be three times\n\t\t * the average value.\n\t\t */\n\t\tif (rtt>((unsigned)sess->stat.rtt.mean*3) && sess->stat.rtt.n!=0)\n\t\t{\n\t\t unsigned orig_rtt = rtt;\n\t\t rtt = (unsigned)sess->stat.rtt.mean*3;\n\t\t PJ_LOG(5,(sess->name, \n\t\t\t \"RTT value %d usec is normalized to %d usec\",\n\t\t\t orig_rtt, rtt));\n\t\t}\n \t\n\t\tTRACE_((sess->name, \"RTCP RTT is set to %d usec\", rtt));\n\t\tpj_math_stat_update(&sess->stat.rtt, rtt);\n\t }\n\t} else {\n\t PJ_LOG(5, (sess->name, \"Internal RTCP NTP clock skew detected: \"\n\t\t\t\t \"lrr=%p, now=%p, dlrr=%p (%d:%03dms), \"\n\t\t\t\t \"diff=%d\",\n\t\t\t\t lrr, now, dlrr, dlrr/65536,\n\t\t\t\t (dlrr%65536)*1000/65536,\n\t\t\t\t dlrr-(now-lrr)));\n\t}\n }\n\n /* Receiving Statistics Summary */\n if (rb_stats) {\n\tpj_uint8_t flags = rb_stats->header.specific;\n\n\tpj_bzero(&sess->stat.tx.stat_sum, sizeof(sess->stat.tx.stat_sum));\n\n\t/* Range of packets sequence reported in this blocks */\n\tsess->stat.tx.stat_sum.begin_seq = pj_ntohs(rb_stats->begin_seq);\n\tsess->stat.tx.stat_sum.end_seq = pj_ntohs(rb_stats->end_seq);\n\n\t/* Get flags of valid fields */\n\tsess->stat.tx.stat_sum.l = (flags & (1 << 7)) != 0;\n\tsess->stat.tx.stat_sum.d = (flags & (1 << 6)) != 0;\n\tsess->stat.tx.stat_sum.j = (flags & (1 << 5)) != 0;\n\tsess->stat.tx.stat_sum.t = (flags & (3 << 3)) != 0;\n\n\t/* Fetch the reports info */\n\tif (sess->stat.tx.stat_sum.l) {\n\t sess->stat.tx.stat_sum.lost = pj_ntohl(rb_stats->lost);\n\t}\n\n\tif (sess->stat.tx.stat_sum.d) {\n\t sess->stat.tx.stat_sum.dup = pj_ntohl(rb_stats->dup);\n\t}\n\n\tif (sess->stat.tx.stat_sum.j) {\n\t sess->stat.tx.stat_sum.jitter.min = pj_ntohl(rb_stats->jitter_min);\n\t sess->stat.tx.stat_sum.jitter.max = pj_ntohl(rb_stats->jitter_max);\n\t sess->stat.tx.stat_sum.jitter.mean= pj_ntohl(rb_stats->jitter_mean);\n\t pj_math_stat_set_stddev(&sess->stat.tx.stat_sum.jitter, \n\t\t\t\t pj_ntohl(rb_stats->jitter_dev));\n\t}\n\n\tif (sess->stat.tx.stat_sum.t) {\n\t sess->stat.tx.stat_sum.toh.min = rb_stats->toh_min;\n\t sess->stat.tx.stat_sum.toh.max = rb_stats->toh_max;\n\t sess->stat.tx.stat_sum.toh.mean= rb_stats->toh_mean;\n\t pj_math_stat_set_stddev(&sess->stat.tx.stat_sum.toh, \n\t\t\t\t pj_ntohl(rb_stats->toh_dev));\n\t}\n\n\tpj_gettimeofday(&sess->stat.tx.stat_sum.update);\n }\n\n /* Receiving VoIP Metrics */\n if (rb_voip_mtc) {\n\tsess->stat.tx.voip_mtc.loss_rate = rb_voip_mtc->loss_rate;\n\tsess->stat.tx.voip_mtc.discard_rate = rb_voip_mtc->discard_rate;\n\tsess->stat.tx.voip_mtc.burst_den = rb_voip_mtc->burst_den;\n\tsess->stat.tx.voip_mtc.gap_den = rb_voip_mtc->gap_den;\n\tsess->stat.tx.voip_mtc.burst_dur = pj_ntohs(rb_voip_mtc->burst_dur);\n\tsess->stat.tx.voip_mtc.gap_dur = pj_ntohs(rb_voip_mtc->gap_dur);\n\tsess->stat.tx.voip_mtc.rnd_trip_delay = \n\t\t\t\t\tpj_ntohs(rb_voip_mtc->rnd_trip_delay);\n\tsess->stat.tx.voip_mtc.end_sys_delay = \n\t\t\t\t\tpj_ntohs(rb_voip_mtc->end_sys_delay);\n\t/* signal & noise level encoded in two's complement form */\n\tsess->stat.tx.voip_mtc.signal_lvl = (pj_int8_t)\n\t\t\t\t ((rb_voip_mtc->signal_lvl > 127)?\n\t\t\t\t ((int)rb_voip_mtc->signal_lvl - 256) : \n\t\t\t\t rb_voip_mtc->signal_lvl);\n\tsess->stat.tx.voip_mtc.noise_lvl = (pj_int8_t)\n\t\t\t\t ((rb_voip_mtc->noise_lvl > 127)?\n\t\t\t\t ((int)rb_voip_mtc->noise_lvl - 256) : \n\t\t\t\t rb_voip_mtc->noise_lvl);\n\tsess->stat.tx.voip_mtc.rerl = rb_voip_mtc->rerl;\n\tsess->stat.tx.voip_mtc.gmin = rb_voip_mtc->gmin;\n\tsess->stat.tx.voip_mtc.r_factor = rb_voip_mtc->r_factor;\n\tsess->stat.tx.voip_mtc.ext_r_factor = rb_voip_mtc->ext_r_factor;\n\tsess->stat.tx.voip_mtc.mos_lq = rb_voip_mtc->mos_lq;\n\tsess->stat.tx.voip_mtc.mos_cq = rb_voip_mtc->mos_cq;\n\tsess->stat.tx.voip_mtc.rx_config = rb_voip_mtc->rx_config;\n\tsess->stat.tx.voip_mtc.jb_nom = pj_ntohs(rb_voip_mtc->jb_nom);\n\tsess->stat.tx.voip_mtc.jb_max = pj_ntohs(rb_voip_mtc->jb_max);\n\tsess->stat.tx.voip_mtc.jb_abs_max = pj_ntohs(rb_voip_mtc->jb_abs_max);\n\n\tpj_gettimeofday(&sess->stat.tx.voip_mtc.update);\n }\n}", "func_hash": 134123814969944330757535232446891920936, "file_name": "rtcp_xr.c", "file_hash": 238632209992792964107720594546671940595, "cwe": ["CWE-125"], "cve": "CVE-2021-43845", "cve_desc": "PJSIP is a free and open source multimedia communication library. In version 2.11.1 and prior, if incoming RTCP XR message contain block, the data field is not checked against the received packet size, potentially resulting in an out-of-bound read access. This affects all users that use PJMEDIA and RTCP XR. A malicious actor can send a RTCP XR message with an invalid packet size.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43845"} {"idx": 195231, "project": "gpac", "commit_id": "893fb99b606eebfae46cde151846a980e689039b", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/893fb99b606eebfae46cde151846a980e689039b", "commit_message": "fixed #1902", "target": 1, "func": "s32 gf_avc_parse_nalu(GF_BitStream *bs, AVCState *avc)\n{\n\tu8 idr_flag;\n\ts32 slice, ret;\n\tu32 nal_hdr;\n\tAVCSliceInfo n_state;\n\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\n\tnal_hdr = gf_bs_read_u8(bs);\n\n\tslice = 0;\n\tmemcpy(&n_state, &avc->s_info, sizeof(AVCSliceInfo));\n\tavc->last_nal_type_parsed = n_state.nal_unit_type = nal_hdr & 0x1F;\n\tn_state.nal_ref_idc = (nal_hdr >> 5) & 0x3;\n\n\tidr_flag = 0;\n\n\tswitch (n_state.nal_unit_type) {\n\tcase GF_AVC_NALU_ACCESS_UNIT:\n\tcase GF_AVC_NALU_END_OF_SEQ:\n\tcase GF_AVC_NALU_END_OF_STREAM:\n\t\tret = 1;\n\t\tbreak;\n\n\tcase GF_AVC_NALU_SVC_SLICE:\n\t\tSVC_ReadNal_header_extension(bs, &n_state.NalHeader);\n\t\t// slice buffer - read the info and compare.\n\t\t/*ret = */svc_parse_slice(bs, avc, &n_state);\n\t\tif (avc->s_info.nal_ref_idc) {\n\t\t\tn_state.poc_lsb_prev = avc->s_info.poc_lsb;\n\t\t\tn_state.poc_msb_prev = avc->s_info.poc_msb;\n\t\t}\n\t\tavc_compute_poc(&n_state);\n\n\t\tif (avc->s_info.poc != n_state.poc) {\n\t\t\tmemcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));\n\t\t\treturn 1;\n\t\t}\n\t\tmemcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));\n\t\treturn 0;\n\n\tcase GF_AVC_NALU_SVC_PREFIX_NALU:\n\t\tSVC_ReadNal_header_extension(bs, &n_state.NalHeader);\n\t\treturn 0;\n\n\tcase GF_AVC_NALU_IDR_SLICE:\n\tcase GF_AVC_NALU_NON_IDR_SLICE:\n\tcase GF_AVC_NALU_DP_A_SLICE:\n\tcase GF_AVC_NALU_DP_B_SLICE:\n\tcase GF_AVC_NALU_DP_C_SLICE:\n\t\tslice = 1;\n\t\t/* slice buffer - read the info and compare.*/\n\t\tret = avc_parse_slice(bs, avc, idr_flag, &n_state);\n\t\tif (ret < 0) return ret;\n\t\tret = 0;\n\t\tif (\n\t\t\t((avc->s_info.nal_unit_type > GF_AVC_NALU_IDR_SLICE) || (avc->s_info.nal_unit_type < GF_AVC_NALU_NON_IDR_SLICE))\n\t\t\t&& (avc->s_info.nal_unit_type != GF_AVC_NALU_SVC_SLICE)\n\t\t\t) {\n\t\t\tbreak;\n\t\t}\n\t\tif (avc->s_info.frame_num != n_state.frame_num) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (avc->s_info.field_pic_flag != n_state.field_pic_flag) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif ((avc->s_info.nal_ref_idc != n_state.nal_ref_idc) &&\n\t\t\t(!avc->s_info.nal_ref_idc || !n_state.nal_ref_idc)) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tassert(avc->s_info.sps);\n\n\t\tif (avc->s_info.sps->poc_type == n_state.sps->poc_type) {\n\t\t\tif (!avc->s_info.sps->poc_type) {\n\t\t\t\tif (!n_state.bottom_field_flag && (avc->s_info.poc_lsb != n_state.poc_lsb)) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (avc->s_info.delta_poc_bottom != n_state.delta_poc_bottom) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (avc->s_info.sps->poc_type == 1) {\n\t\t\t\tif (avc->s_info.delta_poc[0] != n_state.delta_poc[0]) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (avc->s_info.delta_poc[1] != n_state.delta_poc[1]) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (n_state.nal_unit_type == GF_AVC_NALU_IDR_SLICE) {\n\t\t\tif (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE) { /*IdrPicFlag differs in value*/\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (avc->s_info.idr_pic_id != n_state.idr_pic_id) { /*both IDR and idr_pic_id differs*/\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase GF_AVC_NALU_SEQ_PARAM:\n\t\tavc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 0, NULL, nal_hdr);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;\n\n\tcase GF_AVC_NALU_PIC_PARAM:\n\t\tavc->last_ps_idx = gf_avc_read_pps_bs_internal(bs, avc, nal_hdr);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;\n\tcase GF_AVC_NALU_SVC_SUBSEQ_PARAM:\n\t\tavc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 1, NULL, nal_hdr);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;\n\tcase GF_AVC_NALU_SEQ_PARAM_EXT:\n\t\tavc->last_ps_idx = (s32) gf_bs_read_ue(bs);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;\n\n\tcase GF_AVC_NALU_SEI:\n\tcase GF_AVC_NALU_FILLER_DATA:\n\t\treturn 0;\n\n\tdefault:\n\t\tif (avc->s_info.nal_unit_type <= GF_AVC_NALU_IDR_SLICE) ret = 1;\n\t\t//To detect change of AU when multiple sps and pps in stream\n\t\telse if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEI && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE)\n\t\t\tret = 1;\n\t\telse if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEQ_PARAM && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE)\n\t\t\tret = 1;\n\t\telse\n\t\t\tret = 0;\n\t\tbreak;\n\t}\n\n\t/* save _prev values */\n\tif (ret && avc->s_info.sps) {\n\t\tn_state.frame_num_offset_prev = avc->s_info.frame_num_offset;\n\t\tif ((avc->s_info.sps->poc_type != 2) || (avc->s_info.nal_ref_idc != 0))\n\t\t\tn_state.frame_num_prev = avc->s_info.frame_num;\n\t\tif (avc->s_info.nal_ref_idc) {\n\t\t\tn_state.poc_lsb_prev = avc->s_info.poc_lsb;\n\t\t\tn_state.poc_msb_prev = avc->s_info.poc_msb;\n\t\t}\n\t}\n\tif (slice)\n\t\tavc_compute_poc(&n_state);\n\tmemcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));\n\treturn ret;\n}", "func_hash": 99100226875075764129164909998725433232, "file_name": "av_parsers.c", "file_hash": 168517587328341017594269375399465893964, "cwe": ["CWE-476"], "cve": "CVE-2021-40565", "cve_desc": "A Segmentation fault caused by a null pointer dereference vulnerability exists in Gpac through 1.0.1 via the gf_avc_parse_nalu function in av_parsers.c when using mp4box, which causes a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40565"} {"idx": 222739, "project": "gpac", "commit_id": "893fb99b606eebfae46cde151846a980e689039b", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/893fb99b606eebfae46cde151846a980e689039b", "commit_message": "fixed #1902", "target": 0, "func": "s32 gf_avc_parse_nalu(GF_BitStream *bs, AVCState *avc)\n{\n\tu8 idr_flag;\n\ts32 slice, ret;\n\tu32 nal_hdr;\n\tAVCSliceInfo n_state;\n\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\n\tnal_hdr = gf_bs_read_u8(bs);\n\n\tslice = 0;\n\tmemcpy(&n_state, &avc->s_info, sizeof(AVCSliceInfo));\n\tavc->last_nal_type_parsed = n_state.nal_unit_type = nal_hdr & 0x1F;\n\tn_state.nal_ref_idc = (nal_hdr >> 5) & 0x3;\n\n\tidr_flag = 0;\n\n\tswitch (n_state.nal_unit_type) {\n\tcase GF_AVC_NALU_ACCESS_UNIT:\n\tcase GF_AVC_NALU_END_OF_SEQ:\n\tcase GF_AVC_NALU_END_OF_STREAM:\n\t\tret = 1;\n\t\tbreak;\n\n\tcase GF_AVC_NALU_SVC_SLICE:\n\t\tSVC_ReadNal_header_extension(bs, &n_state.NalHeader);\n\t\t// slice buffer - read the info and compare.\n\t\t/*ret = */svc_parse_slice(bs, avc, &n_state);\n\t\tif (avc->s_info.nal_ref_idc) {\n\t\t\tn_state.poc_lsb_prev = avc->s_info.poc_lsb;\n\t\t\tn_state.poc_msb_prev = avc->s_info.poc_msb;\n\t\t}\n\t\tavc_compute_poc(&n_state);\n\n\t\tif (avc->s_info.poc != n_state.poc) {\n\t\t\tmemcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));\n\t\t\treturn 1;\n\t\t}\n\t\tmemcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));\n\t\treturn 0;\n\n\tcase GF_AVC_NALU_SVC_PREFIX_NALU:\n\t\tSVC_ReadNal_header_extension(bs, &n_state.NalHeader);\n\t\treturn 0;\n\n\tcase GF_AVC_NALU_IDR_SLICE:\n\tcase GF_AVC_NALU_NON_IDR_SLICE:\n\tcase GF_AVC_NALU_DP_A_SLICE:\n\tcase GF_AVC_NALU_DP_B_SLICE:\n\tcase GF_AVC_NALU_DP_C_SLICE:\n\t\tslice = 1;\n\t\t/* slice buffer - read the info and compare.*/\n\t\tret = avc_parse_slice(bs, avc, idr_flag, &n_state);\n\t\tif (ret < 0) return ret;\n\t\tret = 0;\n\t\tif (\n\t\t\t((avc->s_info.nal_unit_type > GF_AVC_NALU_IDR_SLICE) || (avc->s_info.nal_unit_type < GF_AVC_NALU_NON_IDR_SLICE))\n\t\t\t&& (avc->s_info.nal_unit_type != GF_AVC_NALU_SVC_SLICE)\n\t\t\t) {\n\t\t\tbreak;\n\t\t}\n\t\tif (avc->s_info.frame_num != n_state.frame_num) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (avc->s_info.field_pic_flag != n_state.field_pic_flag) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif ((avc->s_info.nal_ref_idc != n_state.nal_ref_idc) &&\n\t\t\t(!avc->s_info.nal_ref_idc || !n_state.nal_ref_idc)) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif (!avc->s_info.sps)\n\t\t\treturn -1;\n\n\t\tif (avc->s_info.sps->poc_type == n_state.sps->poc_type) {\n\t\t\tif (!avc->s_info.sps->poc_type) {\n\t\t\t\tif (!n_state.bottom_field_flag && (avc->s_info.poc_lsb != n_state.poc_lsb)) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (avc->s_info.delta_poc_bottom != n_state.delta_poc_bottom) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (avc->s_info.sps->poc_type == 1) {\n\t\t\t\tif (avc->s_info.delta_poc[0] != n_state.delta_poc[0]) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (avc->s_info.delta_poc[1] != n_state.delta_poc[1]) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (n_state.nal_unit_type == GF_AVC_NALU_IDR_SLICE) {\n\t\t\tif (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE) { /*IdrPicFlag differs in value*/\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (avc->s_info.idr_pic_id != n_state.idr_pic_id) { /*both IDR and idr_pic_id differs*/\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase GF_AVC_NALU_SEQ_PARAM:\n\t\tavc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 0, NULL, nal_hdr);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;\n\n\tcase GF_AVC_NALU_PIC_PARAM:\n\t\tavc->last_ps_idx = gf_avc_read_pps_bs_internal(bs, avc, nal_hdr);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;\n\tcase GF_AVC_NALU_SVC_SUBSEQ_PARAM:\n\t\tavc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 1, NULL, nal_hdr);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;\n\tcase GF_AVC_NALU_SEQ_PARAM_EXT:\n\t\tavc->last_ps_idx = (s32) gf_bs_read_ue(bs);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;\n\n\tcase GF_AVC_NALU_SEI:\n\tcase GF_AVC_NALU_FILLER_DATA:\n\t\treturn 0;\n\n\tdefault:\n\t\tif (avc->s_info.nal_unit_type <= GF_AVC_NALU_IDR_SLICE) ret = 1;\n\t\t//To detect change of AU when multiple sps and pps in stream\n\t\telse if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEI && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE)\n\t\t\tret = 1;\n\t\telse if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEQ_PARAM && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE)\n\t\t\tret = 1;\n\t\telse\n\t\t\tret = 0;\n\t\tbreak;\n\t}\n\n\t/* save _prev values */\n\tif (ret && avc->s_info.sps) {\n\t\tn_state.frame_num_offset_prev = avc->s_info.frame_num_offset;\n\t\tif ((avc->s_info.sps->poc_type != 2) || (avc->s_info.nal_ref_idc != 0))\n\t\t\tn_state.frame_num_prev = avc->s_info.frame_num;\n\t\tif (avc->s_info.nal_ref_idc) {\n\t\t\tn_state.poc_lsb_prev = avc->s_info.poc_lsb;\n\t\t\tn_state.poc_msb_prev = avc->s_info.poc_msb;\n\t\t}\n\t}\n\tif (slice)\n\t\tavc_compute_poc(&n_state);\n\tmemcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));\n\treturn ret;\n}", "func_hash": 151148020238252563376772611575796474624, "file_name": "av_parsers.c", "file_hash": 336095072032702615903888752582747164805, "cwe": ["CWE-476"], "cve": "CVE-2021-40565", "cve_desc": "A Segmentation fault caused by a null pointer dereference vulnerability exists in Gpac through 1.0.1 via the gf_avc_parse_nalu function in av_parsers.c when using mp4box, which causes a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40565"} {"idx": 195233, "project": "tensorflow", "commit_id": "97282c6d0d34476b6ba033f961590b783fa184cd", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/97282c6d0d34476b6ba033f961590b783fa184cd", "commit_message": "Prevent a crash due to heap OOB write in grappler.\n\nPiperOrigin-RevId: 408318417\nChange-Id: If095feb8c001e3a8ac4a85b7387b81e8309df47d", "target": 1, "func": " Status SetUnknownShape(const NodeDef* node, int output_port) {\n shape_inference::ShapeHandle shape =\n GetUnknownOutputShape(node, output_port);\n InferenceContext* ctx = GetContext(node);\n if (ctx == nullptr) {\n return errors::InvalidArgument(\"Missing context\");\n }\n ctx->set_output(output_port, shape);\n return Status::OK();\n }", "func_hash": 128649942367020682781968122888762734954, "file_name": "graph_properties.cc", "file_hash": 2473148557397819170260688514824580473, "cwe": ["CWE-787"], "cve": "CVE-2022-23566", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. TensorFlow is vulnerable to a heap OOB write in `Grappler`. The `set_output` function writes to an array at the specified index. Hence, this gives a malicious user a write primitive. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23566"} {"idx": 222906, "project": "tensorflow", "commit_id": "97282c6d0d34476b6ba033f961590b783fa184cd", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/97282c6d0d34476b6ba033f961590b783fa184cd", "commit_message": "Prevent a crash due to heap OOB write in grappler.\n\nPiperOrigin-RevId: 408318417\nChange-Id: If095feb8c001e3a8ac4a85b7387b81e8309df47d", "target": 0, "func": " Status SetUnknownShape(const NodeDef* node, int output_port) {\n shape_inference::ShapeHandle shape =\n GetUnknownOutputShape(node, output_port);\n InferenceContext* ctx = GetContext(node);\n if (ctx == nullptr) {\n return errors::InvalidArgument(\"SetUnknownShape: Missing context\");\n }\n if (output_port < 0 || output_port >= ctx->num_outputs()) {\n return errors::InvalidArgument(\n \"SetUnknownShape: output_port must be in [0, \", ctx->num_outputs(),\n \") but was \", output_port);\n }\n ctx->set_output(output_port, shape);\n return Status::OK();\n }", "func_hash": 99847293040079140904834991959660799210, "file_name": "graph_properties.cc", "file_hash": 331642930758873609530408829371906855419, "cwe": ["CWE-787"], "cve": "CVE-2022-23566", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. TensorFlow is vulnerable to a heap OOB write in `Grappler`. The `set_output` function writes to an array at the specified index. Hence, this gives a malicious user a write primitive. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23566"} {"idx": 195234, "project": "tensorflow", "commit_id": "dcc21c7bc972b10b6fb95c2fb0f4ab5a59680ec2", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/dcc21c7bc972b10b6fb95c2fb0f4ab5a59680ec2", "commit_message": "Eliminate debug `CHECK`-fail from `function.cc`\n\nPiperOrigin-RevId: 409416119\nChange-Id: I8376ee464d434e9b970ff0ad49edfdaa2a273cfe", "target": 1, "func": " Status BuildInputArgIndex(const OpDef::ArgDef& arg_def, AttrSlice attr_values,\n const FunctionDef::ArgAttrs* arg_attrs,\n bool ints_on_device,\n int64_t resource_arg_unique_id) {\n bool is_type_list;\n DataTypeVector dtypes;\n TF_RETURN_IF_ERROR(\n ArgNumType(attr_values, arg_def, &is_type_list, &dtypes));\n if (dtypes.size() < size_t{1}) {\n return errors::Internal(\"Expected a list of at least one dtype\");\n }\n int arg_index = result_.nodes.size();\n TF_RETURN_IF_ERROR(\n AddItem(arg_def.name(), {true, arg_index, 0, is_type_list, dtypes}));\n // Creates dtypes.size() nodes in the graph.\n for (size_t i = 0; i < dtypes.size(); ++i) {\n TF_RETURN_IF_ERROR(AddItem(strings::StrCat(arg_def.name(), \":\", i),\n {true, arg_index, 0, false, {dtypes[i]}}));\n DCHECK_EQ(arg_index, result_.nodes.size());\n string name = arg_def.name();\n if (dtypes.size() > 1) {\n strings::StrAppend(&name, \"_\", i);\n }\n NodeDef* gnode = AddNode(name);\n if (ints_on_device && dtypes[i] == DataType::DT_INT32) {\n gnode->set_op(FunctionLibraryDefinition::kDeviceArgOp);\n } else {\n gnode->set_op(FunctionLibraryDefinition::kArgOp);\n }\n DataType dtype = arg_def.is_ref() ? MakeRefType(dtypes[i]) : dtypes[i];\n AddAttr(\"T\", dtype, gnode);\n AddAttr(\"index\", arg_index, gnode);\n if (resource_arg_unique_id >= 0) {\n AddAttr(\"_resource_arg_unique_id\", resource_arg_unique_id, gnode);\n }\n if (arg_attrs) {\n for (const auto& arg_attr : arg_attrs->attr()) {\n AddAttr(arg_attr.first, arg_attr.second, gnode->mutable_attr());\n }\n }\n result_.arg_types.push_back(dtypes[i]);\n ++arg_index;\n }\n return Status::OK();\n }", "func_hash": 149416980820983113024454385523610384435, "file_name": "function.cc", "file_hash": 275755455359751936167516531130081059449, "cwe": ["CWE-617"], "cve": "CVE-2022-23586", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. A malicious user can cause a denial of service by altering a `SavedModel` such that assertions in `function.cc` would be falsified and crash the Python interpreter. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23586"} {"idx": 222925, "project": "tensorflow", "commit_id": "dcc21c7bc972b10b6fb95c2fb0f4ab5a59680ec2", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/dcc21c7bc972b10b6fb95c2fb0f4ab5a59680ec2", "commit_message": "Eliminate debug `CHECK`-fail from `function.cc`\n\nPiperOrigin-RevId: 409416119\nChange-Id: I8376ee464d434e9b970ff0ad49edfdaa2a273cfe", "target": 0, "func": " Status BuildInputArgIndex(const OpDef::ArgDef& arg_def, AttrSlice attr_values,\n const FunctionDef::ArgAttrs* arg_attrs,\n bool ints_on_device,\n int64_t resource_arg_unique_id) {\n bool is_type_list;\n DataTypeVector dtypes;\n TF_RETURN_IF_ERROR(\n ArgNumType(attr_values, arg_def, &is_type_list, &dtypes));\n if (dtypes.size() < size_t{1}) {\n return errors::Internal(\"Expected a list of at least one dtype\");\n }\n int arg_index = result_.nodes.size();\n TF_RETURN_IF_ERROR(\n AddItem(arg_def.name(), {true, arg_index, 0, is_type_list, dtypes}));\n // Creates dtypes.size() nodes in the graph.\n for (size_t i = 0; i < dtypes.size(); ++i) {\n TF_RETURN_IF_ERROR(AddItem(strings::StrCat(arg_def.name(), \":\", i),\n {true, arg_index, 0, false, {dtypes[i]}}));\n if (arg_index != result_.nodes.size()) {\n return errors::Internal(\n \"Expected arg_index to be equal to the number of nodes in result.\",\n \" Got \", arg_index, \" and \", result_.nodes.size());\n }\n string name = arg_def.name();\n if (dtypes.size() > 1) {\n strings::StrAppend(&name, \"_\", i);\n }\n NodeDef* gnode = AddNode(name);\n if (ints_on_device && dtypes[i] == DataType::DT_INT32) {\n gnode->set_op(FunctionLibraryDefinition::kDeviceArgOp);\n } else {\n gnode->set_op(FunctionLibraryDefinition::kArgOp);\n }\n DataType dtype = arg_def.is_ref() ? MakeRefType(dtypes[i]) : dtypes[i];\n AddAttr(\"T\", dtype, gnode);\n AddAttr(\"index\", arg_index, gnode);\n if (resource_arg_unique_id >= 0) {\n AddAttr(\"_resource_arg_unique_id\", resource_arg_unique_id, gnode);\n }\n if (arg_attrs) {\n for (const auto& arg_attr : arg_attrs->attr()) {\n AddAttr(arg_attr.first, arg_attr.second, gnode->mutable_attr());\n }\n }\n result_.arg_types.push_back(dtypes[i]);\n ++arg_index;\n }\n return Status::OK();\n }", "func_hash": 331541162268703307546562637087708050413, "file_name": "None", "file_hash": null, "cwe": ["CWE-617"], "cve": "CVE-2022-23586", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. A malicious user can cause a denial of service by altering a `SavedModel` such that assertions in `function.cc` would be falsified and crash the Python interpreter. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23586"} {"idx": 195237, "project": "ImageMagick", "commit_id": "f221ea0fa3171f0f4fdf74ac9d81b203b9534c23", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/f221ea0fa3171f0f4fdf74ac9d81b203b9534c23", "commit_message": "Fixes #4985: 4e+26 is outside the range of representable values of type 'unsigned long' at coders/pcl.c:299 (#4986)\n\n* fix Division by zero in XMenuWidget() of MagickCore/widget.c\n\n* Fix memory leak in AnimateImageCommand() of MagickWand/animate.c and DisplayImageCommand() of MagickWand/display.c\n\n* fix Division by zero in ReadEnhMetaFile() of coders/emf.c\n\n* Resolve conflicts\n\n* fix issue: outside the range of representable values of type 'unsigned char' at coders/psd.c:1025\n\n* fix error: 4e+26 is outside the range of representable values of type 'unsigned long' at coders/pcl.c:299\n\nCo-authored-by: zhailiangliang ", "target": 1, "func": "static Image *ReadPCLImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define CropBox \"CropBox\"\n#define DeviceCMYK \"DeviceCMYK\"\n#define MediaBox \"MediaBox\"\n#define RenderPCLText \" Rendering PCL... \"\n\n char\n command[MagickPathExtent],\n *density,\n filename[MagickPathExtent],\n geometry[MagickPathExtent],\n *options,\n input_filename[MagickPathExtent];\n\n const DelegateInfo\n *delegate_info;\n\n Image\n *image,\n *next_image;\n\n ImageInfo\n *read_info;\n\n MagickBooleanType\n cmyk,\n status;\n\n PointInfo\n delta;\n\n RectangleInfo\n bounding_box,\n page;\n\n char\n *p;\n\n ssize_t\n c;\n\n SegmentInfo\n bounds;\n\n size_t\n height,\n width;\n\n ssize_t\n count;\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n /*\n Open image file.\n */\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);\n if (status == MagickFalse)\n {\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image_info->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Set the page density.\n */\n delta.x=DefaultResolution;\n delta.y=DefaultResolution;\n if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0))\n {\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n if ((flags & RhoValue) != 0)\n image->resolution.x=geometry_info.rho;\n image->resolution.y=image->resolution.x;\n if ((flags & SigmaValue) != 0)\n image->resolution.y=geometry_info.sigma;\n }\n /*\n Determine page geometry from the PCL media box.\n */\n cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;\n count=0;\n (void) memset(&bounding_box,0,sizeof(bounding_box));\n (void) memset(&bounds,0,sizeof(bounds));\n (void) memset(&page,0,sizeof(page));\n (void) memset(command,0,sizeof(command));\n p=command;\n for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))\n {\n if (image_info->page != (char *) NULL)\n continue;\n /*\n Note PCL elements.\n */\n *p++=(char) c;\n if ((c != (int) '/') && (c != '\\n') &&\n ((size_t) (p-command) < (MagickPathExtent-1)))\n continue;\n *p='\\0';\n p=command;\n /*\n Is this a CMYK document?\n */\n if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)\n cmyk=MagickTrue;\n if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)\n {\n /*\n Note region defined by crop box.\n */\n count=(ssize_t) sscanf(command,\"CropBox [%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n if (count != 4)\n count=(ssize_t) sscanf(command,\"CropBox[%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n }\n if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)\n {\n /*\n Note region defined by media box.\n */\n count=(ssize_t) sscanf(command,\"MediaBox [%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n if (count != 4)\n count=(ssize_t) sscanf(command,\"MediaBox[%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n }\n if (count != 4)\n continue;\n /*\n Set PCL render geometry.\n */\n width=(size_t) floor(bounds.x2-bounds.x1+0.5);\n height=(size_t) floor(bounds.y2-bounds.y1+0.5);\n if (width > page.width)\n page.width=width;\n if (height > page.height)\n page.height=height;\n }\n (void) CloseBlob(image);\n /*\n Render PCL with the GhostPCL delegate.\n */\n if ((page.width == 0) || (page.height == 0))\n (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n if (image_info->page != (char *) NULL)\n (void) ParseAbsoluteGeometry(image_info->page,&page);\n (void) FormatLocaleString(geometry,MagickPathExtent,\"%.20gx%.20g\",(double)\n page.width,(double) page.height);\n if (image_info->monochrome != MagickFalse)\n delegate_info=GetDelegateInfo(\"pcl:mono\",(char *) NULL,exception);\n else\n if (cmyk != MagickFalse)\n delegate_info=GetDelegateInfo(\"pcl:cmyk\",(char *) NULL,exception);\n else\n delegate_info=GetDelegateInfo(\"pcl:color\",(char *) NULL,exception);\n if (delegate_info == (const DelegateInfo *) NULL)\n {\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n if ((page.width == 0) || (page.height == 0))\n (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n if (image_info->page != (char *) NULL)\n (void) ParseAbsoluteGeometry(image_info->page,&page);\n density=AcquireString(\"\");\n options=AcquireString(\"\");\n (void) FormatLocaleString(density,MagickPathExtent,\"%gx%g\",\n image->resolution.x,image->resolution.y);\n if (image_info->ping != MagickFalse)\n (void) FormatLocaleString(density,MagickPathExtent,\"2.0x2.0\");\n page.width=(size_t) floor(page.width*image->resolution.x/delta.x+0.5);\n page.height=(size_t) floor(page.height*image->resolution.y/delta.y+0.5);\n (void) FormatLocaleString(options,MagickPathExtent,\"-g%.20gx%.20g \",(double)\n page.width,(double) page.height);\n image=DestroyImage(image);\n read_info=CloneImageInfo(image_info);\n *read_info->magick='\\0';\n if (read_info->number_scenes != 0)\n {\n if (read_info->number_scenes != 1)\n (void) FormatLocaleString(options,MagickPathExtent,\"-dLastPage=%.20g\",\n (double) (read_info->scene+read_info->number_scenes));\n else\n (void) FormatLocaleString(options,MagickPathExtent,\n \"-dFirstPage=%.20g -dLastPage=%.20g\",(double) read_info->scene+1,\n (double) (read_info->scene+read_info->number_scenes));\n read_info->number_scenes=0;\n if (read_info->scenes != (char *) NULL)\n *read_info->scenes='\\0';\n }\n (void) CopyMagickString(filename,read_info->filename,MagickPathExtent);\n (void) AcquireUniqueFilename(read_info->filename);\n (void) FormatLocaleString(command,MagickPathExtent,\n GetDelegateCommands(delegate_info),\n read_info->antialias != MagickFalse ? 4 : 1,\n read_info->antialias != MagickFalse ? 4 : 1,density,options,\n read_info->filename,input_filename);\n options=DestroyString(options);\n density=DestroyString(density);\n status=ExternalDelegateCommand(MagickFalse,read_info->verbose,command,\n (char *) NULL,exception) != 0 ? MagickTrue : MagickFalse;\n image=ReadImage(read_info,exception);\n (void) RelinquishUniqueFileResource(read_info->filename);\n (void) RelinquishUniqueFileResource(input_filename);\n read_info=DestroyImageInfo(read_info);\n if (image == (Image *) NULL)\n ThrowReaderException(DelegateError,\"PCLDelegateFailed\");\n if (LocaleCompare(image->magick,\"BMP\") == 0)\n {\n Image\n *cmyk_image;\n\n cmyk_image=ConsolidateCMYKImages(image,exception);\n if (cmyk_image != (Image *) NULL)\n {\n image=DestroyImageList(image);\n image=cmyk_image;\n }\n }\n do\n {\n (void) CopyMagickString(image->filename,filename,MagickPathExtent);\n image->page=page;\n if (image_info->ping != MagickFalse)\n {\n image->magick_columns*=image->resolution.x/2.0;\n image->magick_rows*=image->resolution.y/2.0;\n image->columns*=image->resolution.x/2.0;\n image->rows*=image->resolution.y/2.0;\n }\n next_image=SyncNextImageInList(image);\n if (next_image != (Image *) NULL)\n image=next_image;\n } while (next_image != (Image *) NULL);\n return(GetFirstImageInList(image));\n}", "func_hash": 164108098598115354275502589345492195560, "file_name": "pcl.c", "file_hash": 226900089914426038554396055314138187051, "cwe": ["CWE-190"], "cve": "CVE-2022-32546", "cve_desc": "A vulnerability was found in ImageMagick, causing an outside the range of representable values of type 'unsigned long' at coders/pcl.c, when crafted or untrusted input is processed. This leads to a negative impact to application availability or other problems related to undefined behavior.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32546"} {"idx": 223089, "project": "ImageMagick", "commit_id": "f221ea0fa3171f0f4fdf74ac9d81b203b9534c23", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/f221ea0fa3171f0f4fdf74ac9d81b203b9534c23", "commit_message": "Fixes #4985: 4e+26 is outside the range of representable values of type 'unsigned long' at coders/pcl.c:299 (#4986)\n\n* fix Division by zero in XMenuWidget() of MagickCore/widget.c\n\n* Fix memory leak in AnimateImageCommand() of MagickWand/animate.c and DisplayImageCommand() of MagickWand/display.c\n\n* fix Division by zero in ReadEnhMetaFile() of coders/emf.c\n\n* Resolve conflicts\n\n* fix issue: outside the range of representable values of type 'unsigned char' at coders/psd.c:1025\n\n* fix error: 4e+26 is outside the range of representable values of type 'unsigned long' at coders/pcl.c:299\n\nCo-authored-by: zhailiangliang ", "target": 0, "func": "static Image *ReadPCLImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define CropBox \"CropBox\"\n#define DeviceCMYK \"DeviceCMYK\"\n#define MediaBox \"MediaBox\"\n#define RenderPCLText \" Rendering PCL... \"\n\n char\n command[MagickPathExtent],\n *density,\n filename[MagickPathExtent],\n geometry[MagickPathExtent],\n *options,\n input_filename[MagickPathExtent];\n\n const DelegateInfo\n *delegate_info;\n\n Image\n *image,\n *next_image;\n\n ImageInfo\n *read_info;\n\n MagickBooleanType\n cmyk,\n status;\n\n PointInfo\n delta;\n\n RectangleInfo\n bounding_box,\n page;\n\n char\n *p;\n\n ssize_t\n c;\n\n SegmentInfo\n bounds;\n\n size_t\n height,\n width;\n\n ssize_t\n count;\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n /*\n Open image file.\n */\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);\n if (status == MagickFalse)\n {\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image_info->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Set the page density.\n */\n delta.x=DefaultResolution;\n delta.y=DefaultResolution;\n if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0))\n {\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n if ((flags & RhoValue) != 0)\n image->resolution.x=geometry_info.rho;\n image->resolution.y=image->resolution.x;\n if ((flags & SigmaValue) != 0)\n image->resolution.y=geometry_info.sigma;\n }\n /*\n Determine page geometry from the PCL media box.\n */\n cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;\n count=0;\n (void) memset(&bounding_box,0,sizeof(bounding_box));\n (void) memset(&bounds,0,sizeof(bounds));\n (void) memset(&page,0,sizeof(page));\n (void) memset(command,0,sizeof(command));\n p=command;\n for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))\n {\n if (image_info->page != (char *) NULL)\n continue;\n /*\n Note PCL elements.\n */\n *p++=(char) c;\n if ((c != (int) '/') && (c != '\\n') &&\n ((size_t) (p-command) < (MagickPathExtent-1)))\n continue;\n *p='\\0';\n p=command;\n /*\n Is this a CMYK document?\n */\n if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)\n cmyk=MagickTrue;\n if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)\n {\n /*\n Note region defined by crop box.\n */\n count=(ssize_t) sscanf(command,\"CropBox [%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n if (count != 4)\n count=(ssize_t) sscanf(command,\"CropBox[%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n }\n if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)\n {\n /*\n Note region defined by media box.\n */\n count=(ssize_t) sscanf(command,\"MediaBox [%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n if (count != 4)\n count=(ssize_t) sscanf(command,\"MediaBox[%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n }\n if (count != 4)\n continue;\n /*\n Set PCL render geometry.\n */\n width=(size_t)CastDoubleToLong(floor(bounds.x2-bounds.x1+0.5));\n height=(size_t)CastDoubleToLong(floor(bounds.y2-bounds.y1+0.5));\n if (width > page.width)\n page.width=width;\n if (height > page.height)\n page.height=height;\n }\n (void) CloseBlob(image);\n /*\n Render PCL with the GhostPCL delegate.\n */\n if ((page.width == 0) || (page.height == 0))\n (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n if (image_info->page != (char *) NULL)\n (void) ParseAbsoluteGeometry(image_info->page,&page);\n (void) FormatLocaleString(geometry,MagickPathExtent,\"%.20gx%.20g\",(double)\n page.width,(double) page.height);\n if (image_info->monochrome != MagickFalse)\n delegate_info=GetDelegateInfo(\"pcl:mono\",(char *) NULL,exception);\n else\n if (cmyk != MagickFalse)\n delegate_info=GetDelegateInfo(\"pcl:cmyk\",(char *) NULL,exception);\n else\n delegate_info=GetDelegateInfo(\"pcl:color\",(char *) NULL,exception);\n if (delegate_info == (const DelegateInfo *) NULL)\n {\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n if ((page.width == 0) || (page.height == 0))\n (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n if (image_info->page != (char *) NULL)\n (void) ParseAbsoluteGeometry(image_info->page,&page);\n density=AcquireString(\"\");\n options=AcquireString(\"\");\n (void) FormatLocaleString(density,MagickPathExtent,\"%gx%g\",\n image->resolution.x,image->resolution.y);\n if (image_info->ping != MagickFalse)\n (void) FormatLocaleString(density,MagickPathExtent,\"2.0x2.0\");\n page.width=(size_t) floor(page.width*image->resolution.x/delta.x+0.5);\n page.height=(size_t) floor(page.height*image->resolution.y/delta.y+0.5);\n (void) FormatLocaleString(options,MagickPathExtent,\"-g%.20gx%.20g \",(double)\n page.width,(double) page.height);\n image=DestroyImage(image);\n read_info=CloneImageInfo(image_info);\n *read_info->magick='\\0';\n if (read_info->number_scenes != 0)\n {\n if (read_info->number_scenes != 1)\n (void) FormatLocaleString(options,MagickPathExtent,\"-dLastPage=%.20g\",\n (double) (read_info->scene+read_info->number_scenes));\n else\n (void) FormatLocaleString(options,MagickPathExtent,\n \"-dFirstPage=%.20g -dLastPage=%.20g\",(double) read_info->scene+1,\n (double) (read_info->scene+read_info->number_scenes));\n read_info->number_scenes=0;\n if (read_info->scenes != (char *) NULL)\n *read_info->scenes='\\0';\n }\n (void) CopyMagickString(filename,read_info->filename,MagickPathExtent);\n (void) AcquireUniqueFilename(read_info->filename);\n (void) FormatLocaleString(command,MagickPathExtent,\n GetDelegateCommands(delegate_info),\n read_info->antialias != MagickFalse ? 4 : 1,\n read_info->antialias != MagickFalse ? 4 : 1,density,options,\n read_info->filename,input_filename);\n options=DestroyString(options);\n density=DestroyString(density);\n status=ExternalDelegateCommand(MagickFalse,read_info->verbose,command,\n (char *) NULL,exception) != 0 ? MagickTrue : MagickFalse;\n image=ReadImage(read_info,exception);\n (void) RelinquishUniqueFileResource(read_info->filename);\n (void) RelinquishUniqueFileResource(input_filename);\n read_info=DestroyImageInfo(read_info);\n if (image == (Image *) NULL)\n ThrowReaderException(DelegateError,\"PCLDelegateFailed\");\n if (LocaleCompare(image->magick,\"BMP\") == 0)\n {\n Image\n *cmyk_image;\n\n cmyk_image=ConsolidateCMYKImages(image,exception);\n if (cmyk_image != (Image *) NULL)\n {\n image=DestroyImageList(image);\n image=cmyk_image;\n }\n }\n do\n {\n (void) CopyMagickString(image->filename,filename,MagickPathExtent);\n image->page=page;\n if (image_info->ping != MagickFalse)\n {\n image->magick_columns*=image->resolution.x/2.0;\n image->magick_rows*=image->resolution.y/2.0;\n image->columns*=image->resolution.x/2.0;\n image->rows*=image->resolution.y/2.0;\n }\n next_image=SyncNextImageInList(image);\n if (next_image != (Image *) NULL)\n image=next_image;\n } while (next_image != (Image *) NULL);\n return(GetFirstImageInList(image));\n}", "func_hash": 19106273782202991773902274267597206156, "file_name": "pcl.c", "file_hash": 107050694639473008713363285641232916868, "cwe": ["CWE-190"], "cve": "CVE-2022-32546", "cve_desc": "A vulnerability was found in ImageMagick, causing an outside the range of representable values of type 'unsigned long' at coders/pcl.c, when crafted or untrusted input is processed. This leads to a negative impact to application availability or other problems related to undefined behavior.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32546"} {"idx": 195264, "project": "pcre2", "commit_id": "d4fa336fbcc388f89095b184ba6d99422cfc676c", "project_url": "https://github.com/PCRE2Project/pcre2", "commit_url": "https://github.com/PCRE2Project/pcre2/commit/d4fa336fbcc388f89095b184ba6d99422cfc676c", "commit_message": "Fix incorrect value reading in JIT.", "target": 1, "func": "static void compile_xclass_matchingpath(compiler_common *common, PCRE2_SPTR cc, jump_list **backtracks)\n{\nDEFINE_COMPILER;\njump_list *found = NULL;\njump_list **list = (cc[0] & XCL_NOT) == 0 ? &found : backtracks;\nsljit_uw c, charoffset, max = 256, min = READ_CHAR_MAX;\nstruct sljit_jump *jump = NULL;\nPCRE2_SPTR ccbegin;\nint compares, invertcmp, numberofcmps;\n#if defined SUPPORT_UNICODE && (PCRE2_CODE_UNIT_WIDTH == 8 || PCRE2_CODE_UNIT_WIDTH == 16)\nBOOL utf = common->utf;\n#endif /* SUPPORT_UNICODE && PCRE2_CODE_UNIT_WIDTH == [8|16] */\n\n#ifdef SUPPORT_UNICODE\nsljit_u32 unicode_status = 0;\nint typereg = TMP1;\nconst sljit_u32 *other_cases;\nsljit_uw typeoffset;\n#endif /* SUPPORT_UNICODE */\n\n/* Scanning the necessary info. */\ncc++;\nccbegin = cc;\ncompares = 0;\n\nif (cc[-1] & XCL_MAP)\n {\n min = 0;\n cc += 32 / sizeof(PCRE2_UCHAR);\n }\n\nwhile (*cc != XCL_END)\n {\n compares++;\n if (*cc == XCL_SINGLE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n if (c > max) max = c;\n if (c < min) min = c;\n#ifdef SUPPORT_UNICODE\n unicode_status |= XCLASS_SAVE_CHAR;\n#endif /* SUPPORT_UNICODE */\n }\n else if (*cc == XCL_RANGE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n if (c < min) min = c;\n GETCHARINCTEST(c, cc);\n if (c > max) max = c;\n#ifdef SUPPORT_UNICODE\n unicode_status |= XCLASS_SAVE_CHAR;\n#endif /* SUPPORT_UNICODE */\n }\n#ifdef SUPPORT_UNICODE\n else\n {\n SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);\n cc++;\n if (*cc == PT_CLIST && *cc == XCL_PROP)\n {\n other_cases = PRIV(ucd_caseless_sets) + cc[1];\n while (*other_cases != NOTACHAR)\n {\n if (*other_cases > max) max = *other_cases;\n if (*other_cases < min) min = *other_cases;\n other_cases++;\n }\n }\n else\n {\n max = READ_CHAR_MAX;\n min = 0;\n }\n\n switch(*cc)\n {\n case PT_ANY:\n /* Any either accepts everything or ignored. */\n if (cc[-1] == XCL_PROP)\n {\n compile_char1_matchingpath(common, OP_ALLANY, cc, backtracks, FALSE);\n if (list == backtracks)\n add_jump(compiler, backtracks, JUMP(SLJIT_JUMP));\n return;\n }\n break;\n\n case PT_LAMP:\n case PT_GC:\n case PT_PC:\n case PT_ALNUM:\n unicode_status |= XCLASS_HAS_TYPE;\n break;\n\n case PT_SCX:\n unicode_status |= XCLASS_HAS_SCRIPT_EXTENSION;\n if (cc[-1] == XCL_NOTPROP)\n {\n unicode_status |= XCLASS_SCRIPT_EXTENSION_NOTPROP;\n break;\n }\n compares++;\n /* Fall through */ \n\n case PT_SC:\n unicode_status |= XCLASS_HAS_SCRIPT;\n break;\n\n case PT_SPACE:\n case PT_PXSPACE:\n case PT_WORD:\n case PT_PXGRAPH:\n case PT_PXPRINT:\n case PT_PXPUNCT:\n unicode_status |= XCLASS_SAVE_CHAR | XCLASS_HAS_TYPE;\n break;\n\n case PT_CLIST:\n case PT_UCNC:\n unicode_status |= XCLASS_SAVE_CHAR;\n break;\n\n case PT_BOOL:\n unicode_status |= XCLASS_HAS_BOOL;\n break;\n\n case PT_BIDICL:\n unicode_status |= XCLASS_HAS_BIDICL;\n break;\n\n default:\n SLJIT_UNREACHABLE();\n break;\n }\n cc += 2;\n }\n#endif /* SUPPORT_UNICODE */\n }\nSLJIT_ASSERT(compares > 0);\n\n/* We are not necessary in utf mode even in 8 bit mode. */\ncc = ccbegin;\nif ((cc[-1] & XCL_NOT) != 0)\n read_char(common, min, max, backtracks, READ_CHAR_UPDATE_STR_PTR);\nelse\n {\n#ifdef SUPPORT_UNICODE\n read_char(common, min, max, (unicode_status & XCLASS_NEEDS_UCD) ? backtracks : NULL, 0);\n#else /* !SUPPORT_UNICODE */\n read_char(common, min, max, NULL, 0);\n#endif /* SUPPORT_UNICODE */\n }\n\nif ((cc[-1] & XCL_HASPROP) == 0)\n {\n if ((cc[-1] & XCL_MAP) != 0)\n {\n jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255);\n if (!optimize_class(common, (const sljit_u8 *)cc, (((const sljit_u8 *)cc)[31] & 0x80) != 0, TRUE, &found))\n {\n OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7);\n OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3);\n OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc);\n OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0);\n OP2U(SLJIT_AND | SLJIT_SET_Z, TMP1, 0, TMP2, 0);\n add_jump(compiler, &found, JUMP(SLJIT_NOT_ZERO));\n }\n\n add_jump(compiler, backtracks, JUMP(SLJIT_JUMP));\n JUMPHERE(jump);\n\n cc += 32 / sizeof(PCRE2_UCHAR);\n }\n else\n {\n OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, min);\n add_jump(compiler, (cc[-1] & XCL_NOT) == 0 ? backtracks : &found, CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, max - min));\n }\n }\nelse if ((cc[-1] & XCL_MAP) != 0)\n {\n OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0);\n#ifdef SUPPORT_UNICODE\n unicode_status |= XCLASS_CHAR_SAVED;\n#endif /* SUPPORT_UNICODE */\n if (!optimize_class(common, (const sljit_u8 *)cc, FALSE, TRUE, list))\n {\n#if PCRE2_CODE_UNIT_WIDTH == 8\n jump = NULL;\n if (common->utf)\n#endif /* PCRE2_CODE_UNIT_WIDTH == 8 */\n jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255);\n\n OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7);\n OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3);\n OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc);\n OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0);\n OP2U(SLJIT_AND | SLJIT_SET_Z, TMP1, 0, TMP2, 0);\n add_jump(compiler, list, JUMP(SLJIT_NOT_ZERO));\n\n#if PCRE2_CODE_UNIT_WIDTH == 8\n if (common->utf)\n#endif /* PCRE2_CODE_UNIT_WIDTH == 8 */\n JUMPHERE(jump);\n }\n\n OP1(SLJIT_MOV, TMP1, 0, RETURN_ADDR, 0);\n cc += 32 / sizeof(PCRE2_UCHAR);\n }\n\n#ifdef SUPPORT_UNICODE\nif (unicode_status & XCLASS_NEEDS_UCD)\n {\n if ((unicode_status & (XCLASS_SAVE_CHAR | XCLASS_CHAR_SAVED)) == XCLASS_SAVE_CHAR)\n OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0);\n\n#if PCRE2_CODE_UNIT_WIDTH == 32\n if (!common->utf)\n {\n jump = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, MAX_UTF_CODE_POINT + 1);\n OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, UNASSIGNED_UTF_CHAR);\n JUMPHERE(jump);\n }\n#endif /* PCRE2_CODE_UNIT_WIDTH == 32 */\n\n OP2(SLJIT_LSHR, TMP2, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_SHIFT);\n OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 1);\n OP1(SLJIT_MOV_U16, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_stage1));\n OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_MASK);\n OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, UCD_BLOCK_SHIFT);\n OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, TMP2, 0);\n OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_stage2));\n OP1(SLJIT_MOV_U16, TMP2, 0, SLJIT_MEM2(TMP2, TMP1), 1);\n OP2(SLJIT_SHL, TMP1, 0, TMP2, 0, SLJIT_IMM, 3);\n OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 2);\n OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, TMP1, 0);\n\n ccbegin = cc;\n\n if (unicode_status & XCLASS_HAS_BIDICL)\n {\n OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, scriptx_bidiclass));\n OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BIDICLASS_SHIFT);\n\n while (*cc != XCL_END)\n {\n if (*cc == XCL_SINGLE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n }\n else if (*cc == XCL_RANGE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n GETCHARINCTEST(c, cc);\n }\n else\n {\n SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);\n cc++;\n if (*cc == PT_BIDICL)\n {\n compares--;\n invertcmp = (compares == 0 && list != backtracks);\n if (cc[-1] == XCL_NOTPROP)\n invertcmp ^= 0x1;\n jump = CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (int)cc[1]);\n add_jump(compiler, compares > 0 ? list : backtracks, jump);\n }\n cc += 2;\n }\n }\n\n cc = ccbegin;\n }\n\n if (unicode_status & XCLASS_HAS_BOOL)\n {\n OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, bprops));\n OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BPROPS_MASK);\n OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 2);\n\n while (*cc != XCL_END)\n {\n if (*cc == XCL_SINGLE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n }\n else if (*cc == XCL_RANGE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n GETCHARINCTEST(c, cc);\n }\n else\n {\n SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);\n cc++;\n if (*cc == PT_BOOL)\n {\n compares--;\n invertcmp = (compares == 0 && list != backtracks);\n if (cc[-1] == XCL_NOTPROP)\n invertcmp ^= 0x1;\n\n OP2U(SLJIT_AND32 | SLJIT_SET_Z, SLJIT_MEM1(TMP1), (sljit_sw)(PRIV(ucd_boolprop_sets) + (cc[1] >> 5)), SLJIT_IMM, (sljit_sw)1 << (cc[1] & 0x1f));\n add_jump(compiler, compares > 0 ? list : backtracks, JUMP(SLJIT_NOT_ZERO ^ invertcmp));\n }\n cc += 2;\n }\n }\n\n cc = ccbegin;\n }\n\n if (unicode_status & XCLASS_HAS_SCRIPT)\n {\n OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script));\n\n while (*cc != XCL_END)\n {\n if (*cc == XCL_SINGLE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n }\n else if (*cc == XCL_RANGE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n GETCHARINCTEST(c, cc);\n }\n else\n {\n SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);\n cc++;\n switch (*cc)\n {\n case PT_SCX:\n if (cc[-1] == XCL_NOTPROP)\n break;\n /* Fall through */ \n\n case PT_SC:\n compares--;\n invertcmp = (compares == 0 && list != backtracks);\n if (cc[-1] == XCL_NOTPROP)\n invertcmp ^= 0x1;\n\n add_jump(compiler, compares > 0 ? list : backtracks, CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (int)cc[1]));\n }\n cc += 2;\n }\n }\n\n cc = ccbegin;\n }\n\n if (unicode_status & XCLASS_HAS_SCRIPT_EXTENSION)\n {\n OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, scriptx_bidiclass));\n OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_SCRIPTX_MASK);\n OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 2);\n\n if (unicode_status & XCLASS_SCRIPT_EXTENSION_NOTPROP)\n {\n if (unicode_status & XCLASS_HAS_TYPE)\n {\n if (unicode_status & XCLASS_SAVE_CHAR)\n {\n OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, TMP2, 0);\n unicode_status |= XCLASS_SCRIPT_EXTENSION_RESTORE_LOCALS0;\n }\n else\n {\n OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP2, 0);\n unicode_status |= XCLASS_SCRIPT_EXTENSION_RESTORE_RETURN_ADDR;\n }\n }\n OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script));\n }\n\n while (*cc != XCL_END)\n {\n if (*cc == XCL_SINGLE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n }\n else if (*cc == XCL_RANGE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n GETCHARINCTEST(c, cc);\n }\n else\n {\n SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);\n cc++;\n if (*cc == PT_SCX)\n {\n compares--;\n invertcmp = (compares == 0 && list != backtracks);\n\n jump = NULL;\n if (cc[-1] == XCL_NOTPROP)\n {\n jump = CMP(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, (int)cc[1]);\n if (invertcmp)\n {\n add_jump(compiler, backtracks, jump);\n jump = NULL;\n }\n invertcmp ^= 0x1;\n }\n\n OP2U(SLJIT_AND32 | SLJIT_SET_Z, SLJIT_MEM1(TMP1), (sljit_sw)(PRIV(ucd_script_sets) + (cc[1] >> 5)), SLJIT_IMM, (sljit_sw)1 << (cc[1] & 0x1f));\n add_jump(compiler, compares > 0 ? list : backtracks, JUMP(SLJIT_NOT_ZERO ^ invertcmp));\n\n if (jump != NULL)\n JUMPHERE(jump);\n }\n cc += 2;\n }\n }\n\n if (unicode_status & XCLASS_SCRIPT_EXTENSION_RESTORE_LOCALS0)\n OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0);\n else if (unicode_status & XCLASS_SCRIPT_EXTENSION_RESTORE_RETURN_ADDR)\n OP1(SLJIT_MOV, TMP2, 0, RETURN_ADDR, 0);\n cc = ccbegin;\n }\n\n if (unicode_status & XCLASS_SAVE_CHAR)\n OP1(SLJIT_MOV, TMP1, 0, RETURN_ADDR, 0);\n\n if (unicode_status & XCLASS_HAS_TYPE)\n {\n if (unicode_status & XCLASS_SAVE_CHAR)\n typereg = RETURN_ADDR;\n\n OP1(SLJIT_MOV_U8, typereg, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, chartype));\n }\n }\n#endif /* SUPPORT_UNICODE */\n\n/* Generating code. */\ncharoffset = 0;\nnumberofcmps = 0;\n#ifdef SUPPORT_UNICODE\ntypeoffset = 0;\n#endif /* SUPPORT_UNICODE */\n\nwhile (*cc != XCL_END)\n {\n compares--;\n invertcmp = (compares == 0 && list != backtracks);\n jump = NULL;\n\n if (*cc == XCL_SINGLE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n\n if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE))\n {\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));\n OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n numberofcmps++;\n }\n else if (numberofcmps > 0)\n {\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n numberofcmps = 0;\n }\n else\n {\n jump = CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));\n numberofcmps = 0;\n }\n }\n else if (*cc == XCL_RANGE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n SET_CHAR_OFFSET(c);\n GETCHARINCTEST(c, cc);\n\n if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE))\n {\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));\n OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL);\n numberofcmps++;\n }\n else if (numberofcmps > 0)\n {\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n numberofcmps = 0;\n }\n else\n {\n jump = CMP(SLJIT_LESS_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));\n numberofcmps = 0;\n }\n }\n#ifdef SUPPORT_UNICODE\n else\n {\n SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);\n if (*cc == XCL_NOTPROP)\n invertcmp ^= 0x1;\n cc++;\n switch(*cc)\n {\n case PT_ANY:\n if (!invertcmp)\n jump = JUMP(SLJIT_JUMP);\n break;\n\n case PT_LAMP:\n OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Lu - typeoffset);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);\n OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Ll - typeoffset);\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Lt - typeoffset);\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n break;\n\n case PT_GC:\n c = PRIV(ucp_typerange)[(int)cc[1] * 2];\n SET_TYPE_OFFSET(c);\n jump = CMP(SLJIT_LESS_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, PRIV(ucp_typerange)[(int)cc[1] * 2 + 1] - c);\n break;\n\n case PT_PC:\n jump = CMP(SLJIT_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, (int)cc[1] - typeoffset);\n break;\n\n case PT_SC:\n case PT_SCX:\n case PT_BOOL:\n case PT_BIDICL:\n compares++;\n /* Do nothing. */\n break;\n\n case PT_SPACE:\n case PT_PXSPACE:\n SET_CHAR_OFFSET(9);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0xd - 0x9);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x85 - 0x9);\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x180e - 0x9);\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n\n SET_TYPE_OFFSET(ucp_Zl);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Zl);\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n break;\n\n case PT_WORD:\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_UNDERSCORE - charoffset));\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);\n /* Fall through. */\n\n case PT_ALNUM:\n SET_TYPE_OFFSET(ucp_Ll);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Lu - ucp_Ll);\n OP_FLAGS((*cc == PT_ALNUM) ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL);\n SET_TYPE_OFFSET(ucp_Nd);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_No - ucp_Nd);\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n break;\n\n case PT_CLIST:\n other_cases = PRIV(ucd_caseless_sets) + cc[1];\n\n /* At least three characters are required.\n Otherwise this case would be handled by the normal code path. */\n SLJIT_ASSERT(other_cases[0] != NOTACHAR && other_cases[1] != NOTACHAR && other_cases[2] != NOTACHAR);\n SLJIT_ASSERT(other_cases[0] < other_cases[1] && other_cases[1] < other_cases[2]);\n\n /* Optimizing character pairs, if their difference is power of 2. */\n if (is_powerof2(other_cases[1] ^ other_cases[0]))\n {\n if (charoffset == 0)\n OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]);\n else\n {\n OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset);\n OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]);\n }\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_IMM, other_cases[1]);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);\n other_cases += 2;\n }\n else if (is_powerof2(other_cases[2] ^ other_cases[1]))\n {\n if (charoffset == 0)\n OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[2] ^ other_cases[1]);\n else\n {\n OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset);\n OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]);\n }\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_IMM, other_cases[2]);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(other_cases[0] - charoffset));\n OP_FLAGS(SLJIT_OR | ((other_cases[3] == NOTACHAR) ? SLJIT_SET_Z : 0), TMP2, 0, SLJIT_EQUAL);\n\n other_cases += 3;\n }\n else\n {\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset));\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);\n }\n\n while (*other_cases != NOTACHAR)\n {\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset));\n OP_FLAGS(SLJIT_OR | ((*other_cases == NOTACHAR) ? SLJIT_SET_Z : 0), TMP2, 0, SLJIT_EQUAL);\n }\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n break;\n\n case PT_UCNC:\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_DOLLAR_SIGN - charoffset));\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_COMMERCIAL_AT - charoffset));\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_GRAVE_ACCENT - charoffset));\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n\n SET_CHAR_OFFSET(0xa0);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(0xd7ff - charoffset));\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL);\n SET_CHAR_OFFSET(0);\n OP2U(SLJIT_SUB | SLJIT_SET_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 0xe000 - 0);\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_GREATER_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n break;\n\n case PT_PXGRAPH:\n /* C and Z groups are the farthest two groups. */\n SET_TYPE_OFFSET(ucp_Ll);\n OP2U(SLJIT_SUB | SLJIT_SET_GREATER, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER);\n\n jump = CMP(SLJIT_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll);\n\n /* In case of ucp_Cf, we overwrite the result. */\n SET_CHAR_OFFSET(0x2066);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066);\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x180e - 0x2066);\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n\n JUMPHERE(jump);\n jump = CMP(SLJIT_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0);\n break;\n\n case PT_PXPRINT:\n /* C and Z groups are the farthest two groups. */\n SET_TYPE_OFFSET(ucp_Ll);\n OP2U(SLJIT_SUB | SLJIT_SET_GREATER, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Ll);\n OP_FLAGS(SLJIT_AND, TMP2, 0, SLJIT_NOT_EQUAL);\n\n jump = CMP(SLJIT_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll);\n\n /* In case of ucp_Cf, we overwrite the result. */\n SET_CHAR_OFFSET(0x2066);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066);\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n\n JUMPHERE(jump);\n jump = CMP(SLJIT_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0);\n break;\n\n case PT_PXPUNCT:\n SET_TYPE_OFFSET(ucp_Sc);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_So - ucp_Sc);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);\n\n SET_CHAR_OFFSET(0);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x7f);\n OP_FLAGS(SLJIT_AND, TMP2, 0, SLJIT_LESS_EQUAL);\n\n SET_TYPE_OFFSET(ucp_Pc);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Ps - ucp_Pc);\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n break;\n\n default:\n SLJIT_UNREACHABLE();\n break;\n }\n cc += 2;\n }\n#endif /* SUPPORT_UNICODE */\n\n if (jump != NULL)\n add_jump(compiler, compares > 0 ? list : backtracks, jump);\n }\n\nif (found != NULL)\n set_jumps(found, LABEL());\n}", "func_hash": 183419698766008283102134937176756315954, "file_name": "pcre2_jit_compile.c", "file_hash": 284265016287060690142505784626516203619, "cwe": ["CWE-125"], "cve": "CVE-2022-1586", "cve_desc": "An out-of-bounds read vulnerability was discovered in the PCRE2 library in the compile_xclass_matchingpath() function of the pcre2_jit_compile.c file. This involves a unicode property matching issue in JIT-compiled regular expressions. The issue occurs because the character was not fully read in case-less matching within JIT.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1586"} {"idx": 223368, "project": "pcre2", "commit_id": "d4fa336fbcc388f89095b184ba6d99422cfc676c", "project_url": "https://github.com/PCRE2Project/pcre2", "commit_url": "https://github.com/PCRE2Project/pcre2/commit/d4fa336fbcc388f89095b184ba6d99422cfc676c", "commit_message": "Fix incorrect value reading in JIT.", "target": 0, "func": "static void compile_xclass_matchingpath(compiler_common *common, PCRE2_SPTR cc, jump_list **backtracks)\n{\nDEFINE_COMPILER;\njump_list *found = NULL;\njump_list **list = (cc[0] & XCL_NOT) == 0 ? &found : backtracks;\nsljit_uw c, charoffset, max = 256, min = READ_CHAR_MAX;\nstruct sljit_jump *jump = NULL;\nPCRE2_SPTR ccbegin;\nint compares, invertcmp, numberofcmps;\n#if defined SUPPORT_UNICODE && (PCRE2_CODE_UNIT_WIDTH == 8 || PCRE2_CODE_UNIT_WIDTH == 16)\nBOOL utf = common->utf;\n#endif /* SUPPORT_UNICODE && PCRE2_CODE_UNIT_WIDTH == [8|16] */\n\n#ifdef SUPPORT_UNICODE\nsljit_u32 unicode_status = 0;\nint typereg = TMP1;\nconst sljit_u32 *other_cases;\nsljit_uw typeoffset;\n#endif /* SUPPORT_UNICODE */\n\n/* Scanning the necessary info. */\ncc++;\nccbegin = cc;\ncompares = 0;\n\nif (cc[-1] & XCL_MAP)\n {\n min = 0;\n cc += 32 / sizeof(PCRE2_UCHAR);\n }\n\nwhile (*cc != XCL_END)\n {\n compares++;\n if (*cc == XCL_SINGLE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n if (c > max) max = c;\n if (c < min) min = c;\n#ifdef SUPPORT_UNICODE\n unicode_status |= XCLASS_SAVE_CHAR;\n#endif /* SUPPORT_UNICODE */\n }\n else if (*cc == XCL_RANGE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n if (c < min) min = c;\n GETCHARINCTEST(c, cc);\n if (c > max) max = c;\n#ifdef SUPPORT_UNICODE\n unicode_status |= XCLASS_SAVE_CHAR;\n#endif /* SUPPORT_UNICODE */\n }\n#ifdef SUPPORT_UNICODE\n else\n {\n SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);\n cc++;\n if (*cc == PT_CLIST && cc[-1] == XCL_PROP)\n {\n other_cases = PRIV(ucd_caseless_sets) + cc[1];\n while (*other_cases != NOTACHAR)\n {\n if (*other_cases > max) max = *other_cases;\n if (*other_cases < min) min = *other_cases;\n other_cases++;\n }\n }\n else\n {\n max = READ_CHAR_MAX;\n min = 0;\n }\n\n switch(*cc)\n {\n case PT_ANY:\n /* Any either accepts everything or ignored. */\n if (cc[-1] == XCL_PROP)\n {\n compile_char1_matchingpath(common, OP_ALLANY, cc, backtracks, FALSE);\n if (list == backtracks)\n add_jump(compiler, backtracks, JUMP(SLJIT_JUMP));\n return;\n }\n break;\n\n case PT_LAMP:\n case PT_GC:\n case PT_PC:\n case PT_ALNUM:\n unicode_status |= XCLASS_HAS_TYPE;\n break;\n\n case PT_SCX:\n unicode_status |= XCLASS_HAS_SCRIPT_EXTENSION;\n if (cc[-1] == XCL_NOTPROP)\n {\n unicode_status |= XCLASS_SCRIPT_EXTENSION_NOTPROP;\n break;\n }\n compares++;\n /* Fall through */ \n\n case PT_SC:\n unicode_status |= XCLASS_HAS_SCRIPT;\n break;\n\n case PT_SPACE:\n case PT_PXSPACE:\n case PT_WORD:\n case PT_PXGRAPH:\n case PT_PXPRINT:\n case PT_PXPUNCT:\n unicode_status |= XCLASS_SAVE_CHAR | XCLASS_HAS_TYPE;\n break;\n\n case PT_CLIST:\n case PT_UCNC:\n unicode_status |= XCLASS_SAVE_CHAR;\n break;\n\n case PT_BOOL:\n unicode_status |= XCLASS_HAS_BOOL;\n break;\n\n case PT_BIDICL:\n unicode_status |= XCLASS_HAS_BIDICL;\n break;\n\n default:\n SLJIT_UNREACHABLE();\n break;\n }\n cc += 2;\n }\n#endif /* SUPPORT_UNICODE */\n }\nSLJIT_ASSERT(compares > 0);\n\n/* We are not necessary in utf mode even in 8 bit mode. */\ncc = ccbegin;\nif ((cc[-1] & XCL_NOT) != 0)\n read_char(common, min, max, backtracks, READ_CHAR_UPDATE_STR_PTR);\nelse\n {\n#ifdef SUPPORT_UNICODE\n read_char(common, min, max, (unicode_status & XCLASS_NEEDS_UCD) ? backtracks : NULL, 0);\n#else /* !SUPPORT_UNICODE */\n read_char(common, min, max, NULL, 0);\n#endif /* SUPPORT_UNICODE */\n }\n\nif ((cc[-1] & XCL_HASPROP) == 0)\n {\n if ((cc[-1] & XCL_MAP) != 0)\n {\n jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255);\n if (!optimize_class(common, (const sljit_u8 *)cc, (((const sljit_u8 *)cc)[31] & 0x80) != 0, TRUE, &found))\n {\n OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7);\n OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3);\n OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc);\n OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0);\n OP2U(SLJIT_AND | SLJIT_SET_Z, TMP1, 0, TMP2, 0);\n add_jump(compiler, &found, JUMP(SLJIT_NOT_ZERO));\n }\n\n add_jump(compiler, backtracks, JUMP(SLJIT_JUMP));\n JUMPHERE(jump);\n\n cc += 32 / sizeof(PCRE2_UCHAR);\n }\n else\n {\n OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, min);\n add_jump(compiler, (cc[-1] & XCL_NOT) == 0 ? backtracks : &found, CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, max - min));\n }\n }\nelse if ((cc[-1] & XCL_MAP) != 0)\n {\n OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0);\n#ifdef SUPPORT_UNICODE\n unicode_status |= XCLASS_CHAR_SAVED;\n#endif /* SUPPORT_UNICODE */\n if (!optimize_class(common, (const sljit_u8 *)cc, FALSE, TRUE, list))\n {\n#if PCRE2_CODE_UNIT_WIDTH == 8\n jump = NULL;\n if (common->utf)\n#endif /* PCRE2_CODE_UNIT_WIDTH == 8 */\n jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255);\n\n OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7);\n OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3);\n OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc);\n OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0);\n OP2U(SLJIT_AND | SLJIT_SET_Z, TMP1, 0, TMP2, 0);\n add_jump(compiler, list, JUMP(SLJIT_NOT_ZERO));\n\n#if PCRE2_CODE_UNIT_WIDTH == 8\n if (common->utf)\n#endif /* PCRE2_CODE_UNIT_WIDTH == 8 */\n JUMPHERE(jump);\n }\n\n OP1(SLJIT_MOV, TMP1, 0, RETURN_ADDR, 0);\n cc += 32 / sizeof(PCRE2_UCHAR);\n }\n\n#ifdef SUPPORT_UNICODE\nif (unicode_status & XCLASS_NEEDS_UCD)\n {\n if ((unicode_status & (XCLASS_SAVE_CHAR | XCLASS_CHAR_SAVED)) == XCLASS_SAVE_CHAR)\n OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0);\n\n#if PCRE2_CODE_UNIT_WIDTH == 32\n if (!common->utf)\n {\n jump = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, MAX_UTF_CODE_POINT + 1);\n OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, UNASSIGNED_UTF_CHAR);\n JUMPHERE(jump);\n }\n#endif /* PCRE2_CODE_UNIT_WIDTH == 32 */\n\n OP2(SLJIT_LSHR, TMP2, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_SHIFT);\n OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 1);\n OP1(SLJIT_MOV_U16, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_stage1));\n OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_MASK);\n OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, UCD_BLOCK_SHIFT);\n OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, TMP2, 0);\n OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_stage2));\n OP1(SLJIT_MOV_U16, TMP2, 0, SLJIT_MEM2(TMP2, TMP1), 1);\n OP2(SLJIT_SHL, TMP1, 0, TMP2, 0, SLJIT_IMM, 3);\n OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 2);\n OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, TMP1, 0);\n\n ccbegin = cc;\n\n if (unicode_status & XCLASS_HAS_BIDICL)\n {\n OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, scriptx_bidiclass));\n OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BIDICLASS_SHIFT);\n\n while (*cc != XCL_END)\n {\n if (*cc == XCL_SINGLE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n }\n else if (*cc == XCL_RANGE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n GETCHARINCTEST(c, cc);\n }\n else\n {\n SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);\n cc++;\n if (*cc == PT_BIDICL)\n {\n compares--;\n invertcmp = (compares == 0 && list != backtracks);\n if (cc[-1] == XCL_NOTPROP)\n invertcmp ^= 0x1;\n jump = CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (int)cc[1]);\n add_jump(compiler, compares > 0 ? list : backtracks, jump);\n }\n cc += 2;\n }\n }\n\n cc = ccbegin;\n }\n\n if (unicode_status & XCLASS_HAS_BOOL)\n {\n OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, bprops));\n OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BPROPS_MASK);\n OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 2);\n\n while (*cc != XCL_END)\n {\n if (*cc == XCL_SINGLE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n }\n else if (*cc == XCL_RANGE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n GETCHARINCTEST(c, cc);\n }\n else\n {\n SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);\n cc++;\n if (*cc == PT_BOOL)\n {\n compares--;\n invertcmp = (compares == 0 && list != backtracks);\n if (cc[-1] == XCL_NOTPROP)\n invertcmp ^= 0x1;\n\n OP2U(SLJIT_AND32 | SLJIT_SET_Z, SLJIT_MEM1(TMP1), (sljit_sw)(PRIV(ucd_boolprop_sets) + (cc[1] >> 5)), SLJIT_IMM, (sljit_sw)1 << (cc[1] & 0x1f));\n add_jump(compiler, compares > 0 ? list : backtracks, JUMP(SLJIT_NOT_ZERO ^ invertcmp));\n }\n cc += 2;\n }\n }\n\n cc = ccbegin;\n }\n\n if (unicode_status & XCLASS_HAS_SCRIPT)\n {\n OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script));\n\n while (*cc != XCL_END)\n {\n if (*cc == XCL_SINGLE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n }\n else if (*cc == XCL_RANGE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n GETCHARINCTEST(c, cc);\n }\n else\n {\n SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);\n cc++;\n switch (*cc)\n {\n case PT_SCX:\n if (cc[-1] == XCL_NOTPROP)\n break;\n /* Fall through */ \n\n case PT_SC:\n compares--;\n invertcmp = (compares == 0 && list != backtracks);\n if (cc[-1] == XCL_NOTPROP)\n invertcmp ^= 0x1;\n\n add_jump(compiler, compares > 0 ? list : backtracks, CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (int)cc[1]));\n }\n cc += 2;\n }\n }\n\n cc = ccbegin;\n }\n\n if (unicode_status & XCLASS_HAS_SCRIPT_EXTENSION)\n {\n OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, scriptx_bidiclass));\n OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_SCRIPTX_MASK);\n OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 2);\n\n if (unicode_status & XCLASS_SCRIPT_EXTENSION_NOTPROP)\n {\n if (unicode_status & XCLASS_HAS_TYPE)\n {\n if (unicode_status & XCLASS_SAVE_CHAR)\n {\n OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, TMP2, 0);\n unicode_status |= XCLASS_SCRIPT_EXTENSION_RESTORE_LOCALS0;\n }\n else\n {\n OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP2, 0);\n unicode_status |= XCLASS_SCRIPT_EXTENSION_RESTORE_RETURN_ADDR;\n }\n }\n OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script));\n }\n\n while (*cc != XCL_END)\n {\n if (*cc == XCL_SINGLE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n }\n else if (*cc == XCL_RANGE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n GETCHARINCTEST(c, cc);\n }\n else\n {\n SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);\n cc++;\n if (*cc == PT_SCX)\n {\n compares--;\n invertcmp = (compares == 0 && list != backtracks);\n\n jump = NULL;\n if (cc[-1] == XCL_NOTPROP)\n {\n jump = CMP(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, (int)cc[1]);\n if (invertcmp)\n {\n add_jump(compiler, backtracks, jump);\n jump = NULL;\n }\n invertcmp ^= 0x1;\n }\n\n OP2U(SLJIT_AND32 | SLJIT_SET_Z, SLJIT_MEM1(TMP1), (sljit_sw)(PRIV(ucd_script_sets) + (cc[1] >> 5)), SLJIT_IMM, (sljit_sw)1 << (cc[1] & 0x1f));\n add_jump(compiler, compares > 0 ? list : backtracks, JUMP(SLJIT_NOT_ZERO ^ invertcmp));\n\n if (jump != NULL)\n JUMPHERE(jump);\n }\n cc += 2;\n }\n }\n\n if (unicode_status & XCLASS_SCRIPT_EXTENSION_RESTORE_LOCALS0)\n OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0);\n else if (unicode_status & XCLASS_SCRIPT_EXTENSION_RESTORE_RETURN_ADDR)\n OP1(SLJIT_MOV, TMP2, 0, RETURN_ADDR, 0);\n cc = ccbegin;\n }\n\n if (unicode_status & XCLASS_SAVE_CHAR)\n OP1(SLJIT_MOV, TMP1, 0, RETURN_ADDR, 0);\n\n if (unicode_status & XCLASS_HAS_TYPE)\n {\n if (unicode_status & XCLASS_SAVE_CHAR)\n typereg = RETURN_ADDR;\n\n OP1(SLJIT_MOV_U8, typereg, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, chartype));\n }\n }\n#endif /* SUPPORT_UNICODE */\n\n/* Generating code. */\ncharoffset = 0;\nnumberofcmps = 0;\n#ifdef SUPPORT_UNICODE\ntypeoffset = 0;\n#endif /* SUPPORT_UNICODE */\n\nwhile (*cc != XCL_END)\n {\n compares--;\n invertcmp = (compares == 0 && list != backtracks);\n jump = NULL;\n\n if (*cc == XCL_SINGLE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n\n if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE))\n {\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));\n OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n numberofcmps++;\n }\n else if (numberofcmps > 0)\n {\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n numberofcmps = 0;\n }\n else\n {\n jump = CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));\n numberofcmps = 0;\n }\n }\n else if (*cc == XCL_RANGE)\n {\n cc ++;\n GETCHARINCTEST(c, cc);\n SET_CHAR_OFFSET(c);\n GETCHARINCTEST(c, cc);\n\n if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE))\n {\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));\n OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL);\n numberofcmps++;\n }\n else if (numberofcmps > 0)\n {\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n numberofcmps = 0;\n }\n else\n {\n jump = CMP(SLJIT_LESS_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));\n numberofcmps = 0;\n }\n }\n#ifdef SUPPORT_UNICODE\n else\n {\n SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);\n if (*cc == XCL_NOTPROP)\n invertcmp ^= 0x1;\n cc++;\n switch(*cc)\n {\n case PT_ANY:\n if (!invertcmp)\n jump = JUMP(SLJIT_JUMP);\n break;\n\n case PT_LAMP:\n OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Lu - typeoffset);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);\n OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Ll - typeoffset);\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Lt - typeoffset);\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n break;\n\n case PT_GC:\n c = PRIV(ucp_typerange)[(int)cc[1] * 2];\n SET_TYPE_OFFSET(c);\n jump = CMP(SLJIT_LESS_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, PRIV(ucp_typerange)[(int)cc[1] * 2 + 1] - c);\n break;\n\n case PT_PC:\n jump = CMP(SLJIT_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, (int)cc[1] - typeoffset);\n break;\n\n case PT_SC:\n case PT_SCX:\n case PT_BOOL:\n case PT_BIDICL:\n compares++;\n /* Do nothing. */\n break;\n\n case PT_SPACE:\n case PT_PXSPACE:\n SET_CHAR_OFFSET(9);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0xd - 0x9);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x85 - 0x9);\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x180e - 0x9);\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n\n SET_TYPE_OFFSET(ucp_Zl);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Zl);\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n break;\n\n case PT_WORD:\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_UNDERSCORE - charoffset));\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);\n /* Fall through. */\n\n case PT_ALNUM:\n SET_TYPE_OFFSET(ucp_Ll);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Lu - ucp_Ll);\n OP_FLAGS((*cc == PT_ALNUM) ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL);\n SET_TYPE_OFFSET(ucp_Nd);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_No - ucp_Nd);\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n break;\n\n case PT_CLIST:\n other_cases = PRIV(ucd_caseless_sets) + cc[1];\n\n /* At least three characters are required.\n Otherwise this case would be handled by the normal code path. */\n SLJIT_ASSERT(other_cases[0] != NOTACHAR && other_cases[1] != NOTACHAR && other_cases[2] != NOTACHAR);\n SLJIT_ASSERT(other_cases[0] < other_cases[1] && other_cases[1] < other_cases[2]);\n\n /* Optimizing character pairs, if their difference is power of 2. */\n if (is_powerof2(other_cases[1] ^ other_cases[0]))\n {\n if (charoffset == 0)\n OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]);\n else\n {\n OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset);\n OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]);\n }\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_IMM, other_cases[1]);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);\n other_cases += 2;\n }\n else if (is_powerof2(other_cases[2] ^ other_cases[1]))\n {\n if (charoffset == 0)\n OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[2] ^ other_cases[1]);\n else\n {\n OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset);\n OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]);\n }\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_IMM, other_cases[2]);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(other_cases[0] - charoffset));\n OP_FLAGS(SLJIT_OR | ((other_cases[3] == NOTACHAR) ? SLJIT_SET_Z : 0), TMP2, 0, SLJIT_EQUAL);\n\n other_cases += 3;\n }\n else\n {\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset));\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);\n }\n\n while (*other_cases != NOTACHAR)\n {\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset));\n OP_FLAGS(SLJIT_OR | ((*other_cases == NOTACHAR) ? SLJIT_SET_Z : 0), TMP2, 0, SLJIT_EQUAL);\n }\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n break;\n\n case PT_UCNC:\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_DOLLAR_SIGN - charoffset));\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_COMMERCIAL_AT - charoffset));\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_GRAVE_ACCENT - charoffset));\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n\n SET_CHAR_OFFSET(0xa0);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(0xd7ff - charoffset));\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL);\n SET_CHAR_OFFSET(0);\n OP2U(SLJIT_SUB | SLJIT_SET_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 0xe000 - 0);\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_GREATER_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n break;\n\n case PT_PXGRAPH:\n /* C and Z groups are the farthest two groups. */\n SET_TYPE_OFFSET(ucp_Ll);\n OP2U(SLJIT_SUB | SLJIT_SET_GREATER, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER);\n\n jump = CMP(SLJIT_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll);\n\n /* In case of ucp_Cf, we overwrite the result. */\n SET_CHAR_OFFSET(0x2066);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066);\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x180e - 0x2066);\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n\n JUMPHERE(jump);\n jump = CMP(SLJIT_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0);\n break;\n\n case PT_PXPRINT:\n /* C and Z groups are the farthest two groups. */\n SET_TYPE_OFFSET(ucp_Ll);\n OP2U(SLJIT_SUB | SLJIT_SET_GREATER, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Ll);\n OP_FLAGS(SLJIT_AND, TMP2, 0, SLJIT_NOT_EQUAL);\n\n jump = CMP(SLJIT_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll);\n\n /* In case of ucp_Cf, we overwrite the result. */\n SET_CHAR_OFFSET(0x2066);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);\n\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066);\n OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);\n\n JUMPHERE(jump);\n jump = CMP(SLJIT_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0);\n break;\n\n case PT_PXPUNCT:\n SET_TYPE_OFFSET(ucp_Sc);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_So - ucp_Sc);\n OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);\n\n SET_CHAR_OFFSET(0);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x7f);\n OP_FLAGS(SLJIT_AND, TMP2, 0, SLJIT_LESS_EQUAL);\n\n SET_TYPE_OFFSET(ucp_Pc);\n OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Ps - ucp_Pc);\n OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);\n jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);\n break;\n\n default:\n SLJIT_UNREACHABLE();\n break;\n }\n cc += 2;\n }\n#endif /* SUPPORT_UNICODE */\n\n if (jump != NULL)\n add_jump(compiler, compares > 0 ? list : backtracks, jump);\n }\n\nif (found != NULL)\n set_jumps(found, LABEL());\n}", "func_hash": 144276531294134211562638848702422655084, "file_name": "pcre2_jit_compile.c", "file_hash": 52374969195278947710795935639555031915, "cwe": ["CWE-125"], "cve": "CVE-2022-1586", "cve_desc": "An out-of-bounds read vulnerability was discovered in the PCRE2 library in the compile_xclass_matchingpath() function of the pcre2_jit_compile.c file. This involves a unicode property matching issue in JIT-compiled regular expressions. The issue occurs because the character was not fully read in case-less matching within JIT.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1586"} {"idx": 195274, "project": "tensorflow", "commit_id": "0a365c029e437be0349c31f8d4c9926b69fa3fa1", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/0a365c029e437be0349c31f8d4c9926b69fa3fa1", "commit_message": "Prevent null pointer dereference in constant folding.\n\nUnder certain conditions, an invalid protobuf saved model with invalid nodes would be loaded. During optimization phase, Grappler optimizer will then dereference a null pointer.\n\nPiperOrigin-RevId: 409683530\nChange-Id: I1f10340a7ec384bc9bc587300390f1078cf5caa0", "target": 1, "func": "bool ConstantFolding::MulConvPushDown(GraphDef* optimized_graph, NodeDef* node,\n const GraphProperties& properties) {\n // Push down multiplication on ConvND.\n // * ConvND\n // / \\ / \\\n // ConvND C2 -- > X *\n // / \\ / \\\n // X C1 C1 C2\n //\n // where C1 and C2 are constants and X is non-constant.\n //\n // TODO(rmlarsen): Use PrepareConstantPushDown() to simplify this code.\n\n if (!IsAnyMul(*node) || NumNonControlInputs(*node) != 2) return false;\n\n NodeDef* mul_left_child = node_map_->GetNode(node->input(0));\n NodeDef* mul_right_child = node_map_->GetNode(node->input(1));\n // One child must be constant, and the second must be Conv op.\n const bool left_child_is_constant = IsReallyConstant(*mul_left_child);\n const bool right_child_is_constant = IsReallyConstant(*mul_right_child);\n if (!left_child_is_constant && !right_child_is_constant) {\n return false;\n }\n NodeDef* conv_node =\n left_child_is_constant ? mul_right_child : mul_left_child;\n if (!IsConv2D(*conv_node) && !IsConv3D(*conv_node)) {\n return false;\n }\n if (node->device() != mul_left_child->device() ||\n node->device() != mul_right_child->device()) {\n return false;\n }\n\n // Make sure that it is safe to change the value of the convolution\n // output.\n if (conv_node->input_size() < 2 ||\n NumNonControlOutputs(*conv_node, *node_map_) > 1 ||\n nodes_to_preserve_.find(conv_node->name()) != nodes_to_preserve_.end()) {\n return false;\n }\n\n // Identify the nodes to swap.\n NodeDef* conv_left_child = node_map_->GetNode(conv_node->input(0));\n NodeDef* conv_right_child = node_map_->GetNode(conv_node->input(1));\n const bool conv_left_is_constant = IsReallyConstant(*conv_left_child);\n const bool conv_right_is_constant = IsReallyConstant(*conv_right_child);\n if (!conv_left_is_constant && !conv_right_is_constant) {\n // At least one of the convolution inputs should be constant.\n return false;\n }\n if (conv_left_is_constant && conv_right_is_constant) {\n // Leverage regular constant folding to handle this.\n return false;\n }\n const auto& mul_props = properties.GetOutputProperties(node->name());\n const auto& conv_props = properties.GetOutputProperties(conv_node->name());\n if (mul_props.empty() || conv_props.empty()) {\n return false;\n }\n const auto& mul_shape = mul_props[0].shape();\n const auto& conv_shape = conv_props[0].shape();\n if (!ShapesSymbolicallyEqual(mul_shape, conv_shape)) {\n return false;\n }\n\n const auto& input_props = properties.GetInputProperties(conv_node->name());\n if (input_props.size() < 2) {\n return false;\n }\n const auto& filter_shape = input_props[1].shape();\n\n NodeDef* const_node =\n left_child_is_constant ? mul_left_child : mul_right_child;\n const auto& const_props = properties.GetOutputProperties(const_node->name());\n if (const_props.empty()) {\n return false;\n }\n const auto& const_shape = const_props[0].shape();\n if (!IsValidConstShapeForMulConvPushDown(\n conv_node->attr().at(\"data_format\").s(), filter_shape, const_shape)) {\n return false;\n }\n\n string mul_new_name = AddPrefixToNodeName(\"merged_input\", conv_node->name());\n if (node_map_->NodeExists(mul_new_name)) {\n return false;\n }\n // Make sure we don't introduce loops in the graph by removing control\n // dependencies from the conv2d node to c2.\n string conv_const_input =\n conv_left_is_constant ? conv_node->input(0) : conv_node->input(1);\n if (MaybeRemoveControlInput(conv_node->name(), const_node, optimized_graph,\n node_map_.get())) {\n // Add a control dep from c1 to c2 to ensure c2 is in the right frame\n MaybeAddControlInput(conv_const_input, const_node, optimized_graph,\n node_map_.get());\n }\n\n conv_node->set_name(node->name());\n node->set_name(mul_new_name);\n if (conv_left_is_constant) {\n node_map_->UpdateInput(conv_node->name(), node->input(0), mul_new_name);\n conv_node->set_input(0, mul_new_name);\n } else {\n node_map_->UpdateInput(conv_node->name(), node->input(1), mul_new_name);\n conv_node->set_input(1, mul_new_name);\n }\n NodeDef* conv_const_node =\n conv_left_is_constant ? conv_left_child : conv_right_child;\n if (left_child_is_constant) {\n node->set_input(1, conv_const_node->name());\n } else {\n node->set_input(0, conv_const_node->name());\n }\n node_map_->AddNode(mul_new_name, node);\n\n return true;\n}", "func_hash": 134451371039665673916173676790439576039, "file_name": "constant_folding.cc", "file_hash": 221573695858123615640237954647315751120, "cwe": ["CWE-476"], "cve": "CVE-2022-23589", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. Under certain scenarios, Grappler component of TensorFlow can trigger a null pointer dereference. There are 2 places where this can occur, for the same malicious alteration of a `SavedModel` file (fixing the first one would trigger the same dereference in the second place). First, during constant folding, the `GraphDef` might not have the required nodes for the binary operation. If a node is missing, the correposning `mul_*child` would be null, and the dereference in the subsequent line would be incorrect. We have a similar issue during `IsIdentityConsumingSwitch`. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23589"} {"idx": 223728, "project": "tensorflow", "commit_id": "0a365c029e437be0349c31f8d4c9926b69fa3fa1", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/0a365c029e437be0349c31f8d4c9926b69fa3fa1", "commit_message": "Prevent null pointer dereference in constant folding.\n\nUnder certain conditions, an invalid protobuf saved model with invalid nodes would be loaded. During optimization phase, Grappler optimizer will then dereference a null pointer.\n\nPiperOrigin-RevId: 409683530\nChange-Id: I1f10340a7ec384bc9bc587300390f1078cf5caa0", "target": 0, "func": "bool ConstantFolding::MulConvPushDown(GraphDef* optimized_graph, NodeDef* node,\n const GraphProperties& properties) {\n // Push down multiplication on ConvND.\n // * ConvND\n // / \\ / \\\n // ConvND C2 -- > X *\n // / \\ / \\\n // X C1 C1 C2\n //\n // where C1 and C2 are constants and X is non-constant.\n //\n // TODO(rmlarsen): Use PrepareConstantPushDown() to simplify this code.\n\n if (!IsAnyMul(*node) || NumNonControlInputs(*node) != 2) return false;\n\n NodeDef* mul_left_child = node_map_->GetNode(node->input(0));\n NodeDef* mul_right_child = node_map_->GetNode(node->input(1));\n if (mul_left_child == nullptr || mul_right_child == nullptr) {\n return false;\n }\n // One child must be constant, and the second must be Conv op.\n const bool left_child_is_constant = IsReallyConstant(*mul_left_child);\n const bool right_child_is_constant = IsReallyConstant(*mul_right_child);\n if (!left_child_is_constant && !right_child_is_constant) {\n return false;\n }\n NodeDef* conv_node =\n left_child_is_constant ? mul_right_child : mul_left_child;\n if (!IsConv2D(*conv_node) && !IsConv3D(*conv_node)) {\n return false;\n }\n if (node->device() != mul_left_child->device() ||\n node->device() != mul_right_child->device()) {\n return false;\n }\n\n // Make sure that it is safe to change the value of the convolution\n // output.\n if (conv_node->input_size() < 2 ||\n NumNonControlOutputs(*conv_node, *node_map_) > 1 ||\n nodes_to_preserve_.find(conv_node->name()) != nodes_to_preserve_.end()) {\n return false;\n }\n\n // Identify the nodes to swap.\n NodeDef* conv_left_child = node_map_->GetNode(conv_node->input(0));\n NodeDef* conv_right_child = node_map_->GetNode(conv_node->input(1));\n const bool conv_left_is_constant = IsReallyConstant(*conv_left_child);\n const bool conv_right_is_constant = IsReallyConstant(*conv_right_child);\n if (!conv_left_is_constant && !conv_right_is_constant) {\n // At least one of the convolution inputs should be constant.\n return false;\n }\n if (conv_left_is_constant && conv_right_is_constant) {\n // Leverage regular constant folding to handle this.\n return false;\n }\n const auto& mul_props = properties.GetOutputProperties(node->name());\n const auto& conv_props = properties.GetOutputProperties(conv_node->name());\n if (mul_props.empty() || conv_props.empty()) {\n return false;\n }\n const auto& mul_shape = mul_props[0].shape();\n const auto& conv_shape = conv_props[0].shape();\n if (!ShapesSymbolicallyEqual(mul_shape, conv_shape)) {\n return false;\n }\n\n const auto& input_props = properties.GetInputProperties(conv_node->name());\n if (input_props.size() < 2) {\n return false;\n }\n const auto& filter_shape = input_props[1].shape();\n\n NodeDef* const_node =\n left_child_is_constant ? mul_left_child : mul_right_child;\n const auto& const_props = properties.GetOutputProperties(const_node->name());\n if (const_props.empty()) {\n return false;\n }\n const auto& const_shape = const_props[0].shape();\n if (!IsValidConstShapeForMulConvPushDown(\n conv_node->attr().at(\"data_format\").s(), filter_shape, const_shape)) {\n return false;\n }\n\n string mul_new_name = AddPrefixToNodeName(\"merged_input\", conv_node->name());\n if (node_map_->NodeExists(mul_new_name)) {\n return false;\n }\n // Make sure we don't introduce loops in the graph by removing control\n // dependencies from the conv2d node to c2.\n string conv_const_input =\n conv_left_is_constant ? conv_node->input(0) : conv_node->input(1);\n if (MaybeRemoveControlInput(conv_node->name(), const_node, optimized_graph,\n node_map_.get())) {\n // Add a control dep from c1 to c2 to ensure c2 is in the right frame\n MaybeAddControlInput(conv_const_input, const_node, optimized_graph,\n node_map_.get());\n }\n\n conv_node->set_name(node->name());\n node->set_name(mul_new_name);\n if (conv_left_is_constant) {\n node_map_->UpdateInput(conv_node->name(), node->input(0), mul_new_name);\n conv_node->set_input(0, mul_new_name);\n } else {\n node_map_->UpdateInput(conv_node->name(), node->input(1), mul_new_name);\n conv_node->set_input(1, mul_new_name);\n }\n NodeDef* conv_const_node =\n conv_left_is_constant ? conv_left_child : conv_right_child;\n if (left_child_is_constant) {\n node->set_input(1, conv_const_node->name());\n } else {\n node->set_input(0, conv_const_node->name());\n }\n node_map_->AddNode(mul_new_name, node);\n\n return true;\n}", "func_hash": 283045777051933437914385494105493059717, "file_name": "constant_folding.cc", "file_hash": 149567017925135188078420823730624272905, "cwe": ["CWE-476"], "cve": "CVE-2022-23589", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. Under certain scenarios, Grappler component of TensorFlow can trigger a null pointer dereference. There are 2 places where this can occur, for the same malicious alteration of a `SavedModel` file (fixing the first one would trigger the same dereference in the second place). First, during constant folding, the `GraphDef` might not have the required nodes for the binary operation. If a node is missing, the correposning `mul_*child` would be null, and the dereference in the subsequent line would be incorrect. We have a similar issue during `IsIdentityConsumingSwitch`. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23589"} {"idx": 195291, "project": "tensorflow", "commit_id": "ef1d027be116f25e25bb94a60da491c2cf55bd0b", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/ef1d027be116f25e25bb94a60da491c2cf55bd0b", "commit_message": "Prevent copying uninitialized data in `AssignOp`.\n\nThis prevents harder to debug undefined behaviors that cannot be traced back to the original tensor after assignments occur earlier in the graph execution. Several of these undefined behaviors are just reference bindings to null pointers, which are caught when running under ubsan/asan.\n\nPiperOrigin-RevId: 408654780\nChange-Id: Iad2ec40d43f5fd7ea016c20283356c12d5ddeab1", "target": 1, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& rhs = context->input(1);\n\n // We always return the input ref.\n context->forward_ref_input_to_ref_output(0, 0);\n\n // We can't always know how this value will be used downstream, so make\n // conservative assumptions in specifying constraints on the memory\n // allocation attributes, unless the Grappler graph analysis determined that\n // it was safe not to.\n AllocatorAttributes attr;\n if (!relax_constraints_) {\n attr.set_gpu_compatible(true);\n attr.set_nic_compatible(true);\n }\n\n {\n mutex_lock l(*context->input_ref_mutex(0));\n const Tensor& old_lhs = context->mutable_input(0, /* lock_held */ true);\n const bool same_shape = old_lhs.shape().IsSameSize(rhs.shape());\n if (validate_shape_) {\n OP_REQUIRES(context, same_shape,\n errors::InvalidArgument(\n \"Assign requires shapes of both tensors to match. \"\n \"lhs shape= \",\n old_lhs.shape().DebugString(),\n \" rhs shape= \", rhs.shape().DebugString()));\n }\n\n // In the code below we try to minimize the amount of memory allocation\n // and copying by trying the following two shortcuts:\n // 1. If the lhs is initialized and has the same number of elements as\n // the rhs we can avoid a memory allocation.\n // 2. If we can reuse the rhs buffer we avoid both a memory allocation\n // and copying.\n\n // 1. Try to copy into an existing buffer.\n if (old_lhs.IsInitialized() &&\n old_lhs.shape().num_elements() == rhs.shape().num_elements()) {\n // The existing lhs tensor has already been initialized and the right\n // hand side can fit in the underlying buffer.\n Tensor reshaped_old_lhs;\n if (same_shape) {\n reshaped_old_lhs = old_lhs;\n } else {\n CHECK(reshaped_old_lhs.CopyFrom(old_lhs, rhs.shape()));\n context->replace_ref_input(0, reshaped_old_lhs,\n /* lock_held */ true);\n }\n if (use_exclusive_lock_) {\n Copy(context, &reshaped_old_lhs, rhs);\n return;\n }\n } else {\n // 2. Try to reuse the rhs.\n std::unique_ptr input_alias = context->forward_input(\n 1, OpKernelContext::Params::kNoReservation /*output_index*/,\n rhs.dtype(), rhs.shape(), DEVICE_MEMORY, attr);\n if (input_alias != nullptr) {\n // Update the ref to point to the new buffer.\n context->replace_ref_input(0, *input_alias, /* lock_held */ true);\n return;\n }\n\n // Otherwise, create a new tensor whose shape matches the\n // right hand side, hand off to lhs and copy the rhs into it.\n Tensor copy_tensor;\n OP_REQUIRES_OK(context,\n context->allocate_temp(old_lhs.dtype(), rhs.shape(),\n ©_tensor, attr));\n // We track memory of variables in variable ops instead of in this\n // assign op.\n context->clear_recorded_memory();\n context->replace_ref_input(0, copy_tensor, /* lock_held */ true);\n if (use_exclusive_lock_) {\n Copy(context, ©_tensor, rhs);\n return;\n }\n }\n }\n\n // The tensor has already been initialized and the right hand side\n // matches the left hand side's shape. We have been told to do the\n // copy outside the lock.\n Tensor old_unlocked_lhs = context->mutable_input(0, /* lock_held */ false);\n Copy(context, &old_unlocked_lhs, rhs);\n }", "func_hash": 110563830933859876998490806365273446744, "file_name": "assign_op.h", "file_hash": 69919930869774703131816695670485389180, "cwe": ["CWE-908"], "cve": "CVE-2022-23573", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `AssignOp` can result in copying uninitialized data to a new tensor. This later results in undefined behavior. The implementation has a check that the left hand side of the assignment is initialized (to minimize number of allocations), but does not check that the right hand side is also initialized. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23573"} {"idx": 224153, "project": "tensorflow", "commit_id": "ef1d027be116f25e25bb94a60da491c2cf55bd0b", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/ef1d027be116f25e25bb94a60da491c2cf55bd0b", "commit_message": "Prevent copying uninitialized data in `AssignOp`.\n\nThis prevents harder to debug undefined behaviors that cannot be traced back to the original tensor after assignments occur earlier in the graph execution. Several of these undefined behaviors are just reference bindings to null pointers, which are caught when running under ubsan/asan.\n\nPiperOrigin-RevId: 408654780\nChange-Id: Iad2ec40d43f5fd7ea016c20283356c12d5ddeab1", "target": 0, "func": " void Compute(OpKernelContext* context) override {\n const Tensor& rhs = context->input(1);\n\n // We always return the input ref.\n context->forward_ref_input_to_ref_output(0, 0);\n\n // Prevent copying uninitialized data, to solve harder to debug undefined\n // behaviors that cannot be traced back to the original tensor.\n OP_REQUIRES(\n context, rhs.IsInitialized(),\n errors::Internal(\"Right hand side of AssignOp is not initialized\"));\n\n // We can't always know how this value will be used downstream, so make\n // conservative assumptions in specifying constraints on the memory\n // allocation attributes, unless the Grappler graph analysis determined that\n // it was safe not to.\n AllocatorAttributes attr;\n if (!relax_constraints_) {\n attr.set_gpu_compatible(true);\n attr.set_nic_compatible(true);\n }\n\n {\n mutex_lock l(*context->input_ref_mutex(0));\n const Tensor& old_lhs = context->mutable_input(0, /* lock_held */ true);\n const bool same_shape = old_lhs.shape().IsSameSize(rhs.shape());\n if (validate_shape_) {\n OP_REQUIRES(context, same_shape,\n errors::InvalidArgument(\n \"Assign requires shapes of both tensors to match. \"\n \"lhs shape= \",\n old_lhs.shape().DebugString(),\n \" rhs shape= \", rhs.shape().DebugString()));\n }\n\n // In the code below we try to minimize the amount of memory allocation\n // and copying by trying the following two shortcuts:\n // 1. If the lhs is initialized and has the same number of elements as\n // the rhs we can avoid a memory allocation.\n // 2. If we can reuse the rhs buffer we avoid both a memory allocation\n // and copying.\n\n // 1. Try to copy into an existing buffer.\n if (old_lhs.IsInitialized() &&\n old_lhs.shape().num_elements() == rhs.shape().num_elements()) {\n // The existing lhs tensor has already been initialized and the right\n // hand side can fit in the underlying buffer.\n Tensor reshaped_old_lhs;\n if (same_shape) {\n reshaped_old_lhs = old_lhs;\n } else {\n CHECK(reshaped_old_lhs.CopyFrom(old_lhs, rhs.shape()));\n context->replace_ref_input(0, reshaped_old_lhs,\n /* lock_held */ true);\n }\n if (use_exclusive_lock_) {\n Copy(context, &reshaped_old_lhs, rhs);\n return;\n }\n } else {\n // 2. Try to reuse the rhs.\n std::unique_ptr input_alias = context->forward_input(\n 1, OpKernelContext::Params::kNoReservation /*output_index*/,\n rhs.dtype(), rhs.shape(), DEVICE_MEMORY, attr);\n if (input_alias != nullptr) {\n // Update the ref to point to the new buffer.\n context->replace_ref_input(0, *input_alias, /* lock_held */ true);\n return;\n }\n\n // Otherwise, create a new tensor whose shape matches the\n // right hand side, hand off to lhs and copy the rhs into it.\n Tensor copy_tensor;\n OP_REQUIRES_OK(context,\n context->allocate_temp(old_lhs.dtype(), rhs.shape(),\n ©_tensor, attr));\n // We track memory of variables in variable ops instead of in this\n // assign op.\n context->clear_recorded_memory();\n context->replace_ref_input(0, copy_tensor, /* lock_held */ true);\n if (use_exclusive_lock_) {\n Copy(context, ©_tensor, rhs);\n return;\n }\n }\n }\n\n // The tensor has already been initialized and the right hand side\n // matches the left hand side's shape. We have been told to do the\n // copy outside the lock.\n Tensor old_unlocked_lhs = context->mutable_input(0, /* lock_held */ false);\n Copy(context, &old_unlocked_lhs, rhs);\n }", "func_hash": 305037740106398797533289727050001288809, "file_name": "assign_op.h", "file_hash": 227740622376075800348272805227748641889, "cwe": ["CWE-908"], "cve": "CVE-2022-23573", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `AssignOp` can result in copying uninitialized data to a new tensor. This later results in undefined behavior. The implementation has a check that the left hand side of the assignment is initialized (to minimize number of allocations), but does not check that the right hand side is also initialized. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23573"} {"idx": 195293, "project": "mruby", "commit_id": "ae3c99767a27f5c6c584162e2adc6a5d0eb2c54e", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/ae3c99767a27f5c6c584162e2adc6a5d0eb2c54e", "commit_message": "codegen.c: fixed a bug in hash code generation with `!val`.", "target": 1, "func": "gen_hash(codegen_scope *s, node *tree, int val, int limit)\n{\n int slimit = GEN_VAL_STACK_MAX;\n if (cursp() >= GEN_LIT_ARY_MAX) slimit = INT16_MAX;\n int len = 0;\n mrb_bool update = FALSE;\n\n while (tree) {\n if (nint(tree->car->car->car) == NODE_KW_REST_ARGS) {\n if (len > 0) {\n pop_n(len*2);\n if (!update) {\n genop_2(s, OP_HASH, cursp(), len);\n }\n else {\n pop();\n genop_2(s, OP_HASHADD, cursp(), len);\n }\n push();\n }\n codegen(s, tree->car->cdr, val);\n if (len > 0 || update) {\n pop(); pop();\n genop_1(s, OP_HASHCAT, cursp());\n push();\n }\n update = TRUE;\n len = 0;\n }\n else {\n codegen(s, tree->car->car, val);\n codegen(s, tree->car->cdr, val);\n len++;\n }\n tree = tree->cdr;\n if (val && cursp() >= slimit) {\n pop_n(len*2);\n if (!update) {\n genop_2(s, OP_HASH, cursp(), len);\n }\n else {\n pop();\n genop_2(s, OP_HASHADD, cursp(), len);\n }\n push();\n update = TRUE;\n len = 0;\n }\n }\n if (update) {\n if (val && len > 0) {\n pop_n(len*2+1);\n genop_2(s, OP_HASHADD, cursp(), len);\n push();\n }\n return -1; /* variable length */\n }\n return len;\n}", "func_hash": 193019522040384116683756187518117428466, "file_name": "codegen.c", "file_hash": 187346573288549092337421927147361320618, "cwe": ["CWE-476"], "cve": "CVE-2022-0481", "cve_desc": "NULL Pointer Dereference in Homebrew mruby prior to 3.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0481"} {"idx": 224154, "project": "mruby", "commit_id": "ae3c99767a27f5c6c584162e2adc6a5d0eb2c54e", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/ae3c99767a27f5c6c584162e2adc6a5d0eb2c54e", "commit_message": "codegen.c: fixed a bug in hash code generation with `!val`.", "target": 0, "func": "gen_hash(codegen_scope *s, node *tree, int val, int limit)\n{\n int slimit = GEN_VAL_STACK_MAX;\n if (cursp() >= GEN_LIT_ARY_MAX) slimit = INT16_MAX;\n int len = 0;\n mrb_bool update = FALSE;\n\n while (tree) {\n if (nint(tree->car->car->car) == NODE_KW_REST_ARGS) {\n if (val && len > 0) {\n pop_n(len*2);\n if (!update) {\n genop_2(s, OP_HASH, cursp(), len);\n }\n else {\n pop();\n genop_2(s, OP_HASHADD, cursp(), len);\n }\n push();\n }\n codegen(s, tree->car->cdr, val);\n if (val && (len > 0 || update)) {\n pop(); pop();\n genop_1(s, OP_HASHCAT, cursp());\n push();\n }\n update = TRUE;\n len = 0;\n }\n else {\n codegen(s, tree->car->car, val);\n codegen(s, tree->car->cdr, val);\n len++;\n }\n tree = tree->cdr;\n if (val && cursp() >= slimit) {\n pop_n(len*2);\n if (!update) {\n genop_2(s, OP_HASH, cursp(), len);\n }\n else {\n pop();\n genop_2(s, OP_HASHADD, cursp(), len);\n }\n push();\n update = TRUE;\n len = 0;\n }\n }\n if (update) {\n if (val && len > 0) {\n pop_n(len*2+1);\n genop_2(s, OP_HASHADD, cursp(), len);\n push();\n }\n return -1; /* variable length */\n }\n return len;\n}", "func_hash": 86249756338106133378324988596644701448, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2022-0481", "cve_desc": "NULL Pointer Dereference in Homebrew mruby prior to 3.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0481"} {"idx": 195294, "project": "tensorflow", "commit_id": "f57315566d7094f322b784947093406c2aea0d7d", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f57315566d7094f322b784947093406c2aea0d7d", "commit_message": "Add a check for Key being scalar tensor for MapStage and OrderedMapStage ops.\n\nAccording to documentation[1][2], key must be int64 value, but this wasn't enforced and the ops would fail with check failure for non-scalar key value.\n\n[1]https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/ordered-map-stage\n[2]https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/map-stage\n\nPiperOrigin-RevId: 413822112\nChange-Id: I9d118faf990e6361900aa32272eff486ad9f0e2e", "target": 1, "func": " void Compute(OpKernelContext* ctx) override {\n StagingMap* map = nullptr;\n OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map));\n core::ScopedUnref scope(map);\n typename StagingMap::OptionalTuple tuple;\n\n const Tensor* key_tensor;\n const Tensor* indices_tensor;\n OpInputList values_tensor;\n\n OP_REQUIRES_OK(ctx, ctx->input(\"key\", &key_tensor));\n OP_REQUIRES_OK(ctx, ctx->input(\"indices\", &indices_tensor));\n OP_REQUIRES_OK(ctx, ctx->input_list(\"values\", &values_tensor));\n OP_REQUIRES(ctx, key_tensor->NumElements() > 0,\n errors::InvalidArgument(\"key must not be empty\"));\n\n // Create copy for insertion into Staging Area\n Tensor key(*key_tensor);\n\n // Create the tuple to store\n for (std::size_t i = 0; i < values_tensor.size(); ++i) {\n tuple.push_back(values_tensor[i]);\n }\n\n // Store the tuple in the map\n OP_REQUIRES_OK(ctx, map->put(&key, indices_tensor, &tuple));\n }", "func_hash": 121343016950748954777477429164526353429, "file_name": "map_stage_op.cc", "file_hash": 156634864064326951745718193254274952325, "cwe": ["CWE-843"], "cve": "CVE-2022-21734", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `MapStage` is vulnerable a `CHECK`-fail if the key tensor is not a scalar. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21734"} {"idx": 224181, "project": "tensorflow", "commit_id": "f57315566d7094f322b784947093406c2aea0d7d", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f57315566d7094f322b784947093406c2aea0d7d", "commit_message": "Add a check for Key being scalar tensor for MapStage and OrderedMapStage ops.\n\nAccording to documentation[1][2], key must be int64 value, but this wasn't enforced and the ops would fail with check failure for non-scalar key value.\n\n[1]https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/ordered-map-stage\n[2]https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/map-stage\n\nPiperOrigin-RevId: 413822112\nChange-Id: I9d118faf990e6361900aa32272eff486ad9f0e2e", "target": 0, "func": " void Compute(OpKernelContext* ctx) override {\n StagingMap* map = nullptr;\n OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map));\n core::ScopedUnref scope(map);\n typename StagingMap::OptionalTuple tuple;\n\n const Tensor* key_tensor;\n const Tensor* indices_tensor;\n OpInputList values_tensor;\n\n OP_REQUIRES_OK(ctx, ctx->input(\"key\", &key_tensor));\n OP_REQUIRES_OK(ctx, ctx->input(\"indices\", &indices_tensor));\n OP_REQUIRES_OK(ctx, ctx->input_list(\"values\", &values_tensor));\n OP_REQUIRES(ctx, key_tensor->NumElements() > 0,\n errors::InvalidArgument(\"key must not be empty\"));\n\n OP_REQUIRES(ctx, key_tensor->NumElements() == 1,\n errors::InvalidArgument(\n \"key must be an int64 scalar, got tensor with shape: \",\n key_tensor->shape()));\n\n // Create copy for insertion into Staging Area\n Tensor key(*key_tensor);\n\n // Create the tuple to store\n for (std::size_t i = 0; i < values_tensor.size(); ++i) {\n tuple.push_back(values_tensor[i]);\n }\n\n // Store the tuple in the map\n OP_REQUIRES_OK(ctx, map->put(&key, indices_tensor, &tuple));\n }", "func_hash": 155761287933118551217083530225572870599, "file_name": "map_stage_op.cc", "file_hash": 98786060535014659477894352363015597620, "cwe": ["CWE-843"], "cve": "CVE-2022-21734", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `MapStage` is vulnerable a `CHECK`-fail if the key tensor is not a scalar. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21734"} {"idx": 195295, "project": "mruby", "commit_id": "c8c083cb750606b2da81582cd8e43b442bb143e6", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/c8c083cb750606b2da81582cd8e43b442bb143e6", "commit_message": "codegen.c: need to pack argument when `n==13` too.\n\nBecause we have extra 2 arguments coming (kw and rhs).", "target": 1, "func": "gen_assignment(codegen_scope *s, node *tree, node *rhs, int sp, int val)\n{\n int idx;\n int type = nint(tree->car);\n\n switch (type) {\n case NODE_GVAR:\n case NODE_ARG:\n case NODE_LVAR:\n case NODE_IVAR:\n case NODE_CVAR:\n case NODE_CONST:\n case NODE_NIL:\n case NODE_MASGN:\n if (rhs) {\n codegen(s, rhs, VAL);\n pop();\n sp = cursp();\n }\n break;\n\n case NODE_COLON2:\n case NODE_CALL:\n case NODE_SCALL:\n /* keep evaluation order */\n break;\n\n case NODE_NVAR:\n codegen_error(s, \"Can't assign to numbered parameter\");\n break;\n\n default:\n codegen_error(s, \"unknown lhs\");\n break;\n }\n\n tree = tree->cdr;\n switch (type) {\n case NODE_GVAR:\n gen_setxv(s, OP_SETGV, sp, nsym(tree), val);\n break;\n case NODE_ARG:\n case NODE_LVAR:\n idx = lv_idx(s, nsym(tree));\n if (idx > 0) {\n if (idx != sp) {\n gen_move(s, idx, sp, val);\n }\n break;\n }\n else { /* upvar */\n gen_setupvar(s, sp, nsym(tree));\n }\n break;\n case NODE_IVAR:\n gen_setxv(s, OP_SETIV, sp, nsym(tree), val);\n break;\n case NODE_CVAR:\n gen_setxv(s, OP_SETCV, sp, nsym(tree), val);\n break;\n case NODE_CONST:\n gen_setxv(s, OP_SETCONST, sp, nsym(tree), val);\n break;\n case NODE_COLON2:\n if (sp) {\n gen_move(s, cursp(), sp, 0);\n }\n sp = cursp();\n push();\n codegen(s, tree->car, VAL);\n if (rhs) {\n codegen(s, rhs, VAL); pop();\n gen_move(s, sp, cursp(), 0);\n }\n pop_n(2);\n idx = new_sym(s, nsym(tree->cdr));\n genop_2(s, OP_SETMCNST, sp, idx);\n break;\n\n case NODE_CALL:\n case NODE_SCALL:\n {\n int noself = 0, safe = (type == NODE_SCALL), skip = 0, top, call, n = 0;\n mrb_sym mid = nsym(tree->cdr->car);\n\n top = cursp();\n if (val || sp == cursp()) {\n push(); /* room for retval */\n }\n call = cursp();\n if (!tree->car) {\n noself = 1;\n push();\n }\n else {\n codegen(s, tree->car, VAL); /* receiver */\n }\n if (safe) {\n int recv = cursp()-1;\n gen_move(s, cursp(), recv, 1);\n skip = genjmp2_0(s, OP_JMPNIL, cursp(), val);\n }\n tree = tree->cdr->cdr->car;\n if (tree) {\n if (tree->car) { /* positional arguments */\n n = gen_values(s, tree->car, VAL, (tree->cdr->car)?13:14);\n if (n < 0) { /* variable length */\n n = 15;\n push();\n }\n }\n if (tree->cdr->car) { /* keyword arguments */\n if (n == 14) {\n pop_n(n);\n genop_2(s, OP_ARRAY, cursp(), n);\n push();\n n = 15;\n }\n gen_hash(s, tree->cdr->car->cdr, VAL, 0);\n if (n < 14) {\n n++;\n }\n else {\n pop_n(2);\n genop_2(s, OP_ARYPUSH, cursp(), 1);\n }\n push();\n }\n }\n if (rhs) {\n codegen(s, rhs, VAL);\n pop();\n }\n else {\n gen_move(s, cursp(), sp, 0);\n }\n if (val) {\n gen_move(s, top, cursp(), 1);\n }\n if (n < 15) {\n n++;\n if (n == 15) {\n pop_n(14);\n genop_2(s, OP_ARRAY, cursp(), 15);\n }\n }\n else {\n pop();\n genop_2(s, OP_ARYPUSH, cursp(), 1);\n }\n s->sp = call;\n if (mid == MRB_OPSYM_2(s->mrb, aref) && n == 2) {\n genop_1(s, OP_SETIDX, cursp());\n }\n else {\n genop_3(s, noself ? OP_SSEND : OP_SEND, cursp(), new_sym(s, attrsym(s, mid)), n);\n }\n if (safe) {\n dispatch(s, skip);\n }\n s->sp = top;\n }\n break;\n\n case NODE_MASGN:\n gen_massignment(s, tree->car, sp, val);\n break;\n\n /* splat without assignment */\n case NODE_NIL:\n break;\n\n default:\n codegen_error(s, \"unknown lhs\");\n break;\n }\n if (val) push();\n}", "func_hash": 41954898060187653186067747247923282324, "file_name": "codegen.c", "file_hash": 166306575091061367964033452033729491771, "cwe": ["CWE-125"], "cve": "CVE-2022-1276", "cve_desc": "Out-of-bounds Read in mrb_get_args in GitHub repository mruby/mruby prior to 3.2. Possible arbitrary code execution if being exploited.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1276"} {"idx": 224192, "project": "mruby", "commit_id": "c8c083cb750606b2da81582cd8e43b442bb143e6", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/c8c083cb750606b2da81582cd8e43b442bb143e6", "commit_message": "codegen.c: need to pack argument when `n==13` too.\n\nBecause we have extra 2 arguments coming (kw and rhs).", "target": 0, "func": "gen_assignment(codegen_scope *s, node *tree, node *rhs, int sp, int val)\n{\n int idx;\n int type = nint(tree->car);\n\n switch (type) {\n case NODE_GVAR:\n case NODE_ARG:\n case NODE_LVAR:\n case NODE_IVAR:\n case NODE_CVAR:\n case NODE_CONST:\n case NODE_NIL:\n case NODE_MASGN:\n if (rhs) {\n codegen(s, rhs, VAL);\n pop();\n sp = cursp();\n }\n break;\n\n case NODE_COLON2:\n case NODE_CALL:\n case NODE_SCALL:\n /* keep evaluation order */\n break;\n\n case NODE_NVAR:\n codegen_error(s, \"Can't assign to numbered parameter\");\n break;\n\n default:\n codegen_error(s, \"unknown lhs\");\n break;\n }\n\n tree = tree->cdr;\n switch (type) {\n case NODE_GVAR:\n gen_setxv(s, OP_SETGV, sp, nsym(tree), val);\n break;\n case NODE_ARG:\n case NODE_LVAR:\n idx = lv_idx(s, nsym(tree));\n if (idx > 0) {\n if (idx != sp) {\n gen_move(s, idx, sp, val);\n }\n break;\n }\n else { /* upvar */\n gen_setupvar(s, sp, nsym(tree));\n }\n break;\n case NODE_IVAR:\n gen_setxv(s, OP_SETIV, sp, nsym(tree), val);\n break;\n case NODE_CVAR:\n gen_setxv(s, OP_SETCV, sp, nsym(tree), val);\n break;\n case NODE_CONST:\n gen_setxv(s, OP_SETCONST, sp, nsym(tree), val);\n break;\n case NODE_COLON2:\n if (sp) {\n gen_move(s, cursp(), sp, 0);\n }\n sp = cursp();\n push();\n codegen(s, tree->car, VAL);\n if (rhs) {\n codegen(s, rhs, VAL); pop();\n gen_move(s, sp, cursp(), 0);\n }\n pop_n(2);\n idx = new_sym(s, nsym(tree->cdr));\n genop_2(s, OP_SETMCNST, sp, idx);\n break;\n\n case NODE_CALL:\n case NODE_SCALL:\n {\n int noself = 0, safe = (type == NODE_SCALL), skip = 0, top, call, n = 0;\n mrb_sym mid = nsym(tree->cdr->car);\n\n top = cursp();\n if (val || sp == cursp()) {\n push(); /* room for retval */\n }\n call = cursp();\n if (!tree->car) {\n noself = 1;\n push();\n }\n else {\n codegen(s, tree->car, VAL); /* receiver */\n }\n if (safe) {\n int recv = cursp()-1;\n gen_move(s, cursp(), recv, 1);\n skip = genjmp2_0(s, OP_JMPNIL, cursp(), val);\n }\n tree = tree->cdr->cdr->car;\n if (tree) {\n if (tree->car) { /* positional arguments */\n n = gen_values(s, tree->car, VAL, (tree->cdr->car)?13:14);\n if (n < 0) { /* variable length */\n n = 15;\n push();\n }\n }\n if (tree->cdr->car) { /* keyword arguments */\n if (n == 13 || n == 14) {\n pop_n(n);\n genop_2(s, OP_ARRAY, cursp(), n);\n push();\n n = 15;\n }\n gen_hash(s, tree->cdr->car->cdr, VAL, 0);\n if (n < 14) {\n n++;\n }\n else {\n pop_n(2);\n genop_2(s, OP_ARYPUSH, cursp(), 1);\n }\n push();\n }\n }\n if (rhs) {\n codegen(s, rhs, VAL);\n pop();\n }\n else {\n gen_move(s, cursp(), sp, 0);\n }\n if (val) {\n gen_move(s, top, cursp(), 1);\n }\n if (n < 15) {\n n++;\n if (n == 15) {\n pop_n(14);\n genop_2(s, OP_ARRAY, cursp(), 15);\n }\n }\n else {\n pop();\n genop_2(s, OP_ARYPUSH, cursp(), 1);\n }\n s->sp = call;\n if (mid == MRB_OPSYM_2(s->mrb, aref) && n == 2) {\n genop_1(s, OP_SETIDX, cursp());\n }\n else {\n genop_3(s, noself ? OP_SSEND : OP_SEND, cursp(), new_sym(s, attrsym(s, mid)), n);\n }\n if (safe) {\n dispatch(s, skip);\n }\n s->sp = top;\n }\n break;\n\n case NODE_MASGN:\n gen_massignment(s, tree->car, sp, val);\n break;\n\n /* splat without assignment */\n case NODE_NIL:\n break;\n\n default:\n codegen_error(s, \"unknown lhs\");\n break;\n }\n if (val) push();\n}", "func_hash": 72719402367551467019466616883888506134, "file_name": "codegen.c", "file_hash": 21664036215001583958906059719703447460, "cwe": ["CWE-125"], "cve": "CVE-2022-1276", "cve_desc": "Out-of-bounds Read in mrb_get_args in GitHub repository mruby/mruby prior to 3.2. Possible arbitrary code execution if being exploited.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1276"} {"idx": 195296, "project": "uWebSockets", "commit_id": "03fca626a95130ab80f86adada54b29d27242759", "project_url": "https://github.com/uWebSockets/uWebSockets", "commit_url": "https://github.com/uWebSockets/uWebSockets/commit/03fca626a95130ab80f86adada54b29d27242759", "commit_message": "Fix overflow of triggered topics", "target": 1, "func": " void publish(Topic *iterator, size_t start, size_t stop, std::string_view topic, std::pair message) {\n /* If we already have 64 triggered topics make sure to drain it here */\n if (numTriggeredTopics == 64) {\n drain();\n }\n\n /* Iterate over all segments in given topic */\n for (; stop != std::string::npos; start = stop + 1) {\n stop = topic.find('/', start);\n std::string_view segment = topic.substr(start, stop - start);\n\n /* It is very important to disallow wildcards when publishing.\n * We will not catch EVERY misuse this lazy way, but enough to hinder\n * explosive recursion.\n * Terminating wildcards MAY still get triggered along the way, if for\n * instace the error is found late while iterating the topic segments. */\n if (segment.length() == 1) {\n if (segment[0] == '+' || segment[0] == '#') {\n return;\n }\n }\n\n /* Do we have a terminating wildcard child? */\n if (iterator->terminatingWildcardChild) {\n iterator->terminatingWildcardChild->messages[messageId] = message;\n\n /* Add this topic to triggered */\n if (!iterator->terminatingWildcardChild->triggered) {\n triggeredTopics[numTriggeredTopics++] = iterator->terminatingWildcardChild;\n iterator->terminatingWildcardChild->triggered = true;\n }\n }\n\n /* Do we have a wildcard child? */\n if (iterator->wildcardChild) {\n publish(iterator->wildcardChild, stop + 1, stop, topic, message);\n }\n\n std::map::iterator it = iterator->children.find(segment);\n if (it == iterator->children.end()) {\n /* Stop trying to match by exact string */\n return;\n }\n\n iterator = it->second;\n }\n\n /* If we went all the way we matched exactly */\n iterator->messages[messageId] = message;\n\n /* Add this topic to triggered */\n if (!iterator->triggered) {\n triggeredTopics[numTriggeredTopics++] = iterator;\n iterator->triggered = true;\n }\n }", "func_hash": 134169268379037550524482088626348972483, "file_name": "TopicTree.h", "file_hash": 203813195164088557620454025257855576407, "cwe": ["CWE-787"], "cve": "CVE-2020-36406", "cve_desc": "uWebSockets 18.11.0 and 18.12.0 has a stack-based buffer overflow in uWS::TopicTree::trimTree (called from uWS::TopicTree::unsubscribeAll). NOTE: the vendor's position is that this is \"a minor issue or not even an issue at all\" because the developer of an application (that uses uWebSockets) should not be allowing the large number of triggered topics to accumulate", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36406"} {"idx": 224208, "project": "uWebSockets", "commit_id": "03fca626a95130ab80f86adada54b29d27242759", "project_url": "https://github.com/uWebSockets/uWebSockets", "commit_url": "https://github.com/uWebSockets/uWebSockets/commit/03fca626a95130ab80f86adada54b29d27242759", "commit_message": "Fix overflow of triggered topics", "target": 0, "func": " void publish(Topic *iterator, size_t start, size_t stop, std::string_view topic, std::pair message) {\n\n /* Iterate over all segments in given topic */\n for (; stop != std::string::npos; start = stop + 1) {\n stop = topic.find('/', start);\n std::string_view segment = topic.substr(start, stop - start);\n\n /* It is very important to disallow wildcards when publishing.\n * We will not catch EVERY misuse this lazy way, but enough to hinder\n * explosive recursion.\n * Terminating wildcards MAY still get triggered along the way, if for\n * instace the error is found late while iterating the topic segments. */\n if (segment.length() == 1) {\n if (segment[0] == '+' || segment[0] == '#') {\n return;\n }\n }\n\n /* Do we have a terminating wildcard child? */\n if (iterator->terminatingWildcardChild) {\n iterator->terminatingWildcardChild->messages[messageId] = message;\n\n /* Add this topic to triggered */\n if (!iterator->terminatingWildcardChild->triggered) {\n /* If we already have 64 triggered topics make sure to drain it here */\n if (numTriggeredTopics == 64) {\n drain();\n }\n\n triggeredTopics[numTriggeredTopics++] = iterator->terminatingWildcardChild;\n iterator->terminatingWildcardChild->triggered = true;\n }\n }\n\n /* Do we have a wildcard child? */\n if (iterator->wildcardChild) {\n publish(iterator->wildcardChild, stop + 1, stop, topic, message);\n }\n\n std::map::iterator it = iterator->children.find(segment);\n if (it == iterator->children.end()) {\n /* Stop trying to match by exact string */\n return;\n }\n\n iterator = it->second;\n }\n\n /* If we went all the way we matched exactly */\n iterator->messages[messageId] = message;\n\n /* Add this topic to triggered */\n if (!iterator->triggered) {\n /* If we already have 64 triggered topics make sure to drain it here */\n if (numTriggeredTopics == 64) {\n drain();\n }\n\n triggeredTopics[numTriggeredTopics++] = iterator;\n iterator->triggered = true;\n }\n }", "func_hash": 239871427944982498561615868059507506120, "file_name": "TopicTree.h", "file_hash": 110499788872538385962916215167459222787, "cwe": ["CWE-787"], "cve": "CVE-2020-36406", "cve_desc": "uWebSockets 18.11.0 and 18.12.0 has a stack-based buffer overflow in uWS::TopicTree::trimTree (called from uWS::TopicTree::unsubscribeAll). NOTE: the vendor's position is that this is \"a minor issue or not even an issue at all\" because the developer of an application (that uses uWebSockets) should not be allowing the large number of triggered topics to accumulate", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36406"} {"idx": 195308, "project": "flatpak", "commit_id": "462fca2c666e0cd2b60d6d2593a7216a83047aaf", "project_url": "https://github.com/flatpak/flatpak", "commit_url": "https://github.com/flatpak/flatpak/commit/462fca2c666e0cd2b60d6d2593a7216a83047aaf", "commit_message": "run: Don't allow chroot()\n\nIf we don't allow pivot_root() then there seems no reason why we should\nallow chroot().\n\nPartially fixes GHSA-67h7-w3jq-vh4q.\n\nSigned-off-by: Simon McVittie ", "target": 1, "func": "setup_seccomp (FlatpakBwrap *bwrap,\n const char *arch,\n gulong allowed_personality,\n FlatpakRunFlags run_flags,\n GError **error)\n{\n gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0;\n gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0;\n\n __attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL;\n\n /**** BEGIN NOTE ON CODE SHARING\n *\n * There are today a number of different Linux container\n * implementations. That will likely continue for long into the\n * future. But we can still try to share code, and it's important\n * to do so because it affects what library and application writers\n * can do, and we should support code portability between different\n * container tools.\n *\n * This syscall blocklist is copied from linux-user-chroot, which was in turn\n * clearly influenced by the Sandstorm.io blocklist.\n *\n * If you make any changes here, I suggest sending the changes along\n * to other sandbox maintainers. Using the libseccomp list is also\n * an appropriate venue:\n * https://groups.google.com/forum/#!forum/libseccomp\n *\n * A non-exhaustive list of links to container tooling that might\n * want to share this blocklist:\n *\n * https://github.com/sandstorm-io/sandstorm\n * in src/sandstorm/supervisor.c++\n * https://github.com/flatpak/flatpak.git\n * in common/flatpak-run.c\n * https://git.gnome.org/browse/linux-user-chroot\n * in src/setup-seccomp.c\n *\n * Other useful resources:\n * https://github.com/systemd/systemd/blob/HEAD/src/shared/seccomp-util.c\n * https://github.com/moby/moby/blob/HEAD/profiles/seccomp/default.json\n *\n **** END NOTE ON CODE SHARING\n */\n struct\n {\n int scall;\n int errnum;\n struct scmp_arg_cmp *arg;\n } syscall_blocklist[] = {\n /* Block dmesg */\n {SCMP_SYS (syslog), EPERM},\n /* Useless old syscall */\n {SCMP_SYS (uselib), EPERM},\n /* Don't allow disabling accounting */\n {SCMP_SYS (acct), EPERM},\n /* 16-bit code is unnecessary in the sandbox, and modify_ldt is a\n historic source of interesting information leaks. */\n {SCMP_SYS (modify_ldt), EPERM},\n /* Don't allow reading current quota use */\n {SCMP_SYS (quotactl), EPERM},\n\n /* Don't allow access to the kernel keyring */\n {SCMP_SYS (add_key), EPERM},\n {SCMP_SYS (keyctl), EPERM},\n {SCMP_SYS (request_key), EPERM},\n\n /* Scary VM/NUMA ops */\n {SCMP_SYS (move_pages), EPERM},\n {SCMP_SYS (mbind), EPERM},\n {SCMP_SYS (get_mempolicy), EPERM},\n {SCMP_SYS (set_mempolicy), EPERM},\n {SCMP_SYS (migrate_pages), EPERM},\n\n /* Don't allow subnamespace setups: */\n {SCMP_SYS (unshare), EPERM},\n {SCMP_SYS (setns), EPERM},\n {SCMP_SYS (mount), EPERM},\n {SCMP_SYS (umount), EPERM},\n {SCMP_SYS (umount2), EPERM},\n {SCMP_SYS (pivot_root), EPERM},\n#if defined(__s390__) || defined(__s390x__) || defined(__CRIS__)\n /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack\n * and flags arguments are reversed so the flags come second */\n {SCMP_SYS (clone), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},\n#else\n /* Normally the flags come first */\n {SCMP_SYS (clone), EPERM, &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},\n#endif\n\n /* Don't allow faking input to the controlling tty (CVE-2017-5226) */\n {SCMP_SYS (ioctl), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)},\n\n /* seccomp can't look into clone3()'s struct clone_args to check whether\n * the flags are OK, so we have no choice but to block clone3().\n * Return ENOSYS so user-space will fall back to clone().\n * (GHSA-67h7-w3jq-vh4q; see also https://github.com/moby/moby/commit/9f6b562d) */\n {SCMP_SYS (clone3), ENOSYS},\n\n /* New mount manipulation APIs can also change our VFS. There's no\n * legitimate reason to do these in the sandbox, so block all of them\n * rather than thinking about which ones might be dangerous.\n * (GHSA-67h7-w3jq-vh4q) */\n {SCMP_SYS (open_tree), ENOSYS},\n {SCMP_SYS (move_mount), ENOSYS},\n {SCMP_SYS (fsopen), ENOSYS},\n {SCMP_SYS (fsconfig), ENOSYS},\n {SCMP_SYS (fsmount), ENOSYS},\n {SCMP_SYS (fspick), ENOSYS},\n {SCMP_SYS (mount_setattr), ENOSYS},\n };\n\n struct\n {\n int scall;\n int errnum;\n struct scmp_arg_cmp *arg;\n } syscall_nondevel_blocklist[] = {\n /* Profiling operations; we expect these to be done by tools from outside\n * the sandbox. In particular perf has been the source of many CVEs.\n */\n {SCMP_SYS (perf_event_open), EPERM},\n /* Don't allow you to switch to bsd emulation or whatnot */\n {SCMP_SYS (personality), EPERM, &SCMP_A0 (SCMP_CMP_NE, allowed_personality)},\n {SCMP_SYS (ptrace), EPERM}\n };\n /* Blocklist all but unix, inet, inet6 and netlink */\n struct\n {\n int family;\n FlatpakRunFlags flags_mask;\n } socket_family_allowlist[] = {\n /* NOTE: Keep in numerical order */\n { AF_UNSPEC, 0 },\n { AF_LOCAL, 0 },\n { AF_INET, 0 },\n { AF_INET6, 0 },\n { AF_NETLINK, 0 },\n { AF_CAN, FLATPAK_RUN_FLAG_CANBUS },\n { AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH },\n };\n int last_allowed_family;\n int i, r;\n g_auto(GLnxTmpfile) seccomp_tmpf = { 0, };\n\n seccomp = seccomp_init (SCMP_ACT_ALLOW);\n if (!seccomp)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Initialize seccomp failed\"));\n\n if (arch != NULL)\n {\n uint32_t arch_id = 0;\n const uint32_t *extra_arches = NULL;\n\n if (strcmp (arch, \"i386\") == 0)\n {\n arch_id = SCMP_ARCH_X86;\n }\n else if (strcmp (arch, \"x86_64\") == 0)\n {\n arch_id = SCMP_ARCH_X86_64;\n extra_arches = seccomp_x86_64_extra_arches;\n }\n else if (strcmp (arch, \"arm\") == 0)\n {\n arch_id = SCMP_ARCH_ARM;\n }\n#ifdef SCMP_ARCH_AARCH64\n else if (strcmp (arch, \"aarch64\") == 0)\n {\n arch_id = SCMP_ARCH_AARCH64;\n extra_arches = seccomp_aarch64_extra_arches;\n }\n#endif\n\n /* We only really need to handle arches on multiarch systems.\n * If only one arch is supported the default is fine */\n if (arch_id != 0)\n {\n /* This *adds* the target arch, instead of replacing the\n native one. This is not ideal, because we'd like to only\n allow the target arch, but we can't really disallow the\n native arch at this point, because then bubblewrap\n couldn't continue running. */\n r = seccomp_arch_add (seccomp, arch_id);\n if (r < 0 && r != -EEXIST)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to add architecture to seccomp filter\"));\n\n if (multiarch && extra_arches != NULL)\n {\n for (i = 0; extra_arches[i] != 0; i++)\n {\n r = seccomp_arch_add (seccomp, extra_arches[i]);\n if (r < 0 && r != -EEXIST)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to add multiarch architecture to seccomp filter\"));\n }\n }\n }\n }\n\n /* TODO: Should we filter the kernel keyring syscalls in some way?\n * We do want them to be used by desktop apps, but they could also perhaps\n * leak system stuff or secrets from other apps.\n */\n\n for (i = 0; i < G_N_ELEMENTS (syscall_blocklist); i++)\n {\n int scall = syscall_blocklist[i].scall;\n int errnum = syscall_blocklist[i].errnum;\n\n g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE);\n\n if (syscall_blocklist[i].arg)\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_blocklist[i].arg);\n else\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 0);\n if (r < 0 && r == -EFAULT /* unknown syscall */)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to block syscall %d\"), scall);\n }\n\n if (!devel)\n {\n for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blocklist); i++)\n {\n int scall = syscall_nondevel_blocklist[i].scall;\n int errnum = syscall_nondevel_blocklist[i].errnum;\n\n g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE);\n\n if (syscall_nondevel_blocklist[i].arg)\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_nondevel_blocklist[i].arg);\n else\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 0);\n\n if (r < 0 && r == -EFAULT /* unknown syscall */)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to block syscall %d\"), scall);\n }\n }\n\n /* Socket filtering doesn't work on e.g. i386, so ignore failures here\n * However, we need to user seccomp_rule_add_exact to avoid libseccomp doing\n * something else: https://github.com/seccomp/libseccomp/issues/8 */\n last_allowed_family = -1;\n for (i = 0; i < G_N_ELEMENTS (socket_family_allowlist); i++)\n {\n int family = socket_family_allowlist[i].family;\n int disallowed;\n\n if (socket_family_allowlist[i].flags_mask != 0 &&\n (socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask)\n continue;\n\n for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++)\n {\n /* Blocklist the in-between valid families */\n seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed));\n }\n last_allowed_family = family;\n }\n /* Blocklist the rest */\n seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1));\n\n if (!glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, \"/tmp\", &seccomp_tmpf, error))\n return FALSE;\n\n if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to export bpf\"));\n\n lseek (seccomp_tmpf.fd, 0, SEEK_SET);\n\n flatpak_bwrap_add_args_data_fd (bwrap,\n \"--seccomp\", glnx_steal_fd (&seccomp_tmpf.fd), NULL);\n\n return TRUE;\n}", "func_hash": 116661486604620809625071911593237669795, "file_name": "flatpak-run.c", "file_hash": 32398709380082441128978861691951488575, "cwe": ["CWE-20"], "cve": "CVE-2021-41133", "cve_desc": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. In versions prior to 1.10.4 and 1.12.0, Flatpak apps with direct access to AF_UNIX sockets such as those used by Wayland, Pipewire or pipewire-pulse can trick portals and other host-OS services into treating the Flatpak app as though it was an ordinary, non-sandboxed host-OS process. They can do this by manipulating the VFS using recent mount-related syscalls that are not blocked by Flatpak's denylist seccomp filter, in order to substitute a crafted `/.flatpak-info` or make that file disappear entirely. Flatpak apps that act as clients for AF_UNIX sockets such as those used by Wayland, Pipewire or pipewire-pulse can escalate the privileges that the corresponding services will believe the Flatpak app has. Note that protocols that operate entirely over the D-Bus session bus (user bus), system bus or accessibility bus are not affected by this. This is due to the use of a proxy process `xdg-dbus-proxy`, whose VFS cannot be manipulated by the Flatpak app, when interacting with these buses. Patches exist for versions 1.10.4 and 1.12.0, and as of time of publication, a patch for version 1.8.2 is being planned. There are no workarounds aside from upgrading to a patched version.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41133"} {"idx": 224277, "project": "flatpak", "commit_id": "462fca2c666e0cd2b60d6d2593a7216a83047aaf", "project_url": "https://github.com/flatpak/flatpak", "commit_url": "https://github.com/flatpak/flatpak/commit/462fca2c666e0cd2b60d6d2593a7216a83047aaf", "commit_message": "run: Don't allow chroot()\n\nIf we don't allow pivot_root() then there seems no reason why we should\nallow chroot().\n\nPartially fixes GHSA-67h7-w3jq-vh4q.\n\nSigned-off-by: Simon McVittie ", "target": 0, "func": "setup_seccomp (FlatpakBwrap *bwrap,\n const char *arch,\n gulong allowed_personality,\n FlatpakRunFlags run_flags,\n GError **error)\n{\n gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0;\n gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0;\n\n __attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL;\n\n /**** BEGIN NOTE ON CODE SHARING\n *\n * There are today a number of different Linux container\n * implementations. That will likely continue for long into the\n * future. But we can still try to share code, and it's important\n * to do so because it affects what library and application writers\n * can do, and we should support code portability between different\n * container tools.\n *\n * This syscall blocklist is copied from linux-user-chroot, which was in turn\n * clearly influenced by the Sandstorm.io blocklist.\n *\n * If you make any changes here, I suggest sending the changes along\n * to other sandbox maintainers. Using the libseccomp list is also\n * an appropriate venue:\n * https://groups.google.com/forum/#!forum/libseccomp\n *\n * A non-exhaustive list of links to container tooling that might\n * want to share this blocklist:\n *\n * https://github.com/sandstorm-io/sandstorm\n * in src/sandstorm/supervisor.c++\n * https://github.com/flatpak/flatpak.git\n * in common/flatpak-run.c\n * https://git.gnome.org/browse/linux-user-chroot\n * in src/setup-seccomp.c\n *\n * Other useful resources:\n * https://github.com/systemd/systemd/blob/HEAD/src/shared/seccomp-util.c\n * https://github.com/moby/moby/blob/HEAD/profiles/seccomp/default.json\n *\n **** END NOTE ON CODE SHARING\n */\n struct\n {\n int scall;\n int errnum;\n struct scmp_arg_cmp *arg;\n } syscall_blocklist[] = {\n /* Block dmesg */\n {SCMP_SYS (syslog), EPERM},\n /* Useless old syscall */\n {SCMP_SYS (uselib), EPERM},\n /* Don't allow disabling accounting */\n {SCMP_SYS (acct), EPERM},\n /* 16-bit code is unnecessary in the sandbox, and modify_ldt is a\n historic source of interesting information leaks. */\n {SCMP_SYS (modify_ldt), EPERM},\n /* Don't allow reading current quota use */\n {SCMP_SYS (quotactl), EPERM},\n\n /* Don't allow access to the kernel keyring */\n {SCMP_SYS (add_key), EPERM},\n {SCMP_SYS (keyctl), EPERM},\n {SCMP_SYS (request_key), EPERM},\n\n /* Scary VM/NUMA ops */\n {SCMP_SYS (move_pages), EPERM},\n {SCMP_SYS (mbind), EPERM},\n {SCMP_SYS (get_mempolicy), EPERM},\n {SCMP_SYS (set_mempolicy), EPERM},\n {SCMP_SYS (migrate_pages), EPERM},\n\n /* Don't allow subnamespace setups: */\n {SCMP_SYS (unshare), EPERM},\n {SCMP_SYS (setns), EPERM},\n {SCMP_SYS (mount), EPERM},\n {SCMP_SYS (umount), EPERM},\n {SCMP_SYS (umount2), EPERM},\n {SCMP_SYS (pivot_root), EPERM},\n {SCMP_SYS (chroot), EPERM},\n#if defined(__s390__) || defined(__s390x__) || defined(__CRIS__)\n /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack\n * and flags arguments are reversed so the flags come second */\n {SCMP_SYS (clone), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},\n#else\n /* Normally the flags come first */\n {SCMP_SYS (clone), EPERM, &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},\n#endif\n\n /* Don't allow faking input to the controlling tty (CVE-2017-5226) */\n {SCMP_SYS (ioctl), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)},\n\n /* seccomp can't look into clone3()'s struct clone_args to check whether\n * the flags are OK, so we have no choice but to block clone3().\n * Return ENOSYS so user-space will fall back to clone().\n * (GHSA-67h7-w3jq-vh4q; see also https://github.com/moby/moby/commit/9f6b562d) */\n {SCMP_SYS (clone3), ENOSYS},\n\n /* New mount manipulation APIs can also change our VFS. There's no\n * legitimate reason to do these in the sandbox, so block all of them\n * rather than thinking about which ones might be dangerous.\n * (GHSA-67h7-w3jq-vh4q) */\n {SCMP_SYS (open_tree), ENOSYS},\n {SCMP_SYS (move_mount), ENOSYS},\n {SCMP_SYS (fsopen), ENOSYS},\n {SCMP_SYS (fsconfig), ENOSYS},\n {SCMP_SYS (fsmount), ENOSYS},\n {SCMP_SYS (fspick), ENOSYS},\n {SCMP_SYS (mount_setattr), ENOSYS},\n };\n\n struct\n {\n int scall;\n int errnum;\n struct scmp_arg_cmp *arg;\n } syscall_nondevel_blocklist[] = {\n /* Profiling operations; we expect these to be done by tools from outside\n * the sandbox. In particular perf has been the source of many CVEs.\n */\n {SCMP_SYS (perf_event_open), EPERM},\n /* Don't allow you to switch to bsd emulation or whatnot */\n {SCMP_SYS (personality), EPERM, &SCMP_A0 (SCMP_CMP_NE, allowed_personality)},\n {SCMP_SYS (ptrace), EPERM}\n };\n /* Blocklist all but unix, inet, inet6 and netlink */\n struct\n {\n int family;\n FlatpakRunFlags flags_mask;\n } socket_family_allowlist[] = {\n /* NOTE: Keep in numerical order */\n { AF_UNSPEC, 0 },\n { AF_LOCAL, 0 },\n { AF_INET, 0 },\n { AF_INET6, 0 },\n { AF_NETLINK, 0 },\n { AF_CAN, FLATPAK_RUN_FLAG_CANBUS },\n { AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH },\n };\n int last_allowed_family;\n int i, r;\n g_auto(GLnxTmpfile) seccomp_tmpf = { 0, };\n\n seccomp = seccomp_init (SCMP_ACT_ALLOW);\n if (!seccomp)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Initialize seccomp failed\"));\n\n if (arch != NULL)\n {\n uint32_t arch_id = 0;\n const uint32_t *extra_arches = NULL;\n\n if (strcmp (arch, \"i386\") == 0)\n {\n arch_id = SCMP_ARCH_X86;\n }\n else if (strcmp (arch, \"x86_64\") == 0)\n {\n arch_id = SCMP_ARCH_X86_64;\n extra_arches = seccomp_x86_64_extra_arches;\n }\n else if (strcmp (arch, \"arm\") == 0)\n {\n arch_id = SCMP_ARCH_ARM;\n }\n#ifdef SCMP_ARCH_AARCH64\n else if (strcmp (arch, \"aarch64\") == 0)\n {\n arch_id = SCMP_ARCH_AARCH64;\n extra_arches = seccomp_aarch64_extra_arches;\n }\n#endif\n\n /* We only really need to handle arches on multiarch systems.\n * If only one arch is supported the default is fine */\n if (arch_id != 0)\n {\n /* This *adds* the target arch, instead of replacing the\n native one. This is not ideal, because we'd like to only\n allow the target arch, but we can't really disallow the\n native arch at this point, because then bubblewrap\n couldn't continue running. */\n r = seccomp_arch_add (seccomp, arch_id);\n if (r < 0 && r != -EEXIST)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to add architecture to seccomp filter\"));\n\n if (multiarch && extra_arches != NULL)\n {\n for (i = 0; extra_arches[i] != 0; i++)\n {\n r = seccomp_arch_add (seccomp, extra_arches[i]);\n if (r < 0 && r != -EEXIST)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to add multiarch architecture to seccomp filter\"));\n }\n }\n }\n }\n\n /* TODO: Should we filter the kernel keyring syscalls in some way?\n * We do want them to be used by desktop apps, but they could also perhaps\n * leak system stuff or secrets from other apps.\n */\n\n for (i = 0; i < G_N_ELEMENTS (syscall_blocklist); i++)\n {\n int scall = syscall_blocklist[i].scall;\n int errnum = syscall_blocklist[i].errnum;\n\n g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE);\n\n if (syscall_blocklist[i].arg)\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_blocklist[i].arg);\n else\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 0);\n if (r < 0 && r == -EFAULT /* unknown syscall */)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to block syscall %d\"), scall);\n }\n\n if (!devel)\n {\n for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blocklist); i++)\n {\n int scall = syscall_nondevel_blocklist[i].scall;\n int errnum = syscall_nondevel_blocklist[i].errnum;\n\n g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE);\n\n if (syscall_nondevel_blocklist[i].arg)\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_nondevel_blocklist[i].arg);\n else\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 0);\n\n if (r < 0 && r == -EFAULT /* unknown syscall */)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to block syscall %d\"), scall);\n }\n }\n\n /* Socket filtering doesn't work on e.g. i386, so ignore failures here\n * However, we need to user seccomp_rule_add_exact to avoid libseccomp doing\n * something else: https://github.com/seccomp/libseccomp/issues/8 */\n last_allowed_family = -1;\n for (i = 0; i < G_N_ELEMENTS (socket_family_allowlist); i++)\n {\n int family = socket_family_allowlist[i].family;\n int disallowed;\n\n if (socket_family_allowlist[i].flags_mask != 0 &&\n (socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask)\n continue;\n\n for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++)\n {\n /* Blocklist the in-between valid families */\n seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed));\n }\n last_allowed_family = family;\n }\n /* Blocklist the rest */\n seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1));\n\n if (!glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, \"/tmp\", &seccomp_tmpf, error))\n return FALSE;\n\n if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to export bpf\"));\n\n lseek (seccomp_tmpf.fd, 0, SEEK_SET);\n\n flatpak_bwrap_add_args_data_fd (bwrap,\n \"--seccomp\", glnx_steal_fd (&seccomp_tmpf.fd), NULL);\n\n return TRUE;\n}", "func_hash": 98799963199923512278205367577377591800, "file_name": "flatpak-run.c", "file_hash": 147844647821640300549119412024985340412, "cwe": ["CWE-20"], "cve": "CVE-2021-41133", "cve_desc": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. In versions prior to 1.10.4 and 1.12.0, Flatpak apps with direct access to AF_UNIX sockets such as those used by Wayland, Pipewire or pipewire-pulse can trick portals and other host-OS services into treating the Flatpak app as though it was an ordinary, non-sandboxed host-OS process. They can do this by manipulating the VFS using recent mount-related syscalls that are not blocked by Flatpak's denylist seccomp filter, in order to substitute a crafted `/.flatpak-info` or make that file disappear entirely. Flatpak apps that act as clients for AF_UNIX sockets such as those used by Wayland, Pipewire or pipewire-pulse can escalate the privileges that the corresponding services will believe the Flatpak app has. Note that protocols that operate entirely over the D-Bus session bus (user bus), system bus or accessibility bus are not affected by this. This is due to the use of a proxy process `xdg-dbus-proxy`, whose VFS cannot be manipulated by the Flatpak app, when interacting with these buses. Patches exist for versions 1.10.4 and 1.12.0, and as of time of publication, a patch for version 1.8.2 is being planned. There are no workarounds aside from upgrading to a patched version.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41133"} {"idx": 195309, "project": "squid", "commit_id": "5e2ea2b13bd98f53e29964ca26bb0d602a8a12b9", "project_url": "https://github.com/squid-cache/squid", "commit_url": "https://github.com/squid-cache/squid/commit/5e2ea2b13bd98f53e29964ca26bb0d602a8a12b9", "commit_message": "Improve handling of Gopher responses (#1022)", "target": 1, "func": "gopherToHTML(GopherStateData * gopherState, char *inbuf, int len)\n{\n char *pos = inbuf;\n char *lpos = NULL;\n char *tline = NULL;\n LOCAL_ARRAY(char, line, TEMP_BUF_SIZE);\n LOCAL_ARRAY(char, tmpbuf, TEMP_BUF_SIZE);\n char *name = NULL;\n char *selector = NULL;\n char *host = NULL;\n char *port = NULL;\n char *escaped_selector = NULL;\n const char *icon_url = NULL;\n char gtype;\n StoreEntry *entry = NULL;\n\n memset(tmpbuf, '\\0', TEMP_BUF_SIZE);\n memset(line, '\\0', TEMP_BUF_SIZE);\n\n entry = gopherState->entry;\n\n if (gopherState->conversion == GopherStateData::HTML_INDEX_PAGE) {\n char *html_url = html_quote(entry->url());\n gopherHTMLHeader(entry, \"Gopher Index %s\", html_url);\n storeAppendPrintf(entry,\n \"

This is a searchable Gopher index. Use the search\\n\"\n \"function of your browser to enter search terms.\\n\"\n \"\\n\");\n gopherHTMLFooter(entry);\n /* now let start sending stuff to client */\n entry->flush();\n gopherState->HTML_header_added = 1;\n\n return;\n }\n\n if (gopherState->conversion == GopherStateData::HTML_CSO_PAGE) {\n char *html_url = html_quote(entry->url());\n gopherHTMLHeader(entry, \"CSO Search of %s\", html_url);\n storeAppendPrintf(entry,\n \"

A CSO database usually contains a phonebook or\\n\"\n \"directory. Use the search function of your browser to enter\\n\"\n \"search terms.

\\n\");\n gopherHTMLFooter(entry);\n /* now let start sending stuff to client */\n entry->flush();\n gopherState->HTML_header_added = 1;\n\n return;\n }\n\n String outbuf;\n\n if (!gopherState->HTML_header_added) {\n if (gopherState->conversion == GopherStateData::HTML_CSO_RESULT)\n gopherHTMLHeader(entry, \"CSO Search Result\", NULL);\n else\n gopherHTMLHeader(entry, \"Gopher Menu\", NULL);\n\n outbuf.append (\"
\");\n\n        gopherState->HTML_header_added = 1;\n\n        gopherState->HTML_pre = 1;\n    }\n\n    while (pos < inbuf + len) {\n        int llen;\n        int left = len - (pos - inbuf);\n        lpos = (char *)memchr(pos, '\\n', left);\n        if (lpos) {\n            ++lpos;             /* Next line is after \\n */\n            llen = lpos - pos;\n        } else {\n            llen = left;\n        }\n        if (gopherState->len + llen >= TEMP_BUF_SIZE) {\n            debugs(10, DBG_IMPORTANT, \"GopherHTML: Buffer overflow. Lost some data on URL: \" << entry->url()  );\n            llen = TEMP_BUF_SIZE - gopherState->len - 1;\n            gopherState->overflowed = true; // may already be true\n        }\n        if (!lpos) {\n            /* there is no complete line in inbuf */\n            /* copy it to temp buffer */\n            /* note: llen is adjusted above */\n            memcpy(gopherState->buf + gopherState->len, pos, llen);\n            gopherState->len += llen;\n            break;\n        }\n        if (gopherState->len != 0) {\n            /* there is something left from last tx. */\n            memcpy(line, gopherState->buf, gopherState->len);\n            memcpy(line + gopherState->len, pos, llen);\n            llen += gopherState->len;\n            gopherState->len = 0;\n        } else {\n            memcpy(line, pos, llen);\n        }\n        line[llen + 1] = '\\0';\n        /* move input to next line */\n        pos = lpos;\n\n        /* at this point. We should have one line in buffer to process */\n\n        if (*line == '.') {\n            /* skip it */\n            memset(line, '\\0', TEMP_BUF_SIZE);\n            continue;\n        }\n\n        switch (gopherState->conversion) {\n\n        case GopherStateData::HTML_INDEX_RESULT:\n\n        case GopherStateData::HTML_DIR: {\n            tline = line;\n            gtype = *tline;\n            ++tline;\n            name = tline;\n            selector = strchr(tline, TAB);\n\n            if (selector) {\n                *selector = '\\0';\n                ++selector;\n                host = strchr(selector, TAB);\n\n                if (host) {\n                    *host = '\\0';\n                    ++host;\n                    port = strchr(host, TAB);\n\n                    if (port) {\n                        char *junk;\n                        port[0] = ':';\n                        junk = strchr(host, TAB);\n\n                        if (junk)\n                            *junk++ = 0;    /* Chop port */\n                        else {\n                            junk = strchr(host, '\\r');\n\n                            if (junk)\n                                *junk++ = 0;    /* Chop port */\n                            else {\n                                junk = strchr(host, '\\n');\n\n                                if (junk)\n                                    *junk++ = 0;    /* Chop port */\n                            }\n                        }\n\n                        if ((port[1] == '0') && (!port[2]))\n                            port[0] = 0;    /* 0 means none */\n                    }\n\n                    /* escape a selector here */\n                    escaped_selector = xstrdup(rfc1738_escape_part(selector));\n\n                    switch (gtype) {\n\n                    case GOPHER_DIRECTORY:\n                        icon_url = mimeGetIconURL(\"internal-menu\");\n                        break;\n\n                    case GOPHER_HTML:\n\n                    case GOPHER_FILE:\n                        icon_url = mimeGetIconURL(\"internal-text\");\n                        break;\n\n                    case GOPHER_INDEX:\n\n                    case GOPHER_CSO:\n                        icon_url = mimeGetIconURL(\"internal-index\");\n                        break;\n\n                    case GOPHER_IMAGE:\n\n                    case GOPHER_GIF:\n\n                    case GOPHER_PLUS_IMAGE:\n                        icon_url = mimeGetIconURL(\"internal-image\");\n                        break;\n\n                    case GOPHER_SOUND:\n\n                    case GOPHER_PLUS_SOUND:\n                        icon_url = mimeGetIconURL(\"internal-sound\");\n                        break;\n\n                    case GOPHER_PLUS_MOVIE:\n                        icon_url = mimeGetIconURL(\"internal-movie\");\n                        break;\n\n                    case GOPHER_TELNET:\n\n                    case GOPHER_3270:\n                        icon_url = mimeGetIconURL(\"internal-telnet\");\n                        break;\n\n                    case GOPHER_BIN:\n\n                    case GOPHER_MACBINHEX:\n\n                    case GOPHER_DOSBIN:\n\n                    case GOPHER_UUENCODED:\n                        icon_url = mimeGetIconURL(\"internal-binary\");\n                        break;\n\n                    case GOPHER_INFO:\n                        icon_url = NULL;\n                        break;\n\n                    case GOPHER_WWW:\n                        icon_url = mimeGetIconURL(\"internal-link\");\n                        break;\n\n                    default:\n                        icon_url = mimeGetIconURL(\"internal-unknown\");\n                        break;\n                    }\n\n                    memset(tmpbuf, '\\0', TEMP_BUF_SIZE);\n\n                    if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) {\n                        if (strlen(escaped_selector) != 0)\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, escaped_selector, rfc1738_escape_part(host),\n                                     *port ? \":\" : \"\", port, html_quote(name));\n                        else\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, rfc1738_escape_part(host), *port ? \":\" : \"\",\n                                     port, html_quote(name));\n\n                    } else if (gtype == GOPHER_INFO) {\n                        snprintf(tmpbuf, TEMP_BUF_SIZE, \"\\t%s\\n\", html_quote(name));\n                    } else {\n                        if (strncmp(selector, \"GET /\", 5) == 0) {\n                            /* WWW link */\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name));\n                        } else if (gtype == GOPHER_WWW) {\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, rfc1738_escape_unescaped(selector), html_quote(name));\n                        } else {\n                            /* Standard link */\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, host, gtype, escaped_selector, html_quote(name));\n                        }\n                    }\n\n                    safe_free(escaped_selector);\n                    outbuf.append(tmpbuf);\n                } else {\n                    memset(line, '\\0', TEMP_BUF_SIZE);\n                    continue;\n                }\n            } else {\n                memset(line, '\\0', TEMP_BUF_SIZE);\n                continue;\n            }\n\n            break;\n            }           /* HTML_DIR, HTML_INDEX_RESULT */\n\n        case GopherStateData::HTML_CSO_RESULT: {\n            if (line[0] == '-') {\n                int code, recno;\n                char *s_code, *s_recno, *result;\n\n                s_code = strtok(line + 1, \":\\n\");\n                s_recno = strtok(NULL, \":\\n\");\n                result = strtok(NULL, \"\\n\");\n\n                if (!result)\n                    break;\n\n                code = atoi(s_code);\n\n                recno = atoi(s_recno);\n\n                if (code != 200)\n                    break;\n\n                if (gopherState->cso_recno != recno) {\n                    snprintf(tmpbuf, TEMP_BUF_SIZE, \"

Record# %d
%s

\\n
\", recno, html_quote(result));\n                    gopherState->cso_recno = recno;\n                } else {\n                    snprintf(tmpbuf, TEMP_BUF_SIZE, \"%s\\n\", html_quote(result));\n                }\n\n                outbuf.append(tmpbuf);\n                break;\n            } else {\n                int code;\n                char *s_code, *result;\n\n                s_code = strtok(line, \":\");\n                result = strtok(NULL, \"\\n\");\n\n                if (!result)\n                    break;\n\n                code = atoi(s_code);\n\n                switch (code) {\n\n                case 200: {\n                    /* OK */\n                    /* Do nothing here */\n                    break;\n                }\n\n                case 102:   /* Number of matches */\n\n                case 501:   /* No Match */\n\n                case 502: { /* Too Many Matches */\n                    /* Print the message the server returns */\n                    snprintf(tmpbuf, TEMP_BUF_SIZE, \"

%s

\\n
\", html_quote(result));\n                    outbuf.append(tmpbuf);\n                    break;\n                }\n\n                }\n            }\n\n            break;\n            }           /* HTML_CSO_RESULT */\n        default:\n            break;      /* do nothing */\n\n        }           /* switch */\n\n    }               /* while loop */\n\n    if (outbuf.size() > 0) {\n        entry->append(outbuf.rawBuf(), outbuf.size());\n        /* now let start sending stuff to client */\n        entry->flush();\n    }\n\n    outbuf.clean();\n    return;\n}", "func_hash": 274182330078791984686066092776381139807, "file_name": "gopher.cc", "file_hash": 53940162348551394934251092714566998881, "cwe": ["CWE-400"], "cve": "CVE-2021-46784", "cve_desc": "In Squid 3.x through 3.5.28, 4.x through 4.17, and 5.x before 5.6, due to improper buffer management, a Denial of Service can occur when processing long Gopher server responses.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46784"}
{"idx": 224281, "project": "squid", "commit_id": "5e2ea2b13bd98f53e29964ca26bb0d602a8a12b9", "project_url": "https://github.com/squid-cache/squid", "commit_url": "https://github.com/squid-cache/squid/commit/5e2ea2b13bd98f53e29964ca26bb0d602a8a12b9", "commit_message": "Improve handling of Gopher responses (#1022)", "target": 0, "func": "gopherToHTML(GopherStateData * gopherState, char *inbuf, int len)\n{\n    char *pos = inbuf;\n    char *lpos = NULL;\n    char *tline = NULL;\n    LOCAL_ARRAY(char, line, TEMP_BUF_SIZE);\n    char *name = NULL;\n    char *selector = NULL;\n    char *host = NULL;\n    char *port = NULL;\n    char *escaped_selector = NULL;\n    const char *icon_url = NULL;\n    char gtype;\n    StoreEntry *entry = NULL;\n\n    memset(line, '\\0', TEMP_BUF_SIZE);\n\n    entry = gopherState->entry;\n\n    if (gopherState->conversion == GopherStateData::HTML_INDEX_PAGE) {\n        char *html_url = html_quote(entry->url());\n        gopherHTMLHeader(entry, \"Gopher Index %s\", html_url);\n        storeAppendPrintf(entry,\n                          \"

This is a searchable Gopher index. Use the search\\n\"\n \"function of your browser to enter search terms.\\n\"\n \"\\n\");\n gopherHTMLFooter(entry);\n /* now let start sending stuff to client */\n entry->flush();\n gopherState->HTML_header_added = 1;\n\n return;\n }\n\n if (gopherState->conversion == GopherStateData::HTML_CSO_PAGE) {\n char *html_url = html_quote(entry->url());\n gopherHTMLHeader(entry, \"CSO Search of %s\", html_url);\n storeAppendPrintf(entry,\n \"

A CSO database usually contains a phonebook or\\n\"\n \"directory. Use the search function of your browser to enter\\n\"\n \"search terms.

\\n\");\n gopherHTMLFooter(entry);\n /* now let start sending stuff to client */\n entry->flush();\n gopherState->HTML_header_added = 1;\n\n return;\n }\n\n SBuf outbuf;\n\n if (!gopherState->HTML_header_added) {\n if (gopherState->conversion == GopherStateData::HTML_CSO_RESULT)\n gopherHTMLHeader(entry, \"CSO Search Result\", NULL);\n else\n gopherHTMLHeader(entry, \"Gopher Menu\", NULL);\n\n outbuf.append (\"
\");\n\n        gopherState->HTML_header_added = 1;\n\n        gopherState->HTML_pre = 1;\n    }\n\n    while (pos < inbuf + len) {\n        int llen;\n        int left = len - (pos - inbuf);\n        lpos = (char *)memchr(pos, '\\n', left);\n        if (lpos) {\n            ++lpos;             /* Next line is after \\n */\n            llen = lpos - pos;\n        } else {\n            llen = left;\n        }\n        if (gopherState->len + llen >= TEMP_BUF_SIZE) {\n            debugs(10, DBG_IMPORTANT, \"GopherHTML: Buffer overflow. Lost some data on URL: \" << entry->url()  );\n            llen = TEMP_BUF_SIZE - gopherState->len - 1;\n            gopherState->overflowed = true; // may already be true\n        }\n        if (!lpos) {\n            /* there is no complete line in inbuf */\n            /* copy it to temp buffer */\n            /* note: llen is adjusted above */\n            memcpy(gopherState->buf + gopherState->len, pos, llen);\n            gopherState->len += llen;\n            break;\n        }\n        if (gopherState->len != 0) {\n            /* there is something left from last tx. */\n            memcpy(line, gopherState->buf, gopherState->len);\n            memcpy(line + gopherState->len, pos, llen);\n            llen += gopherState->len;\n            gopherState->len = 0;\n        } else {\n            memcpy(line, pos, llen);\n        }\n        line[llen + 1] = '\\0';\n        /* move input to next line */\n        pos = lpos;\n\n        /* at this point. We should have one line in buffer to process */\n\n        if (*line == '.') {\n            /* skip it */\n            memset(line, '\\0', TEMP_BUF_SIZE);\n            continue;\n        }\n\n        switch (gopherState->conversion) {\n\n        case GopherStateData::HTML_INDEX_RESULT:\n\n        case GopherStateData::HTML_DIR: {\n            tline = line;\n            gtype = *tline;\n            ++tline;\n            name = tline;\n            selector = strchr(tline, TAB);\n\n            if (selector) {\n                *selector = '\\0';\n                ++selector;\n                host = strchr(selector, TAB);\n\n                if (host) {\n                    *host = '\\0';\n                    ++host;\n                    port = strchr(host, TAB);\n\n                    if (port) {\n                        char *junk;\n                        port[0] = ':';\n                        junk = strchr(host, TAB);\n\n                        if (junk)\n                            *junk++ = 0;    /* Chop port */\n                        else {\n                            junk = strchr(host, '\\r');\n\n                            if (junk)\n                                *junk++ = 0;    /* Chop port */\n                            else {\n                                junk = strchr(host, '\\n');\n\n                                if (junk)\n                                    *junk++ = 0;    /* Chop port */\n                            }\n                        }\n\n                        if ((port[1] == '0') && (!port[2]))\n                            port[0] = 0;    /* 0 means none */\n                    }\n\n                    /* escape a selector here */\n                    escaped_selector = xstrdup(rfc1738_escape_part(selector));\n\n                    switch (gtype) {\n\n                    case GOPHER_DIRECTORY:\n                        icon_url = mimeGetIconURL(\"internal-menu\");\n                        break;\n\n                    case GOPHER_HTML:\n\n                    case GOPHER_FILE:\n                        icon_url = mimeGetIconURL(\"internal-text\");\n                        break;\n\n                    case GOPHER_INDEX:\n\n                    case GOPHER_CSO:\n                        icon_url = mimeGetIconURL(\"internal-index\");\n                        break;\n\n                    case GOPHER_IMAGE:\n\n                    case GOPHER_GIF:\n\n                    case GOPHER_PLUS_IMAGE:\n                        icon_url = mimeGetIconURL(\"internal-image\");\n                        break;\n\n                    case GOPHER_SOUND:\n\n                    case GOPHER_PLUS_SOUND:\n                        icon_url = mimeGetIconURL(\"internal-sound\");\n                        break;\n\n                    case GOPHER_PLUS_MOVIE:\n                        icon_url = mimeGetIconURL(\"internal-movie\");\n                        break;\n\n                    case GOPHER_TELNET:\n\n                    case GOPHER_3270:\n                        icon_url = mimeGetIconURL(\"internal-telnet\");\n                        break;\n\n                    case GOPHER_BIN:\n\n                    case GOPHER_MACBINHEX:\n\n                    case GOPHER_DOSBIN:\n\n                    case GOPHER_UUENCODED:\n                        icon_url = mimeGetIconURL(\"internal-binary\");\n                        break;\n\n                    case GOPHER_INFO:\n                        icon_url = NULL;\n                        break;\n\n                    case GOPHER_WWW:\n                        icon_url = mimeGetIconURL(\"internal-link\");\n                        break;\n\n                    default:\n                        icon_url = mimeGetIconURL(\"internal-unknown\");\n                        break;\n                    }\n\n                    if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) {\n                        if (strlen(escaped_selector) != 0)\n                            outbuf.appendf(\" %s\\n\",\n                                     icon_url, escaped_selector, rfc1738_escape_part(host),\n                                     *port ? \":\" : \"\", port, html_quote(name));\n                        else\n                            outbuf.appendf(\" %s\\n\",\n                                     icon_url, rfc1738_escape_part(host), *port ? \":\" : \"\",\n                                     port, html_quote(name));\n\n                    } else if (gtype == GOPHER_INFO) {\n                        outbuf.appendf(\"\\t%s\\n\", html_quote(name));\n                    } else {\n                        if (strncmp(selector, \"GET /\", 5) == 0) {\n                            /* WWW link */\n                            outbuf.appendf(\" %s\\n\",\n                                     icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name));\n                        } else if (gtype == GOPHER_WWW) {\n                            outbuf.appendf(\" %s\\n\",\n                                     icon_url, rfc1738_escape_unescaped(selector), html_quote(name));\n                        } else {\n                            /* Standard link */\n                            outbuf.appendf(\" %s\\n\",\n                                     icon_url, host, gtype, escaped_selector, html_quote(name));\n                        }\n                    }\n\n                    safe_free(escaped_selector);\n                } else {\n                    memset(line, '\\0', TEMP_BUF_SIZE);\n                    continue;\n                }\n            } else {\n                memset(line, '\\0', TEMP_BUF_SIZE);\n                continue;\n            }\n\n            break;\n            }           /* HTML_DIR, HTML_INDEX_RESULT */\n\n        case GopherStateData::HTML_CSO_RESULT: {\n            if (line[0] == '-') {\n                int code, recno;\n                char *s_code, *s_recno, *result;\n\n                s_code = strtok(line + 1, \":\\n\");\n                s_recno = strtok(NULL, \":\\n\");\n                result = strtok(NULL, \"\\n\");\n\n                if (!result)\n                    break;\n\n                code = atoi(s_code);\n\n                recno = atoi(s_recno);\n\n                if (code != 200)\n                    break;\n\n                if (gopherState->cso_recno != recno) {\n                    outbuf.appendf(\"

Record# %d
%s

\\n
\", recno, html_quote(result));\n                    gopherState->cso_recno = recno;\n                } else {\n                    outbuf.appendf(\"%s\\n\", html_quote(result));\n                }\n\n                break;\n            } else {\n                int code;\n                char *s_code, *result;\n\n                s_code = strtok(line, \":\");\n                result = strtok(NULL, \"\\n\");\n\n                if (!result)\n                    break;\n\n                code = atoi(s_code);\n\n                switch (code) {\n\n                case 200: {\n                    /* OK */\n                    /* Do nothing here */\n                    break;\n                }\n\n                case 102:   /* Number of matches */\n\n                case 501:   /* No Match */\n\n                case 502: { /* Too Many Matches */\n                    /* Print the message the server returns */\n                    outbuf.appendf(\"

%s

\\n
\", html_quote(result));\n                    break;\n                }\n\n                }\n            }\n\n            break;\n            }           /* HTML_CSO_RESULT */\n        default:\n            break;      /* do nothing */\n\n        }           /* switch */\n\n    }               /* while loop */\n\n    if (outbuf.length() > 0) {\n        entry->append(outbuf.rawContent(), outbuf.length());\n        /* now let start sending stuff to client */\n        entry->flush();\n    }\n\n    return;\n}", "func_hash": 21640942922320975299915998505575451737, "file_name": "gopher.cc", "file_hash": 190939052563115961351574589449206812826, "cwe": ["CWE-400"], "cve": "CVE-2021-46784", "cve_desc": "In Squid 3.x through 3.5.28, 4.x through 4.17, and 5.x before 5.6, due to improper buffer management, a Denial of Service can occur when processing long Gopher server responses.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46784"}
{"idx": 195328, "project": "gpac", "commit_id": "30ac5e5236b790accd1f25347eebf2dc8c6c1bcb", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/30ac5e5236b790accd1f25347eebf2dc8c6c1bcb", "commit_message": "fixed #1897", "target": 1, "func": "char *gf_text_get_utf8_line(char *szLine, u32 lineSize, FILE *txt_in, s32 unicode_type)\n{\n\tu32 i, j, len;\n\tchar *sOK;\n\tchar szLineConv[1024];\n\tunsigned short *sptr;\n\n\tmemset(szLine, 0, sizeof(char)*lineSize);\n\tsOK = gf_fgets(szLine, lineSize, txt_in);\n\tif (!sOK) return NULL;\n\tif (unicode_type<=1) {\n\t\tj=0;\n\t\tlen = (u32) strlen(szLine);\n\t\tfor (i=0; i> 6) & 0x3 );\n\t\t\t\t\tj++;\n\t\t\t\t\tszLine[i] &= 0xbf;\n\t\t\t\t}\n\t\t\t\t/*UTF8 2 bytes char*/\n\t\t\t\telse if ( (szLine[i] & 0xe0) == 0xc0) {\n\t\t\t\t\tszLineConv[j] = szLine[i];\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t\t/*UTF8 3 bytes char*/\n\t\t\t\telse if ( (szLine[i] & 0xf0) == 0xe0) {\n\t\t\t\t\tszLineConv[j] = szLine[i];\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t\tszLineConv[j] = szLine[i];\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t\t/*UTF8 4 bytes char*/\n\t\t\t\telse if ( (szLine[i] & 0xf8) == 0xf0) {\n\t\t\t\t\tszLineConv[j] = szLine[i];\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t\tszLineConv[j] = szLine[i];\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t\tszLineConv[j] = szLine[i];\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t} else {\n\t\t\t\t\ti+=1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tszLineConv[j] = szLine[i];\n\t\t\tj++;\n\t\t}\n\t\tszLineConv[j] = 0;\n\t\tstrcpy(szLine, szLineConv);\n\t\treturn sOK;\n\t}\n\n#ifdef GPAC_BIG_ENDIAN\n\tif (unicode_type==3)\n#else\n\tif (unicode_type==2)\n#endif\n\t{\n\t\ti=0;\n\t\twhile (1) {\n\t\t\tchar c;\n\t\t\tif (!szLine[i] && !szLine[i+1]) break;\n\t\t\tc = szLine[i+1];\n\t\t\tszLine[i+1] = szLine[i];\n\t\t\tszLine[i] = c;\n\t\t\ti+=2;\n\t\t}\n\t}\n\tsptr = (u16 *)szLine;\n\ti = (u32) gf_utf8_wcstombs(szLineConv, 1024, (const unsigned short **) &sptr);\n\tszLineConv[i] = 0;\n\tstrcpy(szLine, szLineConv);\n\t/*this is ugly indeed: since input is UTF16-LE, there are many chances the gf_fgets never reads the \\0 after a \\n*/\n\tif (unicode_type==3) gf_fgetc(txt_in);\n\treturn sOK;\n}", "func_hash": 117427486429117846714647428036887377373, "file_name": "load_text.c", "file_hash": 196742273187479774331460388493063544419, "cwe": ["CWE-415"], "cve": "CVE-2021-40574", "cve_desc": "The binary MP4Box in Gpac 1.0.1 has a double-free vulnerability in the gf_text_get_utf8_line function in load_text.c, which allows attackers to cause a denial of service, even code execution and escalation of privileges.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40574"}
{"idx": 224472, "project": "gpac", "commit_id": "30ac5e5236b790accd1f25347eebf2dc8c6c1bcb", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/30ac5e5236b790accd1f25347eebf2dc8c6c1bcb", "commit_message": "fixed #1897", "target": 0, "func": "char *gf_text_get_utf8_line(char *szLine, u32 lineSize, FILE *txt_in, s32 unicode_type)\n{\n\tu32 i, j, len;\n\tchar *sOK;\n\tchar szLineConv[2048];\n\tunsigned short *sptr;\n\n\tmemset(szLine, 0, sizeof(char)*lineSize);\n\tsOK = gf_fgets(szLine, lineSize, txt_in);\n\tif (!sOK) return NULL;\n\tif (unicode_type<=1) {\n\t\tj=0;\n\t\tlen = (u32) strlen(szLine);\n\t\tfor (i=0; i> 6) & 0x3 );\n\t\t\t\t\tj++;\n\t\t\t\t\tszLine[i] &= 0xbf;\n\t\t\t\t}\n\t\t\t\t/*UTF8 2 bytes char*/\n\t\t\t\telse if ( (szLine[i] & 0xe0) == 0xc0) {\n\t\t\t\t\tszLineConv[j] = szLine[i];\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t\t/*UTF8 3 bytes char*/\n\t\t\t\telse if ( (szLine[i] & 0xf0) == 0xe0) {\n\t\t\t\t\tszLineConv[j] = szLine[i];\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t\tszLineConv[j] = szLine[i];\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t\t/*UTF8 4 bytes char*/\n\t\t\t\telse if ( (szLine[i] & 0xf8) == 0xf0) {\n\t\t\t\t\tszLineConv[j] = szLine[i];\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t\tszLineConv[j] = szLine[i];\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t\tszLineConv[j] = szLine[i];\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t} else {\n\t\t\t\t\ti+=1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tszLineConv[j] = szLine[i];\n\t\t\tj++;\n\t\t}\n\t\tszLineConv[j] = 0;\n\t\tstrcpy(szLine, szLineConv);\n\t\treturn sOK;\n\t}\n\n#ifdef GPAC_BIG_ENDIAN\n\tif (unicode_type==3)\n#else\n\tif (unicode_type==2)\n#endif\n\t{\n\t\ti=0;\n\t\twhile (1) {\n\t\t\tchar c;\n\t\t\tif (!szLine[i] && !szLine[i+1]) break;\n\t\t\tc = szLine[i+1];\n\t\t\tszLine[i+1] = szLine[i];\n\t\t\tszLine[i] = c;\n\t\t\ti+=2;\n\t\t}\n\t}\n\tsptr = (u16 *)szLine;\n\ti = (u32) gf_utf8_wcstombs(szLineConv, 2048, (const unsigned short **) &sptr);\n\tszLineConv[i] = 0;\n\tstrcpy(szLine, szLineConv);\n\t/*this is ugly indeed: since input is UTF16-LE, there are many chances the gf_fgets never reads the \\0 after a \\n*/\n\tif (unicode_type==3) gf_fgetc(txt_in);\n\treturn sOK;\n}", "func_hash": 206448432363907113546512643676658303982, "file_name": "load_text.c", "file_hash": 270779576910744156479880021794579702395, "cwe": ["CWE-415"], "cve": "CVE-2021-40574", "cve_desc": "The binary MP4Box in Gpac 1.0.1 has a double-free vulnerability in the gf_text_get_utf8_line function in load_text.c, which allows attackers to cause a denial of service, even code execution and escalation of privileges.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40574"}
{"idx": 195331, "project": "tensorflow", "commit_id": "08d7b00c0a5a20926363849f611729f53f3ec022", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/08d7b00c0a5a20926363849f611729f53f3ec022", "commit_message": "Fix Segfault in Concat V2 shape function.\n\nPiperOrigin-RevId: 412120654\nChange-Id: I3ff915faea694f9ad8b00024e9af2de9909011be", "target": 1, "func": "Status ConcatShapeHelper(InferenceContext* c, int start_value_index,\n                         int end_value_index, int dim_index) {\n  ShapeHandle unused;\n  TF_RETURN_IF_ERROR(c->WithRank(c->input(dim_index), 0, &unused));\n  const Tensor* concat_dim_t = c->input_tensor(dim_index);\n  if (concat_dim_t == nullptr) {\n    // Return an unknown shape with same rank as inputs, or an unknown rank\n    // if no input's rank is known.\n\n    // Find rank.\n    int32_t rank = InferenceContext::kUnknownRank;\n    for (int i = start_value_index; i < end_value_index; ++i) {\n      if (rank == InferenceContext::kUnknownRank) rank = c->Rank(c->input(i));\n      if (rank != InferenceContext::kUnknownRank) {\n        break;\n      }\n    }\n    if (rank == InferenceContext::kUnknownRank) {\n      c->set_output(0, c->UnknownShape());\n      return Status::OK();\n    } else if (rank == 0) {\n      return errors::InvalidArgument(\n          \"Can't concatenate scalars (use tf.stack instead)\");\n    } else {\n      for (int i = start_value_index; i < end_value_index; ++i) {\n        // Check that all the inputs are of the correct rank.\n        TF_RETURN_IF_ERROR(c->WithRank(c->input(i), rank, &unused));\n      }\n    }\n    // Build result of  different unknown dims.\n    std::vector dims;\n    dims.reserve(rank);\n    for (int i = 0; i < rank; ++i) dims.push_back(c->UnknownDim());\n    c->set_output(0, c->MakeShape(dims));\n    return Status::OK();\n  }\n\n  // Merge all the non-concat dims, and sum the concat dim to make an output\n  // shape.\n  int64_t concat_dim;\n  if (concat_dim_t->dtype() == DT_INT32) {\n    concat_dim = static_cast(concat_dim_t->flat()(0));\n  } else {\n    concat_dim = concat_dim_t->flat()(0);\n  }\n\n  // Minimum required number of dimensions.\n  const int min_rank = concat_dim < 0 ? -concat_dim : concat_dim + 1;\n\n  ShapeHandle output_before;\n  ShapeHandle output_after;\n\n  ShapeHandle input = c->input(end_value_index - 1);\n  TF_RETURN_IF_ERROR(c->WithRankAtLeast(input, min_rank, &input));\n  TF_RETURN_IF_ERROR(c->Subshape(input, 0, concat_dim, &output_before));\n  DimensionHandle output_middle = c->Dim(input, concat_dim);\n  if (concat_dim == -1) {\n    output_after = c->Scalar();  // no dimensions.\n  } else {\n    TF_RETURN_IF_ERROR(c->Subshape(input, concat_dim + 1, &output_after));\n  }\n\n  for (int i = end_value_index - 2; i >= start_value_index; --i) {\n    ShapeHandle before;\n    ShapeHandle after;\n    input = c->input(i);\n    TF_RETURN_IF_ERROR(c->WithRankAtLeast(input, min_rank, &input));\n    TF_RETURN_IF_ERROR(c->Subshape(input, 0, concat_dim, &before));\n    DimensionHandle middle = c->Dim(input, concat_dim);\n    if (concat_dim == -1) {\n      after = c->Scalar();\n    } else {\n      TF_RETURN_IF_ERROR(c->Subshape(input, concat_dim + 1, &after));\n    }\n\n    TF_RETURN_IF_ERROR(c->Merge(before, output_before, &output_before));\n    TF_RETURN_IF_ERROR(c->Add(output_middle, middle, &output_middle));\n    TF_RETURN_IF_ERROR(c->Merge(after, output_after, &output_after));\n  }\n\n  ShapeHandle s;\n  TF_RETURN_IF_ERROR(\n      c->Concatenate(output_before, c->Vector(output_middle), &s));\n  TF_RETURN_IF_ERROR(c->Concatenate(s, output_after, &s));\n  c->set_output(0, s);\n  return Status::OK();\n}", "func_hash": 115004012549325804010611397133680502113, "file_name": "common_shape_fns.cc", "file_hash": 114394888048780454732842913577124501919, "cwe": ["CWE-843"], "cve": "CVE-2022-21731", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of shape inference for `ConcatV2` can be used to trigger a denial of service attack via a segfault caused by a type confusion. The `axis` argument is translated into `concat_dim` in the `ConcatShapeHelper` helper function. Then, a value for `min_rank` is computed based on `concat_dim`. This is then used to validate that the `values` tensor has at least the required rank. However, `WithRankAtLeast` receives the lower bound as a 64-bits value and then compares it against the maximum 32-bits integer value that could be represented. Due to the fact that `min_rank` is a 32-bits value and the value of `axis`, the `rank` argument is a negative value, so the error check is bypassed. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21731"}
{"idx": 224570, "project": "tensorflow", "commit_id": "08d7b00c0a5a20926363849f611729f53f3ec022", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/08d7b00c0a5a20926363849f611729f53f3ec022", "commit_message": "Fix Segfault in Concat V2 shape function.\n\nPiperOrigin-RevId: 412120654\nChange-Id: I3ff915faea694f9ad8b00024e9af2de9909011be", "target": 0, "func": "Status ConcatShapeHelper(InferenceContext* c, int start_value_index,\n                         int end_value_index, int dim_index) {\n  ShapeHandle unused;\n  TF_RETURN_IF_ERROR(c->WithRank(c->input(dim_index), 0, &unused));\n  const Tensor* concat_dim_t = c->input_tensor(dim_index);\n  if (concat_dim_t == nullptr) {\n    // Return an unknown shape with same rank as inputs, or an unknown rank\n    // if no input's rank is known.\n\n    // Find rank.\n    int32_t rank = InferenceContext::kUnknownRank;\n    for (int i = start_value_index; i < end_value_index; ++i) {\n      if (rank == InferenceContext::kUnknownRank) rank = c->Rank(c->input(i));\n      if (rank != InferenceContext::kUnknownRank) {\n        break;\n      }\n    }\n    if (rank == InferenceContext::kUnknownRank) {\n      c->set_output(0, c->UnknownShape());\n      return Status::OK();\n    } else if (rank == 0) {\n      return errors::InvalidArgument(\n          \"Can't concatenate scalars (use tf.stack instead)\");\n    } else {\n      for (int i = start_value_index; i < end_value_index; ++i) {\n        // Check that all the inputs are of the correct rank.\n        TF_RETURN_IF_ERROR(c->WithRank(c->input(i), rank, &unused));\n      }\n    }\n    // Build result of  different unknown dims.\n    std::vector dims;\n    dims.reserve(rank);\n    for (int i = 0; i < rank; ++i) dims.push_back(c->UnknownDim());\n    c->set_output(0, c->MakeShape(dims));\n    return Status::OK();\n  }\n\n  // Merge all the non-concat dims, and sum the concat dim to make an output\n  // shape.\n  int64_t concat_dim;\n  if (concat_dim_t->dtype() == DT_INT32) {\n    concat_dim = static_cast(concat_dim_t->flat()(0));\n  } else {\n    concat_dim = concat_dim_t->flat()(0);\n  }\n\n  // Minimum required number of dimensions.\n  const int64 min_rank = concat_dim < 0 ? -concat_dim : concat_dim + 1;\n\n  ShapeHandle output_before;\n  ShapeHandle output_after;\n\n  ShapeHandle input = c->input(end_value_index - 1);\n  TF_RETURN_IF_ERROR(c->WithRankAtLeast(input, min_rank, &input));\n  TF_RETURN_IF_ERROR(c->Subshape(input, 0, concat_dim, &output_before));\n  DimensionHandle output_middle = c->Dim(input, concat_dim);\n  if (concat_dim == -1) {\n    output_after = c->Scalar();  // no dimensions.\n  } else {\n    TF_RETURN_IF_ERROR(c->Subshape(input, concat_dim + 1, &output_after));\n  }\n\n  for (int i = end_value_index - 2; i >= start_value_index; --i) {\n    ShapeHandle before;\n    ShapeHandle after;\n    input = c->input(i);\n    TF_RETURN_IF_ERROR(c->WithRankAtLeast(input, min_rank, &input));\n    TF_RETURN_IF_ERROR(c->Subshape(input, 0, concat_dim, &before));\n    DimensionHandle middle = c->Dim(input, concat_dim);\n    if (concat_dim == -1) {\n      after = c->Scalar();\n    } else {\n      TF_RETURN_IF_ERROR(c->Subshape(input, concat_dim + 1, &after));\n    }\n\n    TF_RETURN_IF_ERROR(c->Merge(before, output_before, &output_before));\n    TF_RETURN_IF_ERROR(c->Add(output_middle, middle, &output_middle));\n    TF_RETURN_IF_ERROR(c->Merge(after, output_after, &output_after));\n  }\n\n  ShapeHandle s;\n  TF_RETURN_IF_ERROR(\n      c->Concatenate(output_before, c->Vector(output_middle), &s));\n  TF_RETURN_IF_ERROR(c->Concatenate(s, output_after, &s));\n  c->set_output(0, s);\n  return Status::OK();\n}", "func_hash": 224848617993634630925206364943386826300, "file_name": "common_shape_fns.cc", "file_hash": 56524265073448960566855170405566896543, "cwe": ["CWE-843"], "cve": "CVE-2022-21731", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of shape inference for `ConcatV2` can be used to trigger a denial of service attack via a segfault caused by a type confusion. The `axis` argument is translated into `concat_dim` in the `ConcatShapeHelper` helper function. Then, a value for `min_rank` is computed based on `concat_dim`. This is then used to validate that the `values` tensor has at least the required rank. However, `WithRankAtLeast` receives the lower bound as a 64-bits value and then compares it against the maximum 32-bits integer value that could be represented. Due to the fact that `min_rank` is a 32-bits value and the value of `axis`, the `rank` argument is a negative value, so the error check is bypassed. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21731"}
{"idx": 195334, "project": "gpac", "commit_id": "b03c9f252526bb42fbd1b87b9f5e339c3cf2390a", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/b03c9f252526bb42fbd1b87b9f5e339c3cf2390a", "commit_message": "fixed #1890", "target": 1, "func": "GF_Err iloc_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tu32 item_count, extent_count, i, j;\n\tGF_ItemLocationBox *ptr = (GF_ItemLocationBox *)s;\n\n\tISOM_DECREASE_SIZE(ptr, 2)\n\tptr->offset_size = gf_bs_read_int(bs, 4);\n\tptr->length_size = gf_bs_read_int(bs, 4);\n\tptr->base_offset_size = gf_bs_read_int(bs, 4);\n\tif (ptr->version == 1 || ptr->version == 2) {\n\t\tptr->index_size = gf_bs_read_int(bs, 4);\n\t} else {\n\t\tgf_bs_read_int(bs, 4);\n\t}\n\tif (ptr->version < 2) {\n\t\tISOM_DECREASE_SIZE(ptr, 2)\n\t\titem_count = gf_bs_read_u16(bs);\n\t} else {\n\t\tISOM_DECREASE_SIZE(ptr, 4)\n\t\titem_count = gf_bs_read_u32(bs);\n\t}\n\n\tfor (i = 0; i < item_count; i++) {\n\t\tGF_ItemLocationEntry *location_entry = (GF_ItemLocationEntry *)gf_malloc(sizeof(GF_ItemLocationEntry));\n\t\tif (!location_entry) return GF_OUT_OF_MEM;\n\n\t\tgf_list_add(ptr->location_entries, location_entry);\n\t\tif (ptr->version < 2) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 2)\n\t\t\tlocation_entry->item_ID = gf_bs_read_u16(bs);\n\t\t} else {\n\t\t\tISOM_DECREASE_SIZE(ptr, 4)\n\t\t\tlocation_entry->item_ID = gf_bs_read_u32(bs);\n\t\t}\n\t\tif (ptr->version == 1 || ptr->version == 2) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 2)\n\t\t\tlocation_entry->construction_method = gf_bs_read_u16(bs);\n\t\t}\n\t\telse {\n\t\t\tlocation_entry->construction_method = 0;\n\t\t}\n\t\tISOM_DECREASE_SIZE(ptr, (2 + ptr->base_offset_size) )\n\t\tlocation_entry->data_reference_index = gf_bs_read_u16(bs);\n\t\tlocation_entry->base_offset = gf_bs_read_int(bs, 8*ptr->base_offset_size);\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\t\tlocation_entry->original_base_offset = location_entry->base_offset;\n#endif\n\n\t\tISOM_DECREASE_SIZE(ptr, 2)\n\t\textent_count = gf_bs_read_u16(bs);\n\t\tlocation_entry->extent_entries = gf_list_new();\n\t\tfor (j = 0; j < extent_count; j++) {\n\t\t\tGF_ItemExtentEntry *extent_entry = (GF_ItemExtentEntry *)gf_malloc(sizeof(GF_ItemExtentEntry));\n\t\t\tif (!extent_entry) return GF_OUT_OF_MEM;\n\t\t\t\n\t\t\tgf_list_add(location_entry->extent_entries, extent_entry);\n\t\t\tif ((ptr->version == 1 || ptr->version == 2) && ptr->index_size > 0) {\n\t\t\t\tISOM_DECREASE_SIZE(ptr, ptr->index_size)\n\t\t\t\textent_entry->extent_index = gf_bs_read_int(bs, 8 * ptr->index_size);\n\t\t\t}\n\t\t\telse {\n\t\t\t\textent_entry->extent_index = 0;\n\t\t\t}\n\t\t\tISOM_DECREASE_SIZE(ptr, (ptr->offset_size+ptr->length_size) )\n\n\t\t\textent_entry->extent_offset = gf_bs_read_int(bs, 8*ptr->offset_size);\n\t\t\textent_entry->extent_length = gf_bs_read_int(bs, 8*ptr->length_size);\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\t\t\textent_entry->original_extent_offset = extent_entry->extent_offset;\n#endif\n\t\t}\n\t}\n\treturn GF_OK;\n}", "func_hash": 85275035202223574859308673912965262169, "file_name": "box_code_meta.c", "file_hash": 315220373545459860670428553876078791185, "cwe": ["CWE-415"], "cve": "CVE-2021-40573", "cve_desc": "The binary MP4Box in Gpac 1.0.1 has a double-free vulnerability in the gf_list_del function in list.c, which allows attackers to cause a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40573"}
{"idx": 224728, "project": "gpac", "commit_id": "b03c9f252526bb42fbd1b87b9f5e339c3cf2390a", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/b03c9f252526bb42fbd1b87b9f5e339c3cf2390a", "commit_message": "fixed #1890", "target": 0, "func": "GF_Err iloc_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tu32 item_count, extent_count, i, j;\n\tGF_ItemLocationBox *ptr = (GF_ItemLocationBox *)s;\n\n\tISOM_DECREASE_SIZE(ptr, 2)\n\tptr->offset_size = gf_bs_read_int(bs, 4);\n\tptr->length_size = gf_bs_read_int(bs, 4);\n\tptr->base_offset_size = gf_bs_read_int(bs, 4);\n\tif (ptr->version == 1 || ptr->version == 2) {\n\t\tptr->index_size = gf_bs_read_int(bs, 4);\n\t} else {\n\t\tgf_bs_read_int(bs, 4);\n\t}\n\tif (ptr->version < 2) {\n\t\tISOM_DECREASE_SIZE(ptr, 2)\n\t\titem_count = gf_bs_read_u16(bs);\n\t} else {\n\t\tISOM_DECREASE_SIZE(ptr, 4)\n\t\titem_count = gf_bs_read_u32(bs);\n\t}\n\n\tfor (i = 0; i < item_count; i++) {\n\t\tGF_ItemLocationEntry *location_entry;\n\t\tGF_SAFEALLOC(location_entry, GF_ItemLocationEntry);\n\t\tif (!location_entry) return GF_OUT_OF_MEM;\n\n\t\tgf_list_add(ptr->location_entries, location_entry);\n\t\tif (ptr->version < 2) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 2)\n\t\t\tlocation_entry->item_ID = gf_bs_read_u16(bs);\n\t\t} else {\n\t\t\tISOM_DECREASE_SIZE(ptr, 4)\n\t\t\tlocation_entry->item_ID = gf_bs_read_u32(bs);\n\t\t}\n\t\tif (ptr->version == 1 || ptr->version == 2) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 2)\n\t\t\tlocation_entry->construction_method = gf_bs_read_u16(bs);\n\t\t}\n\t\telse {\n\t\t\tlocation_entry->construction_method = 0;\n\t\t}\n\t\tISOM_DECREASE_SIZE(ptr, (2 + ptr->base_offset_size) )\n\t\tlocation_entry->data_reference_index = gf_bs_read_u16(bs);\n\t\tlocation_entry->base_offset = gf_bs_read_int(bs, 8*ptr->base_offset_size);\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\t\tlocation_entry->original_base_offset = location_entry->base_offset;\n#endif\n\n\t\tISOM_DECREASE_SIZE(ptr, 2)\n\t\textent_count = gf_bs_read_u16(bs);\n\t\tlocation_entry->extent_entries = gf_list_new();\n\t\tfor (j = 0; j < extent_count; j++) {\n\t\t\tGF_ItemExtentEntry *extent_entry;\n\t\t\tGF_SAFEALLOC(extent_entry, GF_ItemExtentEntry);\n\t\t\tif (!extent_entry) return GF_OUT_OF_MEM;\n\t\t\t\n\t\t\tgf_list_add(location_entry->extent_entries, extent_entry);\n\t\t\tif ((ptr->version == 1 || ptr->version == 2) && ptr->index_size > 0) {\n\t\t\t\tISOM_DECREASE_SIZE(ptr, ptr->index_size)\n\t\t\t\textent_entry->extent_index = gf_bs_read_int(bs, 8 * ptr->index_size);\n\t\t\t}\n\t\t\telse {\n\t\t\t\textent_entry->extent_index = 0;\n\t\t\t}\n\t\t\tISOM_DECREASE_SIZE(ptr, (ptr->offset_size+ptr->length_size) )\n\n\t\t\textent_entry->extent_offset = gf_bs_read_int(bs, 8*ptr->offset_size);\n\t\t\textent_entry->extent_length = gf_bs_read_int(bs, 8*ptr->length_size);\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\t\t\textent_entry->original_extent_offset = extent_entry->extent_offset;\n#endif\n\t\t}\n\t}\n\treturn GF_OK;\n}", "func_hash": 326603429121921341428150431158212875495, "file_name": "box_code_meta.c", "file_hash": 99521214022509816524954281629288020612, "cwe": ["CWE-415"], "cve": "CVE-2021-40573", "cve_desc": "The binary MP4Box in Gpac 1.0.1 has a double-free vulnerability in the gf_list_del function in list.c, which allows attackers to cause a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40573"}
{"idx": 195340, "project": "tensorflow", "commit_id": "e952a89b7026b98fe8cbe626514a93ed68b7c510", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e952a89b7026b98fe8cbe626514a93ed68b7c510", "commit_message": "Prevent overflow in sparse dense cwise ops.\n\nPiperOrigin-RevId: 415543171\nChange-Id: I22dab7c41be2121ab5efe5403ca0e2f9b7cb24b8", "target": 1, "func": "  void Compute(OpKernelContext *ctx) override {\n    const Tensor *indices_t, *values_t, *shape_t, *dense_t;\n    OP_REQUIRES_OK(ctx, ctx->input(\"sp_indices\", &indices_t));\n    OP_REQUIRES_OK(ctx, ctx->input(\"sp_values\", &values_t));\n    OP_REQUIRES_OK(ctx, ctx->input(\"sp_shape\", &shape_t));\n    OP_REQUIRES_OK(ctx, ctx->input(\"dense\", &dense_t));\n\n    // Validations.\n    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()),\n                errors::InvalidArgument(\n                    \"Input sp_indices should be a matrix but received shape: \",\n                    indices_t->shape().DebugString()));\n    OP_REQUIRES(ctx,\n                TensorShapeUtils::IsVector(values_t->shape()) &&\n                    TensorShapeUtils::IsVector(shape_t->shape()),\n                errors::InvalidArgument(\n                    \"Inputs sp_values and sp_shape should be vectors \"\n                    \"but received shapes: \",\n                    values_t->shape().DebugString(), \" and \",\n                    shape_t->shape().DebugString()));\n    OP_REQUIRES(\n        ctx, TensorShapeUtils::IsVector(shape_t->shape()),\n        errors::InvalidArgument(\"Input sp_shape must be a vector. Got: \",\n                                shape_t->shape().DebugString()));\n    OP_REQUIRES(\n        ctx, values_t->dim_size(0) == indices_t->dim_size(0),\n        errors::InvalidArgument(\n            \"The first dimension of values and indices should match. (\",\n            values_t->dim_size(0), \" vs. \", indices_t->dim_size(0), \")\"));\n    OP_REQUIRES(\n        ctx, shape_t->shape().dim_size(0) == indices_t->shape().dim_size(1),\n        errors::InvalidArgument(\n            \"Number of dimensions must match second dimension of indices. \",\n            \"Got \", shape_t->shape().dim_size(0),\n            \" dimensions, indices shape: \", indices_t->shape().DebugString()));\n    OP_REQUIRES(ctx, shape_t->NumElements() > 0,\n                errors::InvalidArgument(\n                    \"The shape argument requires at least one element.\"));\n\n    const auto indices_mat = indices_t->matrix();\n    const auto shape_vec = shape_t->vec();\n    const auto lhs_dims = BCast::FromShape(TensorShape(shape_vec));\n    const auto rhs_dims = BCast::FromShape(dense_t->shape());\n    BCast b(lhs_dims, rhs_dims, false);  // false for keeping the same num dims.\n\n    // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal\n    // to dims in rhs (from right to left).\n    auto VecGreaterEq = [](ArraySlice lhs, ArraySlice rhs) {\n      if (lhs.size() < rhs.size()) return false;\n      for (size_t i = 0; i < rhs.size(); ++i) {\n        if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false;\n      }\n      return true;\n    };\n    OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(),\n                errors::InvalidArgument(\n                    \"SparseDenseBinaryOpShared broadcasts dense to sparse \"\n                    \"only; got incompatible shapes: [\",\n                    absl::StrJoin(lhs_dims, \",\"), \"] vs. [\",\n                    absl::StrJoin(rhs_dims, \",\"), \"]\"));\n\n    Tensor *output_values = nullptr;\n    Tensor dense_gathered;\n    const int64_t nnz = indices_t->dim_size(0);\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(0, TensorShape({nnz}), &output_values));\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_temp(DataTypeToEnum::value, TensorShape({nnz}),\n                                &dense_gathered));\n    bool op_is_div = false;\n    if (absl::StrContains(ctx->op_kernel().type_string_view(), \"Div\")) {\n      op_is_div = true;\n    }\n    // Pulls relevant entries from the dense side, with reshape and broadcasting\n    // *of the dense side* taken into account.  Use a TensorRef to avoid blowing\n    // up memory.\n    //\n    // We can directly use the sparse indices to look up dense side, because\n    // \"b.y_reshape()\" and \"b.y_bcast()\" are guaranteed to have rank \"ndims\".\n    auto dense_gathered_flat = dense_gathered.flat();\n    const int ndims = lhs_dims.size();\n    switch (ndims) {\n#define CASE(NDIM)                                                             \\\n  case NDIM: {                                                                 \\\n    TensorRef> rhs_ref =         \\\n        dense_t->shaped(b.y_reshape())                                \\\n            .broadcast(BCast::ToIndexArray(b.y_bcast()));                \\\n    Eigen::array idx;                                 \\\n    bool indices_valid = true;                                                 \\\n    for (int i = 0; i < nnz; ++i) {                                            \\\n      for (int d = 0; d < NDIM; ++d) {                                         \\\n        idx[d] = internal::SubtleMustCopy(indices_mat(i, d));                  \\\n        if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) {                  \\\n          indices_valid = false;                                               \\\n        }                                                                      \\\n      }                                                                        \\\n      OP_REQUIRES(                                                             \\\n          ctx, indices_valid,                                                  \\\n          errors::InvalidArgument(\"Provided indices are out-of-bounds w.r.t. \" \\\n                                  \"dense side with broadcasted shape\"));       \\\n      dense_gathered_flat(i) = rhs_ref.coeff(idx);                             \\\n      if (op_is_div) {                                                         \\\n        OP_REQUIRES(ctx, dense_gathered_flat(i) != 0,                          \\\n                    errors::InvalidArgument(                                   \\\n                        \"SparseDenseCwiseDiv cannot divide by zero,\"           \\\n                        \"but input dense tensor contains zero \"));             \\\n      }                                                                        \\\n    }                                                                          \\\n    break;                                                                     \\\n  }\n\n      CASE(1);\n      CASE(2);\n      CASE(3);\n      CASE(4);\n      CASE(5);\n      default:\n        OP_REQUIRES(\n            ctx, false,\n            errors::InvalidArgument(\"Only tensors with ranks between 1 and 5 \"\n                                    \"are currently supported.  Tensor rank: \",\n                                    ndims));\n#undef CASE\n    }\n\n    output_values->flat().device(ctx->eigen_device()) =\n        values_t->flat().binaryExpr(dense_gathered_flat,\n                                       typename Functor::func());\n  }", "func_hash": 171281295800875024521736226102204042037, "file_name": "sparse_dense_binary_op_shared.cc", "file_hash": 32986558098184077015668984064800916453, "cwe": ["CWE-190"], "cve": "CVE-2022-23567", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementations of `Sparse*Cwise*` ops are vulnerable to integer overflows. These can be used to trigger large allocations (so, OOM based denial of service) or `CHECK`-fails when building new `TensorShape` objects (so, assert failures based denial of service). We are missing some validation on the shapes of the input tensors as well as directly constructing a large `TensorShape` with user-provided dimensions. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23567"}
{"idx": 224862, "project": "tensorflow", "commit_id": "e952a89b7026b98fe8cbe626514a93ed68b7c510", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e952a89b7026b98fe8cbe626514a93ed68b7c510", "commit_message": "Prevent overflow in sparse dense cwise ops.\n\nPiperOrigin-RevId: 415543171\nChange-Id: I22dab7c41be2121ab5efe5403ca0e2f9b7cb24b8", "target": 0, "func": "  void Compute(OpKernelContext *ctx) override {\n    const Tensor *indices_t, *values_t, *shape_t, *dense_t;\n    OP_REQUIRES_OK(ctx, ctx->input(\"sp_indices\", &indices_t));\n    OP_REQUIRES_OK(ctx, ctx->input(\"sp_values\", &values_t));\n    OP_REQUIRES_OK(ctx, ctx->input(\"sp_shape\", &shape_t));\n    OP_REQUIRES_OK(ctx, ctx->input(\"dense\", &dense_t));\n\n    // Validations.\n    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()),\n                errors::InvalidArgument(\n                    \"Input sp_indices should be a matrix but received shape: \",\n                    indices_t->shape().DebugString()));\n    OP_REQUIRES(ctx,\n                TensorShapeUtils::IsVector(values_t->shape()) &&\n                    TensorShapeUtils::IsVector(shape_t->shape()),\n                errors::InvalidArgument(\n                    \"Inputs sp_values and sp_shape should be vectors \"\n                    \"but received shapes: \",\n                    values_t->shape().DebugString(), \" and \",\n                    shape_t->shape().DebugString()));\n    OP_REQUIRES(\n        ctx, TensorShapeUtils::IsVector(shape_t->shape()),\n        errors::InvalidArgument(\"Input sp_shape must be a vector. Got: \",\n                                shape_t->shape().DebugString()));\n    OP_REQUIRES(\n        ctx, values_t->dim_size(0) == indices_t->dim_size(0),\n        errors::InvalidArgument(\n            \"The first dimension of values and indices should match. (\",\n            values_t->dim_size(0), \" vs. \", indices_t->dim_size(0), \")\"));\n    OP_REQUIRES(\n        ctx, shape_t->shape().dim_size(0) == indices_t->shape().dim_size(1),\n        errors::InvalidArgument(\n            \"Number of dimensions must match second dimension of indices. \",\n            \"Got \", shape_t->shape().dim_size(0),\n            \" dimensions, indices shape: \", indices_t->shape().DebugString()));\n    OP_REQUIRES(ctx, shape_t->NumElements() > 0,\n                errors::InvalidArgument(\n                    \"The shape argument requires at least one element.\"));\n\n    const auto indices_mat = indices_t->matrix();\n    const auto shape_vec = shape_t->vec();\n    TensorShape lhs_shape;\n    OP_REQUIRES_OK(ctx, TensorShape::BuildTensorShape(shape_vec, &lhs_shape));\n    const auto lhs_dims = BCast::FromShape(lhs_shape);\n    const auto rhs_dims = BCast::FromShape(dense_t->shape());\n    BCast b(lhs_dims, rhs_dims, false);  // false for keeping the same num dims.\n\n    // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal\n    // to dims in rhs (from right to left).\n    auto VecGreaterEq = [](ArraySlice lhs, ArraySlice rhs) {\n      if (lhs.size() < rhs.size()) return false;\n      for (size_t i = 0; i < rhs.size(); ++i) {\n        if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false;\n      }\n      return true;\n    };\n    OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(),\n                errors::InvalidArgument(\n                    \"SparseDenseBinaryOpShared broadcasts dense to sparse \"\n                    \"only; got incompatible shapes: [\",\n                    absl::StrJoin(lhs_dims, \",\"), \"] vs. [\",\n                    absl::StrJoin(rhs_dims, \",\"), \"]\"));\n\n    Tensor *output_values = nullptr;\n    Tensor dense_gathered;\n    const int64_t nnz = indices_t->dim_size(0);\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(0, TensorShape({nnz}), &output_values));\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_temp(DataTypeToEnum::value, TensorShape({nnz}),\n                                &dense_gathered));\n    bool op_is_div = false;\n    if (absl::StrContains(ctx->op_kernel().type_string_view(), \"Div\")) {\n      op_is_div = true;\n    }\n    // Pulls relevant entries from the dense side, with reshape and broadcasting\n    // *of the dense side* taken into account.  Use a TensorRef to avoid blowing\n    // up memory.\n    //\n    // We can directly use the sparse indices to look up dense side, because\n    // \"b.y_reshape()\" and \"b.y_bcast()\" are guaranteed to have rank \"ndims\".\n    auto dense_gathered_flat = dense_gathered.flat();\n    const int ndims = lhs_dims.size();\n    switch (ndims) {\n#define CASE(NDIM)                                                             \\\n  case NDIM: {                                                                 \\\n    TensorRef> rhs_ref =         \\\n        dense_t->shaped(b.y_reshape())                                \\\n            .broadcast(BCast::ToIndexArray(b.y_bcast()));                \\\n    Eigen::array idx;                                 \\\n    bool indices_valid = true;                                                 \\\n    for (int i = 0; i < nnz; ++i) {                                            \\\n      for (int d = 0; d < NDIM; ++d) {                                         \\\n        idx[d] = internal::SubtleMustCopy(indices_mat(i, d));                  \\\n        if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) {                  \\\n          indices_valid = false;                                               \\\n        }                                                                      \\\n      }                                                                        \\\n      OP_REQUIRES(                                                             \\\n          ctx, indices_valid,                                                  \\\n          errors::InvalidArgument(\"Provided indices are out-of-bounds w.r.t. \" \\\n                                  \"dense side with broadcasted shape\"));       \\\n      dense_gathered_flat(i) = rhs_ref.coeff(idx);                             \\\n      if (op_is_div) {                                                         \\\n        OP_REQUIRES(ctx, dense_gathered_flat(i) != 0,                          \\\n                    errors::InvalidArgument(                                   \\\n                        \"SparseDenseCwiseDiv cannot divide by zero,\"           \\\n                        \"but input dense tensor contains zero \"));             \\\n      }                                                                        \\\n    }                                                                          \\\n    break;                                                                     \\\n  }\n\n      CASE(1);\n      CASE(2);\n      CASE(3);\n      CASE(4);\n      CASE(5);\n      default:\n        OP_REQUIRES(\n            ctx, false,\n            errors::InvalidArgument(\"Only tensors with ranks between 1 and 5 \"\n                                    \"are currently supported.  Tensor rank: \",\n                                    ndims));\n#undef CASE\n    }\n\n    output_values->flat().device(ctx->eigen_device()) =\n        values_t->flat().binaryExpr(dense_gathered_flat,\n                                       typename Functor::func());\n  }", "func_hash": 278624482255408254449933942747189407257, "file_name": "sparse_dense_binary_op_shared.cc", "file_hash": 247841744604256295308587005697650201397, "cwe": ["CWE-190"], "cve": "CVE-2022-23567", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementations of `Sparse*Cwise*` ops are vulnerable to integer overflows. These can be used to trigger large allocations (so, OOM based denial of service) or `CHECK`-fails when building new `TensorShape` objects (so, assert failures based denial of service). We are missing some validation on the shapes of the input tensors as well as directly constructing a large `TensorShape` with user-provided dimensions. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23567"}
{"idx": 195343, "project": "tensorflow", "commit_id": "002408c3696b173863228223d535f9de72a101a9", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/002408c3696b173863228223d535f9de72a101a9", "commit_message": "Add negative bound check for row and column pooling_sequence in FractionalAvgPoolGrad op to avoid out of bound heap access\n\nPiperOrigin-RevId: 413837346\nChange-Id: I2b86034101df31bee161abcb781755e236c7bccd", "target": 1, "func": "  void Compute(OpKernelContext* context) override {\n    // Here's the basic idea:\n    // Batch and depth dimension are independent from row and col dimension. And\n    // because FractionalAvgPool currently only support pooling along row and\n    // col, we can basically think of this 4D tensor backpropagation as\n    // operation of a series of 2D planes.\n    //\n    // For each element of a 'slice' (2D plane) of output_backprop, we need to\n    // figure out its contributors when doing FractionalAvgPool operation. This\n    // can be done based on row_pooling_sequence, col_pooling_seq and\n    // overlapping.\n    // Once we figure out the original contributors, we just need to evenly\n    // divide the value of this element among these contributors.\n    //\n    // Internally, we divide the out_backprop tensor and store it in a temporary\n    // tensor of double type. And cast it to the corresponding type.\n    typedef Eigen::Map>\n        ConstEigenMatrixMap;\n    typedef Eigen::Map>\n        EigenDoubleMatrixMap;\n\n    // Grab the inputs.\n    const Tensor& orig_input_tensor_shape = context->input(0);\n    OP_REQUIRES(context,\n                orig_input_tensor_shape.dims() == 1 &&\n                    orig_input_tensor_shape.NumElements() == 4,\n                errors::InvalidArgument(\"original input tensor shape must be\"\n                                        \"1-dimensional and 4 elements\"));\n    const Tensor& out_backprop = context->input(1);\n    const Tensor& row_seq_tensor = context->input(2);\n    const Tensor& col_seq_tensor = context->input(3);\n\n    const int64_t out_batch = out_backprop.dim_size(0);\n    const int64_t out_rows = out_backprop.dim_size(1);\n    const int64_t out_cols = out_backprop.dim_size(2);\n    const int64_t out_depth = out_backprop.dim_size(3);\n\n    OP_REQUIRES(context, row_seq_tensor.NumElements() > out_rows,\n                errors::InvalidArgument(\"Given out_backprop shape \",\n                                        out_backprop.shape().DebugString(),\n                                        \", row_seq_tensor must have at least \",\n                                        out_rows + 1, \" elements, but got \",\n                                        row_seq_tensor.NumElements()));\n    OP_REQUIRES(context, col_seq_tensor.NumElements() > out_cols,\n                errors::InvalidArgument(\"Given out_backprop shape \",\n                                        out_backprop.shape().DebugString(),\n                                        \", col_seq_tensor must have at least \",\n                                        out_cols + 1, \" elements, but got \",\n                                        col_seq_tensor.NumElements()));\n\n    auto row_seq_tensor_flat = row_seq_tensor.flat();\n    auto col_seq_tensor_flat = col_seq_tensor.flat();\n    auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat();\n\n    const int64_t in_batch = orig_input_tensor_shape_flat(0);\n    const int64_t in_rows = orig_input_tensor_shape_flat(1);\n    const int64_t in_cols = orig_input_tensor_shape_flat(2);\n    const int64_t in_depth = orig_input_tensor_shape_flat(3);\n    OP_REQUIRES(\n        context, in_batch != 0,\n        errors::InvalidArgument(\"Batch dimension of input must not be 0\"));\n    OP_REQUIRES(\n        context, in_rows != 0,\n        errors::InvalidArgument(\"Rows dimension of input must not be 0\"));\n    OP_REQUIRES(\n        context, in_cols != 0,\n        errors::InvalidArgument(\"Columns dimension of input must not be 0\"));\n    OP_REQUIRES(\n        context, in_depth != 0,\n        errors::InvalidArgument(\"Depth dimension of input must not be 0\"));\n\n    constexpr int tensor_in_and_out_dims = 4;\n    // Transform orig_input_tensor_shape into TensorShape\n    TensorShape in_shape;\n    for (auto i = 0; i < tensor_in_and_out_dims; ++i) {\n      in_shape.AddDim(orig_input_tensor_shape_flat(i));\n    }\n\n    // Create intermediate in_backprop.\n    Tensor in_backprop_tensor_temp;\n    OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(\n                                {0}, DataTypeToEnum::v(), in_shape,\n                                &in_backprop_tensor_temp));\n    in_backprop_tensor_temp.flat().setZero();\n    // Transform 4D tensor to 2D matrix.\n    EigenDoubleMatrixMap in_backprop_tensor_temp_mat(\n        in_backprop_tensor_temp.flat().data(), in_depth,\n        in_cols * in_rows * in_batch);\n    ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(),\n                                         out_depth,\n                                         out_cols * out_rows * out_batch);\n    // Loop through each element of out_backprop and evenly distribute the\n    // element to the corresponding pooling cell.\n    const int64_t in_max_row_index = in_rows - 1;\n    const int64_t in_max_col_index = in_cols - 1;\n    for (int64_t b = 0; b < out_batch; ++b) {\n      for (int64_t r = 0; r < out_rows; ++r) {\n        const int64_t in_row_start = row_seq_tensor_flat(r);\n        int64_t in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)\n                                          : row_seq_tensor_flat(r + 1) - 1;\n        in_row_end = std::min(in_row_end, in_max_row_index);\n        for (int64_t c = 0; c < out_cols; ++c) {\n          const int64_t in_col_start = col_seq_tensor_flat(c);\n          int64_t in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)\n                                            : col_seq_tensor_flat(c + 1) - 1;\n          in_col_end = std::min(in_col_end, in_max_col_index);\n\n          const int64_t num_elements_in_pooling_cell =\n              (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);\n          const int64_t out_index = (b * out_rows + r) * out_cols + c;\n          // Now we can evenly distribute out_backprop(b, h, w, *) to\n          // in_backprop(b, hs:he, ws:we, *).\n          for (int64_t in_r = in_row_start; in_r <= in_row_end; ++in_r) {\n            for (int64_t in_c = in_col_start; in_c <= in_col_end; ++in_c) {\n              const int64_t in_index = (b * in_rows + in_r) * in_cols + in_c;\n              // Walk through each channel (depth).\n              for (int64_t d = 0; d < out_depth; ++d) {\n                const double out_backprop_element = static_cast(\n                    out_backprop_mat.coeffRef(d, out_index));\n                double& in_backprop_ref =\n                    in_backprop_tensor_temp_mat.coeffRef(d, in_index);\n                in_backprop_ref +=\n                    out_backprop_element / num_elements_in_pooling_cell;\n              }\n            }\n          }\n        }\n      }\n    }\n\n    // Depending on the type, cast double to type T.\n    Tensor* in_backprop_tensor = nullptr;\n    OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n                                {0}, 0, in_shape, &in_backprop_tensor));\n    auto in_backprop_tensor_flat = in_backprop_tensor->flat();\n    auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat();\n    for (int64_t i = 0; i < in_backprop_tensor_flat.size(); ++i) {\n      in_backprop_tensor_flat(i) =\n          static_cast(in_backprop_tensor_temp_flat(i));\n    }\n  }", "func_hash": 91555834572386312187860770421206034544, "file_name": "fractional_avg_pool_op.cc", "file_hash": 221866619851129952189561551151828727755, "cwe": ["CWE-125"], "cve": "CVE-2022-21730", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `FractionalAvgPoolGrad` does not consider cases where the input tensors are invalid allowing an attacker to read from outside of bounds of heap. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21730"}
{"idx": 224891, "project": "tensorflow", "commit_id": "002408c3696b173863228223d535f9de72a101a9", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/002408c3696b173863228223d535f9de72a101a9", "commit_message": "Add negative bound check for row and column pooling_sequence in FractionalAvgPoolGrad op to avoid out of bound heap access\n\nPiperOrigin-RevId: 413837346\nChange-Id: I2b86034101df31bee161abcb781755e236c7bccd", "target": 0, "func": "  void Compute(OpKernelContext* context) override {\n    // Here's the basic idea:\n    // Batch and depth dimension are independent from row and col dimension. And\n    // because FractionalAvgPool currently only support pooling along row and\n    // col, we can basically think of this 4D tensor backpropagation as\n    // operation of a series of 2D planes.\n    //\n    // For each element of a 'slice' (2D plane) of output_backprop, we need to\n    // figure out its contributors when doing FractionalAvgPool operation. This\n    // can be done based on row_pooling_sequence, col_pooling_seq and\n    // overlapping.\n    // Once we figure out the original contributors, we just need to evenly\n    // divide the value of this element among these contributors.\n    //\n    // Internally, we divide the out_backprop tensor and store it in a temporary\n    // tensor of double type. And cast it to the corresponding type.\n    typedef Eigen::Map>\n        ConstEigenMatrixMap;\n    typedef Eigen::Map>\n        EigenDoubleMatrixMap;\n\n    // Grab the inputs.\n    const Tensor& orig_input_tensor_shape = context->input(0);\n    OP_REQUIRES(context,\n                orig_input_tensor_shape.dims() == 1 &&\n                    orig_input_tensor_shape.NumElements() == 4,\n                errors::InvalidArgument(\"original input tensor shape must be\"\n                                        \"1-dimensional and 4 elements\"));\n    const Tensor& out_backprop = context->input(1);\n    const Tensor& row_seq_tensor = context->input(2);\n    const Tensor& col_seq_tensor = context->input(3);\n\n    const int64_t out_batch = out_backprop.dim_size(0);\n    const int64_t out_rows = out_backprop.dim_size(1);\n    const int64_t out_cols = out_backprop.dim_size(2);\n    const int64_t out_depth = out_backprop.dim_size(3);\n\n    OP_REQUIRES(context, row_seq_tensor.NumElements() > out_rows,\n                errors::InvalidArgument(\"Given out_backprop shape \",\n                                        out_backprop.shape().DebugString(),\n                                        \", row_seq_tensor must have at least \",\n                                        out_rows + 1, \" elements, but got \",\n                                        row_seq_tensor.NumElements()));\n    OP_REQUIRES(context, col_seq_tensor.NumElements() > out_cols,\n                errors::InvalidArgument(\"Given out_backprop shape \",\n                                        out_backprop.shape().DebugString(),\n                                        \", col_seq_tensor must have at least \",\n                                        out_cols + 1, \" elements, but got \",\n                                        col_seq_tensor.NumElements()));\n\n    auto row_seq_tensor_flat = row_seq_tensor.flat();\n    auto col_seq_tensor_flat = col_seq_tensor.flat();\n    auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat();\n\n    const int64_t in_batch = orig_input_tensor_shape_flat(0);\n    const int64_t in_rows = orig_input_tensor_shape_flat(1);\n    const int64_t in_cols = orig_input_tensor_shape_flat(2);\n    const int64_t in_depth = orig_input_tensor_shape_flat(3);\n    OP_REQUIRES(\n        context, in_batch != 0,\n        errors::InvalidArgument(\"Batch dimension of input must not be 0\"));\n    OP_REQUIRES(\n        context, in_rows != 0,\n        errors::InvalidArgument(\"Rows dimension of input must not be 0\"));\n    OP_REQUIRES(\n        context, in_cols != 0,\n        errors::InvalidArgument(\"Columns dimension of input must not be 0\"));\n    OP_REQUIRES(\n        context, in_depth != 0,\n        errors::InvalidArgument(\"Depth dimension of input must not be 0\"));\n\n    constexpr int tensor_in_and_out_dims = 4;\n    // Transform orig_input_tensor_shape into TensorShape\n    TensorShape in_shape;\n    for (auto i = 0; i < tensor_in_and_out_dims; ++i) {\n      in_shape.AddDim(orig_input_tensor_shape_flat(i));\n    }\n\n    // Create intermediate in_backprop.\n    Tensor in_backprop_tensor_temp;\n    OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(\n                                {0}, DataTypeToEnum::v(), in_shape,\n                                &in_backprop_tensor_temp));\n    in_backprop_tensor_temp.flat().setZero();\n    // Transform 4D tensor to 2D matrix.\n    EigenDoubleMatrixMap in_backprop_tensor_temp_mat(\n        in_backprop_tensor_temp.flat().data(), in_depth,\n        in_cols * in_rows * in_batch);\n    ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(),\n                                         out_depth,\n                                         out_cols * out_rows * out_batch);\n    // Loop through each element of out_backprop and evenly distribute the\n    // element to the corresponding pooling cell.\n    const int64_t in_max_row_index = in_rows - 1;\n    const int64_t in_max_col_index = in_cols - 1;\n    for (int64_t b = 0; b < out_batch; ++b) {\n      for (int64_t r = 0; r < out_rows; ++r) {\n        const int64_t in_row_start = row_seq_tensor_flat(r);\n\n        int64_t in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)\n                                          : row_seq_tensor_flat(r + 1) - 1;\n        in_row_end = std::min(in_row_end, in_max_row_index);\n        OP_REQUIRES(context, in_row_start >= 0 && in_row_end >= 0,\n                    errors::InvalidArgument(\n                        \"Row sequence tensor values must not be negative, got \",\n                        row_seq_tensor_flat));\n\n        for (int64_t c = 0; c < out_cols; ++c) {\n          const int64_t in_col_start = col_seq_tensor_flat(c);\n          int64_t in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)\n                                            : col_seq_tensor_flat(c + 1) - 1;\n          in_col_end = std::min(in_col_end, in_max_col_index);\n\n          OP_REQUIRES(\n              context, in_col_start >= 0 && in_col_end >= 0,\n              errors::InvalidArgument(\n                  \"Column sequence tensor values must not be negative, got \",\n                  col_seq_tensor_flat));\n          const int64_t num_elements_in_pooling_cell =\n              (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);\n          const int64_t out_index = (b * out_rows + r) * out_cols + c;\n          // Now we can evenly distribute out_backprop(b, h, w, *) to\n          // in_backprop(b, hs:he, ws:we, *).\n          for (int64_t in_r = in_row_start; in_r <= in_row_end; ++in_r) {\n            for (int64_t in_c = in_col_start; in_c <= in_col_end; ++in_c) {\n              const int64_t in_index = (b * in_rows + in_r) * in_cols + in_c;\n              // Walk through each channel (depth).\n              for (int64_t d = 0; d < out_depth; ++d) {\n                const double out_backprop_element = static_cast(\n                    out_backprop_mat.coeffRef(d, out_index));\n                double& in_backprop_ref =\n                    in_backprop_tensor_temp_mat.coeffRef(d, in_index);\n                in_backprop_ref +=\n                    out_backprop_element / num_elements_in_pooling_cell;\n              }\n            }\n          }\n        }\n      }\n    }\n\n    // Depending on the type, cast double to type T.\n    Tensor* in_backprop_tensor = nullptr;\n    OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n                                {0}, 0, in_shape, &in_backprop_tensor));\n    auto in_backprop_tensor_flat = in_backprop_tensor->flat();\n    auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat();\n    for (int64_t i = 0; i < in_backprop_tensor_flat.size(); ++i) {\n      in_backprop_tensor_flat(i) =\n          static_cast(in_backprop_tensor_temp_flat(i));\n    }\n  }", "func_hash": 7916647560171328705762237734439424087, "file_name": "fractional_avg_pool_op.cc", "file_hash": 273616659727040190050886150342189772450, "cwe": ["CWE-125"], "cve": "CVE-2022-21730", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `FractionalAvgPoolGrad` does not consider cases where the input tensors are invalid allowing an attacker to read from outside of bounds of heap. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21730"}
{"idx": 195385, "project": "flatpak", "commit_id": "65cbfac982cb1c83993a9e19aa424daee8e9f042", "project_url": "https://github.com/flatpak/flatpak", "commit_url": "https://github.com/flatpak/flatpak/commit/65cbfac982cb1c83993a9e19aa424daee8e9f042", "commit_message": "Ensure that bundles have metadata on install\n\nIf we have a bundle without metadata we wouldn't properly present\nthe permissions in the transaction.", "target": 1, "func": "flatpak_dir_ensure_bundle_remote (FlatpakDir         *self,\n                                  GFile              *file,\n                                  GBytes             *extra_gpg_data,\n                                  FlatpakDecomposed **out_ref,\n                                  char              **out_checksum,\n                                  char              **out_metadata,\n                                  gboolean           *out_created_remote,\n                                  GCancellable       *cancellable,\n                                  GError            **error)\n{\n  g_autoptr(FlatpakDecomposed) ref = NULL;\n  gboolean created_remote = FALSE;\n  g_autoptr(GBytes) deploy_data = NULL;\n  g_autoptr(GVariant) metadata = NULL;\n  g_autofree char *origin = NULL;\n  g_autofree char *fp_metadata = NULL;\n  g_autofree char *basename = NULL;\n  g_autoptr(GBytes) included_gpg_data = NULL;\n  GBytes *gpg_data = NULL;\n  g_autofree char *to_checksum = NULL;\n  g_autofree char *remote = NULL;\n  g_autofree char *collection_id = NULL;\n\n  if (!flatpak_dir_ensure_repo (self, cancellable, error))\n    return NULL;\n\n  metadata = flatpak_bundle_load (file, &to_checksum,\n                                  &ref,\n                                  &origin,\n                                  NULL, &fp_metadata, NULL,\n                                  &included_gpg_data,\n                                  &collection_id,\n                                  error);\n  if (metadata == NULL)\n    return NULL;\n\n  gpg_data = extra_gpg_data ? extra_gpg_data : included_gpg_data;\n\n  deploy_data = flatpak_dir_get_deploy_data (self, ref, FLATPAK_DEPLOY_VERSION_ANY, cancellable, NULL);\n  if (deploy_data != NULL)\n    {\n      remote = g_strdup (flatpak_deploy_data_get_origin (deploy_data));\n\n      /* We need to import any gpg keys because otherwise the pull will fail */\n      if (gpg_data != NULL)\n        {\n          g_autoptr(GKeyFile) new_config = NULL;\n\n          new_config = ostree_repo_copy_config (flatpak_dir_get_repo (self));\n\n          if (!flatpak_dir_modify_remote (self, remote, new_config,\n                                          gpg_data, cancellable, error))\n            return NULL;\n        }\n    }\n  else\n    {\n      g_autofree char *id = flatpak_decomposed_dup_id (ref);\n      /* Add a remote for later updates */\n      basename = g_file_get_basename (file);\n      remote = flatpak_dir_create_origin_remote (self,\n                                                 origin,\n                                                 id,\n                                                 basename,\n                                                 flatpak_decomposed_get_ref (ref),\n                                                 gpg_data,\n                                                 collection_id,\n                                                 &created_remote,\n                                                 cancellable,\n                                                 error);\n      if (remote == NULL)\n        return NULL;\n    }\n\n  if (out_created_remote)\n    *out_created_remote = created_remote;\n\n  if (out_ref)\n    *out_ref = g_steal_pointer (&ref);\n\n  if (out_checksum)\n    *out_checksum = g_steal_pointer (&to_checksum);\n\n  if (out_metadata)\n    *out_metadata = g_steal_pointer (&fp_metadata);\n\n\n  return g_steal_pointer (&remote);\n}", "func_hash": 117751554146896350574194025697057651898, "file_name": "flatpak-dir.c", "file_hash": 41005800026546918810123079124181990480, "cwe": ["CWE-276"], "cve": "CVE-2021-43860", "cve_desc": "Flatpak is a Linux application sandboxing and distribution framework. Prior to versions 1.12.3 and 1.10.6, Flatpak doesn't properly validate that the permissions displayed to the user for an app at install time match the actual permissions granted to the app at runtime, in the case that there's a null byte in the metadata file of an app. Therefore apps can grant themselves permissions without the consent of the user. Flatpak shows permissions to the user during install by reading them from the \"xa.metadata\" key in the commit metadata. This cannot contain a null terminator, because it is an untrusted GVariant. Flatpak compares these permissions to the *actual* metadata, from the \"metadata\" file to ensure it wasn't lied to. However, the actual metadata contents are loaded in several places where they are read as simple C-style strings. That means that, if the metadata file includes a null terminator, only the content of the file from *before* the terminator gets compared to xa.metadata. Thus, any permissions that appear in the metadata file after a null terminator are applied at runtime but not shown to the user. So maliciously crafted apps can give themselves hidden permissions. Users who have Flatpaks installed from untrusted sources are at risk in case the Flatpak has a maliciously crafted metadata file, either initially or in an update. This issue is patched in versions 1.12.3 and 1.10.6. As a workaround, users can manually check the permissions of installed apps by checking the metadata file or the xa.metadata key on the commit metadata.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43860"}
{"idx": 224964, "project": "flatpak", "commit_id": "65cbfac982cb1c83993a9e19aa424daee8e9f042", "project_url": "https://github.com/flatpak/flatpak", "commit_url": "https://github.com/flatpak/flatpak/commit/65cbfac982cb1c83993a9e19aa424daee8e9f042", "commit_message": "Ensure that bundles have metadata on install\n\nIf we have a bundle without metadata we wouldn't properly present\nthe permissions in the transaction.", "target": 0, "func": "flatpak_dir_ensure_bundle_remote (FlatpakDir         *self,\n                                  GFile              *file,\n                                  GBytes             *extra_gpg_data,\n                                  FlatpakDecomposed **out_ref,\n                                  char              **out_checksum,\n                                  char              **out_metadata,\n                                  gboolean           *out_created_remote,\n                                  GCancellable       *cancellable,\n                                  GError            **error)\n{\n  g_autoptr(FlatpakDecomposed) ref = NULL;\n  gboolean created_remote = FALSE;\n  g_autoptr(GBytes) deploy_data = NULL;\n  g_autoptr(GVariant) metadata = NULL;\n  g_autofree char *origin = NULL;\n  g_autofree char *fp_metadata = NULL;\n  g_autofree char *basename = NULL;\n  g_autoptr(GBytes) included_gpg_data = NULL;\n  GBytes *gpg_data = NULL;\n  g_autofree char *to_checksum = NULL;\n  g_autofree char *remote = NULL;\n  g_autofree char *collection_id = NULL;\n\n  if (!flatpak_dir_ensure_repo (self, cancellable, error))\n    return NULL;\n\n  metadata = flatpak_bundle_load (file, &to_checksum,\n                                  &ref,\n                                  &origin,\n                                  NULL, &fp_metadata, NULL,\n                                  &included_gpg_data,\n                                  &collection_id,\n                                  error);\n  if (metadata == NULL)\n    return NULL;\n\n  /* If we rely on metadata (to e.g. print permissions), check it exists before creating the remote */\n  if (out_metadata && fp_metadata == NULL)\n    {\n      flatpak_fail_error (error, FLATPAK_ERROR_INVALID_DATA, \"No metadata in bundler header\");\n      return NULL;\n    }\n\n  gpg_data = extra_gpg_data ? extra_gpg_data : included_gpg_data;\n\n  deploy_data = flatpak_dir_get_deploy_data (self, ref, FLATPAK_DEPLOY_VERSION_ANY, cancellable, NULL);\n  if (deploy_data != NULL)\n    {\n      remote = g_strdup (flatpak_deploy_data_get_origin (deploy_data));\n\n      /* We need to import any gpg keys because otherwise the pull will fail */\n      if (gpg_data != NULL)\n        {\n          g_autoptr(GKeyFile) new_config = NULL;\n\n          new_config = ostree_repo_copy_config (flatpak_dir_get_repo (self));\n\n          if (!flatpak_dir_modify_remote (self, remote, new_config,\n                                          gpg_data, cancellable, error))\n            return NULL;\n        }\n    }\n  else\n    {\n      g_autofree char *id = flatpak_decomposed_dup_id (ref);\n      /* Add a remote for later updates */\n      basename = g_file_get_basename (file);\n      remote = flatpak_dir_create_origin_remote (self,\n                                                 origin,\n                                                 id,\n                                                 basename,\n                                                 flatpak_decomposed_get_ref (ref),\n                                                 gpg_data,\n                                                 collection_id,\n                                                 &created_remote,\n                                                 cancellable,\n                                                 error);\n      if (remote == NULL)\n        return NULL;\n    }\n\n  if (out_created_remote)\n    *out_created_remote = created_remote;\n\n  if (out_ref)\n    *out_ref = g_steal_pointer (&ref);\n\n  if (out_checksum)\n    *out_checksum = g_steal_pointer (&to_checksum);\n\n  if (out_metadata)\n    *out_metadata = g_steal_pointer (&fp_metadata);\n\n\n  return g_steal_pointer (&remote);\n}", "func_hash": 57199236180630525002318569009544856929, "file_name": "flatpak-dir.c", "file_hash": 126847826047276531038327785325265722415, "cwe": ["CWE-276"], "cve": "CVE-2021-43860", "cve_desc": "Flatpak is a Linux application sandboxing and distribution framework. Prior to versions 1.12.3 and 1.10.6, Flatpak doesn't properly validate that the permissions displayed to the user for an app at install time match the actual permissions granted to the app at runtime, in the case that there's a null byte in the metadata file of an app. Therefore apps can grant themselves permissions without the consent of the user. Flatpak shows permissions to the user during install by reading them from the \"xa.metadata\" key in the commit metadata. This cannot contain a null terminator, because it is an untrusted GVariant. Flatpak compares these permissions to the *actual* metadata, from the \"metadata\" file to ensure it wasn't lied to. However, the actual metadata contents are loaded in several places where they are read as simple C-style strings. That means that, if the metadata file includes a null terminator, only the content of the file from *before* the terminator gets compared to xa.metadata. Thus, any permissions that appear in the metadata file after a null terminator are applied at runtime but not shown to the user. So maliciously crafted apps can give themselves hidden permissions. Users who have Flatpaks installed from untrusted sources are at risk in case the Flatpak has a maliciously crafted metadata file, either initially or in an update. This issue is patched in versions 1.12.3 and 1.10.6. As a workaround, users can manually check the permissions of installed apps by checking the metadata file or the xa.metadata key on the commit metadata.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43860"}
{"idx": 195388, "project": "postgres", "commit_id": "160c0258802d10b0600d7671b1bbea55d8e17d45", "project_url": "https://github.com/postgres/postgres", "commit_url": "https://github.com/postgres/postgres/commit/160c0258802d10b0600d7671b1bbea55d8e17d45", "commit_message": "libpq: reject extraneous data after SSL or GSS encryption handshake.\n\nlibpq collects up to a bufferload of data whenever it reads data from\nthe socket.  When SSL or GSS encryption is requested during startup,\nany additional data received with the server's yes-or-no reply\nremained in the buffer, and would be treated as already-decrypted data\nonce the encryption handshake completed.  Thus, a man-in-the-middle\nwith the ability to inject data into the TCP connection could stuff\nsome cleartext data into the start of a supposedly encryption-protected\ndatabase session.\n\nThis could probably be abused to inject faked responses to the\nclient's first few queries, although other details of libpq's behavior\nmake that harder than it sounds.  A different line of attack is to\nexfiltrate the client's password, or other sensitive data that might\nbe sent early in the session.  That has been shown to be possible with\na server vulnerable to CVE-2021-23214.\n\nTo fix, throw a protocol-violation error if the internal buffer\nis not empty after the encryption handshake.\n\nOur thanks to Jacob Champion for reporting this problem.\n\nSecurity: CVE-2021-23222", "target": 1, "func": "PQconnectPoll(PGconn *conn)\n{\n\tbool\t\treset_connection_state_machine = false;\n\tbool\t\tneed_new_connection = false;\n\tPGresult   *res;\n\tchar\t\tsebuf[PG_STRERROR_R_BUFLEN];\n\tint\t\t\toptval;\n\n\tif (conn == NULL)\n\t\treturn PGRES_POLLING_FAILED;\n\n\t/* Get the new data */\n\tswitch (conn->status)\n\t{\n\t\t\t/*\n\t\t\t * We really shouldn't have been polled in these two cases, but we\n\t\t\t * can handle it.\n\t\t\t */\n\t\tcase CONNECTION_BAD:\n\t\t\treturn PGRES_POLLING_FAILED;\n\t\tcase CONNECTION_OK:\n\t\t\treturn PGRES_POLLING_OK;\n\n\t\t\t/* These are reading states */\n\t\tcase CONNECTION_AWAITING_RESPONSE:\n\t\tcase CONNECTION_AUTH_OK:\n\t\tcase CONNECTION_CHECK_WRITABLE:\n\t\tcase CONNECTION_CONSUME:\n\t\tcase CONNECTION_CHECK_STANDBY:\n\t\t\t{\n\t\t\t\t/* Load waiting data */\n\t\t\t\tint\t\t\tn = pqReadData(conn);\n\n\t\t\t\tif (n < 0)\n\t\t\t\t\tgoto error_return;\n\t\t\t\tif (n == 0)\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* These are writing states, so we just proceed. */\n\t\tcase CONNECTION_STARTED:\n\t\tcase CONNECTION_MADE:\n\t\t\tbreak;\n\n\t\t\t/* Special cases: proceed without waiting. */\n\t\tcase CONNECTION_SSL_STARTUP:\n\t\tcase CONNECTION_NEEDED:\n\t\tcase CONNECTION_GSS_STARTUP:\n\t\tcase CONNECTION_CHECK_TARGET:\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t libpq_gettext(\"invalid connection state, probably indicative of memory corruption\\n\"));\n\t\t\tgoto error_return;\n\t}\n\n\nkeep_going:\t\t\t\t\t\t/* We will come back to here until there is\n\t\t\t\t\t\t\t\t * nothing left to do. */\n\n\t/* Time to advance to next address, or next host if no more addresses? */\n\tif (conn->try_next_addr)\n\t{\n\t\tif (conn->addr_cur && conn->addr_cur->ai_next)\n\t\t{\n\t\t\tconn->addr_cur = conn->addr_cur->ai_next;\n\t\t\treset_connection_state_machine = true;\n\t\t}\n\t\telse\n\t\t\tconn->try_next_host = true;\n\t\tconn->try_next_addr = false;\n\t}\n\n\t/* Time to advance to next connhost[] entry? */\n\tif (conn->try_next_host)\n\t{\n\t\tpg_conn_host *ch;\n\t\tstruct addrinfo hint;\n\t\tint\t\t\tthisport;\n\t\tint\t\t\tret;\n\t\tchar\t\tportstr[MAXPGPATH];\n\n\t\tif (conn->whichhost + 1 < conn->nconnhost)\n\t\t\tconn->whichhost++;\n\t\telse\n\t\t{\n\t\t\t/*\n\t\t\t * Oops, no more hosts.\n\t\t\t *\n\t\t\t * If we are trying to connect in \"prefer-standby\" mode, then drop\n\t\t\t * the standby requirement and start over.\n\t\t\t *\n\t\t\t * Otherwise, an appropriate error message is already set up, so\n\t\t\t * we just need to set the right status.\n\t\t\t */\n\t\t\tif (conn->target_server_type == SERVER_TYPE_PREFER_STANDBY &&\n\t\t\t\tconn->nconnhost > 0)\n\t\t\t{\n\t\t\t\tconn->target_server_type = SERVER_TYPE_PREFER_STANDBY_PASS2;\n\t\t\t\tconn->whichhost = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t\tgoto error_return;\n\t\t}\n\n\t\t/* Drop any address info for previous host */\n\t\trelease_conn_addrinfo(conn);\n\n\t\t/*\n\t\t * Look up info for the new host.  On failure, log the problem in\n\t\t * conn->errorMessage, then loop around to try the next host.  (Note\n\t\t * we don't clear try_next_host until we've succeeded.)\n\t\t */\n\t\tch = &conn->connhost[conn->whichhost];\n\n\t\t/* Initialize hint structure */\n\t\tMemSet(&hint, 0, sizeof(hint));\n\t\thint.ai_socktype = SOCK_STREAM;\n\t\tconn->addrlist_family = hint.ai_family = AF_UNSPEC;\n\n\t\t/* Figure out the port number we're going to use. */\n\t\tif (ch->port == NULL || ch->port[0] == '\\0')\n\t\t\tthisport = DEF_PGPORT;\n\t\telse\n\t\t{\n\t\t\tif (!parse_int_param(ch->port, &thisport, conn, \"port\"))\n\t\t\t\tgoto error_return;\n\n\t\t\tif (thisport < 1 || thisport > 65535)\n\t\t\t{\n\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t  libpq_gettext(\"invalid port number: \\\"%s\\\"\\n\"),\n\t\t\t\t\t\t\t\t  ch->port);\n\t\t\t\tgoto keep_going;\n\t\t\t}\n\t\t}\n\t\tsnprintf(portstr, sizeof(portstr), \"%d\", thisport);\n\n\t\t/* Use pg_getaddrinfo_all() to resolve the address */\n\t\tswitch (ch->type)\n\t\t{\n\t\t\tcase CHT_HOST_NAME:\n\t\t\t\tret = pg_getaddrinfo_all(ch->host, portstr, &hint,\n\t\t\t\t\t\t\t\t\t\t &conn->addrlist);\n\t\t\t\tif (ret || !conn->addrlist)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not translate host name \\\"%s\\\" to address: %s\\n\"),\n\t\t\t\t\t\t\t\t\t  ch->host, gai_strerror(ret));\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CHT_HOST_ADDRESS:\n\t\t\t\thint.ai_flags = AI_NUMERICHOST;\n\t\t\t\tret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,\n\t\t\t\t\t\t\t\t\t\t &conn->addrlist);\n\t\t\t\tif (ret || !conn->addrlist)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not parse network address \\\"%s\\\": %s\\n\"),\n\t\t\t\t\t\t\t\t\t  ch->hostaddr, gai_strerror(ret));\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CHT_UNIX_SOCKET:\n#ifdef HAVE_UNIX_SOCKETS\n\t\t\t\tconn->addrlist_family = hint.ai_family = AF_UNIX;\n\t\t\t\tUNIXSOCK_PATH(portstr, thisport, ch->host);\n\t\t\t\tif (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"Unix-domain socket path \\\"%s\\\" is too long (maximum %d bytes)\\n\"),\n\t\t\t\t\t\t\t\t\t  portstr,\n\t\t\t\t\t\t\t\t\t  (int) (UNIXSOCK_PATH_BUFLEN - 1));\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * NULL hostname tells pg_getaddrinfo_all to parse the service\n\t\t\t\t * name as a Unix-domain socket path.\n\t\t\t\t */\n\t\t\t\tret = pg_getaddrinfo_all(NULL, portstr, &hint,\n\t\t\t\t\t\t\t\t\t\t &conn->addrlist);\n\t\t\t\tif (ret || !conn->addrlist)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not translate Unix-domain socket path \\\"%s\\\" to address: %s\\n\"),\n\t\t\t\t\t\t\t\t\t  portstr, gai_strerror(ret));\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n#else\n\t\t\t\tAssert(false);\n#endif\n\t\t\t\tbreak;\n\t\t}\n\n\t\t/* OK, scan this addrlist for a working server address */\n\t\tconn->addr_cur = conn->addrlist;\n\t\treset_connection_state_machine = true;\n\t\tconn->try_next_host = false;\n\t}\n\n\t/* Reset connection state machine? */\n\tif (reset_connection_state_machine)\n\t{\n\t\t/*\n\t\t * (Re) initialize our connection control variables for a set of\n\t\t * connection attempts to a single server address.  These variables\n\t\t * must persist across individual connection attempts, but we must\n\t\t * reset them when we start to consider a new server.\n\t\t */\n\t\tconn->pversion = PG_PROTOCOL(3, 0);\n\t\tconn->send_appname = true;\n#ifdef USE_SSL\n\t\t/* initialize these values based on SSL mode */\n\t\tconn->allow_ssl_try = (conn->sslmode[0] != 'd');\t/* \"disable\" */\n\t\tconn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* \"allow\" */\n#endif\n#ifdef ENABLE_GSS\n\t\tconn->try_gss = (conn->gssencmode[0] != 'd');\t/* \"disable\" */\n#endif\n\n\t\treset_connection_state_machine = false;\n\t\tneed_new_connection = true;\n\t}\n\n\t/* Force a new connection (perhaps to the same server as before)? */\n\tif (need_new_connection)\n\t{\n\t\t/* Drop any existing connection */\n\t\tpqDropConnection(conn, true);\n\n\t\t/* Reset all state obtained from old server */\n\t\tpqDropServerData(conn);\n\n\t\t/* Drop any PGresult we might have, too */\n\t\tconn->asyncStatus = PGASYNC_IDLE;\n\t\tconn->xactStatus = PQTRANS_IDLE;\n\t\tconn->pipelineStatus = PQ_PIPELINE_OFF;\n\t\tpqClearAsyncResult(conn);\n\n\t\t/* Reset conn->status to put the state machine in the right state */\n\t\tconn->status = CONNECTION_NEEDED;\n\n\t\tneed_new_connection = false;\n\t}\n\n\t/* Now try to advance the state machine for this connection */\n\tswitch (conn->status)\n\t{\n\t\tcase CONNECTION_NEEDED:\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Try to initiate a connection to one of the addresses\n\t\t\t\t * returned by pg_getaddrinfo_all().  conn->addr_cur is the\n\t\t\t\t * next one to try.\n\t\t\t\t *\n\t\t\t\t * The extra level of braces here is historical.  It's not\n\t\t\t\t * worth reindenting this whole switch case to remove 'em.\n\t\t\t\t */\n\t\t\t\t{\n\t\t\t\t\tstruct addrinfo *addr_cur = conn->addr_cur;\n\t\t\t\t\tchar\t\thost_addr[NI_MAXHOST];\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Advance to next possible host, if we've tried all of\n\t\t\t\t\t * the addresses for the current host.\n\t\t\t\t\t */\n\t\t\t\t\tif (addr_cur == NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tconn->try_next_host = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Remember current address for possible use later */\n\t\t\t\t\tmemcpy(&conn->raddr.addr, addr_cur->ai_addr,\n\t\t\t\t\t\t   addr_cur->ai_addrlen);\n\t\t\t\t\tconn->raddr.salen = addr_cur->ai_addrlen;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Set connip, too.  Note we purposely ignore strdup\n\t\t\t\t\t * failure; not a big problem if it fails.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->connip != NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tfree(conn->connip);\n\t\t\t\t\t\tconn->connip = NULL;\n\t\t\t\t\t}\n\t\t\t\t\tgetHostaddr(conn, host_addr, NI_MAXHOST);\n\t\t\t\t\tif (host_addr[0])\n\t\t\t\t\t\tconn->connip = strdup(host_addr);\n\n\t\t\t\t\t/* Try to create the socket */\n\t\t\t\t\tconn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);\n\t\t\t\t\tif (conn->sock == PGINVALID_SOCKET)\n\t\t\t\t\t{\n\t\t\t\t\t\tint\t\t\terrorno = SOCK_ERRNO;\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Silently ignore socket() failure if we have more\n\t\t\t\t\t\t * addresses to try; this reduces useless chatter in\n\t\t\t\t\t\t * cases where the address list includes both IPv4 and\n\t\t\t\t\t\t * IPv6 but kernel only accepts one family.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (addr_cur->ai_next != NULL ||\n\t\t\t\t\t\t\tconn->whichhost + 1 < conn->nconnhost)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t\t}\n\t\t\t\t\t\temitHostIdentityInfo(conn, host_addr);\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not create socket: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Once we've identified a target address, all errors\n\t\t\t\t\t * except the preceding socket()-failure case should be\n\t\t\t\t\t * prefixed with host-identity information.  (If the\n\t\t\t\t\t * connection succeeds, the contents of conn->errorMessage\n\t\t\t\t\t * won't matter, so this is harmless.)\n\t\t\t\t\t */\n\t\t\t\t\temitHostIdentityInfo(conn, host_addr);\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Select socket options: no delay of outgoing data for\n\t\t\t\t\t * TCP sockets, nonblock mode, close-on-exec.  Try the\n\t\t\t\t\t * next address if any of this fails.\n\t\t\t\t\t */\n\t\t\t\t\tif (!IS_AF_UNIX(addr_cur->ai_family))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!connectNoDelay(conn))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/* error message already created */\n\t\t\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!pg_set_noblock(conn->sock))\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not set socket to nonblocking mode: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\n#ifdef F_SETFD\n\t\t\t\t\tif (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not set socket to close-on-exec mode: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n#endif\t\t\t\t\t\t\t/* F_SETFD */\n\n\t\t\t\t\tif (!IS_AF_UNIX(addr_cur->ai_family))\n\t\t\t\t\t{\n#ifndef WIN32\n\t\t\t\t\t\tint\t\t\ton = 1;\n#endif\n\t\t\t\t\t\tint\t\t\tusekeepalives = useKeepalives(conn);\n\t\t\t\t\t\tint\t\t\terr = 0;\n\n\t\t\t\t\t\tif (usekeepalives < 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"keepalives parameter must be an integer\\n\"));\n\t\t\t\t\t\t\terr = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (usekeepalives == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/* Do nothing */\n\t\t\t\t\t\t}\n#ifndef WIN32\n\t\t\t\t\t\telse if (setsockopt(conn->sock,\n\t\t\t\t\t\t\t\t\t\t\tSOL_SOCKET, SO_KEEPALIVE,\n\t\t\t\t\t\t\t\t\t\t\t(char *) &on, sizeof(on)) < 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"%s(%s) failed: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t\t  \"setsockopt\",\n\t\t\t\t\t\t\t\t\t\t\t  \"SO_KEEPALIVE\",\n\t\t\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\t\terr = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (!setKeepalivesIdle(conn)\n\t\t\t\t\t\t\t\t || !setKeepalivesInterval(conn)\n\t\t\t\t\t\t\t\t || !setKeepalivesCount(conn))\n\t\t\t\t\t\t\terr = 1;\n#else\t\t\t\t\t\t\t/* WIN32 */\n#ifdef SIO_KEEPALIVE_VALS\n\t\t\t\t\t\telse if (!setKeepalivesWin32(conn))\n\t\t\t\t\t\t\terr = 1;\n#endif\t\t\t\t\t\t\t/* SIO_KEEPALIVE_VALS */\n#endif\t\t\t\t\t\t\t/* WIN32 */\n\t\t\t\t\t\telse if (!setTCPUserTimeout(conn))\n\t\t\t\t\t\t\terr = 1;\n\n\t\t\t\t\t\tif (err)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t/*----------\n\t\t\t\t\t * We have three methods of blocking SIGPIPE during\n\t\t\t\t\t * send() calls to this socket:\n\t\t\t\t\t *\n\t\t\t\t\t *\t- setsockopt(sock, SO_NOSIGPIPE)\n\t\t\t\t\t *\t- send(sock, ..., MSG_NOSIGNAL)\n\t\t\t\t\t *\t- setting the signal mask to SIG_IGN during send()\n\t\t\t\t\t *\n\t\t\t\t\t * The third method requires three syscalls per send,\n\t\t\t\t\t * so we prefer either of the first two, but they are\n\t\t\t\t\t * less portable.  The state is tracked in the following\n\t\t\t\t\t * members of PGconn:\n\t\t\t\t\t *\n\t\t\t\t\t * conn->sigpipe_so\t\t- we have set up SO_NOSIGPIPE\n\t\t\t\t\t * conn->sigpipe_flag\t- we're specifying MSG_NOSIGNAL\n\t\t\t\t\t *\n\t\t\t\t\t * If we can use SO_NOSIGPIPE, then set sigpipe_so here\n\t\t\t\t\t * and we're done.  Otherwise, set sigpipe_flag so that\n\t\t\t\t\t * we will try MSG_NOSIGNAL on sends.  If we get an error\n\t\t\t\t\t * with MSG_NOSIGNAL, we'll clear that flag and revert to\n\t\t\t\t\t * signal masking.\n\t\t\t\t\t *----------\n\t\t\t\t\t */\n\t\t\t\t\tconn->sigpipe_so = false;\n#ifdef MSG_NOSIGNAL\n\t\t\t\t\tconn->sigpipe_flag = true;\n#else\n\t\t\t\t\tconn->sigpipe_flag = false;\n#endif\t\t\t\t\t\t\t/* MSG_NOSIGNAL */\n\n#ifdef SO_NOSIGPIPE\n\t\t\t\t\toptval = 1;\n\t\t\t\t\tif (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,\n\t\t\t\t\t\t\t\t   (char *) &optval, sizeof(optval)) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tconn->sigpipe_so = true;\n\t\t\t\t\t\tconn->sigpipe_flag = false;\n\t\t\t\t\t}\n#endif\t\t\t\t\t\t\t/* SO_NOSIGPIPE */\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Start/make connection.  This should not block, since we\n\t\t\t\t\t * are in nonblock mode.  If it does, well, too bad.\n\t\t\t\t\t */\n\t\t\t\t\tif (connect(conn->sock, addr_cur->ai_addr,\n\t\t\t\t\t\t\t\taddr_cur->ai_addrlen) < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (SOCK_ERRNO == EINPROGRESS ||\n#ifdef WIN32\n\t\t\t\t\t\t\tSOCK_ERRNO == EWOULDBLOCK ||\n#endif\n\t\t\t\t\t\t\tSOCK_ERRNO == EINTR)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * This is fine - we're in non-blocking mode, and\n\t\t\t\t\t\t\t * the connection is in progress.  Tell caller to\n\t\t\t\t\t\t\t * wait for write-ready on socket.\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tconn->status = CONNECTION_STARTED;\n\t\t\t\t\t\t\treturn PGRES_POLLING_WRITING;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* otherwise, trouble */\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Hm, we're connected already --- seems the \"nonblock\n\t\t\t\t\t\t * connection\" wasn't.  Advance the state machine and\n\t\t\t\t\t\t * go do the next stuff.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->status = CONNECTION_STARTED;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\t * This connection failed.  Add the error report to\n\t\t\t\t\t * conn->errorMessage, then try the next address if any.\n\t\t\t\t\t */\n\t\t\t\t\tconnectFailureMessage(conn, SOCK_ERRNO);\n\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase CONNECTION_STARTED:\n\t\t\t{\n\t\t\t\tACCEPT_TYPE_ARG3 optlen = sizeof(optval);\n\n\t\t\t\t/*\n\t\t\t\t * Write ready, since we've made it here, so the connection\n\t\t\t\t * has been made ... or has failed.\n\t\t\t\t */\n\n\t\t\t\t/*\n\t\t\t\t * Now check (using getsockopt) that there is not an error\n\t\t\t\t * state waiting for us on the socket.\n\t\t\t\t */\n\n\t\t\t\tif (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,\n\t\t\t\t\t\t\t   (char *) &optval, &optlen) == -1)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not get socket error status: %s\\n\"),\n\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\t\t\t\telse if (optval != 0)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * When using a nonblocking connect, we will typically see\n\t\t\t\t\t * connect failures at this point, so provide a friendly\n\t\t\t\t\t * error message.\n\t\t\t\t\t */\n\t\t\t\t\tconnectFailureMessage(conn, optval);\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Try the next address if any, just as in the case where\n\t\t\t\t\t * connect() returned failure immediately.\n\t\t\t\t\t */\n\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\n\t\t\t\t/* Fill in the client address */\n\t\t\t\tconn->laddr.salen = sizeof(conn->laddr.addr);\n\t\t\t\tif (getsockname(conn->sock,\n\t\t\t\t\t\t\t\t(struct sockaddr *) &conn->laddr.addr,\n\t\t\t\t\t\t\t\t&conn->laddr.salen) < 0)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not get client address from socket: %s\\n\"),\n\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Make sure we can write before advancing to next step.\n\t\t\t\t */\n\t\t\t\tconn->status = CONNECTION_MADE;\n\t\t\t\treturn PGRES_POLLING_WRITING;\n\t\t\t}\n\n\t\tcase CONNECTION_MADE:\n\t\t\t{\n\t\t\t\tchar\t   *startpacket;\n\t\t\t\tint\t\t\tpacketlen;\n\n\t\t\t\t/*\n\t\t\t\t * Implement requirepeer check, if requested and it's a\n\t\t\t\t * Unix-domain socket.\n\t\t\t\t */\n\t\t\t\tif (conn->requirepeer && conn->requirepeer[0] &&\n\t\t\t\t\tIS_AF_UNIX(conn->raddr.addr.ss_family))\n\t\t\t\t{\n#ifndef WIN32\n\t\t\t\t\tchar\t\tpwdbuf[BUFSIZ];\n\t\t\t\t\tstruct passwd pass_buf;\n\t\t\t\t\tstruct passwd *pass;\n\t\t\t\t\tint\t\t\tpasserr;\n#endif\n\t\t\t\t\tuid_t\t\tuid;\n\t\t\t\t\tgid_t\t\tgid;\n\n\t\t\t\t\terrno = 0;\n\t\t\t\t\tif (getpeereid(conn->sock, &uid, &gid) != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Provide special error message if getpeereid is a\n\t\t\t\t\t\t * stub\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (errno == ENOSYS)\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"requirepeer parameter is not supported on this platform\\n\"));\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not get peer credentials: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t\t  strerror_r(errno, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\n#ifndef WIN32\n\t\t\t\t\tpasserr = pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);\n\t\t\t\t\tif (pass == NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (passerr != 0)\n\t\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not look up local user ID %d: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t\t  (int) uid,\n\t\t\t\t\t\t\t\t\t\t\t  strerror_r(passerr, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"local user with ID %d does not exist\\n\"),\n\t\t\t\t\t\t\t\t\t\t\t  (int) uid);\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (strcmp(pass->pw_name, conn->requirepeer) != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"requirepeer specifies \\\"%s\\\", but actual peer user name is \\\"%s\\\"\\n\"),\n\t\t\t\t\t\t\t\t\t\t  conn->requirepeer, pass->pw_name);\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n#else\t\t\t\t\t\t\t/* WIN32 */\n\t\t\t\t\t/* should have failed with ENOSYS above */\n\t\t\t\t\tAssert(false);\n#endif\t\t\t\t\t\t\t/* WIN32 */\n\t\t\t\t}\n\n\t\t\t\tif (IS_AF_UNIX(conn->raddr.addr.ss_family))\n\t\t\t\t{\n\t\t\t\t\t/* Don't request SSL or GSSAPI over Unix sockets */\n#ifdef USE_SSL\n\t\t\t\t\tconn->allow_ssl_try = false;\n#endif\n#ifdef ENABLE_GSS\n\t\t\t\t\tconn->try_gss = false;\n#endif\n\t\t\t\t}\n\n#ifdef ENABLE_GSS\n\n\t\t\t\t/*\n\t\t\t\t * If GSSAPI encryption is enabled, then call\n\t\t\t\t * pg_GSS_have_cred_cache() which will return true if we can\n\t\t\t\t * acquire credentials (and give us a handle to use in\n\t\t\t\t * conn->gcred), and then send a packet to the server asking\n\t\t\t\t * for GSSAPI Encryption (and skip past SSL negotiation and\n\t\t\t\t * regular startup below).\n\t\t\t\t */\n\t\t\t\tif (conn->try_gss && !conn->gctx)\n\t\t\t\t\tconn->try_gss = pg_GSS_have_cred_cache(&conn->gcred);\n\t\t\t\tif (conn->try_gss && !conn->gctx)\n\t\t\t\t{\n\t\t\t\t\tProtocolVersion pv = pg_hton32(NEGOTIATE_GSS_CODE);\n\n\t\t\t\t\tif (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not send GSSAPI negotiation packet: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Ok, wait for response */\n\t\t\t\t\tconn->status = CONNECTION_GSS_STARTUP;\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\t\t\t\telse if (!conn->gctx && conn->gssencmode[0] == 'r')\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)\\n\"));\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n#endif\n\n#ifdef USE_SSL\n\n\t\t\t\t/*\n\t\t\t\t * Enable the libcrypto callbacks before checking if SSL needs\n\t\t\t\t * to be done.  This is done before sending the startup packet\n\t\t\t\t * as depending on the type of authentication done, like MD5\n\t\t\t\t * or SCRAM that use cryptohashes, the callbacks would be\n\t\t\t\t * required even without a SSL connection\n\t\t\t\t */\n\t\t\t\tif (pqsecure_initialize(conn, false, true) < 0)\n\t\t\t\t\tgoto error_return;\n\n\t\t\t\t/*\n\t\t\t\t * If SSL is enabled and we haven't already got encryption of\n\t\t\t\t * some sort running, request SSL instead of sending the\n\t\t\t\t * startup message.\n\t\t\t\t */\n\t\t\t\tif (conn->allow_ssl_try && !conn->wait_ssl_try &&\n\t\t\t\t\t!conn->ssl_in_use\n#ifdef ENABLE_GSS\n\t\t\t\t\t&& !conn->gssenc\n#endif\n\t\t\t\t\t)\n\t\t\t\t{\n\t\t\t\t\tProtocolVersion pv;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Send the SSL request packet.\n\t\t\t\t\t *\n\t\t\t\t\t * Theoretically, this could block, but it really\n\t\t\t\t\t * shouldn't since we only got here if the socket is\n\t\t\t\t\t * write-ready.\n\t\t\t\t\t */\n\t\t\t\t\tpv = pg_hton32(NEGOTIATE_SSL_CODE);\n\t\t\t\t\tif (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not send SSL negotiation packet: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\t\t\t\t\t/* Ok, wait for response */\n\t\t\t\t\tconn->status = CONNECTION_SSL_STARTUP;\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n#endif\t\t\t\t\t\t\t/* USE_SSL */\n\n\t\t\t\t/*\n\t\t\t\t * Build the startup packet.\n\t\t\t\t */\n\t\t\t\tstartpacket = pqBuildStartupPacket3(conn, &packetlen,\n\t\t\t\t\t\t\t\t\t\t\t\t\tEnvironmentOptions);\n\t\t\t\tif (!startpacket)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"out of memory\\n\"));\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Send the startup packet.\n\t\t\t\t *\n\t\t\t\t * Theoretically, this could block, but it really shouldn't\n\t\t\t\t * since we only got here if the socket is write-ready.\n\t\t\t\t */\n\t\t\t\tif (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not send startup packet: %s\\n\"),\n\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\tfree(startpacket);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\tfree(startpacket);\n\n\t\t\t\tconn->status = CONNECTION_AWAITING_RESPONSE;\n\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Handle SSL negotiation: wait for postmaster messages and\n\t\t\t * respond as necessary.\n\t\t\t */\n\t\tcase CONNECTION_SSL_STARTUP:\n\t\t\t{\n#ifdef USE_SSL\n\t\t\t\tPostgresPollingStatusType pollres;\n\n\t\t\t\t/*\n\t\t\t\t * On first time through, get the postmaster's response to our\n\t\t\t\t * SSL negotiation packet.\n\t\t\t\t */\n\t\t\t\tif (!conn->ssl_in_use)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * We use pqReadData here since it has the logic to\n\t\t\t\t\t * distinguish no-data-yet from connection closure. Since\n\t\t\t\t\t * conn->ssl isn't set, a plain recv() will occur.\n\t\t\t\t\t */\n\t\t\t\t\tchar\t\tSSLok;\n\t\t\t\t\tint\t\t\trdresult;\n\n\t\t\t\t\trdresult = pqReadData(conn);\n\t\t\t\t\tif (rdresult < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* errorMessage is already filled in */\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\t\t\t\t\tif (rdresult == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* caller failed to wait for data */\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\t}\n\t\t\t\t\tif (pqGetc(&SSLok, conn) < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* should not happen really */\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\t}\n\t\t\t\t\tif (SSLok == 'S')\n\t\t\t\t\t{\n\t\t\t\t\t\t/* mark byte consumed */\n\t\t\t\t\t\tconn->inStart = conn->inCursor;\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Set up global SSL state if required.  The crypto\n\t\t\t\t\t\t * state has already been set if libpq took care of\n\t\t\t\t\t\t * doing that, so there is no need to make that happen\n\t\t\t\t\t\t * again.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (pqsecure_initialize(conn, true, false) != 0)\n\t\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\t\t\t\t\telse if (SSLok == 'N')\n\t\t\t\t\t{\n\t\t\t\t\t\t/* mark byte consumed */\n\t\t\t\t\t\tconn->inStart = conn->inCursor;\n\t\t\t\t\t\t/* OK to do without SSL? */\n\t\t\t\t\t\tif (conn->sslmode[0] == 'r' ||\t/* \"require\" */\n\t\t\t\t\t\t\tconn->sslmode[0] == 'v')\t/* \"verify-ca\" or\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"verify-full\" */\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/* Require SSL, but server does not want it */\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"server does not support SSL, but SSL was required\\n\"));\n\t\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* Otherwise, proceed with normal startup */\n\t\t\t\t\t\tconn->allow_ssl_try = false;\n\t\t\t\t\t\t/* We can proceed using this connection */\n\t\t\t\t\t\tconn->status = CONNECTION_MADE;\n\t\t\t\t\t\treturn PGRES_POLLING_WRITING;\n\t\t\t\t\t}\n\t\t\t\t\telse if (SSLok == 'E')\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Server failure of some sort, such as failure to\n\t\t\t\t\t\t * fork a backend process.  We need to process and\n\t\t\t\t\t\t * report the error message, which might be formatted\n\t\t\t\t\t\t * according to either protocol 2 or protocol 3.\n\t\t\t\t\t\t * Rather than duplicate the code for that, we flip\n\t\t\t\t\t\t * into AWAITING_RESPONSE state and let the code there\n\t\t\t\t\t\t * deal with it.  Note we have *not* consumed the \"E\"\n\t\t\t\t\t\t * byte here.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->status = CONNECTION_AWAITING_RESPONSE;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"received invalid response to SSL negotiation: %c\\n\"),\n\t\t\t\t\t\t\t\t\t\t  SSLok);\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Begin or continue the SSL negotiation process.\n\t\t\t\t */\n\t\t\t\tpollres = pqsecure_open_client(conn);\n\t\t\t\tif (pollres == PGRES_POLLING_OK)\n\t\t\t\t{\n\t\t\t\t\t/* SSL handshake done, ready to send startup packet */\n\t\t\t\t\tconn->status = CONNECTION_MADE;\n\t\t\t\t\treturn PGRES_POLLING_WRITING;\n\t\t\t\t}\n\t\t\t\tif (pollres == PGRES_POLLING_FAILED)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * Failed ... if sslmode is \"prefer\" then do a non-SSL\n\t\t\t\t\t * retry\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->sslmode[0] == 'p' /* \"prefer\" */\n\t\t\t\t\t\t&& conn->allow_ssl_try\t/* redundant? */\n\t\t\t\t\t\t&& !conn->wait_ssl_try) /* redundant? */\n\t\t\t\t\t{\n\t\t\t\t\t\t/* only retry once */\n\t\t\t\t\t\tconn->allow_ssl_try = false;\n\t\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\t\t\t\t\t/* Else it's a hard failure */\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\t\t\t\t/* Else, return POLLING_READING or POLLING_WRITING status */\n\t\t\t\treturn pollres;\n#else\t\t\t\t\t\t\t/* !USE_SSL */\n\t\t\t\t/* can't get here */\n\t\t\t\tgoto error_return;\n#endif\t\t\t\t\t\t\t/* USE_SSL */\n\t\t\t}\n\n\t\tcase CONNECTION_GSS_STARTUP:\n\t\t\t{\n#ifdef ENABLE_GSS\n\t\t\t\tPostgresPollingStatusType pollres;\n\n\t\t\t\t/*\n\t\t\t\t * If we haven't yet, get the postmaster's response to our\n\t\t\t\t * negotiation packet\n\t\t\t\t */\n\t\t\t\tif (conn->try_gss && !conn->gctx)\n\t\t\t\t{\n\t\t\t\t\tchar\t\tgss_ok;\n\t\t\t\t\tint\t\t\trdresult = pqReadData(conn);\n\n\t\t\t\t\tif (rdresult < 0)\n\t\t\t\t\t\t/* pqReadData fills in error message */\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\telse if (rdresult == 0)\n\t\t\t\t\t\t/* caller failed to wait for data */\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\tif (pqGetc(&gss_ok, conn) < 0)\n\t\t\t\t\t\t/* shouldn't happen... */\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\n\t\t\t\t\tif (gss_ok == 'E')\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Server failure of some sort.  Assume it's a\n\t\t\t\t\t\t * protocol version support failure, and let's see if\n\t\t\t\t\t\t * we can't recover (if it's not, we'll get a better\n\t\t\t\t\t\t * error message on retry).  Server gets fussy if we\n\t\t\t\t\t\t * don't hang up the socket, though.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->try_gss = false;\n\t\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* mark byte consumed */\n\t\t\t\t\tconn->inStart = conn->inCursor;\n\n\t\t\t\t\tif (gss_ok == 'N')\n\t\t\t\t\t{\n\t\t\t\t\t\t/* Server doesn't want GSSAPI; fall back if we can */\n\t\t\t\t\t\tif (conn->gssencmode[0] == 'r')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"server doesn't support GSSAPI encryption, but it was required\\n\"));\n\t\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconn->try_gss = false;\n\t\t\t\t\t\t/* We can proceed using this connection */\n\t\t\t\t\t\tconn->status = CONNECTION_MADE;\n\t\t\t\t\t\treturn PGRES_POLLING_WRITING;\n\t\t\t\t\t}\n\t\t\t\t\telse if (gss_ok != 'G')\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"received invalid response to GSSAPI negotiation: %c\\n\"),\n\t\t\t\t\t\t\t\t\t\t  gss_ok);\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/* Begin or continue GSSAPI negotiation */\n\t\t\t\tpollres = pqsecure_open_gss(conn);\n\t\t\t\tif (pollres == PGRES_POLLING_OK)\n\t\t\t\t{\n\t\t\t\t\t/* All set for startup packet */\n\t\t\t\t\tconn->status = CONNECTION_MADE;\n\t\t\t\t\treturn PGRES_POLLING_WRITING;\n\t\t\t\t}\n\t\t\t\telse if (pollres == PGRES_POLLING_FAILED &&\n\t\t\t\t\t\t conn->gssencmode[0] == 'p')\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * We failed, but we can retry on \"prefer\".  Have to drop\n\t\t\t\t\t * the current connection to do so, though.\n\t\t\t\t\t */\n\t\t\t\t\tconn->try_gss = false;\n\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\t\t\t\treturn pollres;\n#else\t\t\t\t\t\t\t/* !ENABLE_GSS */\n\t\t\t\t/* unreachable */\n\t\t\t\tgoto error_return;\n#endif\t\t\t\t\t\t\t/* ENABLE_GSS */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Handle authentication exchange: wait for postmaster messages\n\t\t\t * and respond as necessary.\n\t\t\t */\n\t\tcase CONNECTION_AWAITING_RESPONSE:\n\t\t\t{\n\t\t\t\tchar\t\tberesp;\n\t\t\t\tint\t\t\tmsgLength;\n\t\t\t\tint\t\t\tavail;\n\t\t\t\tAuthRequest areq;\n\t\t\t\tint\t\t\tres;\n\n\t\t\t\t/*\n\t\t\t\t * Scan the message from current point (note that if we find\n\t\t\t\t * the message is incomplete, we will return without advancing\n\t\t\t\t * inStart, and resume here next time).\n\t\t\t\t */\n\t\t\t\tconn->inCursor = conn->inStart;\n\n\t\t\t\t/* Read type byte */\n\t\t\t\tif (pqGetc(&beresp, conn))\n\t\t\t\t{\n\t\t\t\t\t/* We'll come back when there is more data */\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Validate message type: we expect only an authentication\n\t\t\t\t * request or an error here.  Anything else probably means\n\t\t\t\t * it's not Postgres on the other end at all.\n\t\t\t\t */\n\t\t\t\tif (!(beresp == 'R' || beresp == 'E'))\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"expected authentication request from server, but received %c\\n\"),\n\t\t\t\t\t\t\t\t\t  beresp);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t/* Read message length word */\n\t\t\t\tif (pqGetInt(&msgLength, 4, conn))\n\t\t\t\t{\n\t\t\t\t\t/* We'll come back when there is more data */\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Try to validate message length before using it.\n\t\t\t\t * Authentication requests can't be very large, although GSS\n\t\t\t\t * auth requests may not be that small.  Errors can be a\n\t\t\t\t * little larger, but not huge.  If we see a large apparent\n\t\t\t\t * length in an error, it means we're really talking to a\n\t\t\t\t * pre-3.0-protocol server; cope.  (Before version 14, the\n\t\t\t\t * server also used the old protocol for errors that happened\n\t\t\t\t * before processing the startup packet.)\n\t\t\t\t */\n\t\t\t\tif (beresp == 'R' && (msgLength < 8 || msgLength > 2000))\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"expected authentication request from server, but received %c\\n\"),\n\t\t\t\t\t\t\t\t\t  beresp);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\tif (beresp == 'E' && (msgLength < 8 || msgLength > 30000))\n\t\t\t\t{\n\t\t\t\t\t/* Handle error from a pre-3.0 server */\n\t\t\t\t\tconn->inCursor = conn->inStart + 1; /* reread data */\n\t\t\t\t\tif (pqGets_append(&conn->errorMessage, conn))\n\t\t\t\t\t{\n\t\t\t\t\t\t/* We'll come back when there is more data */\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\t}\n\t\t\t\t\t/* OK, we read the message; mark data consumed */\n\t\t\t\t\tconn->inStart = conn->inCursor;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Before 7.2, the postmaster didn't always end its\n\t\t\t\t\t * messages with a newline, so add one if needed to\n\t\t\t\t\t * conform to libpq conventions.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->errorMessage.len == 0 ||\n\t\t\t\t\t\tconn->errorMessage.data[conn->errorMessage.len - 1] != '\\n')\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBufferChar(&conn->errorMessage, '\\n');\n\t\t\t\t\t}\n\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Can't process if message body isn't all here yet.\n\t\t\t\t */\n\t\t\t\tmsgLength -= 4;\n\t\t\t\tavail = conn->inEnd - conn->inCursor;\n\t\t\t\tif (avail < msgLength)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * Before returning, try to enlarge the input buffer if\n\t\t\t\t\t * needed to hold the whole message; see notes in\n\t\t\t\t\t * pqParseInput3.\n\t\t\t\t\t */\n\t\t\t\t\tif (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,\n\t\t\t\t\t\t\t\t\t\t\t conn))\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t/* We'll come back when there is more data */\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\t/* Handle errors. */\n\t\t\t\tif (beresp == 'E')\n\t\t\t\t{\n\t\t\t\t\tif (pqGetErrorNotice3(conn, true))\n\t\t\t\t\t{\n\t\t\t\t\t\t/* We'll come back when there is more data */\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\t}\n\t\t\t\t\t/* OK, we read the message; mark data consumed */\n\t\t\t\t\tconn->inStart = conn->inCursor;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * If error is \"cannot connect now\", try the next host if\n\t\t\t\t\t * any (but we don't want to consider additional addresses\n\t\t\t\t\t * for this host, nor is there much point in changing SSL\n\t\t\t\t\t * or GSS mode).  This is helpful when dealing with\n\t\t\t\t\t * standby servers that might not be in hot-standby state.\n\t\t\t\t\t */\n\t\t\t\t\tif (strcmp(conn->last_sqlstate,\n\t\t\t\t\t\t\t   ERRCODE_CANNOT_CONNECT_NOW) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tconn->try_next_host = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Check to see if we should mention pgpassfile */\n\t\t\t\t\tpgpassfileWarning(conn);\n\n#ifdef ENABLE_GSS\n\n\t\t\t\t\t/*\n\t\t\t\t\t * If gssencmode is \"prefer\" and we're using GSSAPI, retry\n\t\t\t\t\t * without it.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->gssenc && conn->gssencmode[0] == 'p')\n\t\t\t\t\t{\n\t\t\t\t\t\t/* only retry once */\n\t\t\t\t\t\tconn->try_gss = false;\n\t\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n#endif\n\n#ifdef USE_SSL\n\n\t\t\t\t\t/*\n\t\t\t\t\t * if sslmode is \"allow\" and we haven't tried an SSL\n\t\t\t\t\t * connection already, then retry with an SSL connection\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->sslmode[0] == 'a' /* \"allow\" */\n\t\t\t\t\t\t&& !conn->ssl_in_use\n\t\t\t\t\t\t&& conn->allow_ssl_try\n\t\t\t\t\t\t&& conn->wait_ssl_try)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* only retry once */\n\t\t\t\t\t\tconn->wait_ssl_try = false;\n\t\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\t * if sslmode is \"prefer\" and we're in an SSL connection,\n\t\t\t\t\t * then do a non-SSL retry\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->sslmode[0] == 'p' /* \"prefer\" */\n\t\t\t\t\t\t&& conn->ssl_in_use\n\t\t\t\t\t\t&& conn->allow_ssl_try\t/* redundant? */\n\t\t\t\t\t\t&& !conn->wait_ssl_try) /* redundant? */\n\t\t\t\t\t{\n\t\t\t\t\t\t/* only retry once */\n\t\t\t\t\t\tconn->allow_ssl_try = false;\n\t\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n#endif\n\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t/* It is an authentication request. */\n\t\t\t\tconn->auth_req_received = true;\n\n\t\t\t\t/* Get the type of request. */\n\t\t\t\tif (pqGetInt((int *) &areq, 4, conn))\n\t\t\t\t{\n\t\t\t\t\t/* We'll come back when there are more data */\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\t\t\t\tmsgLength -= 4;\n\n\t\t\t\t/*\n\t\t\t\t * Process the rest of the authentication request message, and\n\t\t\t\t * respond to it if necessary.\n\t\t\t\t *\n\t\t\t\t * Note that conn->pghost must be non-NULL if we are going to\n\t\t\t\t * avoid the Kerberos code doing a hostname look-up.\n\t\t\t\t */\n\t\t\t\tres = pg_fe_sendauth(areq, msgLength, conn);\n\n\t\t\t\t/* OK, we have processed the message; mark data consumed */\n\t\t\t\tconn->inStart = conn->inCursor;\n\n\t\t\t\tif (res != STATUS_OK)\n\t\t\t\t\tgoto error_return;\n\n\t\t\t\t/*\n\t\t\t\t * Just make sure that any data sent by pg_fe_sendauth is\n\t\t\t\t * flushed out.  Although this theoretically could block, it\n\t\t\t\t * really shouldn't since we don't send large auth responses.\n\t\t\t\t */\n\t\t\t\tif (pqFlush(conn))\n\t\t\t\t\tgoto error_return;\n\n\t\t\t\tif (areq == AUTH_REQ_OK)\n\t\t\t\t{\n\t\t\t\t\t/* We are done with authentication exchange */\n\t\t\t\t\tconn->status = CONNECTION_AUTH_OK;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Set asyncStatus so that PQgetResult will think that\n\t\t\t\t\t * what comes back next is the result of a query.  See\n\t\t\t\t\t * below.\n\t\t\t\t\t */\n\t\t\t\t\tconn->asyncStatus = PGASYNC_BUSY;\n\t\t\t\t}\n\n\t\t\t\t/* Look to see if we have more data yet. */\n\t\t\t\tgoto keep_going;\n\t\t\t}\n\n\t\tcase CONNECTION_AUTH_OK:\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Now we expect to hear from the backend. A ReadyForQuery\n\t\t\t\t * message indicates that startup is successful, but we might\n\t\t\t\t * also get an Error message indicating failure. (Notice\n\t\t\t\t * messages indicating nonfatal warnings are also allowed by\n\t\t\t\t * the protocol, as are ParameterStatus and BackendKeyData\n\t\t\t\t * messages.) Easiest way to handle this is to let\n\t\t\t\t * PQgetResult() read the messages. We just have to fake it\n\t\t\t\t * out about the state of the connection, by setting\n\t\t\t\t * asyncStatus = PGASYNC_BUSY (done above).\n\t\t\t\t */\n\n\t\t\t\tif (PQisBusy(conn))\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\n\t\t\t\tres = PQgetResult(conn);\n\n\t\t\t\t/*\n\t\t\t\t * NULL return indicating we have gone to IDLE state is\n\t\t\t\t * expected\n\t\t\t\t */\n\t\t\t\tif (res)\n\t\t\t\t{\n\t\t\t\t\tif (res->resultStatus != PGRES_FATAL_ERROR)\n\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"unexpected message from server during startup\\n\"));\n\t\t\t\t\telse if (conn->send_appname &&\n\t\t\t\t\t\t\t (conn->appname || conn->fbappname))\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * If we tried to send application_name, check to see\n\t\t\t\t\t\t * if the error is about that --- pre-9.0 servers will\n\t\t\t\t\t\t * reject it at this stage of the process.  If so,\n\t\t\t\t\t\t * close the connection and retry without sending\n\t\t\t\t\t\t * application_name.  We could possibly get a false\n\t\t\t\t\t\t * SQLSTATE match here and retry uselessly, but there\n\t\t\t\t\t\t * seems no great harm in that; we'll just get the\n\t\t\t\t\t\t * same error again if it's unrelated.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconst char *sqlstate;\n\n\t\t\t\t\t\tsqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);\n\t\t\t\t\t\tif (sqlstate &&\n\t\t\t\t\t\t\tstrcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPQclear(res);\n\t\t\t\t\t\t\tconn->send_appname = false;\n\t\t\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\t * if the resultStatus is FATAL, then conn->errorMessage\n\t\t\t\t\t * already has a copy of the error; needn't copy it back.\n\t\t\t\t\t * But add a newline if it's not there already, since\n\t\t\t\t\t * postmaster error messages may not have one.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->errorMessage.len <= 0 ||\n\t\t\t\t\t\tconn->errorMessage.data[conn->errorMessage.len - 1] != '\\n')\n\t\t\t\t\t\tappendPQExpBufferChar(&conn->errorMessage, '\\n');\n\t\t\t\t\tPQclear(res);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t/* Almost there now ... */\n\t\t\t\tconn->status = CONNECTION_CHECK_TARGET;\n\t\t\t\tgoto keep_going;\n\t\t\t}\n\n\t\tcase CONNECTION_CHECK_TARGET:\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * If a read-write, read-only, primary, or standby connection\n\t\t\t\t * is required, see if we have one.\n\t\t\t\t */\n\t\t\t\tif (conn->target_server_type == SERVER_TYPE_READ_WRITE ||\n\t\t\t\t\tconn->target_server_type == SERVER_TYPE_READ_ONLY)\n\t\t\t\t{\n\t\t\t\t\tbool\t\tread_only_server;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * If the server didn't report\n\t\t\t\t\t * \"default_transaction_read_only\" or \"in_hot_standby\" at\n\t\t\t\t\t * startup, we must determine its state by sending the\n\t\t\t\t\t * query \"SHOW transaction_read_only\".  This GUC exists in\n\t\t\t\t\t * all server versions that support 3.0 protocol.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->default_transaction_read_only == PG_BOOL_UNKNOWN ||\n\t\t\t\t\t\tconn->in_hot_standby == PG_BOOL_UNKNOWN)\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * We use PQsendQueryContinue so that\n\t\t\t\t\t\t * conn->errorMessage does not get cleared.  We need\n\t\t\t\t\t\t * to preserve any error messages related to previous\n\t\t\t\t\t\t * hosts we have tried and failed to connect to.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\t\t\tif (!PQsendQueryContinue(conn,\n\t\t\t\t\t\t\t\t\t\t\t\t \"SHOW transaction_read_only\"))\n\t\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t\t/* We'll return to this state when we have the answer */\n\t\t\t\t\t\tconn->status = CONNECTION_CHECK_WRITABLE;\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* OK, we can make the test */\n\t\t\t\t\tread_only_server =\n\t\t\t\t\t\t(conn->default_transaction_read_only == PG_BOOL_YES ||\n\t\t\t\t\t\t conn->in_hot_standby == PG_BOOL_YES);\n\n\t\t\t\t\tif ((conn->target_server_type == SERVER_TYPE_READ_WRITE) ?\n\t\t\t\t\t\tread_only_server : !read_only_server)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* Wrong server state, reject and try the next host */\n\t\t\t\t\t\tif (conn->target_server_type == SERVER_TYPE_READ_WRITE)\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"session is read-only\\n\"));\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"session is not read-only\\n\"));\n\n\t\t\t\t\t\t/* Close connection politely. */\n\t\t\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\t\t\tsendTerminateConn(conn);\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Try next host if any, but we don't want to consider\n\t\t\t\t\t\t * additional addresses for this host.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->try_next_host = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (conn->target_server_type == SERVER_TYPE_PRIMARY ||\n\t\t\t\t\t\t conn->target_server_type == SERVER_TYPE_STANDBY ||\n\t\t\t\t\t\t conn->target_server_type == SERVER_TYPE_PREFER_STANDBY)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * If the server didn't report \"in_hot_standby\" at\n\t\t\t\t\t * startup, we must determine its state by sending the\n\t\t\t\t\t * query \"SELECT pg_catalog.pg_is_in_recovery()\".  Servers\n\t\t\t\t\t * before 9.0 don't have that function, but by the same\n\t\t\t\t\t * token they don't have any standby mode, so we may just\n\t\t\t\t\t * assume the result.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->sversion < 90000)\n\t\t\t\t\t\tconn->in_hot_standby = PG_BOOL_NO;\n\n\t\t\t\t\tif (conn->in_hot_standby == PG_BOOL_UNKNOWN)\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * We use PQsendQueryContinue so that\n\t\t\t\t\t\t * conn->errorMessage does not get cleared.  We need\n\t\t\t\t\t\t * to preserve any error messages related to previous\n\t\t\t\t\t\t * hosts we have tried and failed to connect to.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\t\t\tif (!PQsendQueryContinue(conn,\n\t\t\t\t\t\t\t\t\t\t\t\t \"SELECT pg_catalog.pg_is_in_recovery()\"))\n\t\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t\t/* We'll return to this state when we have the answer */\n\t\t\t\t\t\tconn->status = CONNECTION_CHECK_STANDBY;\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* OK, we can make the test */\n\t\t\t\t\tif ((conn->target_server_type == SERVER_TYPE_PRIMARY) ?\n\t\t\t\t\t\t(conn->in_hot_standby == PG_BOOL_YES) :\n\t\t\t\t\t\t(conn->in_hot_standby == PG_BOOL_NO))\n\t\t\t\t\t{\n\t\t\t\t\t\t/* Wrong server state, reject and try the next host */\n\t\t\t\t\t\tif (conn->target_server_type == SERVER_TYPE_PRIMARY)\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"server is in hot standby mode\\n\"));\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"server is not in hot standby mode\\n\"));\n\n\t\t\t\t\t\t/* Close connection politely. */\n\t\t\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\t\t\tsendTerminateConn(conn);\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Try next host if any, but we don't want to consider\n\t\t\t\t\t\t * additional addresses for this host.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->try_next_host = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/* We can release the address list now. */\n\t\t\t\trelease_conn_addrinfo(conn);\n\n\t\t\t\t/*\n\t\t\t\t * Contents of conn->errorMessage are no longer interesting\n\t\t\t\t * (and it seems some clients expect it to be empty after a\n\t\t\t\t * successful connection).\n\t\t\t\t */\n\t\t\t\tresetPQExpBuffer(&conn->errorMessage);\n\n\t\t\t\t/* We are open for business! */\n\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\treturn PGRES_POLLING_OK;\n\t\t\t}\n\n\t\tcase CONNECTION_CONSUME:\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * This state just makes sure the connection is idle after\n\t\t\t\t * we've obtained the result of a SHOW or SELECT query.  Once\n\t\t\t\t * we're clear, return to CONNECTION_CHECK_TARGET state to\n\t\t\t\t * decide what to do next.  We must transiently set status =\n\t\t\t\t * CONNECTION_OK in order to use the result-consuming\n\t\t\t\t * subroutines.\n\t\t\t\t */\n\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\tif (!PQconsumeInput(conn))\n\t\t\t\t\tgoto error_return;\n\n\t\t\t\tif (PQisBusy(conn))\n\t\t\t\t{\n\t\t\t\t\tconn->status = CONNECTION_CONSUME;\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\t/* Call PQgetResult() again until we get a NULL result */\n\t\t\t\tres = PQgetResult(conn);\n\t\t\t\tif (res != NULL)\n\t\t\t\t{\n\t\t\t\t\tPQclear(res);\n\t\t\t\t\tconn->status = CONNECTION_CONSUME;\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\tconn->status = CONNECTION_CHECK_TARGET;\n\t\t\t\tgoto keep_going;\n\t\t\t}\n\n\t\tcase CONNECTION_CHECK_WRITABLE:\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Waiting for result of \"SHOW transaction_read_only\".  We\n\t\t\t\t * must transiently set status = CONNECTION_OK in order to use\n\t\t\t\t * the result-consuming subroutines.\n\t\t\t\t */\n\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\tif (!PQconsumeInput(conn))\n\t\t\t\t\tgoto error_return;\n\n\t\t\t\tif (PQisBusy(conn))\n\t\t\t\t{\n\t\t\t\t\tconn->status = CONNECTION_CHECK_WRITABLE;\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\tres = PQgetResult(conn);\n\t\t\t\tif (res && PQresultStatus(res) == PGRES_TUPLES_OK &&\n\t\t\t\t\tPQntuples(res) == 1)\n\t\t\t\t{\n\t\t\t\t\tchar\t   *val = PQgetvalue(res, 0, 0);\n\n\t\t\t\t\t/*\n\t\t\t\t\t * \"transaction_read_only = on\" proves that at least one\n\t\t\t\t\t * of default_transaction_read_only and in_hot_standby is\n\t\t\t\t\t * on, but we don't actually know which.  We don't care\n\t\t\t\t\t * though for the purpose of identifying a read-only\n\t\t\t\t\t * session, so satisfy the CONNECTION_CHECK_TARGET code by\n\t\t\t\t\t * claiming they are both on.  On the other hand, if it's\n\t\t\t\t\t * a read-write session, they are certainly both off.\n\t\t\t\t\t */\n\t\t\t\t\tif (strncmp(val, \"on\", 2) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tconn->default_transaction_read_only = PG_BOOL_YES;\n\t\t\t\t\t\tconn->in_hot_standby = PG_BOOL_YES;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tconn->default_transaction_read_only = PG_BOOL_NO;\n\t\t\t\t\t\tconn->in_hot_standby = PG_BOOL_NO;\n\t\t\t\t\t}\n\t\t\t\t\tPQclear(res);\n\n\t\t\t\t\t/* Finish reading messages before continuing */\n\t\t\t\t\tconn->status = CONNECTION_CONSUME;\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\n\t\t\t\t/* Something went wrong with \"SHOW transaction_read_only\". */\n\t\t\t\tif (res)\n\t\t\t\t\tPQclear(res);\n\n\t\t\t\t/* Append error report to conn->errorMessage. */\n\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t  libpq_gettext(\"\\\"%s\\\" failed\\n\"),\n\t\t\t\t\t\t\t\t  \"SHOW transaction_read_only\");\n\n\t\t\t\t/* Close connection politely. */\n\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\tsendTerminateConn(conn);\n\n\t\t\t\t/* Try next host. */\n\t\t\t\tconn->try_next_host = true;\n\t\t\t\tgoto keep_going;\n\t\t\t}\n\n\t\tcase CONNECTION_CHECK_STANDBY:\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Waiting for result of \"SELECT pg_is_in_recovery()\".  We\n\t\t\t\t * must transiently set status = CONNECTION_OK in order to use\n\t\t\t\t * the result-consuming subroutines.\n\t\t\t\t */\n\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\tif (!PQconsumeInput(conn))\n\t\t\t\t\tgoto error_return;\n\n\t\t\t\tif (PQisBusy(conn))\n\t\t\t\t{\n\t\t\t\t\tconn->status = CONNECTION_CHECK_STANDBY;\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\tres = PQgetResult(conn);\n\t\t\t\tif (res && PQresultStatus(res) == PGRES_TUPLES_OK &&\n\t\t\t\t\tPQntuples(res) == 1)\n\t\t\t\t{\n\t\t\t\t\tchar\t   *val = PQgetvalue(res, 0, 0);\n\n\t\t\t\t\tif (strncmp(val, \"t\", 1) == 0)\n\t\t\t\t\t\tconn->in_hot_standby = PG_BOOL_YES;\n\t\t\t\t\telse\n\t\t\t\t\t\tconn->in_hot_standby = PG_BOOL_NO;\n\t\t\t\t\tPQclear(res);\n\n\t\t\t\t\t/* Finish reading messages before continuing */\n\t\t\t\t\tconn->status = CONNECTION_CONSUME;\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\n\t\t\t\t/* Something went wrong with \"SELECT pg_is_in_recovery()\". */\n\t\t\t\tif (res)\n\t\t\t\t\tPQclear(res);\n\n\t\t\t\t/* Append error report to conn->errorMessage. */\n\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t  libpq_gettext(\"\\\"%s\\\" failed\\n\"),\n\t\t\t\t\t\t\t\t  \"SELECT pg_is_in_recovery()\");\n\n\t\t\t\t/* Close connection politely. */\n\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\tsendTerminateConn(conn);\n\n\t\t\t\t/* Try next host. */\n\t\t\t\tconn->try_next_host = true;\n\t\t\t\tgoto keep_going;\n\t\t\t}\n\n\t\tdefault:\n\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t  libpq_gettext(\"invalid connection state %d, \"\n\t\t\t\t\t\t\t\t\t\t\t\"probably indicative of memory corruption\\n\"),\n\t\t\t\t\t\t\t  conn->status);\n\t\t\tgoto error_return;\n\t}\n\n\t/* Unreachable */\n\nerror_return:\n\n\t/*\n\t * We used to close the socket at this point, but that makes it awkward\n\t * for those above us if they wish to remove this socket from their own\n\t * records (an fd_set for example).  We'll just have this socket closed\n\t * when PQfinish is called (which is compulsory even after an error, since\n\t * the connection structure must be freed).\n\t */\n\tconn->status = CONNECTION_BAD;\n\treturn PGRES_POLLING_FAILED;\n}", "func_hash": 145605680477709719969453491383463044279, "file_name": "fe-connect.c", "file_hash": 157537093140020562394962573075779914657, "cwe": ["CWE-522"], "cve": "CVE-2021-23222", "cve_desc": "A man-in-the-middle attacker can inject false responses to the client's first few queries, despite the use of SSL certificate verification and encryption.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-23222"}
{"idx": 225062, "project": "postgres", "commit_id": "160c0258802d10b0600d7671b1bbea55d8e17d45", "project_url": "https://github.com/postgres/postgres", "commit_url": "https://github.com/postgres/postgres/commit/160c0258802d10b0600d7671b1bbea55d8e17d45", "commit_message": "libpq: reject extraneous data after SSL or GSS encryption handshake.\n\nlibpq collects up to a bufferload of data whenever it reads data from\nthe socket.  When SSL or GSS encryption is requested during startup,\nany additional data received with the server's yes-or-no reply\nremained in the buffer, and would be treated as already-decrypted data\nonce the encryption handshake completed.  Thus, a man-in-the-middle\nwith the ability to inject data into the TCP connection could stuff\nsome cleartext data into the start of a supposedly encryption-protected\ndatabase session.\n\nThis could probably be abused to inject faked responses to the\nclient's first few queries, although other details of libpq's behavior\nmake that harder than it sounds.  A different line of attack is to\nexfiltrate the client's password, or other sensitive data that might\nbe sent early in the session.  That has been shown to be possible with\na server vulnerable to CVE-2021-23214.\n\nTo fix, throw a protocol-violation error if the internal buffer\nis not empty after the encryption handshake.\n\nOur thanks to Jacob Champion for reporting this problem.\n\nSecurity: CVE-2021-23222", "target": 0, "func": "PQconnectPoll(PGconn *conn)\n{\n\tbool\t\treset_connection_state_machine = false;\n\tbool\t\tneed_new_connection = false;\n\tPGresult   *res;\n\tchar\t\tsebuf[PG_STRERROR_R_BUFLEN];\n\tint\t\t\toptval;\n\n\tif (conn == NULL)\n\t\treturn PGRES_POLLING_FAILED;\n\n\t/* Get the new data */\n\tswitch (conn->status)\n\t{\n\t\t\t/*\n\t\t\t * We really shouldn't have been polled in these two cases, but we\n\t\t\t * can handle it.\n\t\t\t */\n\t\tcase CONNECTION_BAD:\n\t\t\treturn PGRES_POLLING_FAILED;\n\t\tcase CONNECTION_OK:\n\t\t\treturn PGRES_POLLING_OK;\n\n\t\t\t/* These are reading states */\n\t\tcase CONNECTION_AWAITING_RESPONSE:\n\t\tcase CONNECTION_AUTH_OK:\n\t\tcase CONNECTION_CHECK_WRITABLE:\n\t\tcase CONNECTION_CONSUME:\n\t\tcase CONNECTION_CHECK_STANDBY:\n\t\t\t{\n\t\t\t\t/* Load waiting data */\n\t\t\t\tint\t\t\tn = pqReadData(conn);\n\n\t\t\t\tif (n < 0)\n\t\t\t\t\tgoto error_return;\n\t\t\t\tif (n == 0)\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* These are writing states, so we just proceed. */\n\t\tcase CONNECTION_STARTED:\n\t\tcase CONNECTION_MADE:\n\t\t\tbreak;\n\n\t\t\t/* Special cases: proceed without waiting. */\n\t\tcase CONNECTION_SSL_STARTUP:\n\t\tcase CONNECTION_NEEDED:\n\t\tcase CONNECTION_GSS_STARTUP:\n\t\tcase CONNECTION_CHECK_TARGET:\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t libpq_gettext(\"invalid connection state, probably indicative of memory corruption\\n\"));\n\t\t\tgoto error_return;\n\t}\n\n\nkeep_going:\t\t\t\t\t\t/* We will come back to here until there is\n\t\t\t\t\t\t\t\t * nothing left to do. */\n\n\t/* Time to advance to next address, or next host if no more addresses? */\n\tif (conn->try_next_addr)\n\t{\n\t\tif (conn->addr_cur && conn->addr_cur->ai_next)\n\t\t{\n\t\t\tconn->addr_cur = conn->addr_cur->ai_next;\n\t\t\treset_connection_state_machine = true;\n\t\t}\n\t\telse\n\t\t\tconn->try_next_host = true;\n\t\tconn->try_next_addr = false;\n\t}\n\n\t/* Time to advance to next connhost[] entry? */\n\tif (conn->try_next_host)\n\t{\n\t\tpg_conn_host *ch;\n\t\tstruct addrinfo hint;\n\t\tint\t\t\tthisport;\n\t\tint\t\t\tret;\n\t\tchar\t\tportstr[MAXPGPATH];\n\n\t\tif (conn->whichhost + 1 < conn->nconnhost)\n\t\t\tconn->whichhost++;\n\t\telse\n\t\t{\n\t\t\t/*\n\t\t\t * Oops, no more hosts.\n\t\t\t *\n\t\t\t * If we are trying to connect in \"prefer-standby\" mode, then drop\n\t\t\t * the standby requirement and start over.\n\t\t\t *\n\t\t\t * Otherwise, an appropriate error message is already set up, so\n\t\t\t * we just need to set the right status.\n\t\t\t */\n\t\t\tif (conn->target_server_type == SERVER_TYPE_PREFER_STANDBY &&\n\t\t\t\tconn->nconnhost > 0)\n\t\t\t{\n\t\t\t\tconn->target_server_type = SERVER_TYPE_PREFER_STANDBY_PASS2;\n\t\t\t\tconn->whichhost = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t\tgoto error_return;\n\t\t}\n\n\t\t/* Drop any address info for previous host */\n\t\trelease_conn_addrinfo(conn);\n\n\t\t/*\n\t\t * Look up info for the new host.  On failure, log the problem in\n\t\t * conn->errorMessage, then loop around to try the next host.  (Note\n\t\t * we don't clear try_next_host until we've succeeded.)\n\t\t */\n\t\tch = &conn->connhost[conn->whichhost];\n\n\t\t/* Initialize hint structure */\n\t\tMemSet(&hint, 0, sizeof(hint));\n\t\thint.ai_socktype = SOCK_STREAM;\n\t\tconn->addrlist_family = hint.ai_family = AF_UNSPEC;\n\n\t\t/* Figure out the port number we're going to use. */\n\t\tif (ch->port == NULL || ch->port[0] == '\\0')\n\t\t\tthisport = DEF_PGPORT;\n\t\telse\n\t\t{\n\t\t\tif (!parse_int_param(ch->port, &thisport, conn, \"port\"))\n\t\t\t\tgoto error_return;\n\n\t\t\tif (thisport < 1 || thisport > 65535)\n\t\t\t{\n\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t  libpq_gettext(\"invalid port number: \\\"%s\\\"\\n\"),\n\t\t\t\t\t\t\t\t  ch->port);\n\t\t\t\tgoto keep_going;\n\t\t\t}\n\t\t}\n\t\tsnprintf(portstr, sizeof(portstr), \"%d\", thisport);\n\n\t\t/* Use pg_getaddrinfo_all() to resolve the address */\n\t\tswitch (ch->type)\n\t\t{\n\t\t\tcase CHT_HOST_NAME:\n\t\t\t\tret = pg_getaddrinfo_all(ch->host, portstr, &hint,\n\t\t\t\t\t\t\t\t\t\t &conn->addrlist);\n\t\t\t\tif (ret || !conn->addrlist)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not translate host name \\\"%s\\\" to address: %s\\n\"),\n\t\t\t\t\t\t\t\t\t  ch->host, gai_strerror(ret));\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CHT_HOST_ADDRESS:\n\t\t\t\thint.ai_flags = AI_NUMERICHOST;\n\t\t\t\tret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,\n\t\t\t\t\t\t\t\t\t\t &conn->addrlist);\n\t\t\t\tif (ret || !conn->addrlist)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not parse network address \\\"%s\\\": %s\\n\"),\n\t\t\t\t\t\t\t\t\t  ch->hostaddr, gai_strerror(ret));\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CHT_UNIX_SOCKET:\n#ifdef HAVE_UNIX_SOCKETS\n\t\t\t\tconn->addrlist_family = hint.ai_family = AF_UNIX;\n\t\t\t\tUNIXSOCK_PATH(portstr, thisport, ch->host);\n\t\t\t\tif (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"Unix-domain socket path \\\"%s\\\" is too long (maximum %d bytes)\\n\"),\n\t\t\t\t\t\t\t\t\t  portstr,\n\t\t\t\t\t\t\t\t\t  (int) (UNIXSOCK_PATH_BUFLEN - 1));\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * NULL hostname tells pg_getaddrinfo_all to parse the service\n\t\t\t\t * name as a Unix-domain socket path.\n\t\t\t\t */\n\t\t\t\tret = pg_getaddrinfo_all(NULL, portstr, &hint,\n\t\t\t\t\t\t\t\t\t\t &conn->addrlist);\n\t\t\t\tif (ret || !conn->addrlist)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not translate Unix-domain socket path \\\"%s\\\" to address: %s\\n\"),\n\t\t\t\t\t\t\t\t\t  portstr, gai_strerror(ret));\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n#else\n\t\t\t\tAssert(false);\n#endif\n\t\t\t\tbreak;\n\t\t}\n\n\t\t/* OK, scan this addrlist for a working server address */\n\t\tconn->addr_cur = conn->addrlist;\n\t\treset_connection_state_machine = true;\n\t\tconn->try_next_host = false;\n\t}\n\n\t/* Reset connection state machine? */\n\tif (reset_connection_state_machine)\n\t{\n\t\t/*\n\t\t * (Re) initialize our connection control variables for a set of\n\t\t * connection attempts to a single server address.  These variables\n\t\t * must persist across individual connection attempts, but we must\n\t\t * reset them when we start to consider a new server.\n\t\t */\n\t\tconn->pversion = PG_PROTOCOL(3, 0);\n\t\tconn->send_appname = true;\n#ifdef USE_SSL\n\t\t/* initialize these values based on SSL mode */\n\t\tconn->allow_ssl_try = (conn->sslmode[0] != 'd');\t/* \"disable\" */\n\t\tconn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* \"allow\" */\n#endif\n#ifdef ENABLE_GSS\n\t\tconn->try_gss = (conn->gssencmode[0] != 'd');\t/* \"disable\" */\n#endif\n\n\t\treset_connection_state_machine = false;\n\t\tneed_new_connection = true;\n\t}\n\n\t/* Force a new connection (perhaps to the same server as before)? */\n\tif (need_new_connection)\n\t{\n\t\t/* Drop any existing connection */\n\t\tpqDropConnection(conn, true);\n\n\t\t/* Reset all state obtained from old server */\n\t\tpqDropServerData(conn);\n\n\t\t/* Drop any PGresult we might have, too */\n\t\tconn->asyncStatus = PGASYNC_IDLE;\n\t\tconn->xactStatus = PQTRANS_IDLE;\n\t\tconn->pipelineStatus = PQ_PIPELINE_OFF;\n\t\tpqClearAsyncResult(conn);\n\n\t\t/* Reset conn->status to put the state machine in the right state */\n\t\tconn->status = CONNECTION_NEEDED;\n\n\t\tneed_new_connection = false;\n\t}\n\n\t/* Now try to advance the state machine for this connection */\n\tswitch (conn->status)\n\t{\n\t\tcase CONNECTION_NEEDED:\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Try to initiate a connection to one of the addresses\n\t\t\t\t * returned by pg_getaddrinfo_all().  conn->addr_cur is the\n\t\t\t\t * next one to try.\n\t\t\t\t *\n\t\t\t\t * The extra level of braces here is historical.  It's not\n\t\t\t\t * worth reindenting this whole switch case to remove 'em.\n\t\t\t\t */\n\t\t\t\t{\n\t\t\t\t\tstruct addrinfo *addr_cur = conn->addr_cur;\n\t\t\t\t\tchar\t\thost_addr[NI_MAXHOST];\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Advance to next possible host, if we've tried all of\n\t\t\t\t\t * the addresses for the current host.\n\t\t\t\t\t */\n\t\t\t\t\tif (addr_cur == NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tconn->try_next_host = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Remember current address for possible use later */\n\t\t\t\t\tmemcpy(&conn->raddr.addr, addr_cur->ai_addr,\n\t\t\t\t\t\t   addr_cur->ai_addrlen);\n\t\t\t\t\tconn->raddr.salen = addr_cur->ai_addrlen;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Set connip, too.  Note we purposely ignore strdup\n\t\t\t\t\t * failure; not a big problem if it fails.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->connip != NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tfree(conn->connip);\n\t\t\t\t\t\tconn->connip = NULL;\n\t\t\t\t\t}\n\t\t\t\t\tgetHostaddr(conn, host_addr, NI_MAXHOST);\n\t\t\t\t\tif (host_addr[0])\n\t\t\t\t\t\tconn->connip = strdup(host_addr);\n\n\t\t\t\t\t/* Try to create the socket */\n\t\t\t\t\tconn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);\n\t\t\t\t\tif (conn->sock == PGINVALID_SOCKET)\n\t\t\t\t\t{\n\t\t\t\t\t\tint\t\t\terrorno = SOCK_ERRNO;\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Silently ignore socket() failure if we have more\n\t\t\t\t\t\t * addresses to try; this reduces useless chatter in\n\t\t\t\t\t\t * cases where the address list includes both IPv4 and\n\t\t\t\t\t\t * IPv6 but kernel only accepts one family.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (addr_cur->ai_next != NULL ||\n\t\t\t\t\t\t\tconn->whichhost + 1 < conn->nconnhost)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t\t}\n\t\t\t\t\t\temitHostIdentityInfo(conn, host_addr);\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not create socket: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Once we've identified a target address, all errors\n\t\t\t\t\t * except the preceding socket()-failure case should be\n\t\t\t\t\t * prefixed with host-identity information.  (If the\n\t\t\t\t\t * connection succeeds, the contents of conn->errorMessage\n\t\t\t\t\t * won't matter, so this is harmless.)\n\t\t\t\t\t */\n\t\t\t\t\temitHostIdentityInfo(conn, host_addr);\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Select socket options: no delay of outgoing data for\n\t\t\t\t\t * TCP sockets, nonblock mode, close-on-exec.  Try the\n\t\t\t\t\t * next address if any of this fails.\n\t\t\t\t\t */\n\t\t\t\t\tif (!IS_AF_UNIX(addr_cur->ai_family))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!connectNoDelay(conn))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/* error message already created */\n\t\t\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!pg_set_noblock(conn->sock))\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not set socket to nonblocking mode: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\n#ifdef F_SETFD\n\t\t\t\t\tif (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not set socket to close-on-exec mode: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n#endif\t\t\t\t\t\t\t/* F_SETFD */\n\n\t\t\t\t\tif (!IS_AF_UNIX(addr_cur->ai_family))\n\t\t\t\t\t{\n#ifndef WIN32\n\t\t\t\t\t\tint\t\t\ton = 1;\n#endif\n\t\t\t\t\t\tint\t\t\tusekeepalives = useKeepalives(conn);\n\t\t\t\t\t\tint\t\t\terr = 0;\n\n\t\t\t\t\t\tif (usekeepalives < 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"keepalives parameter must be an integer\\n\"));\n\t\t\t\t\t\t\terr = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (usekeepalives == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/* Do nothing */\n\t\t\t\t\t\t}\n#ifndef WIN32\n\t\t\t\t\t\telse if (setsockopt(conn->sock,\n\t\t\t\t\t\t\t\t\t\t\tSOL_SOCKET, SO_KEEPALIVE,\n\t\t\t\t\t\t\t\t\t\t\t(char *) &on, sizeof(on)) < 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"%s(%s) failed: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t\t  \"setsockopt\",\n\t\t\t\t\t\t\t\t\t\t\t  \"SO_KEEPALIVE\",\n\t\t\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\t\terr = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (!setKeepalivesIdle(conn)\n\t\t\t\t\t\t\t\t || !setKeepalivesInterval(conn)\n\t\t\t\t\t\t\t\t || !setKeepalivesCount(conn))\n\t\t\t\t\t\t\terr = 1;\n#else\t\t\t\t\t\t\t/* WIN32 */\n#ifdef SIO_KEEPALIVE_VALS\n\t\t\t\t\t\telse if (!setKeepalivesWin32(conn))\n\t\t\t\t\t\t\terr = 1;\n#endif\t\t\t\t\t\t\t/* SIO_KEEPALIVE_VALS */\n#endif\t\t\t\t\t\t\t/* WIN32 */\n\t\t\t\t\t\telse if (!setTCPUserTimeout(conn))\n\t\t\t\t\t\t\terr = 1;\n\n\t\t\t\t\t\tif (err)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t/*----------\n\t\t\t\t\t * We have three methods of blocking SIGPIPE during\n\t\t\t\t\t * send() calls to this socket:\n\t\t\t\t\t *\n\t\t\t\t\t *\t- setsockopt(sock, SO_NOSIGPIPE)\n\t\t\t\t\t *\t- send(sock, ..., MSG_NOSIGNAL)\n\t\t\t\t\t *\t- setting the signal mask to SIG_IGN during send()\n\t\t\t\t\t *\n\t\t\t\t\t * The third method requires three syscalls per send,\n\t\t\t\t\t * so we prefer either of the first two, but they are\n\t\t\t\t\t * less portable.  The state is tracked in the following\n\t\t\t\t\t * members of PGconn:\n\t\t\t\t\t *\n\t\t\t\t\t * conn->sigpipe_so\t\t- we have set up SO_NOSIGPIPE\n\t\t\t\t\t * conn->sigpipe_flag\t- we're specifying MSG_NOSIGNAL\n\t\t\t\t\t *\n\t\t\t\t\t * If we can use SO_NOSIGPIPE, then set sigpipe_so here\n\t\t\t\t\t * and we're done.  Otherwise, set sigpipe_flag so that\n\t\t\t\t\t * we will try MSG_NOSIGNAL on sends.  If we get an error\n\t\t\t\t\t * with MSG_NOSIGNAL, we'll clear that flag and revert to\n\t\t\t\t\t * signal masking.\n\t\t\t\t\t *----------\n\t\t\t\t\t */\n\t\t\t\t\tconn->sigpipe_so = false;\n#ifdef MSG_NOSIGNAL\n\t\t\t\t\tconn->sigpipe_flag = true;\n#else\n\t\t\t\t\tconn->sigpipe_flag = false;\n#endif\t\t\t\t\t\t\t/* MSG_NOSIGNAL */\n\n#ifdef SO_NOSIGPIPE\n\t\t\t\t\toptval = 1;\n\t\t\t\t\tif (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,\n\t\t\t\t\t\t\t\t   (char *) &optval, sizeof(optval)) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tconn->sigpipe_so = true;\n\t\t\t\t\t\tconn->sigpipe_flag = false;\n\t\t\t\t\t}\n#endif\t\t\t\t\t\t\t/* SO_NOSIGPIPE */\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Start/make connection.  This should not block, since we\n\t\t\t\t\t * are in nonblock mode.  If it does, well, too bad.\n\t\t\t\t\t */\n\t\t\t\t\tif (connect(conn->sock, addr_cur->ai_addr,\n\t\t\t\t\t\t\t\taddr_cur->ai_addrlen) < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (SOCK_ERRNO == EINPROGRESS ||\n#ifdef WIN32\n\t\t\t\t\t\t\tSOCK_ERRNO == EWOULDBLOCK ||\n#endif\n\t\t\t\t\t\t\tSOCK_ERRNO == EINTR)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * This is fine - we're in non-blocking mode, and\n\t\t\t\t\t\t\t * the connection is in progress.  Tell caller to\n\t\t\t\t\t\t\t * wait for write-ready on socket.\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tconn->status = CONNECTION_STARTED;\n\t\t\t\t\t\t\treturn PGRES_POLLING_WRITING;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* otherwise, trouble */\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Hm, we're connected already --- seems the \"nonblock\n\t\t\t\t\t\t * connection\" wasn't.  Advance the state machine and\n\t\t\t\t\t\t * go do the next stuff.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->status = CONNECTION_STARTED;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\t * This connection failed.  Add the error report to\n\t\t\t\t\t * conn->errorMessage, then try the next address if any.\n\t\t\t\t\t */\n\t\t\t\t\tconnectFailureMessage(conn, SOCK_ERRNO);\n\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase CONNECTION_STARTED:\n\t\t\t{\n\t\t\t\tACCEPT_TYPE_ARG3 optlen = sizeof(optval);\n\n\t\t\t\t/*\n\t\t\t\t * Write ready, since we've made it here, so the connection\n\t\t\t\t * has been made ... or has failed.\n\t\t\t\t */\n\n\t\t\t\t/*\n\t\t\t\t * Now check (using getsockopt) that there is not an error\n\t\t\t\t * state waiting for us on the socket.\n\t\t\t\t */\n\n\t\t\t\tif (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,\n\t\t\t\t\t\t\t   (char *) &optval, &optlen) == -1)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not get socket error status: %s\\n\"),\n\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\t\t\t\telse if (optval != 0)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * When using a nonblocking connect, we will typically see\n\t\t\t\t\t * connect failures at this point, so provide a friendly\n\t\t\t\t\t * error message.\n\t\t\t\t\t */\n\t\t\t\t\tconnectFailureMessage(conn, optval);\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Try the next address if any, just as in the case where\n\t\t\t\t\t * connect() returned failure immediately.\n\t\t\t\t\t */\n\t\t\t\t\tconn->try_next_addr = true;\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\n\t\t\t\t/* Fill in the client address */\n\t\t\t\tconn->laddr.salen = sizeof(conn->laddr.addr);\n\t\t\t\tif (getsockname(conn->sock,\n\t\t\t\t\t\t\t\t(struct sockaddr *) &conn->laddr.addr,\n\t\t\t\t\t\t\t\t&conn->laddr.salen) < 0)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not get client address from socket: %s\\n\"),\n\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Make sure we can write before advancing to next step.\n\t\t\t\t */\n\t\t\t\tconn->status = CONNECTION_MADE;\n\t\t\t\treturn PGRES_POLLING_WRITING;\n\t\t\t}\n\n\t\tcase CONNECTION_MADE:\n\t\t\t{\n\t\t\t\tchar\t   *startpacket;\n\t\t\t\tint\t\t\tpacketlen;\n\n\t\t\t\t/*\n\t\t\t\t * Implement requirepeer check, if requested and it's a\n\t\t\t\t * Unix-domain socket.\n\t\t\t\t */\n\t\t\t\tif (conn->requirepeer && conn->requirepeer[0] &&\n\t\t\t\t\tIS_AF_UNIX(conn->raddr.addr.ss_family))\n\t\t\t\t{\n#ifndef WIN32\n\t\t\t\t\tchar\t\tpwdbuf[BUFSIZ];\n\t\t\t\t\tstruct passwd pass_buf;\n\t\t\t\t\tstruct passwd *pass;\n\t\t\t\t\tint\t\t\tpasserr;\n#endif\n\t\t\t\t\tuid_t\t\tuid;\n\t\t\t\t\tgid_t\t\tgid;\n\n\t\t\t\t\terrno = 0;\n\t\t\t\t\tif (getpeereid(conn->sock, &uid, &gid) != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Provide special error message if getpeereid is a\n\t\t\t\t\t\t * stub\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (errno == ENOSYS)\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"requirepeer parameter is not supported on this platform\\n\"));\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not get peer credentials: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t\t  strerror_r(errno, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\n#ifndef WIN32\n\t\t\t\t\tpasserr = pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);\n\t\t\t\t\tif (pass == NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (passerr != 0)\n\t\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not look up local user ID %d: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t\t  (int) uid,\n\t\t\t\t\t\t\t\t\t\t\t  strerror_r(passerr, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"local user with ID %d does not exist\\n\"),\n\t\t\t\t\t\t\t\t\t\t\t  (int) uid);\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (strcmp(pass->pw_name, conn->requirepeer) != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"requirepeer specifies \\\"%s\\\", but actual peer user name is \\\"%s\\\"\\n\"),\n\t\t\t\t\t\t\t\t\t\t  conn->requirepeer, pass->pw_name);\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n#else\t\t\t\t\t\t\t/* WIN32 */\n\t\t\t\t\t/* should have failed with ENOSYS above */\n\t\t\t\t\tAssert(false);\n#endif\t\t\t\t\t\t\t/* WIN32 */\n\t\t\t\t}\n\n\t\t\t\tif (IS_AF_UNIX(conn->raddr.addr.ss_family))\n\t\t\t\t{\n\t\t\t\t\t/* Don't request SSL or GSSAPI over Unix sockets */\n#ifdef USE_SSL\n\t\t\t\t\tconn->allow_ssl_try = false;\n#endif\n#ifdef ENABLE_GSS\n\t\t\t\t\tconn->try_gss = false;\n#endif\n\t\t\t\t}\n\n#ifdef ENABLE_GSS\n\n\t\t\t\t/*\n\t\t\t\t * If GSSAPI encryption is enabled, then call\n\t\t\t\t * pg_GSS_have_cred_cache() which will return true if we can\n\t\t\t\t * acquire credentials (and give us a handle to use in\n\t\t\t\t * conn->gcred), and then send a packet to the server asking\n\t\t\t\t * for GSSAPI Encryption (and skip past SSL negotiation and\n\t\t\t\t * regular startup below).\n\t\t\t\t */\n\t\t\t\tif (conn->try_gss && !conn->gctx)\n\t\t\t\t\tconn->try_gss = pg_GSS_have_cred_cache(&conn->gcred);\n\t\t\t\tif (conn->try_gss && !conn->gctx)\n\t\t\t\t{\n\t\t\t\t\tProtocolVersion pv = pg_hton32(NEGOTIATE_GSS_CODE);\n\n\t\t\t\t\tif (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not send GSSAPI negotiation packet: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Ok, wait for response */\n\t\t\t\t\tconn->status = CONNECTION_GSS_STARTUP;\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\t\t\t\telse if (!conn->gctx && conn->gssencmode[0] == 'r')\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)\\n\"));\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n#endif\n\n#ifdef USE_SSL\n\n\t\t\t\t/*\n\t\t\t\t * Enable the libcrypto callbacks before checking if SSL needs\n\t\t\t\t * to be done.  This is done before sending the startup packet\n\t\t\t\t * as depending on the type of authentication done, like MD5\n\t\t\t\t * or SCRAM that use cryptohashes, the callbacks would be\n\t\t\t\t * required even without a SSL connection\n\t\t\t\t */\n\t\t\t\tif (pqsecure_initialize(conn, false, true) < 0)\n\t\t\t\t\tgoto error_return;\n\n\t\t\t\t/*\n\t\t\t\t * If SSL is enabled and we haven't already got encryption of\n\t\t\t\t * some sort running, request SSL instead of sending the\n\t\t\t\t * startup message.\n\t\t\t\t */\n\t\t\t\tif (conn->allow_ssl_try && !conn->wait_ssl_try &&\n\t\t\t\t\t!conn->ssl_in_use\n#ifdef ENABLE_GSS\n\t\t\t\t\t&& !conn->gssenc\n#endif\n\t\t\t\t\t)\n\t\t\t\t{\n\t\t\t\t\tProtocolVersion pv;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Send the SSL request packet.\n\t\t\t\t\t *\n\t\t\t\t\t * Theoretically, this could block, but it really\n\t\t\t\t\t * shouldn't since we only got here if the socket is\n\t\t\t\t\t * write-ready.\n\t\t\t\t\t */\n\t\t\t\t\tpv = pg_hton32(NEGOTIATE_SSL_CODE);\n\t\t\t\t\tif (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not send SSL negotiation packet: %s\\n\"),\n\t\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\t\t\t\t\t/* Ok, wait for response */\n\t\t\t\t\tconn->status = CONNECTION_SSL_STARTUP;\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n#endif\t\t\t\t\t\t\t/* USE_SSL */\n\n\t\t\t\t/*\n\t\t\t\t * Build the startup packet.\n\t\t\t\t */\n\t\t\t\tstartpacket = pqBuildStartupPacket3(conn, &packetlen,\n\t\t\t\t\t\t\t\t\t\t\t\t\tEnvironmentOptions);\n\t\t\t\tif (!startpacket)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"out of memory\\n\"));\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Send the startup packet.\n\t\t\t\t *\n\t\t\t\t * Theoretically, this could block, but it really shouldn't\n\t\t\t\t * since we only got here if the socket is write-ready.\n\t\t\t\t */\n\t\t\t\tif (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"could not send startup packet: %s\\n\"),\n\t\t\t\t\t\t\t\t\t  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));\n\t\t\t\t\tfree(startpacket);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\tfree(startpacket);\n\n\t\t\t\tconn->status = CONNECTION_AWAITING_RESPONSE;\n\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Handle SSL negotiation: wait for postmaster messages and\n\t\t\t * respond as necessary.\n\t\t\t */\n\t\tcase CONNECTION_SSL_STARTUP:\n\t\t\t{\n#ifdef USE_SSL\n\t\t\t\tPostgresPollingStatusType pollres;\n\n\t\t\t\t/*\n\t\t\t\t * On first time through, get the postmaster's response to our\n\t\t\t\t * SSL negotiation packet.\n\t\t\t\t */\n\t\t\t\tif (!conn->ssl_in_use)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * We use pqReadData here since it has the logic to\n\t\t\t\t\t * distinguish no-data-yet from connection closure. Since\n\t\t\t\t\t * conn->ssl isn't set, a plain recv() will occur.\n\t\t\t\t\t */\n\t\t\t\t\tchar\t\tSSLok;\n\t\t\t\t\tint\t\t\trdresult;\n\n\t\t\t\t\trdresult = pqReadData(conn);\n\t\t\t\t\tif (rdresult < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* errorMessage is already filled in */\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\t\t\t\t\tif (rdresult == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* caller failed to wait for data */\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\t}\n\t\t\t\t\tif (pqGetc(&SSLok, conn) < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* should not happen really */\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\t}\n\t\t\t\t\tif (SSLok == 'S')\n\t\t\t\t\t{\n\t\t\t\t\t\t/* mark byte consumed */\n\t\t\t\t\t\tconn->inStart = conn->inCursor;\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Set up global SSL state if required.  The crypto\n\t\t\t\t\t\t * state has already been set if libpq took care of\n\t\t\t\t\t\t * doing that, so there is no need to make that happen\n\t\t\t\t\t\t * again.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (pqsecure_initialize(conn, true, false) != 0)\n\t\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\t\t\t\t\telse if (SSLok == 'N')\n\t\t\t\t\t{\n\t\t\t\t\t\t/* mark byte consumed */\n\t\t\t\t\t\tconn->inStart = conn->inCursor;\n\t\t\t\t\t\t/* OK to do without SSL? */\n\t\t\t\t\t\tif (conn->sslmode[0] == 'r' ||\t/* \"require\" */\n\t\t\t\t\t\t\tconn->sslmode[0] == 'v')\t/* \"verify-ca\" or\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"verify-full\" */\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/* Require SSL, but server does not want it */\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"server does not support SSL, but SSL was required\\n\"));\n\t\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* Otherwise, proceed with normal startup */\n\t\t\t\t\t\tconn->allow_ssl_try = false;\n\t\t\t\t\t\t/* We can proceed using this connection */\n\t\t\t\t\t\tconn->status = CONNECTION_MADE;\n\t\t\t\t\t\treturn PGRES_POLLING_WRITING;\n\t\t\t\t\t}\n\t\t\t\t\telse if (SSLok == 'E')\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Server failure of some sort, such as failure to\n\t\t\t\t\t\t * fork a backend process.  We need to process and\n\t\t\t\t\t\t * report the error message, which might be formatted\n\t\t\t\t\t\t * according to either protocol 2 or protocol 3.\n\t\t\t\t\t\t * Rather than duplicate the code for that, we flip\n\t\t\t\t\t\t * into AWAITING_RESPONSE state and let the code there\n\t\t\t\t\t\t * deal with it.  Note we have *not* consumed the \"E\"\n\t\t\t\t\t\t * byte here.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->status = CONNECTION_AWAITING_RESPONSE;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"received invalid response to SSL negotiation: %c\\n\"),\n\t\t\t\t\t\t\t\t\t\t  SSLok);\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Begin or continue the SSL negotiation process.\n\t\t\t\t */\n\t\t\t\tpollres = pqsecure_open_client(conn);\n\t\t\t\tif (pollres == PGRES_POLLING_OK)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * At this point we should have no data already buffered.\n\t\t\t\t\t * If we do, it was received before we performed the SSL\n\t\t\t\t\t * handshake, so it wasn't encrypted and indeed may have\n\t\t\t\t\t * been injected by a man-in-the-middle.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->inCursor != conn->inEnd)\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"received unencrypted data after SSL response\\n\"));\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* SSL handshake done, ready to send startup packet */\n\t\t\t\t\tconn->status = CONNECTION_MADE;\n\t\t\t\t\treturn PGRES_POLLING_WRITING;\n\t\t\t\t}\n\t\t\t\tif (pollres == PGRES_POLLING_FAILED)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * Failed ... if sslmode is \"prefer\" then do a non-SSL\n\t\t\t\t\t * retry\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->sslmode[0] == 'p' /* \"prefer\" */\n\t\t\t\t\t\t&& conn->allow_ssl_try\t/* redundant? */\n\t\t\t\t\t\t&& !conn->wait_ssl_try) /* redundant? */\n\t\t\t\t\t{\n\t\t\t\t\t\t/* only retry once */\n\t\t\t\t\t\tconn->allow_ssl_try = false;\n\t\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\t\t\t\t\t/* Else it's a hard failure */\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\t\t\t\t/* Else, return POLLING_READING or POLLING_WRITING status */\n\t\t\t\treturn pollres;\n#else\t\t\t\t\t\t\t/* !USE_SSL */\n\t\t\t\t/* can't get here */\n\t\t\t\tgoto error_return;\n#endif\t\t\t\t\t\t\t/* USE_SSL */\n\t\t\t}\n\n\t\tcase CONNECTION_GSS_STARTUP:\n\t\t\t{\n#ifdef ENABLE_GSS\n\t\t\t\tPostgresPollingStatusType pollres;\n\n\t\t\t\t/*\n\t\t\t\t * If we haven't yet, get the postmaster's response to our\n\t\t\t\t * negotiation packet\n\t\t\t\t */\n\t\t\t\tif (conn->try_gss && !conn->gctx)\n\t\t\t\t{\n\t\t\t\t\tchar\t\tgss_ok;\n\t\t\t\t\tint\t\t\trdresult = pqReadData(conn);\n\n\t\t\t\t\tif (rdresult < 0)\n\t\t\t\t\t\t/* pqReadData fills in error message */\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\telse if (rdresult == 0)\n\t\t\t\t\t\t/* caller failed to wait for data */\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\tif (pqGetc(&gss_ok, conn) < 0)\n\t\t\t\t\t\t/* shouldn't happen... */\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\n\t\t\t\t\tif (gss_ok == 'E')\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Server failure of some sort.  Assume it's a\n\t\t\t\t\t\t * protocol version support failure, and let's see if\n\t\t\t\t\t\t * we can't recover (if it's not, we'll get a better\n\t\t\t\t\t\t * error message on retry).  Server gets fussy if we\n\t\t\t\t\t\t * don't hang up the socket, though.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->try_gss = false;\n\t\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* mark byte consumed */\n\t\t\t\t\tconn->inStart = conn->inCursor;\n\n\t\t\t\t\tif (gss_ok == 'N')\n\t\t\t\t\t{\n\t\t\t\t\t\t/* Server doesn't want GSSAPI; fall back if we can */\n\t\t\t\t\t\tif (conn->gssencmode[0] == 'r')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"server doesn't support GSSAPI encryption, but it was required\\n\"));\n\t\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconn->try_gss = false;\n\t\t\t\t\t\t/* We can proceed using this connection */\n\t\t\t\t\t\tconn->status = CONNECTION_MADE;\n\t\t\t\t\t\treturn PGRES_POLLING_WRITING;\n\t\t\t\t\t}\n\t\t\t\t\telse if (gss_ok != 'G')\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t  libpq_gettext(\"received invalid response to GSSAPI negotiation: %c\\n\"),\n\t\t\t\t\t\t\t\t\t\t  gss_ok);\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/* Begin or continue GSSAPI negotiation */\n\t\t\t\tpollres = pqsecure_open_gss(conn);\n\t\t\t\tif (pollres == PGRES_POLLING_OK)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * At this point we should have no data already buffered.\n\t\t\t\t\t * If we do, it was received before we performed the GSS\n\t\t\t\t\t * handshake, so it wasn't encrypted and indeed may have\n\t\t\t\t\t * been injected by a man-in-the-middle.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->inCursor != conn->inEnd)\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"received unencrypted data after GSSAPI encryption response\\n\"));\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* All set for startup packet */\n\t\t\t\t\tconn->status = CONNECTION_MADE;\n\t\t\t\t\treturn PGRES_POLLING_WRITING;\n\t\t\t\t}\n\t\t\t\telse if (pollres == PGRES_POLLING_FAILED &&\n\t\t\t\t\t\t conn->gssencmode[0] == 'p')\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * We failed, but we can retry on \"prefer\".  Have to drop\n\t\t\t\t\t * the current connection to do so, though.\n\t\t\t\t\t */\n\t\t\t\t\tconn->try_gss = false;\n\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\t\t\t\treturn pollres;\n#else\t\t\t\t\t\t\t/* !ENABLE_GSS */\n\t\t\t\t/* unreachable */\n\t\t\t\tgoto error_return;\n#endif\t\t\t\t\t\t\t/* ENABLE_GSS */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Handle authentication exchange: wait for postmaster messages\n\t\t\t * and respond as necessary.\n\t\t\t */\n\t\tcase CONNECTION_AWAITING_RESPONSE:\n\t\t\t{\n\t\t\t\tchar\t\tberesp;\n\t\t\t\tint\t\t\tmsgLength;\n\t\t\t\tint\t\t\tavail;\n\t\t\t\tAuthRequest areq;\n\t\t\t\tint\t\t\tres;\n\n\t\t\t\t/*\n\t\t\t\t * Scan the message from current point (note that if we find\n\t\t\t\t * the message is incomplete, we will return without advancing\n\t\t\t\t * inStart, and resume here next time).\n\t\t\t\t */\n\t\t\t\tconn->inCursor = conn->inStart;\n\n\t\t\t\t/* Read type byte */\n\t\t\t\tif (pqGetc(&beresp, conn))\n\t\t\t\t{\n\t\t\t\t\t/* We'll come back when there is more data */\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Validate message type: we expect only an authentication\n\t\t\t\t * request or an error here.  Anything else probably means\n\t\t\t\t * it's not Postgres on the other end at all.\n\t\t\t\t */\n\t\t\t\tif (!(beresp == 'R' || beresp == 'E'))\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"expected authentication request from server, but received %c\\n\"),\n\t\t\t\t\t\t\t\t\t  beresp);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t/* Read message length word */\n\t\t\t\tif (pqGetInt(&msgLength, 4, conn))\n\t\t\t\t{\n\t\t\t\t\t/* We'll come back when there is more data */\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Try to validate message length before using it.\n\t\t\t\t * Authentication requests can't be very large, although GSS\n\t\t\t\t * auth requests may not be that small.  Errors can be a\n\t\t\t\t * little larger, but not huge.  If we see a large apparent\n\t\t\t\t * length in an error, it means we're really talking to a\n\t\t\t\t * pre-3.0-protocol server; cope.  (Before version 14, the\n\t\t\t\t * server also used the old protocol for errors that happened\n\t\t\t\t * before processing the startup packet.)\n\t\t\t\t */\n\t\t\t\tif (beresp == 'R' && (msgLength < 8 || msgLength > 2000))\n\t\t\t\t{\n\t\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t  libpq_gettext(\"expected authentication request from server, but received %c\\n\"),\n\t\t\t\t\t\t\t\t\t  beresp);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\tif (beresp == 'E' && (msgLength < 8 || msgLength > 30000))\n\t\t\t\t{\n\t\t\t\t\t/* Handle error from a pre-3.0 server */\n\t\t\t\t\tconn->inCursor = conn->inStart + 1; /* reread data */\n\t\t\t\t\tif (pqGets_append(&conn->errorMessage, conn))\n\t\t\t\t\t{\n\t\t\t\t\t\t/* We'll come back when there is more data */\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\t}\n\t\t\t\t\t/* OK, we read the message; mark data consumed */\n\t\t\t\t\tconn->inStart = conn->inCursor;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Before 7.2, the postmaster didn't always end its\n\t\t\t\t\t * messages with a newline, so add one if needed to\n\t\t\t\t\t * conform to libpq conventions.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->errorMessage.len == 0 ||\n\t\t\t\t\t\tconn->errorMessage.data[conn->errorMessage.len - 1] != '\\n')\n\t\t\t\t\t{\n\t\t\t\t\t\tappendPQExpBufferChar(&conn->errorMessage, '\\n');\n\t\t\t\t\t}\n\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Can't process if message body isn't all here yet.\n\t\t\t\t */\n\t\t\t\tmsgLength -= 4;\n\t\t\t\tavail = conn->inEnd - conn->inCursor;\n\t\t\t\tif (avail < msgLength)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * Before returning, try to enlarge the input buffer if\n\t\t\t\t\t * needed to hold the whole message; see notes in\n\t\t\t\t\t * pqParseInput3.\n\t\t\t\t\t */\n\t\t\t\t\tif (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,\n\t\t\t\t\t\t\t\t\t\t\t conn))\n\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t/* We'll come back when there is more data */\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\t/* Handle errors. */\n\t\t\t\tif (beresp == 'E')\n\t\t\t\t{\n\t\t\t\t\tif (pqGetErrorNotice3(conn, true))\n\t\t\t\t\t{\n\t\t\t\t\t\t/* We'll come back when there is more data */\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\t}\n\t\t\t\t\t/* OK, we read the message; mark data consumed */\n\t\t\t\t\tconn->inStart = conn->inCursor;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * If error is \"cannot connect now\", try the next host if\n\t\t\t\t\t * any (but we don't want to consider additional addresses\n\t\t\t\t\t * for this host, nor is there much point in changing SSL\n\t\t\t\t\t * or GSS mode).  This is helpful when dealing with\n\t\t\t\t\t * standby servers that might not be in hot-standby state.\n\t\t\t\t\t */\n\t\t\t\t\tif (strcmp(conn->last_sqlstate,\n\t\t\t\t\t\t\t   ERRCODE_CANNOT_CONNECT_NOW) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tconn->try_next_host = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Check to see if we should mention pgpassfile */\n\t\t\t\t\tpgpassfileWarning(conn);\n\n#ifdef ENABLE_GSS\n\n\t\t\t\t\t/*\n\t\t\t\t\t * If gssencmode is \"prefer\" and we're using GSSAPI, retry\n\t\t\t\t\t * without it.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->gssenc && conn->gssencmode[0] == 'p')\n\t\t\t\t\t{\n\t\t\t\t\t\t/* only retry once */\n\t\t\t\t\t\tconn->try_gss = false;\n\t\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n#endif\n\n#ifdef USE_SSL\n\n\t\t\t\t\t/*\n\t\t\t\t\t * if sslmode is \"allow\" and we haven't tried an SSL\n\t\t\t\t\t * connection already, then retry with an SSL connection\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->sslmode[0] == 'a' /* \"allow\" */\n\t\t\t\t\t\t&& !conn->ssl_in_use\n\t\t\t\t\t\t&& conn->allow_ssl_try\n\t\t\t\t\t\t&& conn->wait_ssl_try)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* only retry once */\n\t\t\t\t\t\tconn->wait_ssl_try = false;\n\t\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\t * if sslmode is \"prefer\" and we're in an SSL connection,\n\t\t\t\t\t * then do a non-SSL retry\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->sslmode[0] == 'p' /* \"prefer\" */\n\t\t\t\t\t\t&& conn->ssl_in_use\n\t\t\t\t\t\t&& conn->allow_ssl_try\t/* redundant? */\n\t\t\t\t\t\t&& !conn->wait_ssl_try) /* redundant? */\n\t\t\t\t\t{\n\t\t\t\t\t\t/* only retry once */\n\t\t\t\t\t\tconn->allow_ssl_try = false;\n\t\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n#endif\n\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t/* It is an authentication request. */\n\t\t\t\tconn->auth_req_received = true;\n\n\t\t\t\t/* Get the type of request. */\n\t\t\t\tif (pqGetInt((int *) &areq, 4, conn))\n\t\t\t\t{\n\t\t\t\t\t/* We'll come back when there are more data */\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\t\t\t\tmsgLength -= 4;\n\n\t\t\t\t/*\n\t\t\t\t * Process the rest of the authentication request message, and\n\t\t\t\t * respond to it if necessary.\n\t\t\t\t *\n\t\t\t\t * Note that conn->pghost must be non-NULL if we are going to\n\t\t\t\t * avoid the Kerberos code doing a hostname look-up.\n\t\t\t\t */\n\t\t\t\tres = pg_fe_sendauth(areq, msgLength, conn);\n\n\t\t\t\t/* OK, we have processed the message; mark data consumed */\n\t\t\t\tconn->inStart = conn->inCursor;\n\n\t\t\t\tif (res != STATUS_OK)\n\t\t\t\t\tgoto error_return;\n\n\t\t\t\t/*\n\t\t\t\t * Just make sure that any data sent by pg_fe_sendauth is\n\t\t\t\t * flushed out.  Although this theoretically could block, it\n\t\t\t\t * really shouldn't since we don't send large auth responses.\n\t\t\t\t */\n\t\t\t\tif (pqFlush(conn))\n\t\t\t\t\tgoto error_return;\n\n\t\t\t\tif (areq == AUTH_REQ_OK)\n\t\t\t\t{\n\t\t\t\t\t/* We are done with authentication exchange */\n\t\t\t\t\tconn->status = CONNECTION_AUTH_OK;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Set asyncStatus so that PQgetResult will think that\n\t\t\t\t\t * what comes back next is the result of a query.  See\n\t\t\t\t\t * below.\n\t\t\t\t\t */\n\t\t\t\t\tconn->asyncStatus = PGASYNC_BUSY;\n\t\t\t\t}\n\n\t\t\t\t/* Look to see if we have more data yet. */\n\t\t\t\tgoto keep_going;\n\t\t\t}\n\n\t\tcase CONNECTION_AUTH_OK:\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Now we expect to hear from the backend. A ReadyForQuery\n\t\t\t\t * message indicates that startup is successful, but we might\n\t\t\t\t * also get an Error message indicating failure. (Notice\n\t\t\t\t * messages indicating nonfatal warnings are also allowed by\n\t\t\t\t * the protocol, as are ParameterStatus and BackendKeyData\n\t\t\t\t * messages.) Easiest way to handle this is to let\n\t\t\t\t * PQgetResult() read the messages. We just have to fake it\n\t\t\t\t * out about the state of the connection, by setting\n\t\t\t\t * asyncStatus = PGASYNC_BUSY (done above).\n\t\t\t\t */\n\n\t\t\t\tif (PQisBusy(conn))\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\n\t\t\t\tres = PQgetResult(conn);\n\n\t\t\t\t/*\n\t\t\t\t * NULL return indicating we have gone to IDLE state is\n\t\t\t\t * expected\n\t\t\t\t */\n\t\t\t\tif (res)\n\t\t\t\t{\n\t\t\t\t\tif (res->resultStatus != PGRES_FATAL_ERROR)\n\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"unexpected message from server during startup\\n\"));\n\t\t\t\t\telse if (conn->send_appname &&\n\t\t\t\t\t\t\t (conn->appname || conn->fbappname))\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * If we tried to send application_name, check to see\n\t\t\t\t\t\t * if the error is about that --- pre-9.0 servers will\n\t\t\t\t\t\t * reject it at this stage of the process.  If so,\n\t\t\t\t\t\t * close the connection and retry without sending\n\t\t\t\t\t\t * application_name.  We could possibly get a false\n\t\t\t\t\t\t * SQLSTATE match here and retry uselessly, but there\n\t\t\t\t\t\t * seems no great harm in that; we'll just get the\n\t\t\t\t\t\t * same error again if it's unrelated.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconst char *sqlstate;\n\n\t\t\t\t\t\tsqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);\n\t\t\t\t\t\tif (sqlstate &&\n\t\t\t\t\t\t\tstrcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPQclear(res);\n\t\t\t\t\t\t\tconn->send_appname = false;\n\t\t\t\t\t\t\tneed_new_connection = true;\n\t\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\t * if the resultStatus is FATAL, then conn->errorMessage\n\t\t\t\t\t * already has a copy of the error; needn't copy it back.\n\t\t\t\t\t * But add a newline if it's not there already, since\n\t\t\t\t\t * postmaster error messages may not have one.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->errorMessage.len <= 0 ||\n\t\t\t\t\t\tconn->errorMessage.data[conn->errorMessage.len - 1] != '\\n')\n\t\t\t\t\t\tappendPQExpBufferChar(&conn->errorMessage, '\\n');\n\t\t\t\t\tPQclear(res);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t/* Almost there now ... */\n\t\t\t\tconn->status = CONNECTION_CHECK_TARGET;\n\t\t\t\tgoto keep_going;\n\t\t\t}\n\n\t\tcase CONNECTION_CHECK_TARGET:\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * If a read-write, read-only, primary, or standby connection\n\t\t\t\t * is required, see if we have one.\n\t\t\t\t */\n\t\t\t\tif (conn->target_server_type == SERVER_TYPE_READ_WRITE ||\n\t\t\t\t\tconn->target_server_type == SERVER_TYPE_READ_ONLY)\n\t\t\t\t{\n\t\t\t\t\tbool\t\tread_only_server;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * If the server didn't report\n\t\t\t\t\t * \"default_transaction_read_only\" or \"in_hot_standby\" at\n\t\t\t\t\t * startup, we must determine its state by sending the\n\t\t\t\t\t * query \"SHOW transaction_read_only\".  This GUC exists in\n\t\t\t\t\t * all server versions that support 3.0 protocol.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->default_transaction_read_only == PG_BOOL_UNKNOWN ||\n\t\t\t\t\t\tconn->in_hot_standby == PG_BOOL_UNKNOWN)\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * We use PQsendQueryContinue so that\n\t\t\t\t\t\t * conn->errorMessage does not get cleared.  We need\n\t\t\t\t\t\t * to preserve any error messages related to previous\n\t\t\t\t\t\t * hosts we have tried and failed to connect to.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\t\t\tif (!PQsendQueryContinue(conn,\n\t\t\t\t\t\t\t\t\t\t\t\t \"SHOW transaction_read_only\"))\n\t\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t\t/* We'll return to this state when we have the answer */\n\t\t\t\t\t\tconn->status = CONNECTION_CHECK_WRITABLE;\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* OK, we can make the test */\n\t\t\t\t\tread_only_server =\n\t\t\t\t\t\t(conn->default_transaction_read_only == PG_BOOL_YES ||\n\t\t\t\t\t\t conn->in_hot_standby == PG_BOOL_YES);\n\n\t\t\t\t\tif ((conn->target_server_type == SERVER_TYPE_READ_WRITE) ?\n\t\t\t\t\t\tread_only_server : !read_only_server)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* Wrong server state, reject and try the next host */\n\t\t\t\t\t\tif (conn->target_server_type == SERVER_TYPE_READ_WRITE)\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"session is read-only\\n\"));\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"session is not read-only\\n\"));\n\n\t\t\t\t\t\t/* Close connection politely. */\n\t\t\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\t\t\tsendTerminateConn(conn);\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Try next host if any, but we don't want to consider\n\t\t\t\t\t\t * additional addresses for this host.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->try_next_host = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (conn->target_server_type == SERVER_TYPE_PRIMARY ||\n\t\t\t\t\t\t conn->target_server_type == SERVER_TYPE_STANDBY ||\n\t\t\t\t\t\t conn->target_server_type == SERVER_TYPE_PREFER_STANDBY)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * If the server didn't report \"in_hot_standby\" at\n\t\t\t\t\t * startup, we must determine its state by sending the\n\t\t\t\t\t * query \"SELECT pg_catalog.pg_is_in_recovery()\".  Servers\n\t\t\t\t\t * before 9.0 don't have that function, but by the same\n\t\t\t\t\t * token they don't have any standby mode, so we may just\n\t\t\t\t\t * assume the result.\n\t\t\t\t\t */\n\t\t\t\t\tif (conn->sversion < 90000)\n\t\t\t\t\t\tconn->in_hot_standby = PG_BOOL_NO;\n\n\t\t\t\t\tif (conn->in_hot_standby == PG_BOOL_UNKNOWN)\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * We use PQsendQueryContinue so that\n\t\t\t\t\t\t * conn->errorMessage does not get cleared.  We need\n\t\t\t\t\t\t * to preserve any error messages related to previous\n\t\t\t\t\t\t * hosts we have tried and failed to connect to.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\t\t\tif (!PQsendQueryContinue(conn,\n\t\t\t\t\t\t\t\t\t\t\t\t \"SELECT pg_catalog.pg_is_in_recovery()\"))\n\t\t\t\t\t\t\tgoto error_return;\n\t\t\t\t\t\t/* We'll return to this state when we have the answer */\n\t\t\t\t\t\tconn->status = CONNECTION_CHECK_STANDBY;\n\t\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* OK, we can make the test */\n\t\t\t\t\tif ((conn->target_server_type == SERVER_TYPE_PRIMARY) ?\n\t\t\t\t\t\t(conn->in_hot_standby == PG_BOOL_YES) :\n\t\t\t\t\t\t(conn->in_hot_standby == PG_BOOL_NO))\n\t\t\t\t\t{\n\t\t\t\t\t\t/* Wrong server state, reject and try the next host */\n\t\t\t\t\t\tif (conn->target_server_type == SERVER_TYPE_PRIMARY)\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"server is in hot standby mode\\n\"));\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tappendPQExpBufferStr(&conn->errorMessage,\n\t\t\t\t\t\t\t\t\t\t\t\t libpq_gettext(\"server is not in hot standby mode\\n\"));\n\n\t\t\t\t\t\t/* Close connection politely. */\n\t\t\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\t\t\tsendTerminateConn(conn);\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Try next host if any, but we don't want to consider\n\t\t\t\t\t\t * additional addresses for this host.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tconn->try_next_host = true;\n\t\t\t\t\t\tgoto keep_going;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/* We can release the address list now. */\n\t\t\t\trelease_conn_addrinfo(conn);\n\n\t\t\t\t/*\n\t\t\t\t * Contents of conn->errorMessage are no longer interesting\n\t\t\t\t * (and it seems some clients expect it to be empty after a\n\t\t\t\t * successful connection).\n\t\t\t\t */\n\t\t\t\tresetPQExpBuffer(&conn->errorMessage);\n\n\t\t\t\t/* We are open for business! */\n\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\treturn PGRES_POLLING_OK;\n\t\t\t}\n\n\t\tcase CONNECTION_CONSUME:\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * This state just makes sure the connection is idle after\n\t\t\t\t * we've obtained the result of a SHOW or SELECT query.  Once\n\t\t\t\t * we're clear, return to CONNECTION_CHECK_TARGET state to\n\t\t\t\t * decide what to do next.  We must transiently set status =\n\t\t\t\t * CONNECTION_OK in order to use the result-consuming\n\t\t\t\t * subroutines.\n\t\t\t\t */\n\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\tif (!PQconsumeInput(conn))\n\t\t\t\t\tgoto error_return;\n\n\t\t\t\tif (PQisBusy(conn))\n\t\t\t\t{\n\t\t\t\t\tconn->status = CONNECTION_CONSUME;\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\t/* Call PQgetResult() again until we get a NULL result */\n\t\t\t\tres = PQgetResult(conn);\n\t\t\t\tif (res != NULL)\n\t\t\t\t{\n\t\t\t\t\tPQclear(res);\n\t\t\t\t\tconn->status = CONNECTION_CONSUME;\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\tconn->status = CONNECTION_CHECK_TARGET;\n\t\t\t\tgoto keep_going;\n\t\t\t}\n\n\t\tcase CONNECTION_CHECK_WRITABLE:\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Waiting for result of \"SHOW transaction_read_only\".  We\n\t\t\t\t * must transiently set status = CONNECTION_OK in order to use\n\t\t\t\t * the result-consuming subroutines.\n\t\t\t\t */\n\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\tif (!PQconsumeInput(conn))\n\t\t\t\t\tgoto error_return;\n\n\t\t\t\tif (PQisBusy(conn))\n\t\t\t\t{\n\t\t\t\t\tconn->status = CONNECTION_CHECK_WRITABLE;\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\tres = PQgetResult(conn);\n\t\t\t\tif (res && PQresultStatus(res) == PGRES_TUPLES_OK &&\n\t\t\t\t\tPQntuples(res) == 1)\n\t\t\t\t{\n\t\t\t\t\tchar\t   *val = PQgetvalue(res, 0, 0);\n\n\t\t\t\t\t/*\n\t\t\t\t\t * \"transaction_read_only = on\" proves that at least one\n\t\t\t\t\t * of default_transaction_read_only and in_hot_standby is\n\t\t\t\t\t * on, but we don't actually know which.  We don't care\n\t\t\t\t\t * though for the purpose of identifying a read-only\n\t\t\t\t\t * session, so satisfy the CONNECTION_CHECK_TARGET code by\n\t\t\t\t\t * claiming they are both on.  On the other hand, if it's\n\t\t\t\t\t * a read-write session, they are certainly both off.\n\t\t\t\t\t */\n\t\t\t\t\tif (strncmp(val, \"on\", 2) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tconn->default_transaction_read_only = PG_BOOL_YES;\n\t\t\t\t\t\tconn->in_hot_standby = PG_BOOL_YES;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tconn->default_transaction_read_only = PG_BOOL_NO;\n\t\t\t\t\t\tconn->in_hot_standby = PG_BOOL_NO;\n\t\t\t\t\t}\n\t\t\t\t\tPQclear(res);\n\n\t\t\t\t\t/* Finish reading messages before continuing */\n\t\t\t\t\tconn->status = CONNECTION_CONSUME;\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\n\t\t\t\t/* Something went wrong with \"SHOW transaction_read_only\". */\n\t\t\t\tif (res)\n\t\t\t\t\tPQclear(res);\n\n\t\t\t\t/* Append error report to conn->errorMessage. */\n\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t  libpq_gettext(\"\\\"%s\\\" failed\\n\"),\n\t\t\t\t\t\t\t\t  \"SHOW transaction_read_only\");\n\n\t\t\t\t/* Close connection politely. */\n\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\tsendTerminateConn(conn);\n\n\t\t\t\t/* Try next host. */\n\t\t\t\tconn->try_next_host = true;\n\t\t\t\tgoto keep_going;\n\t\t\t}\n\n\t\tcase CONNECTION_CHECK_STANDBY:\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * Waiting for result of \"SELECT pg_is_in_recovery()\".  We\n\t\t\t\t * must transiently set status = CONNECTION_OK in order to use\n\t\t\t\t * the result-consuming subroutines.\n\t\t\t\t */\n\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\tif (!PQconsumeInput(conn))\n\t\t\t\t\tgoto error_return;\n\n\t\t\t\tif (PQisBusy(conn))\n\t\t\t\t{\n\t\t\t\t\tconn->status = CONNECTION_CHECK_STANDBY;\n\t\t\t\t\treturn PGRES_POLLING_READING;\n\t\t\t\t}\n\n\t\t\t\tres = PQgetResult(conn);\n\t\t\t\tif (res && PQresultStatus(res) == PGRES_TUPLES_OK &&\n\t\t\t\t\tPQntuples(res) == 1)\n\t\t\t\t{\n\t\t\t\t\tchar\t   *val = PQgetvalue(res, 0, 0);\n\n\t\t\t\t\tif (strncmp(val, \"t\", 1) == 0)\n\t\t\t\t\t\tconn->in_hot_standby = PG_BOOL_YES;\n\t\t\t\t\telse\n\t\t\t\t\t\tconn->in_hot_standby = PG_BOOL_NO;\n\t\t\t\t\tPQclear(res);\n\n\t\t\t\t\t/* Finish reading messages before continuing */\n\t\t\t\t\tconn->status = CONNECTION_CONSUME;\n\t\t\t\t\tgoto keep_going;\n\t\t\t\t}\n\n\t\t\t\t/* Something went wrong with \"SELECT pg_is_in_recovery()\". */\n\t\t\t\tif (res)\n\t\t\t\t\tPQclear(res);\n\n\t\t\t\t/* Append error report to conn->errorMessage. */\n\t\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t\t  libpq_gettext(\"\\\"%s\\\" failed\\n\"),\n\t\t\t\t\t\t\t\t  \"SELECT pg_is_in_recovery()\");\n\n\t\t\t\t/* Close connection politely. */\n\t\t\t\tconn->status = CONNECTION_OK;\n\t\t\t\tsendTerminateConn(conn);\n\n\t\t\t\t/* Try next host. */\n\t\t\t\tconn->try_next_host = true;\n\t\t\t\tgoto keep_going;\n\t\t\t}\n\n\t\tdefault:\n\t\t\tappendPQExpBuffer(&conn->errorMessage,\n\t\t\t\t\t\t\t  libpq_gettext(\"invalid connection state %d, \"\n\t\t\t\t\t\t\t\t\t\t\t\"probably indicative of memory corruption\\n\"),\n\t\t\t\t\t\t\t  conn->status);\n\t\t\tgoto error_return;\n\t}\n\n\t/* Unreachable */\n\nerror_return:\n\n\t/*\n\t * We used to close the socket at this point, but that makes it awkward\n\t * for those above us if they wish to remove this socket from their own\n\t * records (an fd_set for example).  We'll just have this socket closed\n\t * when PQfinish is called (which is compulsory even after an error, since\n\t * the connection structure must be freed).\n\t */\n\tconn->status = CONNECTION_BAD;\n\treturn PGRES_POLLING_FAILED;\n}", "func_hash": 278272236215939964516135269002509515902, "file_name": "fe-connect.c", "file_hash": 18951971958069127999109334280610413251, "cwe": ["CWE-522"], "cve": "CVE-2021-23222", "cve_desc": "A man-in-the-middle attacker can inject false responses to the client's first few queries, despite the use of SSL certificate verification and encryption.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-23222"}
{"idx": 195389, "project": "tensorflow", "commit_id": "c2b31ff2d3151acb230edc3f5b1832d2c713a9e0", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/c2b31ff2d3151acb230edc3f5b1832d2c713a9e0", "commit_message": "Remove a `DCHECK`-fail, log an error instead.\n\n`DCHECK` in debug mode results in crashes. TensorFlow has had multiple vulnerabilities due to this.\n\nOutside of debug mode, `DCHECK` is a no-op.\n\nA better alternative is to report an error to the log buffer and continue. This should happen both in debug mode and in prod mode.\n\nPiperOrigin-RevId: 408375925\nChange-Id: Id5b3e19c73f3fbe0cc4bba26ca44ff9607bb6356", "target": 1, "func": "bool RepeatedAttrDefEqual(\n    const protobuf::RepeatedPtrField& a1,\n    const protobuf::RepeatedPtrField& a2) {\n  std::unordered_map a1_set;\n  for (const OpDef::AttrDef& def : a1) {\n    DCHECK(a1_set.find(def.name()) == a1_set.end())\n        << \"AttrDef names must be unique, but '\" << def.name()\n        << \"' appears more than once\";\n    a1_set[def.name()] = &def;\n  }\n  for (const OpDef::AttrDef& def : a2) {\n    auto iter = a1_set.find(def.name());\n    if (iter == a1_set.end()) return false;\n    if (!AttrDefEqual(*iter->second, def)) return false;\n    a1_set.erase(iter);\n  }\n  if (!a1_set.empty()) return false;\n  return true;\n}", "func_hash": 228350956694349821922378909162368693155, "file_name": "op_def_util.cc", "file_hash": 43202597261631718571985626227626810269, "cwe": ["CWE-617"], "cve": "CVE-2022-23565", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. An attacker can trigger denial of service via assertion failure by altering a `SavedModel` on disk such that `AttrDef`s of some operation are duplicated. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23565"}
{"idx": 225086, "project": "tensorflow", "commit_id": "c2b31ff2d3151acb230edc3f5b1832d2c713a9e0", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/c2b31ff2d3151acb230edc3f5b1832d2c713a9e0", "commit_message": "Remove a `DCHECK`-fail, log an error instead.\n\n`DCHECK` in debug mode results in crashes. TensorFlow has had multiple vulnerabilities due to this.\n\nOutside of debug mode, `DCHECK` is a no-op.\n\nA better alternative is to report an error to the log buffer and continue. This should happen both in debug mode and in prod mode.\n\nPiperOrigin-RevId: 408375925\nChange-Id: Id5b3e19c73f3fbe0cc4bba26ca44ff9607bb6356", "target": 0, "func": "bool RepeatedAttrDefEqual(\n    const protobuf::RepeatedPtrField& a1,\n    const protobuf::RepeatedPtrField& a2) {\n  std::unordered_map a1_set;\n  for (const OpDef::AttrDef& def : a1) {\n    if (a1_set.find(def.name()) != a1_set.end()) {\n      LOG(ERROR) << \"AttrDef names must be unique, but '\" << def.name()\n                 << \"' appears more than once\";\n    }\n    a1_set[def.name()] = &def;\n  }\n  for (const OpDef::AttrDef& def : a2) {\n    auto iter = a1_set.find(def.name());\n    if (iter == a1_set.end()) return false;\n    if (!AttrDefEqual(*iter->second, def)) return false;\n    a1_set.erase(iter);\n  }\n  if (!a1_set.empty()) return false;\n  return true;\n}", "func_hash": 7221108948147885063916901261116103162, "file_name": "op_def_util.cc", "file_hash": 99670691263177784698689977477403265008, "cwe": ["CWE-617"], "cve": "CVE-2022-23565", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. An attacker can trigger denial of service via assertion failure by altering a `SavedModel` on disk such that `AttrDef`s of some operation are duplicated. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23565"}
{"idx": 195391, "project": "tensorflow", "commit_id": "f68fdab93fb7f4ddb4eb438c8fe052753c9413e8", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f68fdab93fb7f4ddb4eb438c8fe052753c9413e8", "commit_message": "Add a check for pad width to be a positive value.\n\nPiperOrigin-RevId: 413275853\nChange-Id: I261a8db9dabf5ce48a806a9e58129080c9fac619", "target": 1, "func": "  void Compute(tensorflow::OpKernelContext* context) override {\n    for (int ngram_width : ngram_widths_) {\n      OP_REQUIRES(\n          context, ngram_width > 0,\n          errors::InvalidArgument(\"ngram_widths must contain positive values\"));\n    }\n\n    const tensorflow::Tensor* data;\n    OP_REQUIRES_OK(context, context->input(\"data\", &data));\n    const auto& input_data = data->flat().data();\n\n    const tensorflow::Tensor* splits;\n    OP_REQUIRES_OK(context, context->input(\"data_splits\", &splits));\n    const auto& splits_vec = splits->flat();\n\n    // Validate that the splits are valid indices into data, only if there are\n    // splits specified.\n    const int input_data_size = data->flat().size();\n    const int splits_vec_size = splits_vec.size();\n    if (splits_vec_size > 0) {\n      int prev_split = splits_vec(0);\n      OP_REQUIRES(context, prev_split == 0,\n                  errors::InvalidArgument(\"First split value must be 0, got \",\n                                          prev_split));\n      for (int i = 1; i < splits_vec_size; ++i) {\n        bool valid_splits = splits_vec(i) >= prev_split;\n        valid_splits = valid_splits && (splits_vec(i) <= input_data_size);\n        OP_REQUIRES(context, valid_splits,\n                    errors::InvalidArgument(\n                        \"Invalid split value \", splits_vec(i), \", must be in [\",\n                        prev_split, \", \", input_data_size, \"]\"));\n        prev_split = splits_vec(i);\n      }\n      OP_REQUIRES(context, prev_split == input_data_size,\n                  errors::InvalidArgument(\n                      \"Last split value must be data size. Expected \",\n                      input_data_size, \", got \", prev_split));\n    }\n\n    int num_batch_items = splits_vec.size() - 1;\n    tensorflow::Tensor* ngrams_splits;\n    OP_REQUIRES_OK(\n        context, context->allocate_output(1, splits->shape(), &ngrams_splits));\n    auto ngrams_splits_data = ngrams_splits->flat().data();\n\n    // If there is no data or size, return an empty RT.\n    if (data->flat().size() == 0 || splits_vec.size() == 0) {\n      tensorflow::Tensor* empty;\n      OP_REQUIRES_OK(context,\n                     context->allocate_output(0, data->shape(), &empty));\n      for (int i = 0; i <= num_batch_items; ++i) {\n        ngrams_splits_data[i] = 0;\n      }\n      return;\n    }\n\n    ngrams_splits_data[0] = 0;\n    for (int i = 1; i <= num_batch_items; ++i) {\n      int length = splits_vec(i) - splits_vec(i - 1);\n      int num_ngrams = 0;\n      for (int ngram_width : ngram_widths_)\n        num_ngrams += get_num_ngrams(length, ngram_width);\n      if (preserve_short_ && length > 0 && num_ngrams == 0) {\n        num_ngrams = 1;\n      }\n      ngrams_splits_data[i] = ngrams_splits_data[i - 1] + num_ngrams;\n    }\n\n    tensorflow::Tensor* ngrams;\n    OP_REQUIRES_OK(\n        context,\n        context->allocate_output(\n            0, TensorShape({ngrams_splits_data[num_batch_items]}), &ngrams));\n    auto ngrams_data = ngrams->flat().data();\n\n    for (int i = 0; i < num_batch_items; ++i) {\n      auto data_start = &input_data[splits_vec(i)];\n      int output_start_idx = ngrams_splits_data[i];\n      for (int ngram_width : ngram_widths_) {\n        auto output_start = &ngrams_data[output_start_idx];\n        int length = splits_vec(i + 1) - splits_vec(i);\n        int num_ngrams = get_num_ngrams(length, ngram_width);\n        CreateNgrams(data_start, output_start, num_ngrams, ngram_width);\n        output_start_idx += num_ngrams;\n      }\n      // If we're preserving short sequences, check to see if no sequence was\n      // generated by comparing the current output start idx to the original\n      // one (ngram_splits_data). If no ngrams were generated, then they will\n      // be equal (since we increment output_start_idx by num_ngrams every\n      // time we create a set of ngrams.)\n      if (preserve_short_ && output_start_idx == ngrams_splits_data[i]) {\n        int data_length = splits_vec(i + 1) - splits_vec(i);\n        // One legitimate reason to not have any ngrams when preserve_short_\n        // is true is if the sequence itself is empty. In that case, move on.\n        if (data_length == 0) {\n          continue;\n        }\n        // We don't have to worry about dynamic padding sizes here: if padding\n        // was dynamic, every sequence would have had sufficient padding to\n        // generate at least one ngram.\n        int ngram_width = data_length + 2 * pad_width_;\n        auto output_start = &ngrams_data[output_start_idx];\n        int num_ngrams = 1;\n        CreateNgrams(data_start, output_start, num_ngrams, ngram_width);\n      }\n    }\n  }", "func_hash": 93012019628610956612764593105283326156, "file_name": "string_ngrams_op.cc", "file_hash": 245905885483763938680185872776744444218, "cwe": ["CWE-190"], "cve": "CVE-2022-21733", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `StringNGrams` can be used to trigger a denial of service attack by causing an out of memory condition after an integer overflow. We are missing a validation on `pad_witdh` and that result in computing a negative value for `ngram_width` which is later used to allocate parts of the output. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21733"}
{"idx": 225125, "project": "tensorflow", "commit_id": "f68fdab93fb7f4ddb4eb438c8fe052753c9413e8", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f68fdab93fb7f4ddb4eb438c8fe052753c9413e8", "commit_message": "Add a check for pad width to be a positive value.\n\nPiperOrigin-RevId: 413275853\nChange-Id: I261a8db9dabf5ce48a806a9e58129080c9fac619", "target": 0, "func": "  void Compute(tensorflow::OpKernelContext* context) override {\n    for (int ngram_width : ngram_widths_) {\n      OP_REQUIRES(\n          context, ngram_width > 0,\n          errors::InvalidArgument(\"ngram_widths must contain positive values\"));\n    }\n\n    const tensorflow::Tensor* data;\n    OP_REQUIRES_OK(context, context->input(\"data\", &data));\n    const auto& input_data = data->flat().data();\n\n    const tensorflow::Tensor* splits;\n    OP_REQUIRES_OK(context, context->input(\"data_splits\", &splits));\n    const auto& splits_vec = splits->flat();\n\n    // Validate that the splits are valid indices into data, only if there are\n    // splits specified.\n    const int input_data_size = data->flat().size();\n    const int splits_vec_size = splits_vec.size();\n    if (splits_vec_size > 0) {\n      int prev_split = splits_vec(0);\n      OP_REQUIRES(context, prev_split == 0,\n                  errors::InvalidArgument(\"First split value must be 0, got \",\n                                          prev_split));\n      for (int i = 1; i < splits_vec_size; ++i) {\n        bool valid_splits = splits_vec(i) >= prev_split;\n        valid_splits = valid_splits && (splits_vec(i) <= input_data_size);\n        OP_REQUIRES(context, valid_splits,\n                    errors::InvalidArgument(\n                        \"Invalid split value \", splits_vec(i), \", must be in [\",\n                        prev_split, \", \", input_data_size, \"]\"));\n        prev_split = splits_vec(i);\n      }\n      OP_REQUIRES(context, prev_split == input_data_size,\n                  errors::InvalidArgument(\n                      \"Last split value must be data size. Expected \",\n                      input_data_size, \", got \", prev_split));\n    }\n\n    int num_batch_items = splits_vec.size() - 1;\n    tensorflow::Tensor* ngrams_splits;\n    OP_REQUIRES_OK(\n        context, context->allocate_output(1, splits->shape(), &ngrams_splits));\n    auto ngrams_splits_data = ngrams_splits->flat().data();\n\n    // If there is no data or size, return an empty RT.\n    if (data->flat().size() == 0 || splits_vec.size() == 0) {\n      tensorflow::Tensor* empty;\n      OP_REQUIRES_OK(context,\n                     context->allocate_output(0, data->shape(), &empty));\n      for (int i = 0; i <= num_batch_items; ++i) {\n        ngrams_splits_data[i] = 0;\n      }\n      return;\n    }\n\n    ngrams_splits_data[0] = 0;\n    for (int i = 1; i <= num_batch_items; ++i) {\n      int length = splits_vec(i) - splits_vec(i - 1);\n      int num_ngrams = 0;\n      for (int ngram_width : ngram_widths_)\n        num_ngrams += get_num_ngrams(length, ngram_width);\n      if (preserve_short_ && length > 0 && num_ngrams == 0) {\n        num_ngrams = 1;\n      }\n      ngrams_splits_data[i] = ngrams_splits_data[i - 1] + num_ngrams;\n    }\n\n    tensorflow::Tensor* ngrams;\n    OP_REQUIRES_OK(\n        context,\n        context->allocate_output(\n            0, TensorShape({ngrams_splits_data[num_batch_items]}), &ngrams));\n    auto ngrams_data = ngrams->flat().data();\n\n    for (int i = 0; i < num_batch_items; ++i) {\n      auto data_start = &input_data[splits_vec(i)];\n      int output_start_idx = ngrams_splits_data[i];\n      for (int ngram_width : ngram_widths_) {\n        auto output_start = &ngrams_data[output_start_idx];\n        int length = splits_vec(i + 1) - splits_vec(i);\n        int num_ngrams = get_num_ngrams(length, ngram_width);\n        CreateNgrams(data_start, output_start, num_ngrams, ngram_width);\n        output_start_idx += num_ngrams;\n      }\n      // If we're preserving short sequences, check to see if no sequence was\n      // generated by comparing the current output start idx to the original\n      // one (ngram_splits_data). If no ngrams were generated, then they will\n      // be equal (since we increment output_start_idx by num_ngrams every\n      // time we create a set of ngrams.)\n      if (preserve_short_ && output_start_idx == ngrams_splits_data[i]) {\n        int data_length = splits_vec(i + 1) - splits_vec(i);\n        // One legitimate reason to not have any ngrams when preserve_short_\n        // is true is if the sequence itself is empty. In that case, move on.\n        if (data_length == 0) {\n          continue;\n        }\n        // We don't have to worry about dynamic padding sizes here: if padding\n        // was dynamic, every sequence would have had sufficient padding to\n        // generate at least one ngram.\n\n        // If reached here, pad_width should be > 0, pad_width_ = -1,\n        // which indicates max(ngram_widths) - 1 cannot be used here since\n        // ngram_width is not known.\n        OP_REQUIRES(\n            context, pad_width_ >= 0,\n            errors::InvalidArgument(\"Pad width should be >= 0 when \"\n                                    \"preserve_short_sequences is True and \"\n                                    \"ngram_widths are not provided, got \",\n                                    pad_width_));\n        int ngram_width = data_length + 2 * pad_width_;\n        auto output_start = &ngrams_data[output_start_idx];\n        int num_ngrams = 1;\n        CreateNgrams(data_start, output_start, num_ngrams, ngram_width);\n      }\n    }\n  }", "func_hash": 39926051817459528222102206002528990438, "file_name": "string_ngrams_op.cc", "file_hash": 275635386609741564508341080525906256433, "cwe": ["CWE-190"], "cve": "CVE-2022-21733", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `StringNGrams` can be used to trigger a denial of service attack by causing an out of memory condition after an integer overflow. We are missing a validation on `pad_witdh` and that result in computing a negative value for `ngram_width` which is later used to allocate parts of the output. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21733"}
{"idx": 195398, "project": "v4l2loopback", "commit_id": "e4cd225557486c420f6a34411f98c575effd43dd", "project_url": "https://github.com/umlaeute/v4l2loopback", "commit_url": "https://github.com/umlaeute/v4l2loopback/commit/e4cd225557486c420f6a34411f98c575effd43dd", "commit_message": "add explicit format specifier to printf() invocations\n\nCWE-134", "target": 1, "func": "static int vidioc_querycap(struct file *file, void *priv,\n\t\t\t   struct v4l2_capability *cap)\n{\n\tstruct v4l2_loopback_device *dev = v4l2loopback_getdevice(file);\n\tint labellen = (sizeof(cap->card) < sizeof(dev->card_label)) ?\n\t\t\t       sizeof(cap->card) :\n\t\t\t\t     sizeof(dev->card_label);\n\tint device_nr =\n\t\t((struct v4l2loopback_private *)video_get_drvdata(dev->vdev))\n\t\t\t->device_nr;\n\t__u32 capabilities = V4L2_CAP_STREAMING | V4L2_CAP_READWRITE;\n\n\tstrlcpy(cap->driver, \"v4l2 loopback\", sizeof(cap->driver));\n\tsnprintf(cap->card, labellen, dev->card_label);\n\tsnprintf(cap->bus_info, sizeof(cap->bus_info),\n\t\t \"platform:v4l2loopback-%03d\", device_nr);\n\n#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 1, 0)\n\t/* since 3.1.0, the v4l2-core system is supposed to set the version */\n\tcap->version = V4L2LOOPBACK_VERSION_CODE;\n#endif\n\n#ifdef V4L2_CAP_VIDEO_M2M\n\tcapabilities |= V4L2_CAP_VIDEO_M2M;\n#endif /* V4L2_CAP_VIDEO_M2M */\n\n\tif (dev->announce_all_caps) {\n\t\tcapabilities |= V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_OUTPUT;\n\t} else {\n\t\tif (dev->ready_for_capture) {\n\t\t\tcapabilities |= V4L2_CAP_VIDEO_CAPTURE;\n\t\t}\n\t\tif (dev->ready_for_output) {\n\t\t\tcapabilities |= V4L2_CAP_VIDEO_OUTPUT;\n\t\t}\n\t}\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 7, 0)\n\tdev->vdev->device_caps =\n#endif /* >=linux-4.7.0 */\n\t\tcap->device_caps = cap->capabilities = capabilities;\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 3, 0)\n\tcap->capabilities |= V4L2_CAP_DEVICE_CAPS;\n#endif\n\n\tmemset(cap->reserved, 0, sizeof(cap->reserved));\n\treturn 0;\n}", "func_hash": 275249025528691740507199336736969659771, "file_name": "v4l2loopback.c", "file_hash": 113113223463037707180278012059265756483, "cwe": ["CWE-134"], "cve": "CVE-2022-2652", "cve_desc": "Depending on the way the format strings in the card label are crafted it's possible to leak kernel stack memory. There is also the possibility for DoS due to the v4l2loopback kernel module crashing when providing the card label on request (reproduce e.g. with many %s modifiers in a row).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2652"}
{"idx": 225383, "project": "v4l2loopback", "commit_id": "e4cd225557486c420f6a34411f98c575effd43dd", "project_url": "https://github.com/umlaeute/v4l2loopback", "commit_url": "https://github.com/umlaeute/v4l2loopback/commit/e4cd225557486c420f6a34411f98c575effd43dd", "commit_message": "add explicit format specifier to printf() invocations\n\nCWE-134", "target": 0, "func": "static int vidioc_querycap(struct file *file, void *priv,\n\t\t\t   struct v4l2_capability *cap)\n{\n\tstruct v4l2_loopback_device *dev = v4l2loopback_getdevice(file);\n\tint labellen = (sizeof(cap->card) < sizeof(dev->card_label)) ?\n\t\t\t       sizeof(cap->card) :\n\t\t\t\t     sizeof(dev->card_label);\n\tint device_nr =\n\t\t((struct v4l2loopback_private *)video_get_drvdata(dev->vdev))\n\t\t\t->device_nr;\n\t__u32 capabilities = V4L2_CAP_STREAMING | V4L2_CAP_READWRITE;\n\n\tstrlcpy(cap->driver, \"v4l2 loopback\", sizeof(cap->driver));\n\tsnprintf(cap->card, labellen, \"%s\", dev->card_label);\n\tsnprintf(cap->bus_info, sizeof(cap->bus_info),\n\t\t \"platform:v4l2loopback-%03d\", device_nr);\n\n#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 1, 0)\n\t/* since 3.1.0, the v4l2-core system is supposed to set the version */\n\tcap->version = V4L2LOOPBACK_VERSION_CODE;\n#endif\n\n#ifdef V4L2_CAP_VIDEO_M2M\n\tcapabilities |= V4L2_CAP_VIDEO_M2M;\n#endif /* V4L2_CAP_VIDEO_M2M */\n\n\tif (dev->announce_all_caps) {\n\t\tcapabilities |= V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_OUTPUT;\n\t} else {\n\t\tif (dev->ready_for_capture) {\n\t\t\tcapabilities |= V4L2_CAP_VIDEO_CAPTURE;\n\t\t}\n\t\tif (dev->ready_for_output) {\n\t\t\tcapabilities |= V4L2_CAP_VIDEO_OUTPUT;\n\t\t}\n\t}\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 7, 0)\n\tdev->vdev->device_caps =\n#endif /* >=linux-4.7.0 */\n\t\tcap->device_caps = cap->capabilities = capabilities;\n\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 3, 0)\n\tcap->capabilities |= V4L2_CAP_DEVICE_CAPS;\n#endif\n\n\tmemset(cap->reserved, 0, sizeof(cap->reserved));\n\treturn 0;\n}", "func_hash": 178769376518603723181418371440757147493, "file_name": "v4l2loopback.c", "file_hash": 138252299614112344688826607831650943411, "cwe": ["CWE-134"], "cve": "CVE-2022-2652", "cve_desc": "Depending on the way the format strings in the card label are crafted it's possible to leak kernel stack memory. There is also the possibility for DoS due to the v4l2loopback kernel module crashing when providing the card label on request (reproduce e.g. with many %s modifiers in a row).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2652"}
{"idx": 195399, "project": "tensorflow", "commit_id": "045deec1cbdebb27d817008ad5df94d96a08b1bf", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/045deec1cbdebb27d817008ad5df94d96a08b1bf", "commit_message": "Prevent null pointer dereference in `mutable_graph_view`\n\nPiperOrigin-RevId: 409684472\nChange-Id: I577eb9d9ac470fcec0501423171e739a4ec0cb5c", "target": 1, "func": "bool IsIdentityConsumingSwitch(const MutableGraphView& graph,\n                               const NodeDef& node) {\n  if ((IsIdentity(node) || IsIdentityNSingleInput(node)) &&\n      node.input_size() > 0) {\n    TensorId tensor_id = ParseTensorName(node.input(0));\n    if (IsTensorIdControlling(tensor_id)) {\n      return false;\n    }\n\n    NodeDef* input_node = graph.GetNode(tensor_id.node());\n    return IsSwitch(*input_node);\n  }\n  return false;\n}", "func_hash": 313619660222966312087557415210995637728, "file_name": "mutable_graph_view.cc", "file_hash": 11824580899895481141820753687530297202, "cwe": ["CWE-476"], "cve": "CVE-2022-23589", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. Under certain scenarios, Grappler component of TensorFlow can trigger a null pointer dereference. There are 2 places where this can occur, for the same malicious alteration of a `SavedModel` file (fixing the first one would trigger the same dereference in the second place). First, during constant folding, the `GraphDef` might not have the required nodes for the binary operation. If a node is missing, the correposning `mul_*child` would be null, and the dereference in the subsequent line would be incorrect. We have a similar issue during `IsIdentityConsumingSwitch`. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23589"}
{"idx": 225473, "project": "tensorflow", "commit_id": "045deec1cbdebb27d817008ad5df94d96a08b1bf", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/045deec1cbdebb27d817008ad5df94d96a08b1bf", "commit_message": "Prevent null pointer dereference in `mutable_graph_view`\n\nPiperOrigin-RevId: 409684472\nChange-Id: I577eb9d9ac470fcec0501423171e739a4ec0cb5c", "target": 0, "func": "bool IsIdentityConsumingSwitch(const MutableGraphView& graph,\n                               const NodeDef& node) {\n  if ((IsIdentity(node) || IsIdentityNSingleInput(node)) &&\n      node.input_size() > 0) {\n    TensorId tensor_id = ParseTensorName(node.input(0));\n    if (IsTensorIdControlling(tensor_id)) {\n      return false;\n    }\n\n    NodeDef* input_node = graph.GetNode(tensor_id.node());\n    if (input_node == nullptr) {\n      return false;\n    }\n    return IsSwitch(*input_node);\n  }\n  return false;\n}", "func_hash": 186036134407007049668950369044144546274, "file_name": "mutable_graph_view.cc", "file_hash": 183902084895507336616240181892029435869, "cwe": ["CWE-476"], "cve": "CVE-2022-23589", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. Under certain scenarios, Grappler component of TensorFlow can trigger a null pointer dereference. There are 2 places where this can occur, for the same malicious alteration of a `SavedModel` file (fixing the first one would trigger the same dereference in the second place). First, during constant folding, the `GraphDef` might not have the required nodes for the binary operation. If a node is missing, the correposning `mul_*child` would be null, and the dereference in the subsequent line would be incorrect. We have a similar issue during `IsIdentityConsumingSwitch`. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23589"}
{"idx": 195402, "project": "tensorflow", "commit_id": "a1e1511dde36b3f8aa27a6ec630838e7ea40e091", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a1e1511dde36b3f8aa27a6ec630838e7ea40e091", "commit_message": "[lite] Update TfLiteIntArrayCreate to return size_t\n\nPiperOrigin-RevId: 416439896\nChange-Id: I847f69b68d1ddaff4b1e925a09b8b69c1756653b", "target": 1, "func": "int TfLiteIntArrayGetSizeInBytes(int size) {\n  static TfLiteIntArray dummy;\n\n  int computed_size = sizeof(dummy) + sizeof(dummy.data[0]) * size;\n#if defined(_MSC_VER)\n  // Context for why this is needed is in http://b/189926408#comment21\n  computed_size -= sizeof(dummy.data[0]);\n#endif\n  return computed_size;\n}", "func_hash": 331591508579524081379498872268044006906, "file_name": "common.c", "file_hash": 227108095659128555473924245568634074234, "cwe": ["CWE-190"], "cve": "CVE-2022-23558", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. An attacker can craft a TFLite model that would cause an integer overflow in `TfLiteIntArrayCreate`. The `TfLiteIntArrayGetSizeInBytes` returns an `int` instead of a `size_t. An attacker can control model inputs such that `computed_size` overflows the size of `int` datatype. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23558"}
{"idx": 225547, "project": "tensorflow", "commit_id": "a1e1511dde36b3f8aa27a6ec630838e7ea40e091", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a1e1511dde36b3f8aa27a6ec630838e7ea40e091", "commit_message": "[lite] Update TfLiteIntArrayCreate to return size_t\n\nPiperOrigin-RevId: 416439896\nChange-Id: I847f69b68d1ddaff4b1e925a09b8b69c1756653b", "target": 0, "func": "size_t TfLiteIntArrayGetSizeInBytes(int size) {\n  static TfLiteIntArray dummy;\n\n  size_t computed_size = sizeof(dummy) + sizeof(dummy.data[0]) * size;\n#if defined(_MSC_VER)\n  // Context for why this is needed is in http://b/189926408#comment21\n  computed_size -= sizeof(dummy.data[0]);\n#endif\n  return computed_size;\n}", "func_hash": 132887753534839828949485916264712284974, "file_name": "common.c", "file_hash": 141963346575108043523158725755967478163, "cwe": ["CWE-190"], "cve": "CVE-2022-23558", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. An attacker can craft a TFLite model that would cause an integer overflow in `TfLiteIntArrayCreate`. The `TfLiteIntArrayGetSizeInBytes` returns an `int` instead of a `size_t. An attacker can control model inputs such that `computed_size` overflows the size of `int` datatype. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23558"}
{"idx": 195403, "project": "tensorflow", "commit_id": "a1e1511dde36b3f8aa27a6ec630838e7ea40e091", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a1e1511dde36b3f8aa27a6ec630838e7ea40e091", "commit_message": "[lite] Update TfLiteIntArrayCreate to return size_t\n\nPiperOrigin-RevId: 416439896\nChange-Id: I847f69b68d1ddaff4b1e925a09b8b69c1756653b", "target": 1, "func": "TfLiteIntArray* TfLiteIntArrayCreate(int size) {\n  int alloc_size = TfLiteIntArrayGetSizeInBytes(size);\n  if (alloc_size <= 0) return NULL;\n  TfLiteIntArray* ret = (TfLiteIntArray*)malloc(alloc_size);\n  if (!ret) return ret;\n  ret->size = size;\n  return ret;\n}", "func_hash": 64742066879088615123277599572040485093, "file_name": "common.c", "file_hash": 227108095659128555473924245568634074234, "cwe": ["CWE-190"], "cve": "CVE-2022-23558", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. An attacker can craft a TFLite model that would cause an integer overflow in `TfLiteIntArrayCreate`. The `TfLiteIntArrayGetSizeInBytes` returns an `int` instead of a `size_t. An attacker can control model inputs such that `computed_size` overflows the size of `int` datatype. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23558"}
{"idx": 225552, "project": "tensorflow", "commit_id": "a1e1511dde36b3f8aa27a6ec630838e7ea40e091", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a1e1511dde36b3f8aa27a6ec630838e7ea40e091", "commit_message": "[lite] Update TfLiteIntArrayCreate to return size_t\n\nPiperOrigin-RevId: 416439896\nChange-Id: I847f69b68d1ddaff4b1e925a09b8b69c1756653b", "target": 0, "func": "TfLiteIntArray* TfLiteIntArrayCreate(int size) {\n  size_t alloc_size = TfLiteIntArrayGetSizeInBytes(size);\n  if (alloc_size <= 0) return NULL;\n  TfLiteIntArray* ret = (TfLiteIntArray*)malloc(alloc_size);\n  if (!ret) return ret;\n  ret->size = size;\n  return ret;\n}", "func_hash": 125057143458607684207882855383643521977, "file_name": "common.c", "file_hash": 141963346575108043523158725755967478163, "cwe": ["CWE-190"], "cve": "CVE-2022-23558", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. An attacker can craft a TFLite model that would cause an integer overflow in `TfLiteIntArrayCreate`. The `TfLiteIntArrayGetSizeInBytes` returns an `int` instead of a `size_t. An attacker can control model inputs such that `computed_size` overflows the size of `int` datatype. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23558"}
{"idx": 195404, "project": "tensorflow", "commit_id": "ba4e8ac4dc2991e350d5cc407f8598c8d4ee70fb", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/ba4e8ac4dc2991e350d5cc407f8598c8d4ee70fb", "commit_message": "Fix potential divide by zero error when executing FractionalMaxPool, when pooling ratio is higher than input size for a particular dimension.\n\nPiperOrigin-RevId: 412151722\nChange-Id: I06e57cbb8eca43816eff79eac264fa7aae8f7163", "target": 1, "func": "  void Compute(OpKernelContext* context) override {\n    typedef Eigen::Map>\n        ConstEigenMatrixMap;\n    typedef Eigen::Map>\n        EigenMatrixMap;\n\n    constexpr int tensor_in_and_out_dims = 4;\n\n    const Tensor& tensor_in = context->input(0);\n    OP_REQUIRES(context, tensor_in.dims() == tensor_in_and_out_dims,\n                errors::InvalidArgument(\"tensor_in must be 4-dimensional\"));\n\n    std::vector input_size(tensor_in_and_out_dims);\n    std::vector output_size(tensor_in_and_out_dims);\n    for (int i = 0; i < tensor_in_and_out_dims; ++i) {\n      input_size[i] = tensor_in.dim_size(i);\n    }\n    // Output size.\n    for (int i = 0; i < tensor_in_and_out_dims; ++i) {\n      // This must match the same logic in the shape function in\n      // core/ops/nn_ops.cc.\n      output_size[i] =\n          static_cast(std::floor(input_size[i] / pooling_ratio_[i]));\n      DCHECK_GT(output_size[i], 0);\n    }\n\n    // Generate pooling sequence.\n    std::vector height_cum_seq;\n    std::vector width_cum_seq;\n    GuardedPhiloxRandom generator;\n    generator.Init(seed_, seed2_);\n    height_cum_seq = GeneratePoolingSequence(input_size[1], output_size[1],\n                                             &generator, pseudo_random_);\n    width_cum_seq = GeneratePoolingSequence(input_size[2], output_size[2],\n                                            &generator, pseudo_random_);\n\n    // Prepare output.\n    Tensor* output_tensor = nullptr;\n    OP_REQUIRES_OK(context, context->allocate_output(\n                                0,\n                                TensorShape({output_size[0], output_size[1],\n                                             output_size[2], output_size[3]}),\n                                &output_tensor));\n    Tensor* output_height_seq_tensor = nullptr;\n    OP_REQUIRES_OK(\n        context,\n        context->allocate_output(\n            1, TensorShape({static_cast(height_cum_seq.size())}),\n            &output_height_seq_tensor));\n    Tensor* output_width_seq_tensor = nullptr;\n    OP_REQUIRES_OK(\n        context,\n        context->allocate_output(\n            2, TensorShape({static_cast(width_cum_seq.size())}),\n            &output_width_seq_tensor));\n\n    ConstEigenMatrixMap in_mat(tensor_in.flat().data(), input_size[3],\n                               input_size[2] * input_size[1] * input_size[0]);\n\n    EigenMatrixMap out_mat(output_tensor->flat().data(), output_size[3],\n                           output_size[2] * output_size[1] * output_size[0]);\n\n    // Initializes the output tensor with MIN.\n    output_tensor->flat().setConstant(Eigen::NumTraits::lowest());\n\n    auto output_height_seq_flat = output_height_seq_tensor->flat();\n    auto output_width_seq_flat = output_width_seq_tensor->flat();\n\n    // Set output tensors.\n    for (int i = 0; i < height_cum_seq.size(); ++i) {\n      output_height_seq_flat(i) = height_cum_seq[i];\n    }\n\n    for (int i = 0; i < width_cum_seq.size(); ++i) {\n      output_width_seq_flat(i) = width_cum_seq[i];\n    }\n\n    // For both input and output,\n    // 0: batch\n    // 1: height / row\n    // 2: width / col\n    // 3: depth / channel\n    const int64_t height_max = input_size[1] - 1;\n    const int64_t width_max = input_size[2] - 1;\n    for (int64_t b = 0; b < input_size[0]; ++b) {\n      // height sequence.\n      for (int64_t hs = 0; hs < height_cum_seq.size() - 1; ++hs) {\n        // height start and end.\n        const int64_t height_start = height_cum_seq[hs];\n        int64_t height_end =\n            overlapping_ ? height_cum_seq[hs + 1] : height_cum_seq[hs + 1] - 1;\n        height_end = std::min(height_end, height_max);\n\n        // width sequence.\n        for (int64_t ws = 0; ws < width_cum_seq.size() - 1; ++ws) {\n          const int64_t out_offset =\n              (b * output_size[1] + hs) * output_size[2] + ws;\n          // width start and end.\n          const int64_t width_start = width_cum_seq[ws];\n          int64_t width_end =\n              overlapping_ ? width_cum_seq[ws + 1] : width_cum_seq[ws + 1] - 1;\n          width_end = std::min(width_end, width_max);\n          for (int64_t h = height_start; h <= height_end; ++h) {\n            for (int64_t w = width_start; w <= width_end; ++w) {\n              const int64_t in_offset =\n                  (b * input_size[1] + h) * input_size[2] + w;\n              out_mat.col(out_offset) =\n                  out_mat.col(out_offset).cwiseMax(in_mat.col(in_offset));\n            }\n          }\n        }\n      }\n    }\n  }", "func_hash": 329653208386215793548956261636203970964, "file_name": "fractional_max_pool_op.cc", "file_hash": 38088244475067119710916669469162645605, "cwe": ["CWE-369"], "cve": "CVE-2022-21735", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `FractionalMaxPool` can be made to crash a TensorFlow process via a division by 0. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21735"}
{"idx": 225563, "project": "tensorflow", "commit_id": "ba4e8ac4dc2991e350d5cc407f8598c8d4ee70fb", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/ba4e8ac4dc2991e350d5cc407f8598c8d4ee70fb", "commit_message": "Fix potential divide by zero error when executing FractionalMaxPool, when pooling ratio is higher than input size for a particular dimension.\n\nPiperOrigin-RevId: 412151722\nChange-Id: I06e57cbb8eca43816eff79eac264fa7aae8f7163", "target": 0, "func": "  void Compute(OpKernelContext* context) override {\n    typedef Eigen::Map>\n        ConstEigenMatrixMap;\n    typedef Eigen::Map>\n        EigenMatrixMap;\n\n    constexpr int tensor_in_and_out_dims = 4;\n\n    const Tensor& tensor_in = context->input(0);\n    OP_REQUIRES(context, tensor_in.dims() == tensor_in_and_out_dims,\n                errors::InvalidArgument(\"tensor_in must be 4-dimensional\"));\n\n    std::vector input_size(tensor_in_and_out_dims);\n    std::vector output_size(tensor_in_and_out_dims);\n    for (int i = 0; i < tensor_in_and_out_dims; ++i) {\n      input_size[i] = tensor_in.dim_size(i);\n\n      OP_REQUIRES(\n          context, input_size[i] >= pooling_ratio_[i],\n          errors::InvalidArgument(\"Pooling ratio is higher than input \"\n                                  \"dimension size for dimension \",\n                                  i, \". Input dim size: \", input_size[i],\n                                  \" pooling ratio: \", pooling_ratio_[i]));\n    }\n    // Output size.\n    for (int i = 0; i < tensor_in_and_out_dims; ++i) {\n      // This must match the same logic in the shape function in\n      // core/ops/nn_ops.cc.\n      output_size[i] =\n          static_cast(std::floor(input_size[i] / pooling_ratio_[i]));\n      DCHECK_GT(output_size[i], 0);\n    }\n\n    // Generate pooling sequence.\n    std::vector height_cum_seq;\n    std::vector width_cum_seq;\n    GuardedPhiloxRandom generator;\n    generator.Init(seed_, seed2_);\n    height_cum_seq = GeneratePoolingSequence(input_size[1], output_size[1],\n                                             &generator, pseudo_random_);\n    width_cum_seq = GeneratePoolingSequence(input_size[2], output_size[2],\n                                            &generator, pseudo_random_);\n\n    // Prepare output.\n    Tensor* output_tensor = nullptr;\n    OP_REQUIRES_OK(context, context->allocate_output(\n                                0,\n                                TensorShape({output_size[0], output_size[1],\n                                             output_size[2], output_size[3]}),\n                                &output_tensor));\n    Tensor* output_height_seq_tensor = nullptr;\n    OP_REQUIRES_OK(\n        context,\n        context->allocate_output(\n            1, TensorShape({static_cast(height_cum_seq.size())}),\n            &output_height_seq_tensor));\n    Tensor* output_width_seq_tensor = nullptr;\n    OP_REQUIRES_OK(\n        context,\n        context->allocate_output(\n            2, TensorShape({static_cast(width_cum_seq.size())}),\n            &output_width_seq_tensor));\n\n    ConstEigenMatrixMap in_mat(tensor_in.flat().data(), input_size[3],\n                               input_size[2] * input_size[1] * input_size[0]);\n\n    EigenMatrixMap out_mat(output_tensor->flat().data(), output_size[3],\n                           output_size[2] * output_size[1] * output_size[0]);\n\n    // Initializes the output tensor with MIN.\n    output_tensor->flat().setConstant(Eigen::NumTraits::lowest());\n\n    auto output_height_seq_flat = output_height_seq_tensor->flat();\n    auto output_width_seq_flat = output_width_seq_tensor->flat();\n\n    // Set output tensors.\n    for (int i = 0; i < height_cum_seq.size(); ++i) {\n      output_height_seq_flat(i) = height_cum_seq[i];\n    }\n\n    for (int i = 0; i < width_cum_seq.size(); ++i) {\n      output_width_seq_flat(i) = width_cum_seq[i];\n    }\n\n    // For both input and output,\n    // 0: batch\n    // 1: height / row\n    // 2: width / col\n    // 3: depth / channel\n    const int64_t height_max = input_size[1] - 1;\n    const int64_t width_max = input_size[2] - 1;\n    for (int64_t b = 0; b < input_size[0]; ++b) {\n      // height sequence.\n      for (int64_t hs = 0; hs < height_cum_seq.size() - 1; ++hs) {\n        // height start and end.\n        const int64_t height_start = height_cum_seq[hs];\n        int64_t height_end =\n            overlapping_ ? height_cum_seq[hs + 1] : height_cum_seq[hs + 1] - 1;\n        height_end = std::min(height_end, height_max);\n\n        // width sequence.\n        for (int64_t ws = 0; ws < width_cum_seq.size() - 1; ++ws) {\n          const int64_t out_offset =\n              (b * output_size[1] + hs) * output_size[2] + ws;\n          // width start and end.\n          const int64_t width_start = width_cum_seq[ws];\n          int64_t width_end =\n              overlapping_ ? width_cum_seq[ws + 1] : width_cum_seq[ws + 1] - 1;\n          width_end = std::min(width_end, width_max);\n          for (int64_t h = height_start; h <= height_end; ++h) {\n            for (int64_t w = width_start; w <= width_end; ++w) {\n              const int64_t in_offset =\n                  (b * input_size[1] + h) * input_size[2] + w;\n              out_mat.col(out_offset) =\n                  out_mat.col(out_offset).cwiseMax(in_mat.col(in_offset));\n            }\n          }\n        }\n      }\n    }\n  }", "func_hash": 116843352571391588046661724660779526999, "file_name": "fractional_max_pool_op.cc", "file_hash": 167950097941581661250535285107700244508, "cwe": ["CWE-369"], "cve": "CVE-2022-21735", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `FractionalMaxPool` can be made to crash a TensorFlow process via a division by 0. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21735"}
{"idx": 195405, "project": "ImageMagick6", "commit_id": "29c8abce0da56b536542f76a9ddfebdaab5b2943", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/29c8abce0da56b536542f76a9ddfebdaab5b2943", "commit_message": "https://github.com/ImageMagick/ImageMagick/pull/4986", "target": 1, "func": "static Image *ReadPCLImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define CropBox  \"CropBox\"\n#define DeviceCMYK  \"DeviceCMYK\"\n#define MediaBox  \"MediaBox\"\n#define RenderPCLText  \"  Rendering PCL...  \"\n\n  char\n    command[MaxTextExtent],\n    *density,\n    filename[MaxTextExtent],\n    geometry[MaxTextExtent],\n    *options,\n    input_filename[MaxTextExtent];\n\n  const DelegateInfo\n    *delegate_info;\n\n  Image\n    *image,\n    *next_image;\n\n  ImageInfo\n    *read_info;\n\n  int\n    c;\n\n  MagickBooleanType\n    cmyk,\n    status;\n\n  PointInfo\n    delta;\n\n  RectangleInfo\n    bounding_box,\n    page;\n\n  char\n    *p;\n\n  SegmentInfo\n    bounds;\n\n  size_t\n    height,\n    width;\n\n  ssize_t\n    count;\n\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  /*\n    Open image file.\n  */\n  image=AcquireImage(image_info);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);\n  if (status == MagickFalse)\n    {\n      ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n        image_info->filename);\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n    Set the page density.\n  */\n  delta.x=DefaultResolution;\n  delta.y=DefaultResolution;\n  if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))\n    {\n      GeometryInfo\n        geometry_info;\n\n      MagickStatusType\n        flags;\n\n      flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n      if ((flags & RhoValue) != 0)\n        image->x_resolution=geometry_info.rho;\n      image->y_resolution=image->x_resolution;\n      if ((flags & SigmaValue) != 0)\n        image->y_resolution=geometry_info.sigma;\n    }\n  /*\n    Determine page geometry from the PCL media box.\n  */\n  cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;\n  count=0;\n  (void) memset(&bounding_box,0,sizeof(bounding_box));\n  (void) memset(&bounds,0,sizeof(bounds));\n  (void) memset(&page,0,sizeof(page));\n  (void) memset(command,0,sizeof(command));\n  p=command;\n  for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))\n  {\n    if (image_info->page != (char *) NULL)\n      continue;\n    /*\n      Note PCL elements.\n    */\n    *p++=(char) c;\n    if ((c != (int) '/') && (c != '\\n') &&\n        ((size_t) (p-command) < (MaxTextExtent-1)))\n      continue;\n    *p='\\0';\n    p=command;\n    /*\n      Is this a CMYK document?\n    */\n    if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)\n      cmyk=MagickTrue;\n    if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)\n      {\n        /*\n          Note region defined by crop box.\n        */\n        count=(ssize_t) sscanf(command,\"CropBox [%lf %lf %lf %lf\",\n          &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n        if (count != 4)\n          count=(ssize_t) sscanf(command,\"CropBox[%lf %lf %lf %lf\",\n            &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n      }\n    if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)\n      {\n        /*\n          Note region defined by media box.\n        */\n        count=(ssize_t) sscanf(command,\"MediaBox [%lf %lf %lf %lf\",\n          &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n        if (count != 4)\n          count=(ssize_t) sscanf(command,\"MediaBox[%lf %lf %lf %lf\",\n            &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n      }\n    if (count != 4)\n      continue;\n    /*\n      Set PCL render geometry.\n    */\n    width=(size_t) floor(bounds.x2-bounds.x1+0.5);\n    height=(size_t) floor(bounds.y2-bounds.y1+0.5);\n    if (width > page.width)\n      page.width=width;\n    if (height > page.height)\n      page.height=height;\n  }\n  (void) CloseBlob(image);\n  /*\n    Render PCL with the GhostPCL delegate.\n  */\n  if ((page.width == 0) || (page.height == 0))\n    (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n  if (image_info->page != (char *) NULL)\n    (void) ParseAbsoluteGeometry(image_info->page,&page);\n  (void) FormatLocaleString(geometry,MaxTextExtent,\"%.20gx%.20g\",(double)\n    page.width,(double) page.height);\n  if (image_info->monochrome != MagickFalse)\n    delegate_info=GetDelegateInfo(\"pcl:mono\",(char *) NULL,exception);\n  else\n     if (cmyk != MagickFalse)\n       delegate_info=GetDelegateInfo(\"pcl:cmyk\",(char *) NULL,exception);\n     else\n       delegate_info=GetDelegateInfo(\"pcl:color\",(char *) NULL,exception);\n  if (delegate_info == (const DelegateInfo *) NULL)\n    {\n      image=DestroyImage(image);\n      return((Image *) NULL);\n    }\n  if ((page.width == 0) || (page.height == 0))\n    (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n  if (image_info->page != (char *) NULL)\n    (void) ParseAbsoluteGeometry(image_info->page,&page);\n  density=AcquireString(\"\");\n  options=AcquireString(\"\");\n  (void) FormatLocaleString(density,MaxTextExtent,\"%gx%g\",\n    image->x_resolution,image->y_resolution);\n  if (image_info->ping != MagickFalse)\n    (void) FormatLocaleString(density,MagickPathExtent,\"2.0x2.0\");\n  page.width=(size_t) floor((double) page.width*image->x_resolution/delta.x+\n    0.5);\n  page.height=(size_t) floor((double) page.height*image->y_resolution/delta.y+\n    0.5);\n  (void) FormatLocaleString(options,MaxTextExtent,\"-g%.20gx%.20g \",(double)\n     page.width,(double) page.height);\n  image=DestroyImage(image);\n  read_info=CloneImageInfo(image_info);\n  *read_info->magick='\\0';\n  if (read_info->number_scenes != 0)\n    {\n      if (read_info->number_scenes != 1)\n        (void) FormatLocaleString(options,MaxTextExtent,\"-dLastPage=%.20g\",\n          (double) (read_info->scene+read_info->number_scenes));\n      else\n        (void) FormatLocaleString(options,MaxTextExtent,\n          \"-dFirstPage=%.20g -dLastPage=%.20g\",(double) read_info->scene+1,\n          (double) (read_info->scene+read_info->number_scenes));\n      read_info->number_scenes=0;\n      if (read_info->scenes != (char *) NULL)\n        *read_info->scenes='\\0';\n    }\n  (void) CopyMagickString(filename,read_info->filename,MaxTextExtent);\n  (void) AcquireUniqueFilename(read_info->filename);\n  (void) FormatLocaleString(command,MaxTextExtent,\n    GetDelegateCommands(delegate_info),\n    read_info->antialias != MagickFalse ? 4 : 1,\n    read_info->antialias != MagickFalse ? 4 : 1,density,options,\n    read_info->filename,input_filename);\n  options=DestroyString(options);\n  density=DestroyString(density);\n  status=ExternalDelegateCommand(MagickFalse,read_info->verbose,command,\n    (char *) NULL,exception) != 0 ? MagickTrue : MagickFalse;\n  image=ReadImage(read_info,exception);\n  (void) RelinquishUniqueFileResource(read_info->filename);\n  (void) RelinquishUniqueFileResource(input_filename);\n  read_info=DestroyImageInfo(read_info);\n  if (image == (Image *) NULL)\n    ThrowReaderException(DelegateError,\"PCLDelegateFailed\");\n  if (LocaleCompare(image->magick,\"BMP\") == 0)\n    {\n      Image\n        *cmyk_image;\n\n      cmyk_image=ConsolidateCMYKImages(image,&image->exception);\n      if (cmyk_image != (Image *) NULL)\n        {\n          image=DestroyImageList(image);\n          image=cmyk_image;\n        }\n    }\n  do\n  {\n    (void) CopyMagickString(image->filename,filename,MaxTextExtent);\n    image->page=page;\n    if (image_info->ping != MagickFalse)\n      {\n        image->magick_columns*=image->x_resolution/2.0;\n        image->magick_rows*=image->y_resolution/2.0;\n        image->columns*=image->x_resolution/2.0;\n        image->rows*=image->y_resolution/2.0;\n      }\n    next_image=SyncNextImageInList(image);\n    if (next_image != (Image *) NULL)\n      image=next_image;\n  } while (next_image != (Image *) NULL);\n  return(GetFirstImageInList(image));\n}", "func_hash": 285956846610376765198872183403915882061, "file_name": "pcl.c", "file_hash": 338547174937023730341471137685130471169, "cwe": ["CWE-190"], "cve": "CVE-2022-32546", "cve_desc": "A vulnerability was found in ImageMagick, causing an outside the range of representable values of type 'unsigned long' at coders/pcl.c, when crafted or untrusted input is processed. This leads to a negative impact to application availability or other problems related to undefined behavior.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32546"}
{"idx": 225566, "project": "ImageMagick6", "commit_id": "29c8abce0da56b536542f76a9ddfebdaab5b2943", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/29c8abce0da56b536542f76a9ddfebdaab5b2943", "commit_message": "https://github.com/ImageMagick/ImageMagick/pull/4986", "target": 0, "func": "static Image *ReadPCLImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define CropBox  \"CropBox\"\n#define DeviceCMYK  \"DeviceCMYK\"\n#define MediaBox  \"MediaBox\"\n#define RenderPCLText  \"  Rendering PCL...  \"\n\n  char\n    command[MaxTextExtent],\n    *density,\n    filename[MaxTextExtent],\n    geometry[MaxTextExtent],\n    *options,\n    input_filename[MaxTextExtent];\n\n  const DelegateInfo\n    *delegate_info;\n\n  Image\n    *image,\n    *next_image;\n\n  ImageInfo\n    *read_info;\n\n  int\n    c;\n\n  MagickBooleanType\n    cmyk,\n    status;\n\n  PointInfo\n    delta;\n\n  RectangleInfo\n    bounding_box,\n    page;\n\n  char\n    *p;\n\n  SegmentInfo\n    bounds;\n\n  size_t\n    height,\n    width;\n\n  ssize_t\n    count;\n\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  /*\n    Open image file.\n  */\n  image=AcquireImage(image_info);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);\n  if (status == MagickFalse)\n    {\n      ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n        image_info->filename);\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n    Set the page density.\n  */\n  delta.x=DefaultResolution;\n  delta.y=DefaultResolution;\n  if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))\n    {\n      GeometryInfo\n        geometry_info;\n\n      MagickStatusType\n        flags;\n\n      flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n      if ((flags & RhoValue) != 0)\n        image->x_resolution=geometry_info.rho;\n      image->y_resolution=image->x_resolution;\n      if ((flags & SigmaValue) != 0)\n        image->y_resolution=geometry_info.sigma;\n    }\n  /*\n    Determine page geometry from the PCL media box.\n  */\n  cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;\n  count=0;\n  (void) memset(&bounding_box,0,sizeof(bounding_box));\n  (void) memset(&bounds,0,sizeof(bounds));\n  (void) memset(&page,0,sizeof(page));\n  (void) memset(command,0,sizeof(command));\n  p=command;\n  for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))\n  {\n    if (image_info->page != (char *) NULL)\n      continue;\n    /*\n      Note PCL elements.\n    */\n    *p++=(char) c;\n    if ((c != (int) '/') && (c != '\\n') &&\n        ((size_t) (p-command) < (MaxTextExtent-1)))\n      continue;\n    *p='\\0';\n    p=command;\n    /*\n      Is this a CMYK document?\n    */\n    if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)\n      cmyk=MagickTrue;\n    if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)\n      {\n        /*\n          Note region defined by crop box.\n        */\n        count=(ssize_t) sscanf(command,\"CropBox [%lf %lf %lf %lf\",\n          &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n        if (count != 4)\n          count=(ssize_t) sscanf(command,\"CropBox[%lf %lf %lf %lf\",\n            &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n      }\n    if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)\n      {\n        /*\n          Note region defined by media box.\n        */\n        count=(ssize_t) sscanf(command,\"MediaBox [%lf %lf %lf %lf\",\n          &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n        if (count != 4)\n          count=(ssize_t) sscanf(command,\"MediaBox[%lf %lf %lf %lf\",\n            &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n      }\n    if (count != 4)\n      continue;\n    /*\n      Set PCL render geometry.\n    */\n    width=(size_t) CastDoubleToLong(floor(bounds.x2-bounds.x1+0.5));\n    height=(size_t) CastDoubleToLong(floor(bounds.y2-bounds.y1+0.5));\n    if (width > page.width)\n      page.width=width;\n    if (height > page.height)\n      page.height=height;\n  }\n  (void) CloseBlob(image);\n  /*\n    Render PCL with the GhostPCL delegate.\n  */\n  if ((page.width == 0) || (page.height == 0))\n    (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n  if (image_info->page != (char *) NULL)\n    (void) ParseAbsoluteGeometry(image_info->page,&page);\n  (void) FormatLocaleString(geometry,MaxTextExtent,\"%.20gx%.20g\",(double)\n    page.width,(double) page.height);\n  if (image_info->monochrome != MagickFalse)\n    delegate_info=GetDelegateInfo(\"pcl:mono\",(char *) NULL,exception);\n  else\n     if (cmyk != MagickFalse)\n       delegate_info=GetDelegateInfo(\"pcl:cmyk\",(char *) NULL,exception);\n     else\n       delegate_info=GetDelegateInfo(\"pcl:color\",(char *) NULL,exception);\n  if (delegate_info == (const DelegateInfo *) NULL)\n    {\n      image=DestroyImage(image);\n      return((Image *) NULL);\n    }\n  if ((page.width == 0) || (page.height == 0))\n    (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n  if (image_info->page != (char *) NULL)\n    (void) ParseAbsoluteGeometry(image_info->page,&page);\n  density=AcquireString(\"\");\n  options=AcquireString(\"\");\n  (void) FormatLocaleString(density,MaxTextExtent,\"%gx%g\",\n    image->x_resolution,image->y_resolution);\n  if (image_info->ping != MagickFalse)\n    (void) FormatLocaleString(density,MagickPathExtent,\"2.0x2.0\");\n  page.width=(size_t) floor((double) page.width*image->x_resolution/delta.x+\n    0.5);\n  page.height=(size_t) floor((double) page.height*image->y_resolution/delta.y+\n    0.5);\n  (void) FormatLocaleString(options,MaxTextExtent,\"-g%.20gx%.20g \",(double)\n     page.width,(double) page.height);\n  image=DestroyImage(image);\n  read_info=CloneImageInfo(image_info);\n  *read_info->magick='\\0';\n  if (read_info->number_scenes != 0)\n    {\n      if (read_info->number_scenes != 1)\n        (void) FormatLocaleString(options,MaxTextExtent,\"-dLastPage=%.20g\",\n          (double) (read_info->scene+read_info->number_scenes));\n      else\n        (void) FormatLocaleString(options,MaxTextExtent,\n          \"-dFirstPage=%.20g -dLastPage=%.20g\",(double) read_info->scene+1,\n          (double) (read_info->scene+read_info->number_scenes));\n      read_info->number_scenes=0;\n      if (read_info->scenes != (char *) NULL)\n        *read_info->scenes='\\0';\n    }\n  (void) CopyMagickString(filename,read_info->filename,MaxTextExtent);\n  (void) AcquireUniqueFilename(read_info->filename);\n  (void) FormatLocaleString(command,MaxTextExtent,\n    GetDelegateCommands(delegate_info),\n    read_info->antialias != MagickFalse ? 4 : 1,\n    read_info->antialias != MagickFalse ? 4 : 1,density,options,\n    read_info->filename,input_filename);\n  options=DestroyString(options);\n  density=DestroyString(density);\n  status=ExternalDelegateCommand(MagickFalse,read_info->verbose,command,\n    (char *) NULL,exception) != 0 ? MagickTrue : MagickFalse;\n  image=ReadImage(read_info,exception);\n  (void) RelinquishUniqueFileResource(read_info->filename);\n  (void) RelinquishUniqueFileResource(input_filename);\n  read_info=DestroyImageInfo(read_info);\n  if (image == (Image *) NULL)\n    ThrowReaderException(DelegateError,\"PCLDelegateFailed\");\n  if (LocaleCompare(image->magick,\"BMP\") == 0)\n    {\n      Image\n        *cmyk_image;\n\n      cmyk_image=ConsolidateCMYKImages(image,&image->exception);\n      if (cmyk_image != (Image *) NULL)\n        {\n          image=DestroyImageList(image);\n          image=cmyk_image;\n        }\n    }\n  do\n  {\n    (void) CopyMagickString(image->filename,filename,MaxTextExtent);\n    image->page=page;\n    if (image_info->ping != MagickFalse)\n      {\n        image->magick_columns*=image->x_resolution/2.0;\n        image->magick_rows*=image->y_resolution/2.0;\n        image->columns*=image->x_resolution/2.0;\n        image->rows*=image->y_resolution/2.0;\n      }\n    next_image=SyncNextImageInList(image);\n    if (next_image != (Image *) NULL)\n      image=next_image;\n  } while (next_image != (Image *) NULL);\n  return(GetFirstImageInList(image));\n}", "func_hash": 83929363874861063792960158581169163951, "file_name": "pcl.c", "file_hash": 19401947442598835469700605981025281430, "cwe": ["CWE-190"], "cve": "CVE-2022-32546", "cve_desc": "A vulnerability was found in ImageMagick, causing an outside the range of representable values of type 'unsigned long' at coders/pcl.c, when crafted or untrusted input is processed. This leads to a negative impact to application availability or other problems related to undefined behavior.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32546"}
{"idx": 195409, "project": "gpac", "commit_id": "64a2e1b799352ac7d7aad1989bc06e7b0f2b01db", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/64a2e1b799352ac7d7aad1989bc06e7b0f2b01db", "commit_message": "fixed #2092", "target": 1, "func": "\nvoid gitn_box_del(GF_Box *s)\n{\n\tu32 i;\n\tGroupIdToNameBox *ptr = (GroupIdToNameBox *)s;\n\tif (ptr == NULL) return;\n\tfor (i=0; inb_entries; i++) {\n\t\tif (ptr->entries[i].name) gf_free(ptr->entries[i].name);\n\t}\n\tif (ptr->entries) gf_free(ptr->entries);\n\tgf_free(ptr);", "func_hash": 37642310110270321687625000100653046485, "file_name": "box_code_base.c", "file_hash": 212802147696207025803784466432150384318, "cwe": ["CWE-476"], "cve": "CVE-2021-4043", "cve_desc": "NULL Pointer Dereference in GitHub repository gpac/gpac prior to 1.1.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-4043"}
{"idx": 226029, "project": "gpac", "commit_id": "64a2e1b799352ac7d7aad1989bc06e7b0f2b01db", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/64a2e1b799352ac7d7aad1989bc06e7b0f2b01db", "commit_message": "fixed #2092", "target": 0, "func": "\nvoid gitn_box_del(GF_Box *s)\n{\n\tu32 i;\n\tGroupIdToNameBox *ptr = (GroupIdToNameBox *)s;\n\tif (ptr == NULL) return;\n\tif (ptr->entries) {\n\t\tfor (i=0; inb_entries; i++) {\n\t\t\tif (ptr->entries[i].name) gf_free(ptr->entries[i].name);\n\t\t}\n\t\tgf_free(ptr->entries);\n\t}\n\tgf_free(ptr);", "func_hash": 265612189453593240220286582640125308421, "file_name": "box_code_base.c", "file_hash": 49851003819063672326837979869211393199, "cwe": ["CWE-476"], "cve": "CVE-2021-4043", "cve_desc": "NULL Pointer Dereference in GitHub repository gpac/gpac prior to 1.1.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-4043"}
{"idx": 195410, "project": "tensorflow", "commit_id": "965b97e4a9650495cda5a8c210ef6684b4b9eceb", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/965b97e4a9650495cda5a8c210ef6684b4b9eceb", "commit_message": "Properly validate sparse tensor in `SparseTensorSliceDataset`\n\nExisting validation was incomplete.\n\nPiperOrigin-RevId: 415375048\nChange-Id: I14cd18f29ede73286f3ffac35171bd15828997e9", "target": 1, "func": "  void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override {\n    // Create a new SparseTensorSliceDatasetOp::Dataset, insert it in\n    // the step container, and return it as the output.\n    const Tensor* indices;\n    OP_REQUIRES_OK(ctx, ctx->input(\"indices\", &indices));\n    const Tensor* values;\n    OP_REQUIRES_OK(ctx, ctx->input(\"values\", &values));\n    const Tensor* dense_shape;\n    OP_REQUIRES_OK(ctx, ctx->input(\"dense_shape\", &dense_shape));\n\n    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices->shape()),\n                errors::InvalidArgument(\n                    \"Input indices should be a matrix but received shape \",\n                    indices->shape().DebugString()));\n\n    const auto num_indices = indices->NumElements();\n    const auto num_values = values->NumElements();\n    if (num_indices == 0 || num_values == 0) {\n      OP_REQUIRES(ctx, num_indices == num_values,\n                  errors::InvalidArgument(\n                      \"If indices or values are empty, the other one must also \"\n                      \"be. Got indices of shape \",\n                      indices->shape().DebugString(), \" and values of shape \",\n                      values->shape().DebugString()));\n    }\n    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values->shape()),\n                errors::InvalidArgument(\n                    \"Input values should be a vector but received shape \",\n                    indices->shape().DebugString()));\n    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(dense_shape->shape()),\n                errors::InvalidArgument(\n                    \"Input shape should be a vector but received shape \",\n                    dense_shape->shape().DebugString()));\n\n    // We currently ensure that `sparse_tensor` is ordered in the\n    // batch dimension.\n    // TODO(mrry): Investigate ways to avoid this unconditional check\n    // if we can be sure that the sparse tensor was produced in an\n    // appropriate order (e.g. by `tf.parse_example()` or a Dataset\n    // that batches elements into rows of a SparseTensor).\n    int64_t previous_batch_index = -1;\n    for (int64_t i = 0; i < indices->dim_size(0); ++i) {\n      int64_t next_batch_index = indices->matrix()(i, 0);\n      OP_REQUIRES(\n          ctx, next_batch_index >= previous_batch_index,\n          errors::Unimplemented(\"The SparseTensor must be ordered in the batch \"\n                                \"dimension; handling arbitrarily ordered input \"\n                                \"is not currently supported.\"));\n      previous_batch_index = next_batch_index;\n    }\n    gtl::InlinedVector std_order(dense_shape->NumElements(), 0);\n    sparse::SparseTensor tensor;\n    OP_REQUIRES_OK(\n        ctx, sparse::SparseTensor::Create(\n                 *indices, *values, TensorShape(dense_shape->vec()),\n                 std_order, &tensor));\n    *output = new Dataset(ctx, std::move(tensor));\n  }", "func_hash": 232798786480644222523895580158118045723, "file_name": "sparse_tensor_slice_dataset_op.cc", "file_hash": 20179985196620256343354076777909821072, "cwe": ["CWE-476"], "cve": "CVE-2022-21736", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `SparseTensorSliceDataset` has an undefined behavior: under certain condition it can be made to dereference a `nullptr` value. The 3 input arguments to `SparseTensorSliceDataset` represent a sparse tensor. However, there are some preconditions that these arguments must satisfy but these are not validated in the implementation. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21736"}
{"idx": 226433, "project": "tensorflow", "commit_id": "965b97e4a9650495cda5a8c210ef6684b4b9eceb", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/965b97e4a9650495cda5a8c210ef6684b4b9eceb", "commit_message": "Properly validate sparse tensor in `SparseTensorSliceDataset`\n\nExisting validation was incomplete.\n\nPiperOrigin-RevId: 415375048\nChange-Id: I14cd18f29ede73286f3ffac35171bd15828997e9", "target": 0, "func": "  void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override {\n    // Create a new SparseTensorSliceDatasetOp::Dataset, insert it in\n    // the step container, and return it as the output.\n    const Tensor* indices;\n    OP_REQUIRES_OK(ctx, ctx->input(\"indices\", &indices));\n    const Tensor* values;\n    OP_REQUIRES_OK(ctx, ctx->input(\"values\", &values));\n    const Tensor* dense_shape;\n    OP_REQUIRES_OK(ctx, ctx->input(\"dense_shape\", &dense_shape));\n\n    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices->shape()),\n                errors::InvalidArgument(\"Input indices must be a matrix. Got: \",\n                                        indices->shape().DebugString()));\n    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values->shape()),\n                errors::InvalidArgument(\"Input values must be a vector. Got: \",\n                                        values->shape().DebugString()));\n    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(dense_shape->shape()),\n                errors::InvalidArgument(\"Input shape must be a vector. Got: \",\n                                        dense_shape->shape().DebugString()));\n    OP_REQUIRES(\n        ctx, values->shape().dim_size(0) == indices->shape().dim_size(0),\n        errors::InvalidArgument(\n            \"Number of values must match first dimension of indices. \", \"Got \",\n            values->shape().dim_size(0),\n            \" values, indices shape: \", indices->shape().DebugString()));\n    OP_REQUIRES(\n        ctx, dense_shape->shape().dim_size(0) == indices->shape().dim_size(1),\n        errors::InvalidArgument(\n            \"Number of dimensions must match second dimension of indices. \",\n            \"Got \", dense_shape->shape().dim_size(0),\n            \" dimensions, indices shape: \", indices->shape().DebugString()));\n    OP_REQUIRES(ctx, dense_shape->NumElements() > 0,\n                errors::InvalidArgument(\n                    \"The shape argument requires at least one element.\"));\n\n    // We currently ensure that `sparse_tensor` is ordered in the\n    // batch dimension.\n    // TODO(mrry): Investigate ways to avoid this unconditional check\n    // if we can be sure that the sparse tensor was produced in an\n    // appropriate order (e.g. by `tf.parse_example()` or a Dataset\n    // that batches elements into rows of a SparseTensor).\n    int64_t previous_batch_index = -1;\n    for (int64_t i = 0; i < indices->dim_size(0); ++i) {\n      int64_t next_batch_index = indices->matrix()(i, 0);\n      OP_REQUIRES(\n          ctx, next_batch_index >= previous_batch_index,\n          errors::Unimplemented(\"The SparseTensor must be ordered in the batch \"\n                                \"dimension; handling arbitrarily ordered input \"\n                                \"is not currently supported.\"));\n      previous_batch_index = next_batch_index;\n    }\n    gtl::InlinedVector std_order(dense_shape->NumElements(), 0);\n    sparse::SparseTensor tensor;\n    OP_REQUIRES_OK(\n        ctx, sparse::SparseTensor::Create(\n                 *indices, *values, TensorShape(dense_shape->vec()),\n                 std_order, &tensor));\n    *output = new Dataset(ctx, std::move(tensor));\n  }", "func_hash": 227797014623034241967270311347340556143, "file_name": "sparse_tensor_slice_dataset_op.cc", "file_hash": 223168035118292217298610217555690212472, "cwe": ["CWE-476"], "cve": "CVE-2022-21736", "cve_desc": "Tensorflow is an Open Source Machine Learning Framework. The implementation of `SparseTensorSliceDataset` has an undefined behavior: under certain condition it can be made to dereference a `nullptr` value. The 3 input arguments to `SparseTensorSliceDataset` represent a sparse tensor. However, there are some preconditions that these arguments must satisfy but these are not validated in the implementation. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21736"}
{"idx": 195471, "project": "weechat", "commit_id": "9904cb6d2eb40f679d8ff6557c22d53a3e3dc75a", "project_url": "https://github.com/weechat/weechat", "commit_url": "https://github.com/weechat/weechat/commit/9904cb6d2eb40f679d8ff6557c22d53a3e3dc75a", "commit_message": "irc: fix crash when receiving a malformed message 352 (who)\n\nThanks to Stuart Nevans Locke for reporting the issue.", "target": 1, "func": "IRC_PROTOCOL_CALLBACK(352)\n{\n    char *pos_attr, *pos_hopcount, *pos_realname, *str_host;\n    int arg_start, length;\n    struct t_irc_channel *ptr_channel;\n    struct t_irc_nick *ptr_nick;\n\n    IRC_PROTOCOL_MIN_ARGS(5);\n\n    /* silently ignore malformed 352 message (missing infos) */\n    if (argc < 8)\n        return WEECHAT_RC_OK;\n\n    pos_attr = NULL;\n    pos_hopcount = NULL;\n    pos_realname = NULL;\n\n    if (argc > 8)\n    {\n        arg_start = (strcmp (argv[8], \"*\") == 0) ? 9 : 8;\n        if (argv[arg_start][0] == ':')\n        {\n            pos_attr = NULL;\n            pos_hopcount = (argc > arg_start) ? argv[arg_start] + 1 : NULL;\n            pos_realname = (argc > arg_start + 1) ? argv_eol[arg_start + 1] : NULL;\n        }\n        else\n        {\n            pos_attr = argv[arg_start];\n            pos_hopcount = (argc > arg_start + 1) ? argv[arg_start + 1] + 1 : NULL;\n            pos_realname = (argc > arg_start + 2) ? argv_eol[arg_start + 2] : NULL;\n        }\n    }\n\n    ptr_channel = irc_channel_search (server, argv[3]);\n    ptr_nick = (ptr_channel) ?\n        irc_nick_search (server, ptr_channel, argv[7]) : NULL;\n\n    /* update host in nick */\n    if (ptr_nick)\n    {\n        length = strlen (argv[4]) + 1 + strlen (argv[5]) + 1;\n        str_host = malloc (length);\n        if (str_host)\n        {\n            snprintf (str_host, length, \"%s@%s\", argv[4], argv[5]);\n            irc_nick_set_host (ptr_nick, str_host);\n            free (str_host);\n        }\n    }\n\n    /* update away flag in nick */\n    if (ptr_channel && ptr_nick && pos_attr)\n    {\n        irc_nick_set_away (server, ptr_channel, ptr_nick,\n                           (pos_attr[0] == 'G') ? 1 : 0);\n    }\n\n    /* update realname in nick */\n    if (ptr_channel && ptr_nick && pos_realname)\n    {\n        if (ptr_nick->realname)\n            free (ptr_nick->realname);\n        if (pos_realname &&\n            weechat_hashtable_has_key (server->cap_list, \"extended-join\"))\n        {\n            ptr_nick->realname = strdup (pos_realname);\n        }\n        else\n        {\n            ptr_nick->realname = NULL;\n        }\n    }\n\n    /* display output of who (manual who from user) */\n    if (!ptr_channel || (ptr_channel->checking_whox <= 0))\n    {\n        weechat_printf_date_tags (\n            irc_msgbuffer_get_target_buffer (\n                server, NULL, command, \"who\", NULL),\n            date,\n            irc_protocol_tags (command, \"irc_numeric\", NULL, NULL),\n            \"%s%s[%s%s%s] %s%s %s(%s%s@%s%s)%s %s%s%s%s(%s)\",\n            weechat_prefix (\"network\"),\n            IRC_COLOR_CHAT_DELIMITERS,\n            IRC_COLOR_CHAT_CHANNEL,\n            argv[3],\n            IRC_COLOR_CHAT_DELIMITERS,\n            irc_nick_color_for_msg (server, 1, NULL, argv[7]),\n            argv[7],\n            IRC_COLOR_CHAT_DELIMITERS,\n            IRC_COLOR_CHAT_HOST,\n            argv[4],\n            argv[5],\n            IRC_COLOR_CHAT_DELIMITERS,\n            IRC_COLOR_RESET,\n            (pos_attr) ? pos_attr : \"\",\n            (pos_attr) ? \" \" : \"\",\n            (pos_hopcount) ? pos_hopcount : \"\",\n            (pos_hopcount) ? \" \" : \"\",\n            (pos_realname) ? pos_realname : \"\");\n    }\n\n    return WEECHAT_RC_OK;\n}", "func_hash": 334241185700640959176375322270000746009, "file_name": "irc-protocol.c", "file_hash": 25326141648227228091841815556030791460, "cwe": ["CWE-476"], "cve": "CVE-2020-9759", "cve_desc": "A Vulnerability of LG Electronic web OS TV Emulator could allow an attacker to escalate privileges and overwrite certain files. This vulnerability is due to wrong environment setting. An attacker could exploit this vulnerability through crafted configuration files and executable files.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-9759"}
{"idx": 227022, "project": "weechat", "commit_id": "9904cb6d2eb40f679d8ff6557c22d53a3e3dc75a", "project_url": "https://github.com/weechat/weechat", "commit_url": "https://github.com/weechat/weechat/commit/9904cb6d2eb40f679d8ff6557c22d53a3e3dc75a", "commit_message": "irc: fix crash when receiving a malformed message 352 (who)\n\nThanks to Stuart Nevans Locke for reporting the issue.", "target": 0, "func": "IRC_PROTOCOL_CALLBACK(352)\n{\n    char *pos_attr, *pos_hopcount, *pos_realname, *str_host;\n    int arg_start, length;\n    struct t_irc_channel *ptr_channel;\n    struct t_irc_nick *ptr_nick;\n\n    IRC_PROTOCOL_MIN_ARGS(5);\n\n    /* silently ignore malformed 352 message (missing infos) */\n    if (argc < 8)\n        return WEECHAT_RC_OK;\n\n    pos_attr = NULL;\n    pos_hopcount = NULL;\n    pos_realname = NULL;\n\n    if (argc > 8)\n    {\n        arg_start = ((argc > 9) && (strcmp (argv[8], \"*\") == 0)) ? 9 : 8;\n        if (argv[arg_start][0] == ':')\n        {\n            pos_attr = NULL;\n            pos_hopcount = (argc > arg_start) ? argv[arg_start] + 1 : NULL;\n            pos_realname = (argc > arg_start + 1) ? argv_eol[arg_start + 1] : NULL;\n        }\n        else\n        {\n            pos_attr = argv[arg_start];\n            pos_hopcount = (argc > arg_start + 1) ? argv[arg_start + 1] + 1 : NULL;\n            pos_realname = (argc > arg_start + 2) ? argv_eol[arg_start + 2] : NULL;\n        }\n    }\n\n    ptr_channel = irc_channel_search (server, argv[3]);\n    ptr_nick = (ptr_channel) ?\n        irc_nick_search (server, ptr_channel, argv[7]) : NULL;\n\n    /* update host in nick */\n    if (ptr_nick)\n    {\n        length = strlen (argv[4]) + 1 + strlen (argv[5]) + 1;\n        str_host = malloc (length);\n        if (str_host)\n        {\n            snprintf (str_host, length, \"%s@%s\", argv[4], argv[5]);\n            irc_nick_set_host (ptr_nick, str_host);\n            free (str_host);\n        }\n    }\n\n    /* update away flag in nick */\n    if (ptr_channel && ptr_nick && pos_attr)\n    {\n        irc_nick_set_away (server, ptr_channel, ptr_nick,\n                           (pos_attr[0] == 'G') ? 1 : 0);\n    }\n\n    /* update realname in nick */\n    if (ptr_channel && ptr_nick && pos_realname)\n    {\n        if (ptr_nick->realname)\n            free (ptr_nick->realname);\n        if (pos_realname &&\n            weechat_hashtable_has_key (server->cap_list, \"extended-join\"))\n        {\n            ptr_nick->realname = strdup (pos_realname);\n        }\n        else\n        {\n            ptr_nick->realname = NULL;\n        }\n    }\n\n    /* display output of who (manual who from user) */\n    if (!ptr_channel || (ptr_channel->checking_whox <= 0))\n    {\n        weechat_printf_date_tags (\n            irc_msgbuffer_get_target_buffer (\n                server, NULL, command, \"who\", NULL),\n            date,\n            irc_protocol_tags (command, \"irc_numeric\", NULL, NULL),\n            \"%s%s[%s%s%s] %s%s %s(%s%s@%s%s)%s %s%s%s%s(%s)\",\n            weechat_prefix (\"network\"),\n            IRC_COLOR_CHAT_DELIMITERS,\n            IRC_COLOR_CHAT_CHANNEL,\n            argv[3],\n            IRC_COLOR_CHAT_DELIMITERS,\n            irc_nick_color_for_msg (server, 1, NULL, argv[7]),\n            argv[7],\n            IRC_COLOR_CHAT_DELIMITERS,\n            IRC_COLOR_CHAT_HOST,\n            argv[4],\n            argv[5],\n            IRC_COLOR_CHAT_DELIMITERS,\n            IRC_COLOR_RESET,\n            (pos_attr) ? pos_attr : \"\",\n            (pos_attr) ? \" \" : \"\",\n            (pos_hopcount) ? pos_hopcount : \"\",\n            (pos_hopcount) ? \" \" : \"\",\n            (pos_realname) ? pos_realname : \"\");\n    }\n\n    return WEECHAT_RC_OK;\n}", "func_hash": 240473779372461876579512981083881440945, "file_name": "irc-protocol.c", "file_hash": 267510684279184111108460541610753784321, "cwe": ["CWE-476"], "cve": "CVE-2020-9759", "cve_desc": "A Vulnerability of LG Electronic web OS TV Emulator could allow an attacker to escalate privileges and overwrite certain files. This vulnerability is due to wrong environment setting. An attacker could exploit this vulnerability through crafted configuration files and executable files.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-9759"}
{"idx": 195565, "project": "hhvm", "commit_id": "dbeb9a56a638e3fdcef8b691c2a2967132dae692", "project_url": "https://github.com/facebook/hhvm", "commit_url": "https://github.com/facebook/hhvm/commit/dbeb9a56a638e3fdcef8b691c2a2967132dae692", "commit_message": "string_number_format: Correctly handles return value of snprintf\n\nSummary: `snprintf` can return a value greater than the number of bytes copied. In case the first byte of the string is not a digit (could be '-'), size of `tmpstr` was being updated without checking `tmplen`. This resulted in either an assertion error or a heap overflow depending on whether the assertion is compiled or not.\n\nReviewed By: mofarrell, qianxuweiren\n\nDifferential Revision: D17327899\n\nfbshipit-source-id: ee53875d21e02608c6d870388eecf1464de24ff1", "target": 1, "func": "String string_number_format(double d, int dec,\n                            const String& dec_point,\n                            const String& thousand_sep) {\n  char *tmpbuf = nullptr, *resbuf;\n  char *s, *t;  /* source, target */\n  char *dp;\n  int integral;\n  int tmplen, reslen=0;\n  int count=0;\n  int is_negative=0;\n\n  if (d < 0) {\n    is_negative = 1;\n    d = -d;\n  }\n\n  if (dec < 0) dec = 0;\n  d = php_math_round(d, dec);\n\n  // departure from PHP: we got rid of dependencies on spprintf() here.\n  String tmpstr(63, ReserveString);\n  tmpbuf = tmpstr.mutableData();\n  tmplen = snprintf(tmpbuf, 64, \"%.*F\", dec, d);\n  if (tmplen < 0) return empty_string();\n  if (tmpbuf == nullptr || !isdigit((int)tmpbuf[0])) {\n    tmpstr.setSize(tmplen);\n    return tmpstr;\n  }\n  if (tmplen >= 64) {\n    // Uncommon, asked for more than 64 chars worth of precision\n    tmpstr = String(tmplen, ReserveString);\n    tmpbuf = tmpstr.mutableData();\n    tmplen = snprintf(tmpbuf, tmplen + 1, \"%.*F\", dec, d);\n    if (tmplen < 0) return empty_string();\n    if (tmpbuf == nullptr || !isdigit((int)tmpbuf[0])) {\n      tmpstr.setSize(tmplen);\n      return tmpstr;\n    }\n  }\n\n  /* find decimal point, if expected */\n  if (dec) {\n    dp = strpbrk(tmpbuf, \".,\");\n  } else {\n    dp = nullptr;\n  }\n\n  /* calculate the length of the return buffer */\n  if (dp) {\n    integral = dp - tmpbuf;\n  } else {\n    /* no decimal point was found */\n    integral = tmplen;\n  }\n\n  /* allow for thousand separators */\n  if (!thousand_sep.empty()) {\n    if (integral + thousand_sep.size() * ((integral-1) / 3) < integral) {\n      /* overflow */\n      raise_error(\"String overflow\");\n    }\n\n    integral += ((integral-1) / 3) * thousand_sep.size();\n  }\n\n  reslen = integral;\n\n  if (dec) {\n    reslen += dec;\n\n    if (!dec_point.empty()) {\n      if (reslen + dec_point.size() < dec_point.size()) {\n        /* overflow */\n        raise_error(\"String overflow\");\n      }\n      reslen += dec_point.size();\n    }\n  }\n\n  /* add a byte for minus sign */\n  if (is_negative) {\n    reslen++;\n  }\n  String resstr(reslen, ReserveString);\n  resbuf = resstr.mutableData();\n\n  s = tmpbuf+tmplen-1;\n  t = resbuf+reslen-1;\n\n  /* copy the decimal places.\n   * Take care, as the sprintf implementation may return less places than\n   * we requested due to internal buffer limitations */\n  if (dec) {\n    int declen = dp ? s - dp : 0;\n    int topad = dec > declen ? dec - declen : 0;\n\n    /* pad with '0's */\n    while (topad--) {\n      *t-- = '0';\n    }\n\n    if (dp) {\n      s -= declen + 1; /* +1 to skip the point */\n      t -= declen;\n\n      /* now copy the chars after the point */\n      memcpy(t + 1, dp + 1, declen);\n    }\n\n    /* add decimal point */\n    if (!dec_point.empty()) {\n      memcpy(t + (1 - dec_point.size()), dec_point.data(), dec_point.size());\n      t -= dec_point.size();\n    }\n  }\n\n  /* copy the numbers before the decimal point, adding thousand\n   * separator every three digits */\n  while(s >= tmpbuf) {\n    *t-- = *s--;\n    if (thousand_sep && (++count%3)==0 && s>=tmpbuf) {\n      memcpy(t + (1 - thousand_sep.size()),\n             thousand_sep.data(),\n             thousand_sep.size());\n      t -= thousand_sep.size();\n    }\n  }\n\n  /* and a minus sign, if needed */\n  if (is_negative) {\n    *t-- = '-';\n  }\n\n  resstr.setSize(reslen);\n  return resstr;\n}", "func_hash": 125018652199743804521817207176944376682, "file_name": "zend-string.cpp", "file_hash": 157727558891612041764030573186624095506, "cwe": ["CWE-119"], "cve": "CVE-2019-11929", "cve_desc": "Insufficient boundary checks when formatting numbers in number_format allows read/write access to out-of-bounds memory, potentially leading to remote code execution. This issue affects HHVM versions prior to 3.30.10, all versions between 4.0.0 and 4.8.5, all versions between 4.9.0 and 4.18.2, and versions 4.19.0, 4.19.1, 4.20.0, 4.20.1, 4.20.2, 4.21.0, 4.22.0, 4.23.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-11929"}
{"idx": 228563, "project": "hhvm", "commit_id": "dbeb9a56a638e3fdcef8b691c2a2967132dae692", "project_url": "https://github.com/facebook/hhvm", "commit_url": "https://github.com/facebook/hhvm/commit/dbeb9a56a638e3fdcef8b691c2a2967132dae692", "commit_message": "string_number_format: Correctly handles return value of snprintf\n\nSummary: `snprintf` can return a value greater than the number of bytes copied. In case the first byte of the string is not a digit (could be '-'), size of `tmpstr` was being updated without checking `tmplen`. This resulted in either an assertion error or a heap overflow depending on whether the assertion is compiled or not.\n\nReviewed By: mofarrell, qianxuweiren\n\nDifferential Revision: D17327899\n\nfbshipit-source-id: ee53875d21e02608c6d870388eecf1464de24ff1", "target": 0, "func": "String string_number_format(double d, int dec,\n                            const String& dec_point,\n                            const String& thousand_sep) {\n  char *tmpbuf = nullptr, *resbuf;\n  char *s, *t;  /* source, target */\n  char *dp;\n  int integral;\n  int tmplen, reslen=0;\n  int count=0;\n  int is_negative=0;\n\n  if (d < 0) {\n    is_negative = 1;\n    d = -d;\n  }\n\n  if (dec < 0) dec = 0;\n  d = php_math_round(d, dec);\n\n  // departure from PHP: we got rid of dependencies on spprintf() here.\n  // This actually means 63 bytes for characters + 1 byte for '\\0'\n  String tmpstr(63, ReserveString);\n  tmpbuf = tmpstr.mutableData();\n  tmplen = snprintf(tmpbuf, 64, \"%.*F\", dec, d);\n  // From the man page of snprintf, the return value is:\n  // The number of characters that would have been written if n had been\n  // sufficiently large, not counting the terminating null character.\n  if (tmplen < 0) return empty_string();\n  if (tmplen < 64 && (tmpbuf == nullptr || !isdigit((int)tmpbuf[0]))) {\n    tmpstr.setSize(tmplen);\n    return tmpstr;\n  }\n  if (tmplen >= 64) {\n    // Uncommon, asked for more than 64 chars worth of precision\n    tmpstr = String(tmplen, ReserveString);\n    tmpbuf = tmpstr.mutableData();\n    tmplen = snprintf(tmpbuf, tmplen + 1, \"%.*F\", dec, d);\n    if (tmplen < 0) return empty_string();\n    if (tmpbuf == nullptr || !isdigit((int)tmpbuf[0])) {\n      tmpstr.setSize(tmplen);\n      return tmpstr;\n    }\n  }\n\n  /* find decimal point, if expected */\n  if (dec) {\n    dp = strpbrk(tmpbuf, \".,\");\n  } else {\n    dp = nullptr;\n  }\n\n  /* calculate the length of the return buffer */\n  if (dp) {\n    integral = dp - tmpbuf;\n  } else {\n    /* no decimal point was found */\n    integral = tmplen;\n  }\n\n  /* allow for thousand separators */\n  if (!thousand_sep.empty()) {\n    if (integral + thousand_sep.size() * ((integral-1) / 3) < integral) {\n      /* overflow */\n      raise_error(\"String overflow\");\n    }\n\n    integral += ((integral-1) / 3) * thousand_sep.size();\n  }\n\n  reslen = integral;\n\n  if (dec) {\n    reslen += dec;\n\n    if (!dec_point.empty()) {\n      if (reslen + dec_point.size() < dec_point.size()) {\n        /* overflow */\n        raise_error(\"String overflow\");\n      }\n      reslen += dec_point.size();\n    }\n  }\n\n  /* add a byte for minus sign */\n  if (is_negative) {\n    reslen++;\n  }\n  String resstr(reslen, ReserveString);\n  resbuf = resstr.mutableData();\n\n  s = tmpbuf+tmplen-1;\n  t = resbuf+reslen-1;\n\n  /* copy the decimal places.\n   * Take care, as the sprintf implementation may return less places than\n   * we requested due to internal buffer limitations */\n  if (dec) {\n    int declen = dp ? s - dp : 0;\n    int topad = dec > declen ? dec - declen : 0;\n\n    /* pad with '0's */\n    while (topad--) {\n      *t-- = '0';\n    }\n\n    if (dp) {\n      s -= declen + 1; /* +1 to skip the point */\n      t -= declen;\n\n      /* now copy the chars after the point */\n      memcpy(t + 1, dp + 1, declen);\n    }\n\n    /* add decimal point */\n    if (!dec_point.empty()) {\n      memcpy(t + (1 - dec_point.size()), dec_point.data(), dec_point.size());\n      t -= dec_point.size();\n    }\n  }\n\n  /* copy the numbers before the decimal point, adding thousand\n   * separator every three digits */\n  while(s >= tmpbuf) {\n    *t-- = *s--;\n    if (thousand_sep && (++count%3)==0 && s>=tmpbuf) {\n      memcpy(t + (1 - thousand_sep.size()),\n             thousand_sep.data(),\n             thousand_sep.size());\n      t -= thousand_sep.size();\n    }\n  }\n\n  /* and a minus sign, if needed */\n  if (is_negative) {\n    *t-- = '-';\n  }\n\n  resstr.setSize(reslen);\n  return resstr;\n}", "func_hash": 113449506030420962381960959197350451885, "file_name": "zend-string.cpp", "file_hash": 48155053696740279281010358677614070619, "cwe": ["CWE-119"], "cve": "CVE-2019-11929", "cve_desc": "Insufficient boundary checks when formatting numbers in number_format allows read/write access to out-of-bounds memory, potentially leading to remote code execution. This issue affects HHVM versions prior to 3.30.10, all versions between 4.0.0 and 4.8.5, all versions between 4.9.0 and 4.18.2, and versions 4.19.0, 4.19.1, 4.20.0, 4.20.1, 4.20.2, 4.21.0, 4.22.0, 4.23.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-11929"}
{"idx": 195626, "project": "qemu", "commit_id": "7882080388be5088e72c425b02223c02e6cb4295", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://github.com/qemu/qemu/commit/7882080388be5088e72c425b02223c02e6cb4295", "commit_message": "virtio-serial: fix ANY_LAYOUT\n\nDon't assume a specific layout for control messages.\nRequired by virtio 1.\n\nSigned-off-by: Michael S. Tsirkin \nReviewed-by: Amit Shah \nReviewed-by: Jason Wang ", "target": 1, "func": "static size_t send_control_msg(VirtIOSerial *vser, void *buf, size_t len)\n{\n    VirtQueueElement elem;\n    VirtQueue *vq;\n\n    vq = vser->c_ivq;\n    if (!virtio_queue_ready(vq)) {\n        return 0;\n    }\n    if (!virtqueue_pop(vq, &elem)) {\n        return 0;\n    }\n\n    memcpy(elem.in_sg[0].iov_base, buf, len);\n\n    virtqueue_push(vq, &elem, len);\n    virtio_notify(VIRTIO_DEVICE(vser), vq);\n    return len;\n}", "func_hash": 301712778748262907171467771526276497164, "file_name": "virtio-serial-bus.c", "file_hash": 253157734411856913752064284433381457044, "cwe": ["CWE-787"], "cve": "CVE-2015-5745", "cve_desc": "Buffer overflow in the send_control_msg function in hw/char/virtio-serial-bus.c in QEMU before 2.4.0 allows guest users to cause a denial of service (QEMU process crash) via a crafted virtio control message.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-5745"}
{"idx": 229165, "project": "qemu", "commit_id": "7882080388be5088e72c425b02223c02e6cb4295", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://github.com/qemu/qemu/commit/7882080388be5088e72c425b02223c02e6cb4295", "commit_message": "virtio-serial: fix ANY_LAYOUT\n\nDon't assume a specific layout for control messages.\nRequired by virtio 1.\n\nSigned-off-by: Michael S. Tsirkin \nReviewed-by: Amit Shah \nReviewed-by: Jason Wang ", "target": 0, "func": "static size_t send_control_msg(VirtIOSerial *vser, void *buf, size_t len)\n{\n    VirtQueueElement elem;\n    VirtQueue *vq;\n\n    vq = vser->c_ivq;\n    if (!virtio_queue_ready(vq)) {\n        return 0;\n    }\n    if (!virtqueue_pop(vq, &elem)) {\n        return 0;\n    }\n\n    /* TODO: detect a buffer that's too short, set NEEDS_RESET */\n    iov_from_buf(elem.in_sg, elem.in_num, 0, buf, len);\n\n    virtqueue_push(vq, &elem, len);\n    virtio_notify(VIRTIO_DEVICE(vser), vq);\n    return len;\n}", "func_hash": 134405066708210322765218436102220814555, "file_name": "virtio-serial-bus.c", "file_hash": 85242612776593478078186690625596682650, "cwe": ["CWE-787"], "cve": "CVE-2015-5745", "cve_desc": "Buffer overflow in the send_control_msg function in hw/char/virtio-serial-bus.c in QEMU before 2.4.0 allows guest users to cause a denial of service (QEMU process crash) via a crafted virtio control message.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-5745"}
{"idx": 195629, "project": "tensorflow", "commit_id": "a5b89cd68c02329d793356bda85d079e9e69b4e7", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a5b89cd68c02329d793356bda85d079e9e69b4e7", "commit_message": "Fix empty resource handle vulnerability.\n\nSome ops that attempt to extract a resource handle from user input\ncan lead to nullptr dereferences.  This returns an error in such\na case.\n\nPiperOrigin-RevId: 445571938", "target": 1, "func": "Status GetDeviceForInput(const EagerOperation& op, const EagerContext& ctx,\n                         TensorHandle* tensor_handle, Device** result) {\n  Device* cpu_device = ctx.HostCPU();\n  string device_name;\n  if (tensor_handle->Type() != TensorHandle::LOCAL) {\n    Device* device = tensor_handle->device();\n    device_name = device != nullptr ? device->name() : cpu_device->name();\n    *result = (device == nullptr ? cpu_device : device);\n  } else if (tensor_handle->dtype == DT_RESOURCE) {\n    // Use the resource's actual device because it is the device that will\n    // influence partitioning the multi-device function.\n    const Tensor* tensor;\n    // TODO(fishx): Avoid blocking here.\n    TF_RETURN_IF_ERROR(tensor_handle->Tensor(&tensor));\n    const ResourceHandle& handle = tensor->flat()(0);\n    device_name = handle.device();\n\n    Device* input_device;\n    TF_RETURN_IF_ERROR(\n        ctx.FindDeviceFromName(device_name.c_str(), &input_device));\n    *result = input_device;\n  } else {\n    Device* device = tensor_handle->device();\n    const bool is_tpu = device != nullptr && device->device_type() == \"TPU\";\n    // int32 return values can be placed on TPUs.\n    const bool use_host_memory =\n        is_tpu ? MTypeFromDTypeIntsOnDevice(tensor_handle->dtype)\n               : MTypeFromDType(tensor_handle->dtype);\n    if (use_host_memory) {\n      *result = cpu_device;\n    } else {\n      // Eager ops executing as functions should have their preferred inputs set\n      // to the op's device. This allows us to avoid expensive D2H copies if a\n      // mirror of the tensor already exists on the op's device.\n      if (!op.is_function() && device != nullptr && device != cpu_device) {\n        device = absl::get(op.Device());\n      }\n      *result = (device == nullptr ? cpu_device : device);\n    }\n  }\n  return Status::OK();\n}", "func_hash": 227007805370541421392187811352073944672, "file_name": "execute.cc", "file_hash": 250138698264718373642663717664797527317, "cwe": ["CWE-476"], "cve": "CVE-2022-29207", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, multiple TensorFlow operations misbehave in eager mode when the resource handle provided to them is invalid. In graph mode, it would have been impossible to perform these API calls, but migration to TF 2.x eager mode opened up this vulnerability. If the resource handle is empty, then a reference is bound to a null pointer inside TensorFlow codebase (various codepaths). This is undefined behavior. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29207"}
{"idx": 229337, "project": "tensorflow", "commit_id": "a5b89cd68c02329d793356bda85d079e9e69b4e7", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a5b89cd68c02329d793356bda85d079e9e69b4e7", "commit_message": "Fix empty resource handle vulnerability.\n\nSome ops that attempt to extract a resource handle from user input\ncan lead to nullptr dereferences.  This returns an error in such\na case.\n\nPiperOrigin-RevId: 445571938", "target": 0, "func": "Status GetDeviceForInput(const EagerOperation& op, const EagerContext& ctx,\n                         TensorHandle* tensor_handle, Device** result) {\n  Device* cpu_device = ctx.HostCPU();\n  string device_name;\n  if (tensor_handle->Type() != TensorHandle::LOCAL) {\n    Device* device = tensor_handle->device();\n    device_name = device != nullptr ? device->name() : cpu_device->name();\n    *result = (device == nullptr ? cpu_device : device);\n  } else if (tensor_handle->dtype == DT_RESOURCE) {\n    // Use the resource's actual device because it is the device that will\n    // influence partitioning the multi-device function.\n    const Tensor* tensor;\n    // TODO(fishx): Avoid blocking here.\n    TF_RETURN_IF_ERROR(tensor_handle->Tensor(&tensor));\n    if (tensor->NumElements() == 0) {\n      return errors::InvalidArgument(\"Empty resource handle\");\n    }\n    const ResourceHandle& handle = tensor->flat()(0);\n    device_name = handle.device();\n\n    Device* input_device;\n    TF_RETURN_IF_ERROR(\n        ctx.FindDeviceFromName(device_name.c_str(), &input_device));\n    *result = input_device;\n  } else {\n    Device* device = tensor_handle->device();\n    const bool is_tpu = device != nullptr && device->device_type() == \"TPU\";\n    // int32 return values can be placed on TPUs.\n    const bool use_host_memory =\n        is_tpu ? MTypeFromDTypeIntsOnDevice(tensor_handle->dtype)\n               : MTypeFromDType(tensor_handle->dtype);\n    if (use_host_memory) {\n      *result = cpu_device;\n    } else {\n      // Eager ops executing as functions should have their preferred inputs set\n      // to the op's device. This allows us to avoid expensive D2H copies if a\n      // mirror of the tensor already exists on the op's device.\n      if (!op.is_function() && device != nullptr && device != cpu_device) {\n        device = absl::get(op.Device());\n      }\n      *result = (device == nullptr ? cpu_device : device);\n    }\n  }\n  return Status::OK();\n}", "func_hash": 302726579392319306560767073266874435577, "file_name": "execute.cc", "file_hash": 29379316032335742084912200348793889272, "cwe": ["CWE-476"], "cve": "CVE-2022-29207", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, multiple TensorFlow operations misbehave in eager mode when the resource handle provided to them is invalid. In graph mode, it would have been impossible to perform these API calls, but migration to TF 2.x eager mode opened up this vulnerability. If the resource handle is empty, then a reference is bound to a null pointer inside TensorFlow codebase (various codepaths). This is undefined behavior. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29207"}
{"idx": 195665, "project": "njs", "commit_id": "2e00e95473861846aa8538be87db07699d9f676d", "project_url": "https://github.com/nginx/njs", "commit_url": "https://github.com/nginx/njs/commit/2e00e95473861846aa8538be87db07699d9f676d", "commit_message": "Fixed Array.prototype.slice() with slow \"this\" argument.\n\nPreviously, when \"this\" argument was not a fast array, but the \"deleted\" array\nwas a fast array, the \"deleted\" array may be left in uninitialized state if\n\"this\" argument had gaps.\n\nThis fix is to ensure that \"deleted\" is properly initialized.\n\nThis fixes #485 issue on Github.", "target": 1, "func": "njs_array_prototype_splice(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,\n    njs_index_t unused)\n{\n    int64_t      i, n, start, length, items, delta, delete;\n    njs_int_t    ret;\n    njs_value_t  *this, value, del_object;\n    njs_array_t  *array, *deleted;\n\n    this = njs_argument(args, 0);\n\n    ret = njs_value_to_object(vm, this);\n    if (njs_slow_path(ret != NJS_OK)) {\n        return ret;\n    }\n\n    ret = njs_object_length(vm, this, &length);\n    if (njs_slow_path(ret == NJS_ERROR)) {\n        return ret;\n    }\n\n    ret = njs_value_to_integer(vm, njs_arg(args, nargs, 1), &start);\n    if (njs_slow_path(ret != NJS_OK)) {\n        return ret;\n    }\n\n    start = (start < 0) ? njs_max(length + start, 0) : njs_min(start, length);\n\n    items = 0;\n    delete = 0;\n\n    if (nargs == 2) {\n        delete = length - start;\n\n    } else if (nargs > 2) {\n        items = nargs - 3;\n\n        ret = njs_value_to_integer(vm, njs_arg(args, nargs, 2), &delete);\n        if (njs_slow_path(ret != NJS_OK)) {\n            return ret;\n        }\n\n        delete = njs_min(njs_max(delete, 0), length - start);\n    }\n\n    delta = items - delete;\n\n    if (njs_slow_path((length + delta) > NJS_MAX_LENGTH)) {\n        njs_type_error(vm, \"Invalid length\");\n        return NJS_ERROR;\n    }\n\n    /* TODO: ArraySpeciesCreate(). */\n\n    deleted = njs_array_alloc(vm, 0, delete, 0);\n    if (njs_slow_path(deleted == NULL)) {\n        return NJS_ERROR;\n    }\n\n    if (njs_fast_path(njs_is_fast_array(this) && deleted->object.fast_array)) {\n        array = njs_array(this);\n        for (i = 0, n = start; i < delete; i++, n++) {\n            deleted->start[i] = array->start[n];\n        }\n\n    } else {\n        njs_set_array(&del_object, deleted);\n\n        for (i = 0, n = start; i < delete; i++, n++) {\n            ret = njs_value_property_i64(vm, this, n, &value);\n            if (njs_slow_path(ret == NJS_ERROR)) {\n                return NJS_ERROR;\n            }\n\n            if (ret == NJS_OK) {\n                /* TODO:  CreateDataPropertyOrThrow(). */\n                ret = njs_value_property_i64_set(vm, &del_object, i, &value);\n                if (njs_slow_path(ret == NJS_ERROR)) {\n                    return ret;\n                }\n            }\n        }\n\n        ret = njs_object_length_set(vm, &del_object, delete);\n        if (njs_slow_path(ret != NJS_OK)) {\n            return NJS_ERROR;\n        }\n    }\n\n    if (njs_fast_path(njs_is_fast_array(this))) {\n        array = njs_array(this);\n\n        if (delta != 0) {\n            /*\n             * Relocate the rest of items.\n             * Index of the first item is in \"n\".\n             */\n            if (delta > 0) {\n                ret = njs_array_expand(vm, array, 0, delta);\n                if (njs_slow_path(ret != NJS_OK)) {\n                    return ret;\n                }\n            }\n\n            ret = njs_array_copy_within(vm, this, start + items, start + delete,\n                                        array->length - (start + delete), 0);\n            if (njs_slow_path(ret != NJS_OK)) {\n                return ret;\n            }\n\n            array->length += delta;\n        }\n\n        /* Copy new items. */\n\n        if (items > 0) {\n            memcpy(&array->start[start], &args[3],\n                   items * sizeof(njs_value_t));\n        }\n\n    } else {\n\n       if (delta != 0) {\n           ret = njs_array_copy_within(vm, this, start + items, start + delete,\n                                       length - (start + delete), delta < 0);\n            if (njs_slow_path(ret != NJS_OK)) {\n                return ret;\n            }\n\n            for (i = length - 1; i >= length + delta; i--) {\n                ret = njs_value_property_i64_delete(vm, this, i, NULL);\n                if (njs_slow_path(ret == NJS_ERROR)) {\n                    return NJS_ERROR;\n                }\n            }\n       }\n\n        /* Copy new items. */\n\n        for (i = 3, n = start; items-- > 0; i++, n++) {\n            ret = njs_value_property_i64_set(vm, this, n, &args[i]);\n            if (njs_slow_path(ret == NJS_ERROR)) {\n                return NJS_ERROR;\n            }\n        }\n\n        ret = njs_object_length_set(vm, this, length + delta);\n        if (njs_slow_path(ret != NJS_OK)) {\n            return NJS_ERROR;\n        }\n    }\n\n    njs_set_array(&vm->retval, deleted);\n\n    return NJS_OK;\n}", "func_hash": 41889957200154277256182614621042854713, "file_name": "njs_array.c", "file_hash": 27861953644579332654826088207600556930, "cwe": ["CWE-703"], "cve": "CVE-2022-29779", "cve_desc": "Nginx NJS v0.7.2 was discovered to contain a segmentation violation in the function njs_value_own_enumerate at src/njs_value.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29779"}
{"idx": 230302, "project": "njs", "commit_id": "2e00e95473861846aa8538be87db07699d9f676d", "project_url": "https://github.com/nginx/njs", "commit_url": "https://github.com/nginx/njs/commit/2e00e95473861846aa8538be87db07699d9f676d", "commit_message": "Fixed Array.prototype.slice() with slow \"this\" argument.\n\nPreviously, when \"this\" argument was not a fast array, but the \"deleted\" array\nwas a fast array, the \"deleted\" array may be left in uninitialized state if\n\"this\" argument had gaps.\n\nThis fix is to ensure that \"deleted\" is properly initialized.\n\nThis fixes #485 issue on Github.", "target": 0, "func": "njs_array_prototype_splice(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,\n    njs_index_t unused)\n{\n    int64_t      i, n, start, length, items, delta, delete;\n    njs_int_t    ret;\n    njs_value_t  *this, value, del_object;\n    njs_array_t  *array, *deleted;\n\n    this = njs_argument(args, 0);\n\n    ret = njs_value_to_object(vm, this);\n    if (njs_slow_path(ret != NJS_OK)) {\n        return ret;\n    }\n\n    ret = njs_object_length(vm, this, &length);\n    if (njs_slow_path(ret == NJS_ERROR)) {\n        return ret;\n    }\n\n    ret = njs_value_to_integer(vm, njs_arg(args, nargs, 1), &start);\n    if (njs_slow_path(ret != NJS_OK)) {\n        return ret;\n    }\n\n    start = (start < 0) ? njs_max(length + start, 0) : njs_min(start, length);\n\n    items = 0;\n    delete = 0;\n\n    if (nargs == 2) {\n        delete = length - start;\n\n    } else if (nargs > 2) {\n        items = nargs - 3;\n\n        ret = njs_value_to_integer(vm, njs_arg(args, nargs, 2), &delete);\n        if (njs_slow_path(ret != NJS_OK)) {\n            return ret;\n        }\n\n        delete = njs_min(njs_max(delete, 0), length - start);\n    }\n\n    delta = items - delete;\n\n    if (njs_slow_path((length + delta) > NJS_MAX_LENGTH)) {\n        njs_type_error(vm, \"Invalid length\");\n        return NJS_ERROR;\n    }\n\n    /* TODO: ArraySpeciesCreate(). */\n\n    deleted = njs_array_alloc(vm, 0, delete, 0);\n    if (njs_slow_path(deleted == NULL)) {\n        return NJS_ERROR;\n    }\n\n    if (njs_fast_path(njs_is_fast_array(this) && deleted->object.fast_array)) {\n        array = njs_array(this);\n        for (i = 0, n = start; i < delete; i++, n++) {\n            deleted->start[i] = array->start[n];\n        }\n\n    } else {\n        njs_set_array(&del_object, deleted);\n\n        for (i = 0, n = start; i < delete; i++, n++) {\n            ret = njs_value_property_i64(vm, this, n, &value);\n            if (njs_slow_path(ret == NJS_ERROR)) {\n                return NJS_ERROR;\n            }\n\n            if (ret == NJS_OK) {\n                /* TODO:  CreateDataPropertyOrThrow(). */\n                ret = njs_value_property_i64_set(vm, &del_object, i, &value);\n                if (njs_slow_path(ret == NJS_ERROR)) {\n                    return ret;\n                }\n\n            } else {\n                if (deleted->object.fast_array) {\n                    njs_set_invalid(&deleted->start[i]);\n                }\n            }\n        }\n\n        ret = njs_object_length_set(vm, &del_object, delete);\n        if (njs_slow_path(ret != NJS_OK)) {\n            return NJS_ERROR;\n        }\n    }\n\n    if (njs_fast_path(njs_is_fast_array(this))) {\n        array = njs_array(this);\n\n        if (delta != 0) {\n            /*\n             * Relocate the rest of items.\n             * Index of the first item is in \"n\".\n             */\n            if (delta > 0) {\n                ret = njs_array_expand(vm, array, 0, delta);\n                if (njs_slow_path(ret != NJS_OK)) {\n                    return ret;\n                }\n            }\n\n            ret = njs_array_copy_within(vm, this, start + items, start + delete,\n                                        array->length - (start + delete), 0);\n            if (njs_slow_path(ret != NJS_OK)) {\n                return ret;\n            }\n\n            array->length += delta;\n        }\n\n        /* Copy new items. */\n\n        if (items > 0) {\n            memcpy(&array->start[start], &args[3],\n                   items * sizeof(njs_value_t));\n        }\n\n    } else {\n\n       if (delta != 0) {\n           ret = njs_array_copy_within(vm, this, start + items, start + delete,\n                                       length - (start + delete), delta < 0);\n            if (njs_slow_path(ret != NJS_OK)) {\n                return ret;\n            }\n\n            for (i = length - 1; i >= length + delta; i--) {\n                ret = njs_value_property_i64_delete(vm, this, i, NULL);\n                if (njs_slow_path(ret == NJS_ERROR)) {\n                    return NJS_ERROR;\n                }\n            }\n       }\n\n        /* Copy new items. */\n\n        for (i = 3, n = start; items-- > 0; i++, n++) {\n            ret = njs_value_property_i64_set(vm, this, n, &args[i]);\n            if (njs_slow_path(ret == NJS_ERROR)) {\n                return NJS_ERROR;\n            }\n        }\n\n        ret = njs_object_length_set(vm, this, length + delta);\n        if (njs_slow_path(ret != NJS_OK)) {\n            return NJS_ERROR;\n        }\n    }\n\n    njs_set_array(&vm->retval, deleted);\n\n    return NJS_OK;\n}", "func_hash": 91452857281463208584852927019432341939, "file_name": "njs_array.c", "file_hash": 127478727069540736637535553874506726763, "cwe": ["CWE-703"], "cve": "CVE-2022-29779", "cve_desc": "Nginx NJS v0.7.2 was discovered to contain a segmentation violation in the function njs_value_own_enumerate at src/njs_value.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29779"}
{"idx": 195670, "project": "pjproject", "commit_id": "856f87c2e97a27b256482dbe0d748b1194355a21", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/856f87c2e97a27b256482dbe0d748b1194355a21", "commit_message": "Merge pull request from GHSA-5x45-qp78-g4p4\n\n* Prevent infinite loop in scanning xml content\n\n* Simplify scanning method\n\n* Optimization", "target": 1, "func": "static pj_xml_node *xml_parse_node( pj_pool_t *pool, pj_scanner *scanner)\n{\n    pj_xml_node *node;\n    pj_str_t end_name;\n\n    PJ_CHECK_STACK();\n\n    if (*scanner->curptr != '<')\n\ton_syntax_error(scanner);\n\n    /* Handle Processing Instructino (PI) construct (i.e. \"curptr == '<' && *(scanner->curptr+1) == '?') {\n\tpj_scan_advance_n(scanner, 2, PJ_FALSE);\n\tfor (;;) {\n\t    pj_str_t dummy;\n\t    pj_scan_get_until_ch(scanner, '?', &dummy);\n\t    if (*scanner->curptr=='?' && *(scanner->curptr+1)=='>') {\n\t\tpj_scan_advance_n(scanner, 2, PJ_TRUE);\n\t\tbreak;\n\t    } else {\n\t\tpj_scan_advance_n(scanner, 1, PJ_FALSE);\n\t    }\n\t}\n\treturn xml_parse_node(pool, scanner);\n    }\n\n    /* Handle comments construct (i.e. \"', &dummy);\n\t    if (pj_scan_strcmp(scanner, \">\", 1) == 0) {\n\t\tpj_scan_advance_n(scanner, 1, PJ_TRUE);\n\t\tbreak;\n\t    } else {\n\t\tpj_scan_advance_n(scanner, 1, PJ_FALSE);\n\t    }\n\t}\n\treturn xml_parse_node(pool, scanner);\n    }\n\n    /* Alloc node. */\n    node = alloc_node(pool);\n\n    /* Get '<' */\n    pj_scan_get_char(scanner);\n\n    /* Get node name. */\n    pj_scan_get_until_chr( scanner, \" />\\t\\r\\n\", &node->name);\n\n    /* Get attributes. */\n    while (*scanner->curptr != '>' && *scanner->curptr != '/') {\n\tpj_xml_attr *attr = alloc_attr(pool);\n\t\n\tpj_scan_get_until_chr( scanner, \"=> \\t\\r\\n\", &attr->name);\n\tif (*scanner->curptr == '=') {\n\t    pj_scan_get_char( scanner );\n            pj_scan_get_quotes(scanner, \"\\\"'\", \"\\\"'\", 2, &attr->value);\n\t    /* remove quote characters */\n\t    ++attr->value.ptr;\n\t    attr->value.slen -= 2;\n\t}\n\t\n\tpj_list_push_back( &node->attr_head, attr );\n    }\n\n    if (*scanner->curptr == '/') {\n\tpj_scan_get_char(scanner);\n\tif (pj_scan_get_char(scanner) != '>')\n\t    on_syntax_error(scanner);\n\treturn node;\n    }\n\n    /* Enclosing bracket. */\n    if (pj_scan_get_char(scanner) != '>')\n\ton_syntax_error(scanner);\n\n    /* Sub nodes. */\n    while (*scanner->curptr == '<' && *(scanner->curptr+1) != '/'\n\t\t\t\t   && *(scanner->curptr+1) != '!')\n    {\n\tpj_xml_node *sub_node = xml_parse_node(pool, scanner);\n\tpj_list_push_back( &node->node_head, sub_node );\n    }\n\n    /* Content. */\n    if (!pj_scan_is_eof(scanner) && *scanner->curptr != '<') {\n\tpj_scan_get_until_ch(scanner, '<', &node->content);\n    }\n\n    /* CDATA content. */\n    if (*scanner->curptr == '<' && *(scanner->curptr+1) == '!' &&\n\tpj_scan_strcmp(scanner, \"content);\n\twhile (pj_scan_strcmp(scanner, \"]]>\", 3)) {\n\t    pj_str_t dummy;\n\t    pj_scan_get_until_ch(scanner, ']', &dummy);\n\t}\n\tnode->content.slen = scanner->curptr - node->content.ptr;\n\tpj_scan_advance_n(scanner, 3, PJ_TRUE);\n    }\n\n    /* Enclosing node. */\n    if (pj_scan_get_char(scanner) != '<' || pj_scan_get_char(scanner) != '/')\n\ton_syntax_error(scanner);\n\n    pj_scan_get_until_chr(scanner, \" \\t>\", &end_name);\n\n    /* Compare name. */\n    if (pj_stricmp(&node->name, &end_name) != 0)\n\ton_syntax_error(scanner);\n\n    /* Enclosing '>' */\n    if (pj_scan_get_char(scanner) != '>')\n\ton_syntax_error(scanner);\n\n    return node;\n}", "func_hash": 277240174945375908655928995975016589842, "file_name": "xml.c", "file_hash": 319030018310003515806173873266013713455, "cwe": ["CWE-703"], "cve": "CVE-2022-24763", "cve_desc": "PJSIP is a free and open source multimedia communication library written in the C language. Versions 2.12 and prior contain a denial-of-service vulnerability that affects PJSIP users that consume PJSIP's XML parsing in their apps. Users are advised to update. There are no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24763"}
{"idx": 230394, "project": "pjproject", "commit_id": "856f87c2e97a27b256482dbe0d748b1194355a21", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/856f87c2e97a27b256482dbe0d748b1194355a21", "commit_message": "Merge pull request from GHSA-5x45-qp78-g4p4\n\n* Prevent infinite loop in scanning xml content\n\n* Simplify scanning method\n\n* Optimization", "target": 0, "func": "static pj_xml_node *xml_parse_node( pj_pool_t *pool, pj_scanner *scanner)\n{\n    pj_xml_node *node;\n    pj_str_t end_name;\n\n    PJ_CHECK_STACK();\n\n    if (*scanner->curptr != '<')\n\ton_syntax_error(scanner);\n\n    /* Handle Processing Instructino (PI) construct (i.e. \"curptr == '<' && *(scanner->curptr+1) == '?') {\n\tpj_scan_advance_n(scanner, 2, PJ_FALSE);\n\tfor (;;) {\n\t    pj_str_t dummy;\n\t    pj_scan_get_until_ch(scanner, '?', &dummy);\n\t    if (*scanner->curptr=='?' && *(scanner->curptr+1)=='>') {\n\t\tpj_scan_advance_n(scanner, 2, PJ_TRUE);\n\t\tbreak;\n\t    } else {\n\t\tpj_scan_advance_n(scanner, 1, PJ_FALSE);\n\t    }\n\t}\n\treturn xml_parse_node(pool, scanner);\n    }\n\n    /* Handle comments construct (i.e. \"', &dummy);\n\t    if (pj_scan_strcmp(scanner, \">\", 1) == 0) {\n\t\tpj_scan_advance_n(scanner, 1, PJ_TRUE);\n\t\tbreak;\n\t    } else {\n\t\tpj_scan_advance_n(scanner, 1, PJ_FALSE);\n\t    }\n\t}\n\treturn xml_parse_node(pool, scanner);\n    }\n\n    /* Alloc node. */\n    node = alloc_node(pool);\n\n    /* Get '<' */\n    pj_scan_get_char(scanner);\n\n    /* Get node name. */\n    pj_scan_get_until_chr( scanner, \" />\\t\\r\\n\", &node->name);\n\n    /* Get attributes. */\n    while (*scanner->curptr != '>' && *scanner->curptr != '/') {\n\tpj_xml_attr *attr = alloc_attr(pool);\n\t\n\tpj_scan_get_until_chr( scanner, \"=> \\t\\r\\n\", &attr->name);\n\tif (*scanner->curptr == '=') {\n\t    pj_scan_get_char( scanner );\n            pj_scan_get_quotes(scanner, \"\\\"'\", \"\\\"'\", 2, &attr->value);\n\t    /* remove quote characters */\n\t    ++attr->value.ptr;\n\t    attr->value.slen -= 2;\n\t}\n\t\n\tpj_list_push_back( &node->attr_head, attr );\n    }\n\n    if (*scanner->curptr == '/') {\n\tpj_scan_get_char(scanner);\n\tif (pj_scan_get_char(scanner) != '>')\n\t    on_syntax_error(scanner);\n\treturn node;\n    }\n\n    /* Enclosing bracket. */\n    if (pj_scan_get_char(scanner) != '>')\n\ton_syntax_error(scanner);\n\n    /* Sub nodes. */\n    while (*scanner->curptr == '<' && *(scanner->curptr+1) != '/'\n\t\t\t\t   && *(scanner->curptr+1) != '!')\n    {\n\tpj_xml_node *sub_node = xml_parse_node(pool, scanner);\n\tpj_list_push_back( &node->node_head, sub_node );\n    }\n\n    /* Content. */\n    if (!pj_scan_is_eof(scanner) && *scanner->curptr != '<') {\n\tpj_scan_get_until_ch(scanner, '<', &node->content);\n    }\n\n    /* CDATA content. */\n    if (*scanner->curptr == '<' && *(scanner->curptr+1) == '!' &&\n\tpj_scan_strcmp(scanner, \"content);\n\twhile (pj_scan_strcmp(scanner, \"]]>\", 3)) {\n\t    pj_str_t dummy;\n\n\t    pj_scan_advance_n(scanner, 1, PJ_FALSE);\n\t    pj_scan_get_until_ch(scanner, ']', &dummy);\n\t}\n\tnode->content.slen = scanner->curptr - node->content.ptr;\n\tpj_scan_advance_n(scanner, 3, PJ_TRUE);\n    }\n\n    /* Enclosing node. */\n    if (pj_scan_get_char(scanner) != '<' || pj_scan_get_char(scanner) != '/')\n\ton_syntax_error(scanner);\n\n    pj_scan_get_until_chr(scanner, \" \\t>\", &end_name);\n\n    /* Compare name. */\n    if (pj_stricmp(&node->name, &end_name) != 0)\n\ton_syntax_error(scanner);\n\n    /* Enclosing '>' */\n    if (pj_scan_get_char(scanner) != '>')\n\ton_syntax_error(scanner);\n\n    return node;\n}", "func_hash": 333353357538572797993178277028111202319, "file_name": "xml.c", "file_hash": 137943726532385231053862962299057228575, "cwe": ["CWE-703"], "cve": "CVE-2022-24763", "cve_desc": "PJSIP is a free and open source multimedia communication library written in the C language. Versions 2.12 and prior contain a denial-of-service vulnerability that affects PJSIP users that consume PJSIP's XML parsing in their apps. Users are advised to update. There are no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24763"}
{"idx": 195691, "project": "mruby", "commit_id": "a4d97934d51cb88954cc49161dc1d151f64afb6b", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/a4d97934d51cb88954cc49161dc1d151f64afb6b", "commit_message": "vm.c: check if target_class is NULL (when prepended).", "target": 1, "func": "mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc)\n{\n  /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */\n  const mrb_irep *irep = proc->body.irep;\n  const mrb_pool_value *pool = irep->pool;\n  const mrb_sym *syms = irep->syms;\n  mrb_code insn;\n  int ai = mrb_gc_arena_save(mrb);\n  struct mrb_jmpbuf *prev_jmp = mrb->jmp;\n  struct mrb_jmpbuf c_jmp;\n  uint32_t a;\n  uint16_t b;\n  uint16_t c;\n  mrb_sym mid;\n  const struct mrb_irep_catch_handler *ch;\n\n#ifdef DIRECT_THREADED\n  static const void * const optable[] = {\n#define OPCODE(x,_) &&L_OP_ ## x,\n#include \"mruby/ops.h\"\n#undef OPCODE\n  };\n#endif\n\n  mrb_bool exc_catched = FALSE;\nRETRY_TRY_BLOCK:\n\n  MRB_TRY(&c_jmp) {\n\n  if (exc_catched) {\n    exc_catched = FALSE;\n    mrb_gc_arena_restore(mrb, ai);\n    if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)\n      goto L_BREAK;\n    goto L_RAISE;\n  }\n  mrb->jmp = &c_jmp;\n  mrb_vm_ci_proc_set(mrb->c->ci, proc);\n\n#define regs (mrb->c->ci->stack)\n  INIT_DISPATCH {\n    CASE(OP_NOP, Z) {\n      /* do nothing */\n      NEXT;\n    }\n\n    CASE(OP_MOVE, BB) {\n      regs[a] = regs[b];\n      NEXT;\n    }\n\n    CASE(OP_LOADL, BB) {\n      switch (pool[b].tt) {   /* number */\n      case IREP_TT_INT32:\n        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32);\n        break;\n      case IREP_TT_INT64:\n#if defined(MRB_INT64)\n        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n        break;\n#else\n#if defined(MRB_64BIT)\n        if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) {\n          regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n          break;\n        }\n#endif\n        goto L_INT_OVERFLOW;\n#endif\n      case IREP_TT_BIGINT:\n#ifdef MRB_USE_BIGINT\n        {\n          const char *s = pool[b].u.str;\n          regs[a] = mrb_bint_new_str(mrb, s+2, (mrb_int)s[0], (mrb_int)s[1]);\n        }\n        break;\n#else\n        goto L_INT_OVERFLOW;\n#endif\n#ifndef MRB_NO_FLOAT\n      case IREP_TT_FLOAT:\n        regs[a] = mrb_float_value(mrb, pool[b].u.f);\n        break;\n#endif\n      default:\n        /* should not happen (tt:string) */\n        regs[a] = mrb_nil_value();\n        break;\n      }\n      NEXT;\n    }\n\n    CASE(OP_LOADI, BB) {\n      SET_FIXNUM_VALUE(regs[a], b);\n      NEXT;\n    }\n\n    CASE(OP_LOADINEG, BB) {\n      SET_FIXNUM_VALUE(regs[a], -b);\n      NEXT;\n    }\n\n    CASE(OP_LOADI__1,B) goto L_LOADI;\n    CASE(OP_LOADI_0,B) goto L_LOADI;\n    CASE(OP_LOADI_1,B) goto L_LOADI;\n    CASE(OP_LOADI_2,B) goto L_LOADI;\n    CASE(OP_LOADI_3,B) goto L_LOADI;\n    CASE(OP_LOADI_4,B) goto L_LOADI;\n    CASE(OP_LOADI_5,B) goto L_LOADI;\n    CASE(OP_LOADI_6,B) goto L_LOADI;\n    CASE(OP_LOADI_7, B) {\n    L_LOADI:\n      SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0);\n      NEXT;\n    }\n\n    CASE(OP_LOADI16, BS) {\n      SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b);\n      NEXT;\n    }\n\n    CASE(OP_LOADI32, BSS) {\n      SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c));\n      NEXT;\n    }\n\n    CASE(OP_LOADSYM, BB) {\n      SET_SYM_VALUE(regs[a], syms[b]);\n      NEXT;\n    }\n\n    CASE(OP_LOADNIL, B) {\n      SET_NIL_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_LOADSELF, B) {\n      regs[a] = regs[0];\n      NEXT;\n    }\n\n    CASE(OP_LOADT, B) {\n      SET_TRUE_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_LOADF, B) {\n      SET_FALSE_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETGV, BB) {\n      mrb_value val = mrb_gv_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETGV, BB) {\n      mrb_gv_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETSV, BB) {\n      mrb_value val = mrb_vm_special_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETSV, BB) {\n      mrb_vm_special_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETIV, BB) {\n      regs[a] = mrb_iv_get(mrb, regs[0], syms[b]);\n      NEXT;\n    }\n\n    CASE(OP_SETIV, BB) {\n      mrb_iv_set(mrb, regs[0], syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETCV, BB) {\n      mrb_value val;\n      val = mrb_vm_cv_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETCV, BB) {\n      mrb_vm_cv_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETIDX, B) {\n      mrb_value va = regs[a], vb = regs[a+1];\n      switch (mrb_type(va)) {\n      case MRB_TT_ARRAY:\n        if (!mrb_integer_p(vb)) goto getidx_fallback;\n        regs[a] = mrb_ary_entry(va, mrb_integer(vb));\n        break;\n      case MRB_TT_HASH:\n        va = mrb_hash_get(mrb, va, vb);\n        regs[a] = va;\n        break;\n      case MRB_TT_STRING:\n        switch (mrb_type(vb)) {\n        case MRB_TT_INTEGER:\n        case MRB_TT_STRING:\n        case MRB_TT_RANGE:\n          va = mrb_str_aref(mrb, va, vb, mrb_undef_value());\n          regs[a] = va;\n          break;\n        default:\n          goto getidx_fallback;\n        }\n        break;\n      default:\n      getidx_fallback:\n        mid = MRB_OPSYM(aref);\n        goto L_SEND_SYM;\n      }\n      NEXT;\n    }\n\n    CASE(OP_SETIDX, B) {\n      c = 2;\n      mid = MRB_OPSYM(aset);\n      SET_NIL_VALUE(regs[a+3]);\n      goto L_SENDB_SYM;\n    }\n\n    CASE(OP_GETCONST, BB) {\n      mrb_value v = mrb_vm_const_get(mrb, syms[b]);\n      regs[a] = v;\n      NEXT;\n    }\n\n    CASE(OP_SETCONST, BB) {\n      mrb_vm_const_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETMCNST, BB) {\n      mrb_value v = mrb_const_get(mrb, regs[a], syms[b]);\n      regs[a] = v;\n      NEXT;\n    }\n\n    CASE(OP_SETMCNST, BB) {\n      mrb_const_set(mrb, regs[a+1], syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETUPVAR, BBB) {\n      mrb_value *regs_a = regs + a;\n      struct REnv *e = uvenv(mrb, c);\n\n      if (e && b < MRB_ENV_LEN(e)) {\n        *regs_a = e->stack[b];\n      }\n      else {\n        *regs_a = mrb_nil_value();\n      }\n      NEXT;\n    }\n\n    CASE(OP_SETUPVAR, BBB) {\n      struct REnv *e = uvenv(mrb, c);\n\n      if (e) {\n        mrb_value *regs_a = regs + a;\n\n        if (b < MRB_ENV_LEN(e)) {\n          e->stack[b] = *regs_a;\n          mrb_write_barrier(mrb, (struct RBasic*)e);\n        }\n      }\n      NEXT;\n    }\n\n    CASE(OP_JMP, S) {\n      pc += (int16_t)a;\n      JUMP;\n    }\n    CASE(OP_JMPIF, BS) {\n      if (mrb_test(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n    CASE(OP_JMPNOT, BS) {\n      if (!mrb_test(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n    CASE(OP_JMPNIL, BS) {\n      if (mrb_nil_p(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n\n    CASE(OP_JMPUW, S) {\n      a = (uint32_t)((pc - irep->iseq) + (int16_t)a);\n      CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) {\n        struct RBreak *brk = (struct RBreak*)mrb->exc;\n        mrb_value target = mrb_break_value_get(brk);\n        mrb_assert(mrb_integer_p(target));\n        a = (uint32_t)mrb_integer(target);\n        mrb_assert(a >= 0 && a < irep->ilen);\n      }\n      CHECKPOINT_MAIN(RBREAK_TAG_JUMP) {\n        ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE);\n        if (ch) {\n          /* avoiding a jump from a catch handler into the same handler */\n          if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) {\n            THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a));\n          }\n        }\n      }\n      CHECKPOINT_END(RBREAK_TAG_JUMP);\n\n      mrb->exc = NULL; /* clear break object */\n      pc = irep->iseq + a;\n      JUMP;\n    }\n\n    CASE(OP_EXCEPT, B) {\n      mrb_value exc;\n\n      if (mrb->exc == NULL) {\n        exc = mrb_nil_value();\n      }\n      else {\n        switch (mrb->exc->tt) {\n        case MRB_TT_BREAK:\n        case MRB_TT_EXCEPTION:\n          exc = mrb_obj_value(mrb->exc);\n          break;\n        default:\n          mrb_assert(!\"bad mrb_type\");\n          exc = mrb_nil_value();\n          break;\n        }\n        mrb->exc = NULL;\n      }\n      regs[a] = exc;\n      NEXT;\n    }\n    CASE(OP_RESCUE, BB) {\n      mrb_value exc = regs[a];  /* exc on stack */\n      mrb_value e = regs[b];\n      struct RClass *ec;\n\n      switch (mrb_type(e)) {\n      case MRB_TT_CLASS:\n      case MRB_TT_MODULE:\n        break;\n      default:\n        {\n          mrb_value exc;\n\n          exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n                                    \"class or module required for rescue clause\");\n          mrb_exc_set(mrb, exc);\n          goto L_RAISE;\n        }\n      }\n      ec = mrb_class_ptr(e);\n      regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));\n      NEXT;\n    }\n\n    CASE(OP_RAISEIF, B) {\n      mrb_value exc = regs[a];\n      if (mrb_break_p(exc)) {\n        mrb->exc = mrb_obj_ptr(exc);\n        goto L_BREAK;\n      }\n      mrb_exc_set(mrb, exc);\n      if (mrb->exc) {\n        goto L_RAISE;\n      }\n      NEXT;\n    }\n\n    CASE(OP_SSEND, BBB) {\n      regs[a] = regs[0];\n      insn = OP_SEND;\n    }\n    goto L_SENDB;\n\n    CASE(OP_SSENDB, BBB) {\n      regs[a] = regs[0];\n    }\n    goto L_SENDB;\n\n    CASE(OP_SEND, BBB)\n    goto L_SENDB;\n\n    L_SEND_SYM:\n    c = 1;\n    /* push nil after arguments */\n    SET_NIL_VALUE(regs[a+2]);\n    goto L_SENDB_SYM;\n\n    CASE(OP_SENDB, BBB)\n    L_SENDB:\n    mid = syms[b];\n    L_SENDB_SYM:\n    {\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_method_t m;\n      struct RClass *cls;\n      mrb_value recv, blk;\n\n      ARGUMENT_NORMALIZE(a, &c, insn);\n\n      recv = regs[a];\n      cls = mrb_class(mrb, recv);\n      m = mrb_method_search_vm(mrb, &cls, mid);\n      if (MRB_METHOD_UNDEF_P(m)) {\n        m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0);\n        mid = MRB_SYM(method_missing);\n      }\n\n      /* push callinfo */\n      ci = cipush(mrb, a, 0, cls, NULL, mid, c);\n\n      if (MRB_METHOD_CFUNC_P(m)) {\n        if (MRB_METHOD_PROC_P(m)) {\n          struct RProc *p = MRB_METHOD_PROC(m);\n\n          mrb_vm_ci_proc_set(ci, p);\n          recv = p->body.func(mrb, recv);\n        }\n        else {\n          if (MRB_METHOD_NOARG_P(m)) {\n            check_method_noarg(mrb, ci);\n          }\n          recv = MRB_METHOD_FUNC(m)(mrb, recv);\n        }\n        mrb_gc_arena_shrink(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        ci = mrb->c->ci;\n        if (mrb_proc_p(blk)) {\n          struct RProc *p = mrb_proc_ptr(blk);\n          if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n            p->flags |= MRB_PROC_ORPHAN;\n          }\n        }\n        if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */\n          if (ci->cci == CINFO_RESUMED) {\n            mrb->jmp = prev_jmp;\n            return recv;\n          }\n          else {\n            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n            proc = ci[-1].proc;\n            irep = proc->body.irep;\n            pool = irep->pool;\n            syms = irep->syms;\n          }\n        }\n        ci->stack[0] = recv;\n        /* pop stackpos */\n        ci = cipop(mrb);\n        pc = ci->pc;\n      }\n      else {\n        /* setup environment for calling method */\n        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n        pc = irep->iseq;\n      }\n    }\n    JUMP;\n\n    CASE(OP_CALL, Z) {\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_value recv = ci->stack[0];\n      struct RProc *m = mrb_proc_ptr(recv);\n\n      /* replace callinfo */\n      ci->u.target_class = MRB_PROC_TARGET_CLASS(m);\n      mrb_vm_ci_proc_set(ci, m);\n      if (MRB_PROC_ENV_P(m)) {\n        ci->mid = MRB_PROC_ENV(m)->mid;\n      }\n\n      /* prepare stack */\n      if (MRB_PROC_CFUNC_P(m)) {\n        recv = MRB_PROC_CFUNC(m)(mrb, recv);\n        mrb_gc_arena_shrink(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        /* pop stackpos */\n        ci = cipop(mrb);\n        pc = ci->pc;\n        ci[1].stack[0] = recv;\n        irep = mrb->c->ci->proc->body.irep;\n      }\n      else {\n        /* setup environment for calling method */\n        proc = m;\n        irep = m->body.irep;\n        if (!irep) {\n          mrb->c->ci->stack[0] = mrb_nil_value();\n          a = 0;\n          c = OP_R_NORMAL;\n          goto L_OP_RETURN_BODY;\n        }\n        mrb_int nargs = mrb_ci_bidx(ci)+1;\n        if (nargs < irep->nregs) {\n          mrb_stack_extend(mrb, irep->nregs);\n          stack_clear(regs+nargs, irep->nregs-nargs);\n        }\n        if (MRB_PROC_ENV_P(m)) {\n          regs[0] = MRB_PROC_ENV(m)->stack[0];\n        }\n        pc = irep->iseq;\n      }\n      pool = irep->pool;\n      syms = irep->syms;\n      JUMP;\n    }\n\n    CASE(OP_SUPER, BB) {\n      mrb_method_t m;\n      struct RClass *cls;\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_value recv, blk;\n      const struct RProc *p = ci->proc;\n      mrb_sym mid = ci->mid;\n      struct RClass* target_class = MRB_PROC_TARGET_CLASS(p);\n\n      if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */\n        mid = p->e.env->mid;    /* restore old mid */\n      }\n\n      if (mid == 0 || !target_class) {\n        mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n      if (target_class->flags & MRB_FL_CLASS_IS_PREPENDED) {\n        target_class = mrb_vm_ci_target_class(ci);\n      }\n      else if (target_class->tt == MRB_TT_MODULE) {\n        target_class = mrb_vm_ci_target_class(ci);\n        if (!target_class || target_class->tt != MRB_TT_ICLASS) {\n          goto super_typeerror;\n        }\n      }\n      recv = regs[0];\n      if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {\n      super_typeerror: ;\n        mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n                                            \"self has wrong type to call super in this context\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n\n      ARGUMENT_NORMALIZE(a, &b, OP_SUPER);\n\n      cls = target_class->super;\n      m = mrb_method_search_vm(mrb, &cls, mid);\n      if (MRB_METHOD_UNDEF_P(m)) {\n        m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1);\n        mid = MRB_SYM(method_missing);\n      }\n\n      /* push callinfo */\n      ci = cipush(mrb, a, 0, cls, NULL, mid, b);\n\n      /* prepare stack */\n      ci->stack[0] = recv;\n\n      if (MRB_METHOD_CFUNC_P(m)) {\n        mrb_value v;\n\n        if (MRB_METHOD_PROC_P(m)) {\n          mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m));\n        }\n        v = MRB_METHOD_CFUNC(m)(mrb, recv);\n        mrb_gc_arena_restore(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        ci = mrb->c->ci;\n        mrb_assert(!mrb_break_p(v));\n        if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */\n          if (ci->cci == CINFO_RESUMED) {\n            mrb->jmp = prev_jmp;\n            return v;\n          }\n          else {\n            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n            proc = ci[-1].proc;\n            irep = proc->body.irep;\n            pool = irep->pool;\n            syms = irep->syms;\n          }\n        }\n        mrb->c->ci->stack[0] = v;\n        ci = cipop(mrb);\n        pc = ci->pc;\n      }\n      else {\n        /* setup environment for calling method */\n        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n        pc = irep->iseq;\n      }\n      JUMP;\n    }\n\n    CASE(OP_ARGARY, BS) {\n      mrb_int m1 = (b>>11)&0x3f;\n      mrb_int r  = (b>>10)&0x1;\n      mrb_int m2 = (b>>5)&0x1f;\n      mrb_int kd = (b>>4)&0x1;\n      mrb_int lv = (b>>0)&0xf;\n      mrb_value *stack;\n\n      if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) {\n        mrb_value exc;\n\n      L_NOSUPER:\n        exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n      if (lv == 0) stack = regs + 1;\n      else {\n        struct REnv *e = uvenv(mrb, lv-1);\n        if (!e) goto L_NOSUPER;\n        if (MRB_ENV_LEN(e) <= m1+r+m2+1)\n          goto L_NOSUPER;\n        stack = e->stack + 1;\n      }\n      if (r == 0) {\n        regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);\n      }\n      else {\n        mrb_value *pp = NULL;\n        struct RArray *rest;\n        mrb_int len = 0;\n\n        if (mrb_array_p(stack[m1])) {\n          struct RArray *ary = mrb_ary_ptr(stack[m1]);\n\n          pp = ARY_PTR(ary);\n          len = ARY_LEN(ary);\n        }\n        regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);\n        rest = mrb_ary_ptr(regs[a]);\n        if (m1 > 0) {\n          stack_copy(ARY_PTR(rest), stack, m1);\n        }\n        if (len > 0) {\n          stack_copy(ARY_PTR(rest)+m1, pp, len);\n        }\n        if (m2 > 0) {\n          stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);\n        }\n        ARY_SET_LEN(rest, m1+len+m2);\n      }\n      if (kd) {\n        regs[a+1] = stack[m1+r+m2];\n        regs[a+2] = stack[m1+r+m2+1];\n      }\n      else {\n        regs[a+1] = stack[m1+r+m2];\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ENTER, W) {\n      mrb_int m1 = MRB_ASPEC_REQ(a);\n      mrb_int o  = MRB_ASPEC_OPT(a);\n      mrb_int r  = MRB_ASPEC_REST(a);\n      mrb_int m2 = MRB_ASPEC_POST(a);\n      mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0;\n      /* unused\n      int b  = MRB_ASPEC_BLOCK(a);\n      */\n      mrb_int const len = m1 + o + r + m2;\n\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_int argc = ci->n;\n      mrb_value *argv = regs+1;\n      mrb_value * const argv0 = argv;\n      mrb_int const kw_pos = len + kd;    /* where kwhash should be */\n      mrb_int const blk_pos = kw_pos + 1; /* where block should be */\n      mrb_value blk = regs[mrb_ci_bidx(ci)];\n      mrb_value kdict = mrb_nil_value();\n\n      /* keyword arguments */\n      if (ci->nk > 0) {\n        mrb_int kidx = mrb_ci_kidx(ci);\n        kdict = regs[kidx];\n        if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) {\n          kdict = mrb_nil_value();\n          ci->nk = 0;\n        }\n      }\n      if (!kd && !mrb_nil_p(kdict)) {\n        if (argc < 14) {\n          ci->n++;\n          argc++;    /* include kdict in normal arguments */\n        }\n        else if (argc == 14) {\n          /* pack arguments and kdict */\n          regs[1] = mrb_ary_new_from_values(mrb, argc+1, ®s[1]);\n          argc = ci->n = 15;\n        }\n        else {/* argc == 15 */\n          /* push kdict to packed arguments */\n          mrb_ary_push(mrb, regs[1], regs[2]);\n        }\n        ci->nk = 0;\n      }\n      if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) {\n        kdict = mrb_hash_dup(mrb, kdict);\n      }\n\n      /* arguments is passed with Array */\n      if (argc == 15) {\n        struct RArray *ary = mrb_ary_ptr(regs[1]);\n        argv = ARY_PTR(ary);\n        argc = (int)ARY_LEN(ary);\n        mrb_gc_protect(mrb, regs[1]);\n      }\n\n      /* strict argument check */\n      if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) {\n        if (argc < m1 + m2 || (r == 0 && argc > len)) {\n          argnum_error(mrb, m1+m2);\n          goto L_RAISE;\n        }\n      }\n      /* extract first argument array to arguments */\n      else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {\n        mrb_gc_protect(mrb, argv[0]);\n        argc = (int)RARRAY_LEN(argv[0]);\n        argv = RARRAY_PTR(argv[0]);\n      }\n\n      /* rest arguments */\n      mrb_value rest = mrb_nil_value();\n      if (argc < len) {\n        mrb_int mlen = m2;\n        if (argc < m1+m2) {\n          mlen = m1 < argc ? argc - m1 : 0;\n        }\n\n        /* copy mandatory and optional arguments */\n        if (argv0 != argv && argv) {\n          value_move(®s[1], argv, argc-mlen); /* m1 + o */\n        }\n        if (argc < m1) {\n          stack_clear(®s[argc+1], m1-argc);\n        }\n        /* copy post mandatory arguments */\n        if (mlen) {\n          value_move(®s[len-m2+1], &argv[argc-mlen], mlen);\n        }\n        if (mlen < m2) {\n          stack_clear(®s[len-m2+mlen+1], m2-mlen);\n        }\n        /* initialize rest arguments with empty Array */\n        if (r) {\n          rest = mrb_ary_new_capa(mrb, 0);\n          regs[m1+o+1] = rest;\n        }\n        /* skip initializer of passed arguments */\n        if (o > 0 && argc > m1+m2)\n          pc += (argc - m1 - m2)*3;\n      }\n      else {\n        mrb_int rnum = 0;\n        if (argv0 != argv) {\n          value_move(®s[1], argv, m1+o);\n        }\n        if (r) {\n          rnum = argc-m1-o-m2;\n          rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);\n          regs[m1+o+1] = rest;\n        }\n        if (m2 > 0 && argc-m2 > m1) {\n          value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);\n        }\n        pc += o*3;\n      }\n\n      /* need to be update blk first to protect blk from GC */\n      regs[blk_pos] = blk;              /* move block */\n      if (kd) {\n        if (mrb_nil_p(kdict))\n          kdict = mrb_hash_new_capa(mrb, 0);\n        regs[kw_pos] = kdict;           /* set kwhash */\n      }\n\n      /* format arguments for generated code */\n      mrb->c->ci->n = (uint8_t)len;\n\n      /* clear local (but non-argument) variables */\n      if (irep->nlocals-blk_pos-1 > 0) {\n        stack_clear(®s[blk_pos+1], irep->nlocals-blk_pos-1);\n      }\n      JUMP;\n    }\n\n    CASE(OP_KARG, BB) {\n      mrb_value k = mrb_symbol_value(syms[b]);\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict, v;\n\n      if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) {\n        mrb_value str = mrb_format(mrb, \"missing keyword: %v\", k);\n        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n        goto L_RAISE;\n      }\n      v = mrb_hash_get(mrb, kdict, k);\n      regs[a] = v;\n      mrb_hash_delete_key(mrb, kdict, k);\n      NEXT;\n    }\n\n    CASE(OP_KEY_P, BB) {\n      mrb_value k = mrb_symbol_value(syms[b]);\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict;\n      mrb_bool key_p = FALSE;\n\n      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) {\n        key_p = mrb_hash_key_p(mrb, kdict, k);\n      }\n      regs[a] = mrb_bool_value(key_p);\n      NEXT;\n    }\n\n    CASE(OP_KEYEND, Z) {\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict;\n\n      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) {\n        mrb_value keys = mrb_hash_keys(mrb, kdict);\n        mrb_value key1 = RARRAY_PTR(keys)[0];\n        mrb_value str = mrb_format(mrb, \"unknown keyword: %v\", key1);\n        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n        goto L_RAISE;\n      }\n      NEXT;\n    }\n\n    CASE(OP_BREAK, B) {\n      c = OP_R_BREAK;\n      goto L_RETURN;\n    }\n    CASE(OP_RETURN_BLK, B) {\n      c = OP_R_RETURN;\n      goto L_RETURN;\n    }\n    CASE(OP_RETURN, B)\n    c = OP_R_NORMAL;\n    L_RETURN:\n    {\n      mrb_callinfo *ci;\n\n      ci = mrb->c->ci;\n      if (ci->mid) {\n        mrb_value blk = regs[mrb_ci_bidx(ci)];\n\n        if (mrb_proc_p(blk)) {\n          struct RProc *p = mrb_proc_ptr(blk);\n\n          if (!MRB_PROC_STRICT_P(p) &&\n              ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n            p->flags |= MRB_PROC_ORPHAN;\n          }\n        }\n      }\n\n      if (mrb->exc) {\n      L_RAISE:\n        ci = mrb->c->ci;\n        if (ci == mrb->c->cibase) {\n          ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n          if (ch == NULL) goto L_FTOP;\n          goto L_CATCH;\n        }\n        while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) {\n          ci = cipop(mrb);\n          if (ci[1].cci == CINFO_SKIP && prev_jmp) {\n            mrb->jmp = prev_jmp;\n            MRB_THROW(prev_jmp);\n          }\n          pc = ci[0].pc;\n          if (ci == mrb->c->cibase) {\n            ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n            if (ch == NULL) {\n            L_FTOP:             /* fiber top */\n              if (mrb->c == mrb->root_c) {\n                mrb->c->ci->stack = mrb->c->stbase;\n                goto L_STOP;\n              }\n              else {\n                struct mrb_context *c = mrb->c;\n\n                c->status = MRB_FIBER_TERMINATED;\n                mrb->c = c->prev;\n                c->prev = NULL;\n                goto L_RAISE;\n              }\n            }\n            break;\n          }\n        }\n      L_CATCH:\n        if (ch == NULL) goto L_STOP;\n        if (FALSE) {\n        L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */\n          ci = mrb->c->ci;\n        }\n        proc = ci->proc;\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, irep->nregs);\n        pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target);\n      }\n      else {\n        mrb_int acc;\n        mrb_value v;\n\n        ci = mrb->c->ci;\n        v = regs[a];\n        mrb_gc_protect(mrb, v);\n        switch (c) {\n        case OP_R_RETURN:\n          /* Fall through to OP_R_NORMAL otherwise */\n          if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {\n            const struct RProc *dst;\n            mrb_callinfo *cibase;\n            cibase = mrb->c->cibase;\n            dst = top_proc(mrb, proc);\n\n            if (MRB_PROC_ENV_P(dst)) {\n              struct REnv *e = MRB_PROC_ENV(dst);\n\n              if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) {\n                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n                goto L_RAISE;\n              }\n            }\n            /* check jump destination */\n            while (cibase <= ci && ci->proc != dst) {\n              if (ci->cci > CINFO_NONE) { /* jump cross C boundary */\n                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n                goto L_RAISE;\n              }\n              ci--;\n            }\n            if (ci <= cibase) { /* no jump destination */\n              localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n              goto L_RAISE;\n            }\n            ci = mrb->c->ci;\n            while (cibase <= ci && ci->proc != dst) {\n              CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) {\n                cibase = mrb->c->cibase;\n                dst = top_proc(mrb, proc);\n              }\n              CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) {\n                UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v);\n              }\n              CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK);\n              ci = cipop(mrb);\n              pc = ci->pc;\n            }\n            proc = ci->proc;\n            mrb->exc = NULL; /* clear break object */\n            break;\n          }\n          /* fallthrough */\n        case OP_R_NORMAL:\n        NORMAL_RETURN:\n          if (ci == mrb->c->cibase) {\n            struct mrb_context *c;\n            c = mrb->c;\n\n            if (!c->prev) { /* toplevel return */\n              regs[irep->nlocals] = v;\n              goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP);\n            }\n            if (!c->vmexec && c->prev->ci == c->prev->cibase) {\n              mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, \"double resume\");\n              mrb_exc_set(mrb, exc);\n              goto L_RAISE;\n            }\n            CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) {\n              c = mrb->c;\n            }\n            CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) {\n              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v);\n            }\n            CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL);\n            /* automatic yield at the end */\n            c->status = MRB_FIBER_TERMINATED;\n            mrb->c = c->prev;\n            mrb->c->status = MRB_FIBER_RUNNING;\n            c->prev = NULL;\n            if (c->vmexec) {\n              mrb_gc_arena_restore(mrb, ai);\n              c->vmexec = FALSE;\n              mrb->jmp = prev_jmp;\n              return v;\n            }\n            ci = mrb->c->ci;\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_RETURN) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_RETURN);\n          mrb->exc = NULL; /* clear break object */\n          break;\n        case OP_R_BREAK:\n          if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;\n          if (MRB_PROC_ORPHAN_P(proc)) {\n            mrb_value exc;\n\n          L_BREAK_ERROR:\n            exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR,\n                                      \"break from proc-closure\");\n            mrb_exc_set(mrb, exc);\n            goto L_RAISE;\n          }\n          if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) {\n            goto L_BREAK_ERROR;\n          }\n          else {\n            struct REnv *e = MRB_PROC_ENV(proc);\n\n            if (e->cxt != mrb->c) {\n              goto L_BREAK_ERROR;\n            }\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_BREAK) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_BREAK);\n          /* break from fiber block */\n          if (ci == mrb->c->cibase && ci->pc) {\n            struct mrb_context *c = mrb->c;\n\n            mrb->c = c->prev;\n            c->prev = NULL;\n            ci = mrb->c->ci;\n          }\n          if (ci->cci > CINFO_NONE) {\n            ci = cipop(mrb);\n            mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v);\n            mrb_gc_arena_restore(mrb, ai);\n            mrb->c->vmexec = FALSE;\n            mrb->jmp = prev_jmp;\n            MRB_THROW(prev_jmp);\n          }\n          if (FALSE) {\n            struct RBreak *brk;\n\n          L_BREAK:\n            brk = (struct RBreak*)mrb->exc;\n            proc = mrb_break_proc_get(brk);\n            v = mrb_break_value_get(brk);\n            ci = mrb->c->ci;\n\n            switch (mrb_break_tag_get(brk)) {\n#define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n);\n              RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS)\n#undef DISPATCH_CHECKPOINTS\n              default:\n                mrb_assert(!\"wrong break tag\");\n            }\n          }\n          while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) {\n            if (ci[-1].cci == CINFO_SKIP) {\n              goto L_BREAK_ERROR;\n            }\n            CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) {\n              /* do nothing */\n            }\n            CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) {\n              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v);\n            }\n            CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER);\n            ci = cipop(mrb);\n            pc = ci->pc;\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET);\n          if (ci == mrb->c->cibase) {\n            goto L_BREAK_ERROR;\n          }\n          mrb->exc = NULL; /* clear break object */\n          break;\n        default:\n          /* cannot happen */\n          break;\n        }\n        mrb_assert(ci == mrb->c->ci);\n        mrb_assert(mrb->exc == NULL);\n\n        if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) {\n          mrb_gc_arena_restore(mrb, ai);\n          mrb->c->vmexec = FALSE;\n          mrb->jmp = prev_jmp;\n          return v;\n        }\n        acc = ci->cci;\n        ci = cipop(mrb);\n        if (acc == CINFO_SKIP || acc == CINFO_DIRECT) {\n          mrb_gc_arena_restore(mrb, ai);\n          mrb->jmp = prev_jmp;\n          return v;\n        }\n        pc = ci->pc;\n        DEBUG(fprintf(stderr, \"from :%s\\n\", mrb_sym_name(mrb, ci->mid)));\n        proc = ci->proc;\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n\n        ci[1].stack[0] = v;\n        mrb_gc_arena_restore(mrb, ai);\n      }\n      JUMP;\n    }\n\n    CASE(OP_BLKPUSH, BS) {\n      int m1 = (b>>11)&0x3f;\n      int r  = (b>>10)&0x1;\n      int m2 = (b>>5)&0x1f;\n      int kd = (b>>4)&0x1;\n      int lv = (b>>0)&0xf;\n      mrb_value *stack;\n\n      if (lv == 0) stack = regs + 1;\n      else {\n        struct REnv *e = uvenv(mrb, lv-1);\n        if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) ||\n            MRB_ENV_LEN(e) <= m1+r+m2+1) {\n          localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n          goto L_RAISE;\n        }\n        stack = e->stack + 1;\n      }\n      if (mrb_nil_p(stack[m1+r+m2+kd])) {\n        localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n        goto L_RAISE;\n      }\n      regs[a] = stack[m1+r+m2+kd];\n      NEXT;\n    }\n\n#if !defined(MRB_USE_BIGINT) || defined(MRB_INT32)\n  L_INT_OVERFLOW:\n    {\n      mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, \"integer overflow\");\n      mrb_exc_set(mrb, exc);\n    }\n    goto L_RAISE;\n#endif\n\n#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))\n#define OP_MATH(op_name)                                                    \\\n  /* need to check if op is overridden */                                   \\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {                  \\\n    OP_MATH_CASE_INTEGER(op_name);                                          \\\n    OP_MATH_CASE_FLOAT(op_name, integer, float);                            \\\n    OP_MATH_CASE_FLOAT(op_name, float,  integer);                           \\\n    OP_MATH_CASE_FLOAT(op_name, float,  float);                             \\\n    OP_MATH_CASE_STRING_##op_name();                                        \\\n    default:                                                                \\\n      mid = MRB_OPSYM(op_name);                                             \\\n      goto L_SEND_SYM;                                                      \\\n  }                                                                         \\\n  NEXT;\n#define OP_MATH_CASE_INTEGER(op_name)                                       \\\n  case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER):                              \\\n    {                                                                       \\\n      mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z;      \\\n      if (mrb_int_##op_name##_overflow(x, y, &z)) {                         \\\n        OP_MATH_OVERFLOW_INT(op_name,x,y);                                  \\\n      }                                                                     \\\n      else                                                                  \\\n        SET_INT_VALUE(mrb,regs[a], z);                                      \\\n    }                                                                       \\\n    break\n#ifdef MRB_NO_FLOAT\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0\n#else\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2)                                     \\\n  case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2):                                \\\n    {                                                                           \\\n      mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \\\n      SET_FLOAT_VALUE(mrb, regs[a], z);                                         \\\n    }                                                                           \\\n    break\n#endif\n#ifdef MRB_USE_BIGINT\n#define OP_MATH_OVERFLOW_INT(op,x,y) regs[a] = mrb_bint_##op##_ii(mrb,x,y)\n#else\n#define OP_MATH_OVERFLOW_INT(op,x,y) goto L_INT_OVERFLOW\n#endif\n#define OP_MATH_CASE_STRING_add()                                           \\\n  case TYPES2(MRB_TT_STRING, MRB_TT_STRING):                                \\\n    regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]);                        \\\n    mrb_gc_arena_restore(mrb, ai);                                          \\\n    break\n#define OP_MATH_CASE_STRING_sub() (void)0\n#define OP_MATH_CASE_STRING_mul() (void)0\n#define OP_MATH_OP_add +\n#define OP_MATH_OP_sub -\n#define OP_MATH_OP_mul *\n#define OP_MATH_TT_integer MRB_TT_INTEGER\n#define OP_MATH_TT_float   MRB_TT_FLOAT\n\n    CASE(OP_ADD, B) {\n      OP_MATH(add);\n    }\n\n    CASE(OP_SUB, B) {\n      OP_MATH(sub);\n    }\n\n    CASE(OP_MUL, B) {\n      OP_MATH(mul);\n    }\n\n    CASE(OP_DIV, B) {\n#ifndef MRB_NO_FLOAT\n      mrb_float x, y, f;\n#endif\n\n      /* need to check if op is overridden */\n      switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\n      case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\n        {\n          mrb_int x = mrb_integer(regs[a]);\n          mrb_int y = mrb_integer(regs[a+1]);\n          mrb_int div = mrb_div_int(mrb, x, y);\n          SET_INT_VALUE(mrb, regs[a], div);\n        }\n        NEXT;\n#ifndef MRB_NO_FLOAT\n      case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\n        x = (mrb_float)mrb_integer(regs[a]);\n        y = mrb_float(regs[a+1]);\n        break;\n      case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\n        x = mrb_float(regs[a]);\n        y = (mrb_float)mrb_integer(regs[a+1]);\n        break;\n      case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\n        x = mrb_float(regs[a]);\n        y = mrb_float(regs[a+1]);\n        break;\n#endif\n      default:\n        mid = MRB_OPSYM(div);\n        goto L_SEND_SYM;\n      }\n\n#ifndef MRB_NO_FLOAT\n      f = mrb_div_float(x, y);\n      SET_FLOAT_VALUE(mrb, regs[a], f);\n#endif\n      NEXT;\n    }\n\n#define OP_MATHI(op_name)                                                   \\\n  /* need to check if op is overridden */                                   \\\n  switch (mrb_type(regs[a])) {                                              \\\n    OP_MATHI_CASE_INTEGER(op_name);                                         \\\n    OP_MATHI_CASE_FLOAT(op_name);                                           \\\n    default:                                                                \\\n      SET_INT_VALUE(mrb,regs[a+1], b);                                      \\\n      mid = MRB_OPSYM(op_name);                                             \\\n      goto L_SEND_SYM;                                                      \\\n  }                                                                         \\\n  NEXT;\n#define OP_MATHI_CASE_INTEGER(op_name)                                      \\\n  case MRB_TT_INTEGER:                                                      \\\n    {                                                                       \\\n      mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z;                  \\\n      if (mrb_int_##op_name##_overflow(x, y, &z)) {                         \\\n        OP_MATH_OVERFLOW_INT(op_name,x,y);                                  \\\n      }                                                                     \\\n      else                                                                  \\\n        SET_INT_VALUE(mrb,regs[a], z);                                      \\\n    }                                                                       \\\n    break\n#ifdef MRB_NO_FLOAT\n#define OP_MATHI_CASE_FLOAT(op_name) (void)0\n#else\n#define OP_MATHI_CASE_FLOAT(op_name)                                        \\\n  case MRB_TT_FLOAT:                                                        \\\n    {                                                                       \\\n      mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b;              \\\n      SET_FLOAT_VALUE(mrb, regs[a], z);                                     \\\n    }                                                                       \\\n    break\n#endif\n\n    CASE(OP_ADDI, BB) {\n      OP_MATHI(add);\n    }\n\n    CASE(OP_SUBI, BB) {\n      OP_MATHI(sub);\n    }\n\n#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))\n\n#ifdef MRB_NO_FLOAT\n#define OP_CMP(op,sym) do {\\\n  int result;\\\n  /* need to check if - is overridden */\\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n    break;\\\n  default:\\\n    mid = MRB_OPSYM(sym);\\\n    goto L_SEND_SYM;\\\n  }\\\n  if (result) {\\\n    SET_TRUE_VALUE(regs[a]);\\\n  }\\\n  else {\\\n    SET_FALSE_VALUE(regs[a]);\\\n  }\\\n} while(0)\n#else\n#define OP_CMP(op, sym) do {\\\n  int result;\\\n  /* need to check if - is overridden */\\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n    break;\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\\\n    break;\\\n  case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\\\n    break;\\\n  case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\\\n    result = OP_CMP_BODY(op,mrb_float,mrb_float);\\\n    break;\\\n  default:\\\n    mid = MRB_OPSYM(sym);\\\n    goto L_SEND_SYM;\\\n  }\\\n  if (result) {\\\n    SET_TRUE_VALUE(regs[a]);\\\n  }\\\n  else {\\\n    SET_FALSE_VALUE(regs[a]);\\\n  }\\\n} while(0)\n#endif\n\n    CASE(OP_EQ, B) {\n      if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {\n        SET_TRUE_VALUE(regs[a]);\n      }\n      else {\n        OP_CMP(==,eq);\n      }\n      NEXT;\n    }\n\n    CASE(OP_LT, B) {\n      OP_CMP(<,lt);\n      NEXT;\n    }\n\n    CASE(OP_LE, B) {\n      OP_CMP(<=,le);\n      NEXT;\n    }\n\n    CASE(OP_GT, B) {\n      OP_CMP(>,gt);\n      NEXT;\n    }\n\n    CASE(OP_GE, B) {\n      OP_CMP(>=,ge);\n      NEXT;\n    }\n\n    CASE(OP_ARRAY, BB) {\n      regs[a] = mrb_ary_new_from_values(mrb, b, ®s[a]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n    CASE(OP_ARRAY2, BBB) {\n      regs[a] = mrb_ary_new_from_values(mrb, c, ®s[b]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ARYCAT, B) {\n      mrb_value splat = mrb_ary_splat(mrb, regs[a+1]);\n      if (mrb_nil_p(regs[a])) {\n        regs[a] = splat;\n      }\n      else {\n        mrb_assert(mrb_array_p(regs[a]));\n        mrb_ary_concat(mrb, regs[a], splat);\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ARYPUSH, BB) {\n      mrb_assert(mrb_array_p(regs[a]));\n      for (mrb_int i=0; i pre + post) {\n        v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);\n        regs[a++] = v;\n        while (post--) {\n          regs[a++] = ARY_PTR(ary)[len-post-1];\n        }\n      }\n      else {\n        v = mrb_ary_new_capa(mrb, 0);\n        regs[a++] = v;\n        for (idx=0; idx+pre> 2;\n      if (pool[b].tt & IREP_TT_SFLAG) {\n        sym = mrb_intern_static(mrb, pool[b].u.str, len);\n      }\n      else {\n        sym  = mrb_intern(mrb, pool[b].u.str, len);\n      }\n      regs[a] = mrb_symbol_value(sym);\n      NEXT;\n    }\n\n    CASE(OP_STRING, BB) {\n      mrb_int len;\n\n      mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0);\n      len = pool[b].tt >> 2;\n      if (pool[b].tt & IREP_TT_SFLAG) {\n        regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len);\n      }\n      else {\n        regs[a] = mrb_str_new(mrb, pool[b].u.str, len);\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_STRCAT, B) {\n      mrb_assert(mrb_string_p(regs[a]));\n      mrb_str_concat(mrb, regs[a], regs[a+1]);\n      NEXT;\n    }\n\n    CASE(OP_HASH, BB) {\n      mrb_value hash = mrb_hash_new_capa(mrb, b);\n      int i;\n      int lim = a+b*2;\n\n      for (i=a; ireps[b];\n\n      if (c & OP_L_CAPTURE) {\n        p = mrb_closure_new(mrb, nirep);\n      }\n      else {\n        p = mrb_proc_new(mrb, nirep);\n        p->flags |= MRB_PROC_SCOPE;\n      }\n      if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;\n      regs[a] = mrb_obj_value(p);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n    CASE(OP_BLOCK, BB) {\n      c = OP_L_BLOCK;\n      goto L_MAKE_LAMBDA;\n    }\n    CASE(OP_METHOD, BB) {\n      c = OP_L_METHOD;\n      goto L_MAKE_LAMBDA;\n    }\n\n    CASE(OP_RANGE_INC, B) {\n      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE);\n      regs[a] = v;\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_RANGE_EXC, B) {\n      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE);\n      regs[a] = v;\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_OCLASS, B) {\n      regs[a] = mrb_obj_value(mrb->object_class);\n      NEXT;\n    }\n\n    CASE(OP_CLASS, BB) {\n      struct RClass *c = 0, *baseclass;\n      mrb_value base, super;\n      mrb_sym id = syms[b];\n\n      base = regs[a];\n      super = regs[a+1];\n      if (mrb_nil_p(base)) {\n        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n        if (!baseclass) baseclass = mrb->object_class;\n        base = mrb_obj_value(baseclass);\n      }\n      c = mrb_vm_define_class(mrb, base, super, id);\n      regs[a] = mrb_obj_value(c);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_MODULE, BB) {\n      struct RClass *cls = 0, *baseclass;\n      mrb_value base;\n      mrb_sym id = syms[b];\n\n      base = regs[a];\n      if (mrb_nil_p(base)) {\n        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n        if (!baseclass) baseclass = mrb->object_class;\n        base = mrb_obj_value(baseclass);\n      }\n      cls = mrb_vm_define_module(mrb, base, id);\n      regs[a] = mrb_obj_value(cls);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_EXEC, BB)\n    {\n      mrb_value recv = regs[a];\n      struct RProc *p;\n      const mrb_irep *nirep = irep->reps[b];\n\n      /* prepare closure */\n      p = mrb_proc_new(mrb, nirep);\n      p->c = NULL;\n      mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);\n      MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));\n      p->flags |= MRB_PROC_SCOPE;\n\n      /* prepare call stack */\n      cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0);\n\n      irep = p->body.irep;\n      pool = irep->pool;\n      syms = irep->syms;\n      mrb_stack_extend(mrb, irep->nregs);\n      stack_clear(regs+1, irep->nregs-1);\n      pc = irep->iseq;\n      JUMP;\n    }\n\n    CASE(OP_DEF, BB) {\n      struct RClass *target = mrb_class_ptr(regs[a]);\n      struct RProc *p = mrb_proc_ptr(regs[a+1]);\n      mrb_method_t m;\n      mrb_sym mid = syms[b];\n\n      MRB_METHOD_FROM_PROC(m, p);\n      mrb_define_method_raw(mrb, target, mid, m);\n      mrb_method_added(mrb, target, mid);\n      mrb_gc_arena_restore(mrb, ai);\n      regs[a] = mrb_symbol_value(mid);\n      NEXT;\n    }\n\n    CASE(OP_SCLASS, B) {\n      regs[a] = mrb_singleton_class(mrb, regs[a]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_TCLASS, B) {\n      struct RClass *target = check_target_class(mrb);\n      if (!target) goto L_RAISE;\n      regs[a] = mrb_obj_value(target);\n      NEXT;\n    }\n\n    CASE(OP_ALIAS, BB) {\n      struct RClass *target = check_target_class(mrb);\n\n      if (!target) goto L_RAISE;\n      mrb_alias_method(mrb, target, syms[a], syms[b]);\n      mrb_method_added(mrb, target, syms[a]);\n      NEXT;\n    }\n    CASE(OP_UNDEF, B) {\n      struct RClass *target = check_target_class(mrb);\n\n      if (!target) goto L_RAISE;\n      mrb_undef_method_id(mrb, target, syms[a]);\n      NEXT;\n    }\n\n    CASE(OP_DEBUG, Z) {\n      FETCH_BBB();\n#ifdef MRB_USE_DEBUG_HOOK\n      mrb->debug_op_hook(mrb, irep, pc, regs);\n#else\n#ifndef MRB_NO_STDIO\n      printf(\"OP_DEBUG %d %d %d\\n\", a, b, c);\n#else\n      abort();\n#endif\n#endif\n      NEXT;\n    }\n\n    CASE(OP_ERR, B) {\n      size_t len = pool[a].tt >> 2;\n      mrb_value exc;\n\n      mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0);\n      exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len);\n      mrb_exc_set(mrb, exc);\n      goto L_RAISE;\n    }\n\n    CASE(OP_EXT1, Z) {\n      insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n    CASE(OP_EXT2, Z) {\n      insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n    CASE(OP_EXT3, Z) {\n      uint8_t insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n\n    CASE(OP_STOP, Z) {\n      /*        stop VM */\n      CHECKPOINT_RESTORE(RBREAK_TAG_STOP) {\n        /* do nothing */\n      }\n      CHECKPOINT_MAIN(RBREAK_TAG_STOP) {\n        UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value());\n      }\n      CHECKPOINT_END(RBREAK_TAG_STOP);\n    L_STOP:\n      mrb->jmp = prev_jmp;\n      if (mrb->exc) {\n        mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION);\n        return mrb_obj_value(mrb->exc);\n      }\n      return regs[irep->nlocals];\n    }\n  }\n  END_DISPATCH;\n#undef regs\n  }\n  MRB_CATCH(&c_jmp) {\n    mrb_callinfo *ci = mrb->c->ci;\n    while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) {\n      ci = cipop(mrb);\n    }\n    exc_catched = TRUE;\n    pc = ci->pc;\n    goto RETRY_TRY_BLOCK;\n  }\n  MRB_END_EXC(&c_jmp);\n}", "func_hash": 44658455618798852770197569753613577766, "file_name": "vm.c", "file_hash": 164058079299968555060167307813659313262, "cwe": ["CWE-703"], "cve": "CVE-2022-1427", "cve_desc": "Out-of-bounds Read in mrb_obj_is_kind_of in in GitHub repository mruby/mruby prior to 3.2. # Impact: Possible arbitrary code execution if being exploited.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1427"}
{"idx": 231012, "project": "mruby", "commit_id": "a4d97934d51cb88954cc49161dc1d151f64afb6b", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/a4d97934d51cb88954cc49161dc1d151f64afb6b", "commit_message": "vm.c: check if target_class is NULL (when prepended).", "target": 0, "func": "mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc)\n{\n  /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */\n  const mrb_irep *irep = proc->body.irep;\n  const mrb_pool_value *pool = irep->pool;\n  const mrb_sym *syms = irep->syms;\n  mrb_code insn;\n  int ai = mrb_gc_arena_save(mrb);\n  struct mrb_jmpbuf *prev_jmp = mrb->jmp;\n  struct mrb_jmpbuf c_jmp;\n  uint32_t a;\n  uint16_t b;\n  uint16_t c;\n  mrb_sym mid;\n  const struct mrb_irep_catch_handler *ch;\n\n#ifdef DIRECT_THREADED\n  static const void * const optable[] = {\n#define OPCODE(x,_) &&L_OP_ ## x,\n#include \"mruby/ops.h\"\n#undef OPCODE\n  };\n#endif\n\n  mrb_bool exc_catched = FALSE;\nRETRY_TRY_BLOCK:\n\n  MRB_TRY(&c_jmp) {\n\n  if (exc_catched) {\n    exc_catched = FALSE;\n    mrb_gc_arena_restore(mrb, ai);\n    if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)\n      goto L_BREAK;\n    goto L_RAISE;\n  }\n  mrb->jmp = &c_jmp;\n  mrb_vm_ci_proc_set(mrb->c->ci, proc);\n\n#define regs (mrb->c->ci->stack)\n  INIT_DISPATCH {\n    CASE(OP_NOP, Z) {\n      /* do nothing */\n      NEXT;\n    }\n\n    CASE(OP_MOVE, BB) {\n      regs[a] = regs[b];\n      NEXT;\n    }\n\n    CASE(OP_LOADL, BB) {\n      switch (pool[b].tt) {   /* number */\n      case IREP_TT_INT32:\n        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32);\n        break;\n      case IREP_TT_INT64:\n#if defined(MRB_INT64)\n        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n        break;\n#else\n#if defined(MRB_64BIT)\n        if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) {\n          regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n          break;\n        }\n#endif\n        goto L_INT_OVERFLOW;\n#endif\n      case IREP_TT_BIGINT:\n#ifdef MRB_USE_BIGINT\n        {\n          const char *s = pool[b].u.str;\n          regs[a] = mrb_bint_new_str(mrb, s+2, (mrb_int)s[0], (mrb_int)s[1]);\n        }\n        break;\n#else\n        goto L_INT_OVERFLOW;\n#endif\n#ifndef MRB_NO_FLOAT\n      case IREP_TT_FLOAT:\n        regs[a] = mrb_float_value(mrb, pool[b].u.f);\n        break;\n#endif\n      default:\n        /* should not happen (tt:string) */\n        regs[a] = mrb_nil_value();\n        break;\n      }\n      NEXT;\n    }\n\n    CASE(OP_LOADI, BB) {\n      SET_FIXNUM_VALUE(regs[a], b);\n      NEXT;\n    }\n\n    CASE(OP_LOADINEG, BB) {\n      SET_FIXNUM_VALUE(regs[a], -b);\n      NEXT;\n    }\n\n    CASE(OP_LOADI__1,B) goto L_LOADI;\n    CASE(OP_LOADI_0,B) goto L_LOADI;\n    CASE(OP_LOADI_1,B) goto L_LOADI;\n    CASE(OP_LOADI_2,B) goto L_LOADI;\n    CASE(OP_LOADI_3,B) goto L_LOADI;\n    CASE(OP_LOADI_4,B) goto L_LOADI;\n    CASE(OP_LOADI_5,B) goto L_LOADI;\n    CASE(OP_LOADI_6,B) goto L_LOADI;\n    CASE(OP_LOADI_7, B) {\n    L_LOADI:\n      SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0);\n      NEXT;\n    }\n\n    CASE(OP_LOADI16, BS) {\n      SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b);\n      NEXT;\n    }\n\n    CASE(OP_LOADI32, BSS) {\n      SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c));\n      NEXT;\n    }\n\n    CASE(OP_LOADSYM, BB) {\n      SET_SYM_VALUE(regs[a], syms[b]);\n      NEXT;\n    }\n\n    CASE(OP_LOADNIL, B) {\n      SET_NIL_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_LOADSELF, B) {\n      regs[a] = regs[0];\n      NEXT;\n    }\n\n    CASE(OP_LOADT, B) {\n      SET_TRUE_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_LOADF, B) {\n      SET_FALSE_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETGV, BB) {\n      mrb_value val = mrb_gv_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETGV, BB) {\n      mrb_gv_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETSV, BB) {\n      mrb_value val = mrb_vm_special_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETSV, BB) {\n      mrb_vm_special_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETIV, BB) {\n      regs[a] = mrb_iv_get(mrb, regs[0], syms[b]);\n      NEXT;\n    }\n\n    CASE(OP_SETIV, BB) {\n      mrb_iv_set(mrb, regs[0], syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETCV, BB) {\n      mrb_value val;\n      val = mrb_vm_cv_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETCV, BB) {\n      mrb_vm_cv_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETIDX, B) {\n      mrb_value va = regs[a], vb = regs[a+1];\n      switch (mrb_type(va)) {\n      case MRB_TT_ARRAY:\n        if (!mrb_integer_p(vb)) goto getidx_fallback;\n        regs[a] = mrb_ary_entry(va, mrb_integer(vb));\n        break;\n      case MRB_TT_HASH:\n        va = mrb_hash_get(mrb, va, vb);\n        regs[a] = va;\n        break;\n      case MRB_TT_STRING:\n        switch (mrb_type(vb)) {\n        case MRB_TT_INTEGER:\n        case MRB_TT_STRING:\n        case MRB_TT_RANGE:\n          va = mrb_str_aref(mrb, va, vb, mrb_undef_value());\n          regs[a] = va;\n          break;\n        default:\n          goto getidx_fallback;\n        }\n        break;\n      default:\n      getidx_fallback:\n        mid = MRB_OPSYM(aref);\n        goto L_SEND_SYM;\n      }\n      NEXT;\n    }\n\n    CASE(OP_SETIDX, B) {\n      c = 2;\n      mid = MRB_OPSYM(aset);\n      SET_NIL_VALUE(regs[a+3]);\n      goto L_SENDB_SYM;\n    }\n\n    CASE(OP_GETCONST, BB) {\n      mrb_value v = mrb_vm_const_get(mrb, syms[b]);\n      regs[a] = v;\n      NEXT;\n    }\n\n    CASE(OP_SETCONST, BB) {\n      mrb_vm_const_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETMCNST, BB) {\n      mrb_value v = mrb_const_get(mrb, regs[a], syms[b]);\n      regs[a] = v;\n      NEXT;\n    }\n\n    CASE(OP_SETMCNST, BB) {\n      mrb_const_set(mrb, regs[a+1], syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETUPVAR, BBB) {\n      mrb_value *regs_a = regs + a;\n      struct REnv *e = uvenv(mrb, c);\n\n      if (e && b < MRB_ENV_LEN(e)) {\n        *regs_a = e->stack[b];\n      }\n      else {\n        *regs_a = mrb_nil_value();\n      }\n      NEXT;\n    }\n\n    CASE(OP_SETUPVAR, BBB) {\n      struct REnv *e = uvenv(mrb, c);\n\n      if (e) {\n        mrb_value *regs_a = regs + a;\n\n        if (b < MRB_ENV_LEN(e)) {\n          e->stack[b] = *regs_a;\n          mrb_write_barrier(mrb, (struct RBasic*)e);\n        }\n      }\n      NEXT;\n    }\n\n    CASE(OP_JMP, S) {\n      pc += (int16_t)a;\n      JUMP;\n    }\n    CASE(OP_JMPIF, BS) {\n      if (mrb_test(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n    CASE(OP_JMPNOT, BS) {\n      if (!mrb_test(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n    CASE(OP_JMPNIL, BS) {\n      if (mrb_nil_p(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n\n    CASE(OP_JMPUW, S) {\n      a = (uint32_t)((pc - irep->iseq) + (int16_t)a);\n      CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) {\n        struct RBreak *brk = (struct RBreak*)mrb->exc;\n        mrb_value target = mrb_break_value_get(brk);\n        mrb_assert(mrb_integer_p(target));\n        a = (uint32_t)mrb_integer(target);\n        mrb_assert(a >= 0 && a < irep->ilen);\n      }\n      CHECKPOINT_MAIN(RBREAK_TAG_JUMP) {\n        ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE);\n        if (ch) {\n          /* avoiding a jump from a catch handler into the same handler */\n          if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) {\n            THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a));\n          }\n        }\n      }\n      CHECKPOINT_END(RBREAK_TAG_JUMP);\n\n      mrb->exc = NULL; /* clear break object */\n      pc = irep->iseq + a;\n      JUMP;\n    }\n\n    CASE(OP_EXCEPT, B) {\n      mrb_value exc;\n\n      if (mrb->exc == NULL) {\n        exc = mrb_nil_value();\n      }\n      else {\n        switch (mrb->exc->tt) {\n        case MRB_TT_BREAK:\n        case MRB_TT_EXCEPTION:\n          exc = mrb_obj_value(mrb->exc);\n          break;\n        default:\n          mrb_assert(!\"bad mrb_type\");\n          exc = mrb_nil_value();\n          break;\n        }\n        mrb->exc = NULL;\n      }\n      regs[a] = exc;\n      NEXT;\n    }\n    CASE(OP_RESCUE, BB) {\n      mrb_value exc = regs[a];  /* exc on stack */\n      mrb_value e = regs[b];\n      struct RClass *ec;\n\n      switch (mrb_type(e)) {\n      case MRB_TT_CLASS:\n      case MRB_TT_MODULE:\n        break;\n      default:\n        {\n          mrb_value exc;\n\n          exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n                                    \"class or module required for rescue clause\");\n          mrb_exc_set(mrb, exc);\n          goto L_RAISE;\n        }\n      }\n      ec = mrb_class_ptr(e);\n      regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));\n      NEXT;\n    }\n\n    CASE(OP_RAISEIF, B) {\n      mrb_value exc = regs[a];\n      if (mrb_break_p(exc)) {\n        mrb->exc = mrb_obj_ptr(exc);\n        goto L_BREAK;\n      }\n      mrb_exc_set(mrb, exc);\n      if (mrb->exc) {\n        goto L_RAISE;\n      }\n      NEXT;\n    }\n\n    CASE(OP_SSEND, BBB) {\n      regs[a] = regs[0];\n      insn = OP_SEND;\n    }\n    goto L_SENDB;\n\n    CASE(OP_SSENDB, BBB) {\n      regs[a] = regs[0];\n    }\n    goto L_SENDB;\n\n    CASE(OP_SEND, BBB)\n    goto L_SENDB;\n\n    L_SEND_SYM:\n    c = 1;\n    /* push nil after arguments */\n    SET_NIL_VALUE(regs[a+2]);\n    goto L_SENDB_SYM;\n\n    CASE(OP_SENDB, BBB)\n    L_SENDB:\n    mid = syms[b];\n    L_SENDB_SYM:\n    {\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_method_t m;\n      struct RClass *cls;\n      mrb_value recv, blk;\n\n      ARGUMENT_NORMALIZE(a, &c, insn);\n\n      recv = regs[a];\n      cls = mrb_class(mrb, recv);\n      m = mrb_method_search_vm(mrb, &cls, mid);\n      if (MRB_METHOD_UNDEF_P(m)) {\n        m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0);\n        mid = MRB_SYM(method_missing);\n      }\n\n      /* push callinfo */\n      ci = cipush(mrb, a, 0, cls, NULL, mid, c);\n\n      if (MRB_METHOD_CFUNC_P(m)) {\n        if (MRB_METHOD_PROC_P(m)) {\n          struct RProc *p = MRB_METHOD_PROC(m);\n\n          mrb_vm_ci_proc_set(ci, p);\n          recv = p->body.func(mrb, recv);\n        }\n        else {\n          if (MRB_METHOD_NOARG_P(m)) {\n            check_method_noarg(mrb, ci);\n          }\n          recv = MRB_METHOD_FUNC(m)(mrb, recv);\n        }\n        mrb_gc_arena_shrink(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        ci = mrb->c->ci;\n        if (mrb_proc_p(blk)) {\n          struct RProc *p = mrb_proc_ptr(blk);\n          if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n            p->flags |= MRB_PROC_ORPHAN;\n          }\n        }\n        if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */\n          if (ci->cci == CINFO_RESUMED) {\n            mrb->jmp = prev_jmp;\n            return recv;\n          }\n          else {\n            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n            proc = ci[-1].proc;\n            irep = proc->body.irep;\n            pool = irep->pool;\n            syms = irep->syms;\n          }\n        }\n        ci->stack[0] = recv;\n        /* pop stackpos */\n        ci = cipop(mrb);\n        pc = ci->pc;\n      }\n      else {\n        /* setup environment for calling method */\n        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n        pc = irep->iseq;\n      }\n    }\n    JUMP;\n\n    CASE(OP_CALL, Z) {\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_value recv = ci->stack[0];\n      struct RProc *m = mrb_proc_ptr(recv);\n\n      /* replace callinfo */\n      ci->u.target_class = MRB_PROC_TARGET_CLASS(m);\n      mrb_vm_ci_proc_set(ci, m);\n      if (MRB_PROC_ENV_P(m)) {\n        ci->mid = MRB_PROC_ENV(m)->mid;\n      }\n\n      /* prepare stack */\n      if (MRB_PROC_CFUNC_P(m)) {\n        recv = MRB_PROC_CFUNC(m)(mrb, recv);\n        mrb_gc_arena_shrink(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        /* pop stackpos */\n        ci = cipop(mrb);\n        pc = ci->pc;\n        ci[1].stack[0] = recv;\n        irep = mrb->c->ci->proc->body.irep;\n      }\n      else {\n        /* setup environment for calling method */\n        proc = m;\n        irep = m->body.irep;\n        if (!irep) {\n          mrb->c->ci->stack[0] = mrb_nil_value();\n          a = 0;\n          c = OP_R_NORMAL;\n          goto L_OP_RETURN_BODY;\n        }\n        mrb_int nargs = mrb_ci_bidx(ci)+1;\n        if (nargs < irep->nregs) {\n          mrb_stack_extend(mrb, irep->nregs);\n          stack_clear(regs+nargs, irep->nregs-nargs);\n        }\n        if (MRB_PROC_ENV_P(m)) {\n          regs[0] = MRB_PROC_ENV(m)->stack[0];\n        }\n        pc = irep->iseq;\n      }\n      pool = irep->pool;\n      syms = irep->syms;\n      JUMP;\n    }\n\n    CASE(OP_SUPER, BB) {\n      mrb_method_t m;\n      struct RClass *cls;\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_value recv, blk;\n      const struct RProc *p = ci->proc;\n      mrb_sym mid = ci->mid;\n      struct RClass* target_class = MRB_PROC_TARGET_CLASS(p);\n\n      if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */\n        mid = p->e.env->mid;    /* restore old mid */\n      }\n\n      if (mid == 0 || !target_class) {\n        mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n      if ((target_class->flags & MRB_FL_CLASS_IS_PREPENDED) || target_class->tt == MRB_TT_MODULE) {\n        target_class = mrb_vm_ci_target_class(ci);\n        if (!target_class || target_class->tt != MRB_TT_ICLASS) {\n          goto super_typeerror;\n        }\n      }\n      recv = regs[0];\n      if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {\n      super_typeerror: ;\n        mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n                                            \"self has wrong type to call super in this context\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n\n      ARGUMENT_NORMALIZE(a, &b, OP_SUPER);\n\n      cls = target_class->super;\n      m = mrb_method_search_vm(mrb, &cls, mid);\n      if (MRB_METHOD_UNDEF_P(m)) {\n        m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1);\n        mid = MRB_SYM(method_missing);\n      }\n\n      /* push callinfo */\n      ci = cipush(mrb, a, 0, cls, NULL, mid, b);\n\n      /* prepare stack */\n      ci->stack[0] = recv;\n\n      if (MRB_METHOD_CFUNC_P(m)) {\n        mrb_value v;\n\n        if (MRB_METHOD_PROC_P(m)) {\n          mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m));\n        }\n        v = MRB_METHOD_CFUNC(m)(mrb, recv);\n        mrb_gc_arena_restore(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        ci = mrb->c->ci;\n        mrb_assert(!mrb_break_p(v));\n        if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */\n          if (ci->cci == CINFO_RESUMED) {\n            mrb->jmp = prev_jmp;\n            return v;\n          }\n          else {\n            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n            proc = ci[-1].proc;\n            irep = proc->body.irep;\n            pool = irep->pool;\n            syms = irep->syms;\n          }\n        }\n        mrb->c->ci->stack[0] = v;\n        ci = cipop(mrb);\n        pc = ci->pc;\n      }\n      else {\n        /* setup environment for calling method */\n        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n        pc = irep->iseq;\n      }\n      JUMP;\n    }\n\n    CASE(OP_ARGARY, BS) {\n      mrb_int m1 = (b>>11)&0x3f;\n      mrb_int r  = (b>>10)&0x1;\n      mrb_int m2 = (b>>5)&0x1f;\n      mrb_int kd = (b>>4)&0x1;\n      mrb_int lv = (b>>0)&0xf;\n      mrb_value *stack;\n\n      if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) {\n        mrb_value exc;\n\n      L_NOSUPER:\n        exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n      if (lv == 0) stack = regs + 1;\n      else {\n        struct REnv *e = uvenv(mrb, lv-1);\n        if (!e) goto L_NOSUPER;\n        if (MRB_ENV_LEN(e) <= m1+r+m2+1)\n          goto L_NOSUPER;\n        stack = e->stack + 1;\n      }\n      if (r == 0) {\n        regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);\n      }\n      else {\n        mrb_value *pp = NULL;\n        struct RArray *rest;\n        mrb_int len = 0;\n\n        if (mrb_array_p(stack[m1])) {\n          struct RArray *ary = mrb_ary_ptr(stack[m1]);\n\n          pp = ARY_PTR(ary);\n          len = ARY_LEN(ary);\n        }\n        regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);\n        rest = mrb_ary_ptr(regs[a]);\n        if (m1 > 0) {\n          stack_copy(ARY_PTR(rest), stack, m1);\n        }\n        if (len > 0) {\n          stack_copy(ARY_PTR(rest)+m1, pp, len);\n        }\n        if (m2 > 0) {\n          stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);\n        }\n        ARY_SET_LEN(rest, m1+len+m2);\n      }\n      if (kd) {\n        regs[a+1] = stack[m1+r+m2];\n        regs[a+2] = stack[m1+r+m2+1];\n      }\n      else {\n        regs[a+1] = stack[m1+r+m2];\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ENTER, W) {\n      mrb_int m1 = MRB_ASPEC_REQ(a);\n      mrb_int o  = MRB_ASPEC_OPT(a);\n      mrb_int r  = MRB_ASPEC_REST(a);\n      mrb_int m2 = MRB_ASPEC_POST(a);\n      mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0;\n      /* unused\n      int b  = MRB_ASPEC_BLOCK(a);\n      */\n      mrb_int const len = m1 + o + r + m2;\n\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_int argc = ci->n;\n      mrb_value *argv = regs+1;\n      mrb_value * const argv0 = argv;\n      mrb_int const kw_pos = len + kd;    /* where kwhash should be */\n      mrb_int const blk_pos = kw_pos + 1; /* where block should be */\n      mrb_value blk = regs[mrb_ci_bidx(ci)];\n      mrb_value kdict = mrb_nil_value();\n\n      /* keyword arguments */\n      if (ci->nk > 0) {\n        mrb_int kidx = mrb_ci_kidx(ci);\n        kdict = regs[kidx];\n        if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) {\n          kdict = mrb_nil_value();\n          ci->nk = 0;\n        }\n      }\n      if (!kd && !mrb_nil_p(kdict)) {\n        if (argc < 14) {\n          ci->n++;\n          argc++;    /* include kdict in normal arguments */\n        }\n        else if (argc == 14) {\n          /* pack arguments and kdict */\n          regs[1] = mrb_ary_new_from_values(mrb, argc+1, ®s[1]);\n          argc = ci->n = 15;\n        }\n        else {/* argc == 15 */\n          /* push kdict to packed arguments */\n          mrb_ary_push(mrb, regs[1], regs[2]);\n        }\n        ci->nk = 0;\n      }\n      if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) {\n        kdict = mrb_hash_dup(mrb, kdict);\n      }\n\n      /* arguments is passed with Array */\n      if (argc == 15) {\n        struct RArray *ary = mrb_ary_ptr(regs[1]);\n        argv = ARY_PTR(ary);\n        argc = (int)ARY_LEN(ary);\n        mrb_gc_protect(mrb, regs[1]);\n      }\n\n      /* strict argument check */\n      if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) {\n        if (argc < m1 + m2 || (r == 0 && argc > len)) {\n          argnum_error(mrb, m1+m2);\n          goto L_RAISE;\n        }\n      }\n      /* extract first argument array to arguments */\n      else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {\n        mrb_gc_protect(mrb, argv[0]);\n        argc = (int)RARRAY_LEN(argv[0]);\n        argv = RARRAY_PTR(argv[0]);\n      }\n\n      /* rest arguments */\n      mrb_value rest = mrb_nil_value();\n      if (argc < len) {\n        mrb_int mlen = m2;\n        if (argc < m1+m2) {\n          mlen = m1 < argc ? argc - m1 : 0;\n        }\n\n        /* copy mandatory and optional arguments */\n        if (argv0 != argv && argv) {\n          value_move(®s[1], argv, argc-mlen); /* m1 + o */\n        }\n        if (argc < m1) {\n          stack_clear(®s[argc+1], m1-argc);\n        }\n        /* copy post mandatory arguments */\n        if (mlen) {\n          value_move(®s[len-m2+1], &argv[argc-mlen], mlen);\n        }\n        if (mlen < m2) {\n          stack_clear(®s[len-m2+mlen+1], m2-mlen);\n        }\n        /* initialize rest arguments with empty Array */\n        if (r) {\n          rest = mrb_ary_new_capa(mrb, 0);\n          regs[m1+o+1] = rest;\n        }\n        /* skip initializer of passed arguments */\n        if (o > 0 && argc > m1+m2)\n          pc += (argc - m1 - m2)*3;\n      }\n      else {\n        mrb_int rnum = 0;\n        if (argv0 != argv) {\n          value_move(®s[1], argv, m1+o);\n        }\n        if (r) {\n          rnum = argc-m1-o-m2;\n          rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);\n          regs[m1+o+1] = rest;\n        }\n        if (m2 > 0 && argc-m2 > m1) {\n          value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);\n        }\n        pc += o*3;\n      }\n\n      /* need to be update blk first to protect blk from GC */\n      regs[blk_pos] = blk;              /* move block */\n      if (kd) {\n        if (mrb_nil_p(kdict))\n          kdict = mrb_hash_new_capa(mrb, 0);\n        regs[kw_pos] = kdict;           /* set kwhash */\n      }\n\n      /* format arguments for generated code */\n      mrb->c->ci->n = (uint8_t)len;\n\n      /* clear local (but non-argument) variables */\n      if (irep->nlocals-blk_pos-1 > 0) {\n        stack_clear(®s[blk_pos+1], irep->nlocals-blk_pos-1);\n      }\n      JUMP;\n    }\n\n    CASE(OP_KARG, BB) {\n      mrb_value k = mrb_symbol_value(syms[b]);\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict, v;\n\n      if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) {\n        mrb_value str = mrb_format(mrb, \"missing keyword: %v\", k);\n        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n        goto L_RAISE;\n      }\n      v = mrb_hash_get(mrb, kdict, k);\n      regs[a] = v;\n      mrb_hash_delete_key(mrb, kdict, k);\n      NEXT;\n    }\n\n    CASE(OP_KEY_P, BB) {\n      mrb_value k = mrb_symbol_value(syms[b]);\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict;\n      mrb_bool key_p = FALSE;\n\n      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) {\n        key_p = mrb_hash_key_p(mrb, kdict, k);\n      }\n      regs[a] = mrb_bool_value(key_p);\n      NEXT;\n    }\n\n    CASE(OP_KEYEND, Z) {\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict;\n\n      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) {\n        mrb_value keys = mrb_hash_keys(mrb, kdict);\n        mrb_value key1 = RARRAY_PTR(keys)[0];\n        mrb_value str = mrb_format(mrb, \"unknown keyword: %v\", key1);\n        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n        goto L_RAISE;\n      }\n      NEXT;\n    }\n\n    CASE(OP_BREAK, B) {\n      c = OP_R_BREAK;\n      goto L_RETURN;\n    }\n    CASE(OP_RETURN_BLK, B) {\n      c = OP_R_RETURN;\n      goto L_RETURN;\n    }\n    CASE(OP_RETURN, B)\n    c = OP_R_NORMAL;\n    L_RETURN:\n    {\n      mrb_callinfo *ci;\n\n      ci = mrb->c->ci;\n      if (ci->mid) {\n        mrb_value blk = regs[mrb_ci_bidx(ci)];\n\n        if (mrb_proc_p(blk)) {\n          struct RProc *p = mrb_proc_ptr(blk);\n\n          if (!MRB_PROC_STRICT_P(p) &&\n              ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n            p->flags |= MRB_PROC_ORPHAN;\n          }\n        }\n      }\n\n      if (mrb->exc) {\n      L_RAISE:\n        ci = mrb->c->ci;\n        if (ci == mrb->c->cibase) {\n          ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n          if (ch == NULL) goto L_FTOP;\n          goto L_CATCH;\n        }\n        while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) {\n          ci = cipop(mrb);\n          if (ci[1].cci == CINFO_SKIP && prev_jmp) {\n            mrb->jmp = prev_jmp;\n            MRB_THROW(prev_jmp);\n          }\n          pc = ci[0].pc;\n          if (ci == mrb->c->cibase) {\n            ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n            if (ch == NULL) {\n            L_FTOP:             /* fiber top */\n              if (mrb->c == mrb->root_c) {\n                mrb->c->ci->stack = mrb->c->stbase;\n                goto L_STOP;\n              }\n              else {\n                struct mrb_context *c = mrb->c;\n\n                c->status = MRB_FIBER_TERMINATED;\n                mrb->c = c->prev;\n                c->prev = NULL;\n                goto L_RAISE;\n              }\n            }\n            break;\n          }\n        }\n      L_CATCH:\n        if (ch == NULL) goto L_STOP;\n        if (FALSE) {\n        L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */\n          ci = mrb->c->ci;\n        }\n        proc = ci->proc;\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, irep->nregs);\n        pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target);\n      }\n      else {\n        mrb_int acc;\n        mrb_value v;\n\n        ci = mrb->c->ci;\n        v = regs[a];\n        mrb_gc_protect(mrb, v);\n        switch (c) {\n        case OP_R_RETURN:\n          /* Fall through to OP_R_NORMAL otherwise */\n          if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {\n            const struct RProc *dst;\n            mrb_callinfo *cibase;\n            cibase = mrb->c->cibase;\n            dst = top_proc(mrb, proc);\n\n            if (MRB_PROC_ENV_P(dst)) {\n              struct REnv *e = MRB_PROC_ENV(dst);\n\n              if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) {\n                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n                goto L_RAISE;\n              }\n            }\n            /* check jump destination */\n            while (cibase <= ci && ci->proc != dst) {\n              if (ci->cci > CINFO_NONE) { /* jump cross C boundary */\n                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n                goto L_RAISE;\n              }\n              ci--;\n            }\n            if (ci <= cibase) { /* no jump destination */\n              localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n              goto L_RAISE;\n            }\n            ci = mrb->c->ci;\n            while (cibase <= ci && ci->proc != dst) {\n              CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) {\n                cibase = mrb->c->cibase;\n                dst = top_proc(mrb, proc);\n              }\n              CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) {\n                UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v);\n              }\n              CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK);\n              ci = cipop(mrb);\n              pc = ci->pc;\n            }\n            proc = ci->proc;\n            mrb->exc = NULL; /* clear break object */\n            break;\n          }\n          /* fallthrough */\n        case OP_R_NORMAL:\n        NORMAL_RETURN:\n          if (ci == mrb->c->cibase) {\n            struct mrb_context *c;\n            c = mrb->c;\n\n            if (!c->prev) { /* toplevel return */\n              regs[irep->nlocals] = v;\n              goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP);\n            }\n            if (!c->vmexec && c->prev->ci == c->prev->cibase) {\n              mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, \"double resume\");\n              mrb_exc_set(mrb, exc);\n              goto L_RAISE;\n            }\n            CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) {\n              c = mrb->c;\n            }\n            CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) {\n              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v);\n            }\n            CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL);\n            /* automatic yield at the end */\n            c->status = MRB_FIBER_TERMINATED;\n            mrb->c = c->prev;\n            mrb->c->status = MRB_FIBER_RUNNING;\n            c->prev = NULL;\n            if (c->vmexec) {\n              mrb_gc_arena_restore(mrb, ai);\n              c->vmexec = FALSE;\n              mrb->jmp = prev_jmp;\n              return v;\n            }\n            ci = mrb->c->ci;\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_RETURN) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_RETURN);\n          mrb->exc = NULL; /* clear break object */\n          break;\n        case OP_R_BREAK:\n          if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;\n          if (MRB_PROC_ORPHAN_P(proc)) {\n            mrb_value exc;\n\n          L_BREAK_ERROR:\n            exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR,\n                                      \"break from proc-closure\");\n            mrb_exc_set(mrb, exc);\n            goto L_RAISE;\n          }\n          if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) {\n            goto L_BREAK_ERROR;\n          }\n          else {\n            struct REnv *e = MRB_PROC_ENV(proc);\n\n            if (e->cxt != mrb->c) {\n              goto L_BREAK_ERROR;\n            }\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_BREAK) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_BREAK);\n          /* break from fiber block */\n          if (ci == mrb->c->cibase && ci->pc) {\n            struct mrb_context *c = mrb->c;\n\n            mrb->c = c->prev;\n            c->prev = NULL;\n            ci = mrb->c->ci;\n          }\n          if (ci->cci > CINFO_NONE) {\n            ci = cipop(mrb);\n            mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v);\n            mrb_gc_arena_restore(mrb, ai);\n            mrb->c->vmexec = FALSE;\n            mrb->jmp = prev_jmp;\n            MRB_THROW(prev_jmp);\n          }\n          if (FALSE) {\n            struct RBreak *brk;\n\n          L_BREAK:\n            brk = (struct RBreak*)mrb->exc;\n            proc = mrb_break_proc_get(brk);\n            v = mrb_break_value_get(brk);\n            ci = mrb->c->ci;\n\n            switch (mrb_break_tag_get(brk)) {\n#define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n);\n              RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS)\n#undef DISPATCH_CHECKPOINTS\n              default:\n                mrb_assert(!\"wrong break tag\");\n            }\n          }\n          while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) {\n            if (ci[-1].cci == CINFO_SKIP) {\n              goto L_BREAK_ERROR;\n            }\n            CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) {\n              /* do nothing */\n            }\n            CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) {\n              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v);\n            }\n            CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER);\n            ci = cipop(mrb);\n            pc = ci->pc;\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET);\n          if (ci == mrb->c->cibase) {\n            goto L_BREAK_ERROR;\n          }\n          mrb->exc = NULL; /* clear break object */\n          break;\n        default:\n          /* cannot happen */\n          break;\n        }\n        mrb_assert(ci == mrb->c->ci);\n        mrb_assert(mrb->exc == NULL);\n\n        if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) {\n          mrb_gc_arena_restore(mrb, ai);\n          mrb->c->vmexec = FALSE;\n          mrb->jmp = prev_jmp;\n          return v;\n        }\n        acc = ci->cci;\n        ci = cipop(mrb);\n        if (acc == CINFO_SKIP || acc == CINFO_DIRECT) {\n          mrb_gc_arena_restore(mrb, ai);\n          mrb->jmp = prev_jmp;\n          return v;\n        }\n        pc = ci->pc;\n        DEBUG(fprintf(stderr, \"from :%s\\n\", mrb_sym_name(mrb, ci->mid)));\n        proc = ci->proc;\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n\n        ci[1].stack[0] = v;\n        mrb_gc_arena_restore(mrb, ai);\n      }\n      JUMP;\n    }\n\n    CASE(OP_BLKPUSH, BS) {\n      int m1 = (b>>11)&0x3f;\n      int r  = (b>>10)&0x1;\n      int m2 = (b>>5)&0x1f;\n      int kd = (b>>4)&0x1;\n      int lv = (b>>0)&0xf;\n      mrb_value *stack;\n\n      if (lv == 0) stack = regs + 1;\n      else {\n        struct REnv *e = uvenv(mrb, lv-1);\n        if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) ||\n            MRB_ENV_LEN(e) <= m1+r+m2+1) {\n          localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n          goto L_RAISE;\n        }\n        stack = e->stack + 1;\n      }\n      if (mrb_nil_p(stack[m1+r+m2+kd])) {\n        localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n        goto L_RAISE;\n      }\n      regs[a] = stack[m1+r+m2+kd];\n      NEXT;\n    }\n\n#if !defined(MRB_USE_BIGINT) || defined(MRB_INT32)\n  L_INT_OVERFLOW:\n    {\n      mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, \"integer overflow\");\n      mrb_exc_set(mrb, exc);\n    }\n    goto L_RAISE;\n#endif\n\n#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))\n#define OP_MATH(op_name)                                                    \\\n  /* need to check if op is overridden */                                   \\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {                  \\\n    OP_MATH_CASE_INTEGER(op_name);                                          \\\n    OP_MATH_CASE_FLOAT(op_name, integer, float);                            \\\n    OP_MATH_CASE_FLOAT(op_name, float,  integer);                           \\\n    OP_MATH_CASE_FLOAT(op_name, float,  float);                             \\\n    OP_MATH_CASE_STRING_##op_name();                                        \\\n    default:                                                                \\\n      mid = MRB_OPSYM(op_name);                                             \\\n      goto L_SEND_SYM;                                                      \\\n  }                                                                         \\\n  NEXT;\n#define OP_MATH_CASE_INTEGER(op_name)                                       \\\n  case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER):                              \\\n    {                                                                       \\\n      mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z;      \\\n      if (mrb_int_##op_name##_overflow(x, y, &z)) {                         \\\n        OP_MATH_OVERFLOW_INT(op_name,x,y);                                  \\\n      }                                                                     \\\n      else                                                                  \\\n        SET_INT_VALUE(mrb,regs[a], z);                                      \\\n    }                                                                       \\\n    break\n#ifdef MRB_NO_FLOAT\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0\n#else\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2)                                     \\\n  case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2):                                \\\n    {                                                                           \\\n      mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \\\n      SET_FLOAT_VALUE(mrb, regs[a], z);                                         \\\n    }                                                                           \\\n    break\n#endif\n#ifdef MRB_USE_BIGINT\n#define OP_MATH_OVERFLOW_INT(op,x,y) regs[a] = mrb_bint_##op##_ii(mrb,x,y)\n#else\n#define OP_MATH_OVERFLOW_INT(op,x,y) goto L_INT_OVERFLOW\n#endif\n#define OP_MATH_CASE_STRING_add()                                           \\\n  case TYPES2(MRB_TT_STRING, MRB_TT_STRING):                                \\\n    regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]);                        \\\n    mrb_gc_arena_restore(mrb, ai);                                          \\\n    break\n#define OP_MATH_CASE_STRING_sub() (void)0\n#define OP_MATH_CASE_STRING_mul() (void)0\n#define OP_MATH_OP_add +\n#define OP_MATH_OP_sub -\n#define OP_MATH_OP_mul *\n#define OP_MATH_TT_integer MRB_TT_INTEGER\n#define OP_MATH_TT_float   MRB_TT_FLOAT\n\n    CASE(OP_ADD, B) {\n      OP_MATH(add);\n    }\n\n    CASE(OP_SUB, B) {\n      OP_MATH(sub);\n    }\n\n    CASE(OP_MUL, B) {\n      OP_MATH(mul);\n    }\n\n    CASE(OP_DIV, B) {\n#ifndef MRB_NO_FLOAT\n      mrb_float x, y, f;\n#endif\n\n      /* need to check if op is overridden */\n      switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\n      case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\n        {\n          mrb_int x = mrb_integer(regs[a]);\n          mrb_int y = mrb_integer(regs[a+1]);\n          mrb_int div = mrb_div_int(mrb, x, y);\n          SET_INT_VALUE(mrb, regs[a], div);\n        }\n        NEXT;\n#ifndef MRB_NO_FLOAT\n      case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\n        x = (mrb_float)mrb_integer(regs[a]);\n        y = mrb_float(regs[a+1]);\n        break;\n      case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\n        x = mrb_float(regs[a]);\n        y = (mrb_float)mrb_integer(regs[a+1]);\n        break;\n      case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\n        x = mrb_float(regs[a]);\n        y = mrb_float(regs[a+1]);\n        break;\n#endif\n      default:\n        mid = MRB_OPSYM(div);\n        goto L_SEND_SYM;\n      }\n\n#ifndef MRB_NO_FLOAT\n      f = mrb_div_float(x, y);\n      SET_FLOAT_VALUE(mrb, regs[a], f);\n#endif\n      NEXT;\n    }\n\n#define OP_MATHI(op_name)                                                   \\\n  /* need to check if op is overridden */                                   \\\n  switch (mrb_type(regs[a])) {                                              \\\n    OP_MATHI_CASE_INTEGER(op_name);                                         \\\n    OP_MATHI_CASE_FLOAT(op_name);                                           \\\n    default:                                                                \\\n      SET_INT_VALUE(mrb,regs[a+1], b);                                      \\\n      mid = MRB_OPSYM(op_name);                                             \\\n      goto L_SEND_SYM;                                                      \\\n  }                                                                         \\\n  NEXT;\n#define OP_MATHI_CASE_INTEGER(op_name)                                      \\\n  case MRB_TT_INTEGER:                                                      \\\n    {                                                                       \\\n      mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z;                  \\\n      if (mrb_int_##op_name##_overflow(x, y, &z)) {                         \\\n        OP_MATH_OVERFLOW_INT(op_name,x,y);                                  \\\n      }                                                                     \\\n      else                                                                  \\\n        SET_INT_VALUE(mrb,regs[a], z);                                      \\\n    }                                                                       \\\n    break\n#ifdef MRB_NO_FLOAT\n#define OP_MATHI_CASE_FLOAT(op_name) (void)0\n#else\n#define OP_MATHI_CASE_FLOAT(op_name)                                        \\\n  case MRB_TT_FLOAT:                                                        \\\n    {                                                                       \\\n      mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b;              \\\n      SET_FLOAT_VALUE(mrb, regs[a], z);                                     \\\n    }                                                                       \\\n    break\n#endif\n\n    CASE(OP_ADDI, BB) {\n      OP_MATHI(add);\n    }\n\n    CASE(OP_SUBI, BB) {\n      OP_MATHI(sub);\n    }\n\n#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))\n\n#ifdef MRB_NO_FLOAT\n#define OP_CMP(op,sym) do {\\\n  int result;\\\n  /* need to check if - is overridden */\\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n    break;\\\n  default:\\\n    mid = MRB_OPSYM(sym);\\\n    goto L_SEND_SYM;\\\n  }\\\n  if (result) {\\\n    SET_TRUE_VALUE(regs[a]);\\\n  }\\\n  else {\\\n    SET_FALSE_VALUE(regs[a]);\\\n  }\\\n} while(0)\n#else\n#define OP_CMP(op, sym) do {\\\n  int result;\\\n  /* need to check if - is overridden */\\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n    break;\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\\\n    break;\\\n  case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\\\n    break;\\\n  case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\\\n    result = OP_CMP_BODY(op,mrb_float,mrb_float);\\\n    break;\\\n  default:\\\n    mid = MRB_OPSYM(sym);\\\n    goto L_SEND_SYM;\\\n  }\\\n  if (result) {\\\n    SET_TRUE_VALUE(regs[a]);\\\n  }\\\n  else {\\\n    SET_FALSE_VALUE(regs[a]);\\\n  }\\\n} while(0)\n#endif\n\n    CASE(OP_EQ, B) {\n      if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {\n        SET_TRUE_VALUE(regs[a]);\n      }\n      else {\n        OP_CMP(==,eq);\n      }\n      NEXT;\n    }\n\n    CASE(OP_LT, B) {\n      OP_CMP(<,lt);\n      NEXT;\n    }\n\n    CASE(OP_LE, B) {\n      OP_CMP(<=,le);\n      NEXT;\n    }\n\n    CASE(OP_GT, B) {\n      OP_CMP(>,gt);\n      NEXT;\n    }\n\n    CASE(OP_GE, B) {\n      OP_CMP(>=,ge);\n      NEXT;\n    }\n\n    CASE(OP_ARRAY, BB) {\n      regs[a] = mrb_ary_new_from_values(mrb, b, ®s[a]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n    CASE(OP_ARRAY2, BBB) {\n      regs[a] = mrb_ary_new_from_values(mrb, c, ®s[b]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ARYCAT, B) {\n      mrb_value splat = mrb_ary_splat(mrb, regs[a+1]);\n      if (mrb_nil_p(regs[a])) {\n        regs[a] = splat;\n      }\n      else {\n        mrb_assert(mrb_array_p(regs[a]));\n        mrb_ary_concat(mrb, regs[a], splat);\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ARYPUSH, BB) {\n      mrb_assert(mrb_array_p(regs[a]));\n      for (mrb_int i=0; i pre + post) {\n        v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);\n        regs[a++] = v;\n        while (post--) {\n          regs[a++] = ARY_PTR(ary)[len-post-1];\n        }\n      }\n      else {\n        v = mrb_ary_new_capa(mrb, 0);\n        regs[a++] = v;\n        for (idx=0; idx+pre> 2;\n      if (pool[b].tt & IREP_TT_SFLAG) {\n        sym = mrb_intern_static(mrb, pool[b].u.str, len);\n      }\n      else {\n        sym  = mrb_intern(mrb, pool[b].u.str, len);\n      }\n      regs[a] = mrb_symbol_value(sym);\n      NEXT;\n    }\n\n    CASE(OP_STRING, BB) {\n      mrb_int len;\n\n      mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0);\n      len = pool[b].tt >> 2;\n      if (pool[b].tt & IREP_TT_SFLAG) {\n        regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len);\n      }\n      else {\n        regs[a] = mrb_str_new(mrb, pool[b].u.str, len);\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_STRCAT, B) {\n      mrb_assert(mrb_string_p(regs[a]));\n      mrb_str_concat(mrb, regs[a], regs[a+1]);\n      NEXT;\n    }\n\n    CASE(OP_HASH, BB) {\n      mrb_value hash = mrb_hash_new_capa(mrb, b);\n      int i;\n      int lim = a+b*2;\n\n      for (i=a; ireps[b];\n\n      if (c & OP_L_CAPTURE) {\n        p = mrb_closure_new(mrb, nirep);\n      }\n      else {\n        p = mrb_proc_new(mrb, nirep);\n        p->flags |= MRB_PROC_SCOPE;\n      }\n      if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;\n      regs[a] = mrb_obj_value(p);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n    CASE(OP_BLOCK, BB) {\n      c = OP_L_BLOCK;\n      goto L_MAKE_LAMBDA;\n    }\n    CASE(OP_METHOD, BB) {\n      c = OP_L_METHOD;\n      goto L_MAKE_LAMBDA;\n    }\n\n    CASE(OP_RANGE_INC, B) {\n      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE);\n      regs[a] = v;\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_RANGE_EXC, B) {\n      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE);\n      regs[a] = v;\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_OCLASS, B) {\n      regs[a] = mrb_obj_value(mrb->object_class);\n      NEXT;\n    }\n\n    CASE(OP_CLASS, BB) {\n      struct RClass *c = 0, *baseclass;\n      mrb_value base, super;\n      mrb_sym id = syms[b];\n\n      base = regs[a];\n      super = regs[a+1];\n      if (mrb_nil_p(base)) {\n        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n        if (!baseclass) baseclass = mrb->object_class;\n        base = mrb_obj_value(baseclass);\n      }\n      c = mrb_vm_define_class(mrb, base, super, id);\n      regs[a] = mrb_obj_value(c);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_MODULE, BB) {\n      struct RClass *cls = 0, *baseclass;\n      mrb_value base;\n      mrb_sym id = syms[b];\n\n      base = regs[a];\n      if (mrb_nil_p(base)) {\n        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n        if (!baseclass) baseclass = mrb->object_class;\n        base = mrb_obj_value(baseclass);\n      }\n      cls = mrb_vm_define_module(mrb, base, id);\n      regs[a] = mrb_obj_value(cls);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_EXEC, BB)\n    {\n      mrb_value recv = regs[a];\n      struct RProc *p;\n      const mrb_irep *nirep = irep->reps[b];\n\n      /* prepare closure */\n      p = mrb_proc_new(mrb, nirep);\n      p->c = NULL;\n      mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);\n      MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));\n      p->flags |= MRB_PROC_SCOPE;\n\n      /* prepare call stack */\n      cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0);\n\n      irep = p->body.irep;\n      pool = irep->pool;\n      syms = irep->syms;\n      mrb_stack_extend(mrb, irep->nregs);\n      stack_clear(regs+1, irep->nregs-1);\n      pc = irep->iseq;\n      JUMP;\n    }\n\n    CASE(OP_DEF, BB) {\n      struct RClass *target = mrb_class_ptr(regs[a]);\n      struct RProc *p = mrb_proc_ptr(regs[a+1]);\n      mrb_method_t m;\n      mrb_sym mid = syms[b];\n\n      MRB_METHOD_FROM_PROC(m, p);\n      mrb_define_method_raw(mrb, target, mid, m);\n      mrb_method_added(mrb, target, mid);\n      mrb_gc_arena_restore(mrb, ai);\n      regs[a] = mrb_symbol_value(mid);\n      NEXT;\n    }\n\n    CASE(OP_SCLASS, B) {\n      regs[a] = mrb_singleton_class(mrb, regs[a]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_TCLASS, B) {\n      struct RClass *target = check_target_class(mrb);\n      if (!target) goto L_RAISE;\n      regs[a] = mrb_obj_value(target);\n      NEXT;\n    }\n\n    CASE(OP_ALIAS, BB) {\n      struct RClass *target = check_target_class(mrb);\n\n      if (!target) goto L_RAISE;\n      mrb_alias_method(mrb, target, syms[a], syms[b]);\n      mrb_method_added(mrb, target, syms[a]);\n      NEXT;\n    }\n    CASE(OP_UNDEF, B) {\n      struct RClass *target = check_target_class(mrb);\n\n      if (!target) goto L_RAISE;\n      mrb_undef_method_id(mrb, target, syms[a]);\n      NEXT;\n    }\n\n    CASE(OP_DEBUG, Z) {\n      FETCH_BBB();\n#ifdef MRB_USE_DEBUG_HOOK\n      mrb->debug_op_hook(mrb, irep, pc, regs);\n#else\n#ifndef MRB_NO_STDIO\n      printf(\"OP_DEBUG %d %d %d\\n\", a, b, c);\n#else\n      abort();\n#endif\n#endif\n      NEXT;\n    }\n\n    CASE(OP_ERR, B) {\n      size_t len = pool[a].tt >> 2;\n      mrb_value exc;\n\n      mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0);\n      exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len);\n      mrb_exc_set(mrb, exc);\n      goto L_RAISE;\n    }\n\n    CASE(OP_EXT1, Z) {\n      insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n    CASE(OP_EXT2, Z) {\n      insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n    CASE(OP_EXT3, Z) {\n      uint8_t insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n\n    CASE(OP_STOP, Z) {\n      /*        stop VM */\n      CHECKPOINT_RESTORE(RBREAK_TAG_STOP) {\n        /* do nothing */\n      }\n      CHECKPOINT_MAIN(RBREAK_TAG_STOP) {\n        UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value());\n      }\n      CHECKPOINT_END(RBREAK_TAG_STOP);\n    L_STOP:\n      mrb->jmp = prev_jmp;\n      if (mrb->exc) {\n        mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION);\n        return mrb_obj_value(mrb->exc);\n      }\n      return regs[irep->nlocals];\n    }\n  }\n  END_DISPATCH;\n#undef regs\n  }\n  MRB_CATCH(&c_jmp) {\n    mrb_callinfo *ci = mrb->c->ci;\n    while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) {\n      ci = cipop(mrb);\n    }\n    exc_catched = TRUE;\n    pc = ci->pc;\n    goto RETRY_TRY_BLOCK;\n  }\n  MRB_END_EXC(&c_jmp);\n}", "func_hash": 104703994590688087058145131124808583742, "file_name": "vm.c", "file_hash": 126976644189338180144758453935885521875, "cwe": ["CWE-703"], "cve": "CVE-2022-1427", "cve_desc": "Out-of-bounds Read in mrb_obj_is_kind_of in in GitHub repository mruby/mruby prior to 3.2. # Impact: Possible arbitrary code execution if being exploited.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1427"}
{"idx": 195692, "project": "FreeRTOS-Kernel", "commit_id": "47338393f1f79558f6144213409f09f81d7c4837", "project_url": "https://github.com/FreeRTOS/FreeRTOS-Kernel", "commit_url": "https://github.com/FreeRTOS/FreeRTOS-Kernel/commit/47338393f1f79558f6144213409f09f81d7c4837", "commit_message": "add assert for addition overflow on queue creation (#225)", "target": 1, "func": "    QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength,\r\n                                       const UBaseType_t uxItemSize,\r\n                                       const uint8_t ucQueueType )\r\n    {\r\n        Queue_t * pxNewQueue;\r\n        size_t xQueueSizeInBytes;\r\n        uint8_t * pucQueueStorage;\r\n\r\n        configASSERT( uxQueueLength > ( UBaseType_t ) 0 );\r\n\r\n        /* Allocate enough space to hold the maximum number of items that\r\n         * can be in the queue at any time.  It is valid for uxItemSize to be\r\n         * zero in the case the queue is used as a semaphore. */\r\n        xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */\r\n\r\n        /* Check for multiplication overflow. */\r\n        configASSERT( ( uxItemSize == 0 ) || ( uxQueueLength == ( xQueueSizeInBytes / uxItemSize ) ) );\r\n\r\n        /* Allocate the queue and storage area.  Justification for MISRA\r\n         * deviation as follows:  pvPortMalloc() always ensures returned memory\r\n         * blocks are aligned per the requirements of the MCU stack.  In this case\r\n         * pvPortMalloc() must return a pointer that is guaranteed to meet the\r\n         * alignment requirements of the Queue_t structure - which in this case\r\n         * is an int8_t *.  Therefore, whenever the stack alignment requirements\r\n         * are greater than or equal to the pointer to char requirements the cast\r\n         * is safe.  In other cases alignment requirements are not strict (one or\r\n         * two bytes). */\r\n        pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */\r\n\r\n        if( pxNewQueue != NULL )\r\n        {\r\n            /* Jump past the queue structure to find the location of the queue\r\n             * storage area. */\r\n            pucQueueStorage = ( uint8_t * ) pxNewQueue;\r\n            pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */\r\n\r\n            #if ( configSUPPORT_STATIC_ALLOCATION == 1 )\r\n                {\r\n                    /* Queues can be created either statically or dynamically, so\r\n                     * note this task was created dynamically in case it is later\r\n                     * deleted. */\r\n                    pxNewQueue->ucStaticallyAllocated = pdFALSE;\r\n                }\r\n            #endif /* configSUPPORT_STATIC_ALLOCATION */\r\n\r\n            prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue );\r\n        }\r\n        else\r\n        {\r\n            traceQUEUE_CREATE_FAILED( ucQueueType );\r\n            mtCOVERAGE_TEST_MARKER();\r\n        }\r\n\r\n        return pxNewQueue;\r\n    }\r", "func_hash": 278728915886701481135388633284092658774, "file_name": "queue.c", "file_hash": 44156660200315650828929819637760261927, "cwe": ["CWE-200"], "cve": "CVE-2021-31571", "cve_desc": "The kernel in Amazon Web Services FreeRTOS before 10.4.3 has an integer overflow in queue.c for queue creation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31571"}
{"idx": 231048, "project": "FreeRTOS-Kernel", "commit_id": "47338393f1f79558f6144213409f09f81d7c4837", "project_url": "https://github.com/FreeRTOS/FreeRTOS-Kernel", "commit_url": "https://github.com/FreeRTOS/FreeRTOS-Kernel/commit/47338393f1f79558f6144213409f09f81d7c4837", "commit_message": "add assert for addition overflow on queue creation (#225)", "target": 0, "func": "    QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength,\r\n                                       const UBaseType_t uxItemSize,\r\n                                       const uint8_t ucQueueType )\r\n    {\r\n        Queue_t * pxNewQueue;\r\n        size_t xQueueSizeInBytes;\r\n        uint8_t * pucQueueStorage;\r\n\r\n        configASSERT( uxQueueLength > ( UBaseType_t ) 0 );\r\n\r\n        /* Allocate enough space to hold the maximum number of items that\r\n         * can be in the queue at any time.  It is valid for uxItemSize to be\r\n         * zero in the case the queue is used as a semaphore. */\r\n        xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */\r\n\r\n        /* Check for multiplication overflow. */\r\n        configASSERT( ( uxItemSize == 0 ) || ( uxQueueLength == ( xQueueSizeInBytes / uxItemSize ) ) );\r\n\r\n        /* Check for addition overflow. */\r\n        configASSERT( ( sizeof( Queue_t ) + xQueueSizeInBytes ) >  xQueueSizeInBytes );\r\n\r\n        /* Allocate the queue and storage area.  Justification for MISRA\r\n         * deviation as follows:  pvPortMalloc() always ensures returned memory\r\n         * blocks are aligned per the requirements of the MCU stack.  In this case\r\n         * pvPortMalloc() must return a pointer that is guaranteed to meet the\r\n         * alignment requirements of the Queue_t structure - which in this case\r\n         * is an int8_t *.  Therefore, whenever the stack alignment requirements\r\n         * are greater than or equal to the pointer to char requirements the cast\r\n         * is safe.  In other cases alignment requirements are not strict (one or\r\n         * two bytes). */\r\n        pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */\r\n\r\n        if( pxNewQueue != NULL )\r\n        {\r\n            /* Jump past the queue structure to find the location of the queue\r\n             * storage area. */\r\n            pucQueueStorage = ( uint8_t * ) pxNewQueue;\r\n            pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */\r\n\r\n            #if ( configSUPPORT_STATIC_ALLOCATION == 1 )\r\n                {\r\n                    /* Queues can be created either statically or dynamically, so\r\n                     * note this task was created dynamically in case it is later\r\n                     * deleted. */\r\n                    pxNewQueue->ucStaticallyAllocated = pdFALSE;\r\n                }\r\n            #endif /* configSUPPORT_STATIC_ALLOCATION */\r\n\r\n            prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue );\r\n        }\r\n        else\r\n        {\r\n            traceQUEUE_CREATE_FAILED( ucQueueType );\r\n            mtCOVERAGE_TEST_MARKER();\r\n        }\r\n\r\n        return pxNewQueue;\r\n    }\r", "func_hash": 233309018517612713780199359033790626331, "file_name": "queue.c", "file_hash": 257322064233856588492480054392208384035, "cwe": ["CWE-200"], "cve": "CVE-2021-31571", "cve_desc": "The kernel in Amazon Web Services FreeRTOS before 10.4.3 has an integer overflow in queue.c for queue creation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31571"}
{"idx": 195720, "project": "mvfst", "commit_id": "a67083ff4b8dcbb7ee2839da6338032030d712b0", "project_url": "https://github.com/facebookincubator/mvfst", "commit_url": "https://github.com/facebookincubator/mvfst/commit/a67083ff4b8dcbb7ee2839da6338032030d712b0", "commit_message": "Close connection if we derive an extra 1-rtt write cipher\n\nSummary: Fixes CVE-2021-24029\n\nReviewed By: mjoras, lnicco\n\nDifferential Revision: D26613890\n\nfbshipit-source-id: 19bb2be2c731808144e1a074ece313fba11f1945", "target": 1, "func": "void updateHandshakeState(QuicServerConnectionState& conn) {\n  // Zero RTT read cipher is available after chlo is processed with the\n  // condition that early data attempt is accepted.\n  auto handshakeLayer = conn.serverHandshakeLayer;\n  auto zeroRttReadCipher = handshakeLayer->getZeroRttReadCipher();\n  auto zeroRttHeaderCipher = handshakeLayer->getZeroRttReadHeaderCipher();\n  // One RTT write cipher is available at Fizz layer after chlo is processed.\n  // However, the cipher is only exported to QUIC if early data attempt is\n  // accepted. Otherwise, the cipher will be available after cfin is\n  // processed.\n  auto oneRttWriteCipher = handshakeLayer->getOneRttWriteCipher();\n  // One RTT read cipher is available after cfin is processed.\n  auto oneRttReadCipher = handshakeLayer->getOneRttReadCipher();\n\n  auto oneRttWriteHeaderCipher = handshakeLayer->getOneRttWriteHeaderCipher();\n  auto oneRttReadHeaderCipher = handshakeLayer->getOneRttReadHeaderCipher();\n\n  if (zeroRttReadCipher) {\n    if (conn.qLogger) {\n      conn.qLogger->addTransportStateUpdate(kDerivedZeroRttReadCipher);\n    }\n    QUIC_TRACE(fst_trace, conn, \"derived 0-rtt read cipher\");\n    conn.readCodec->setZeroRttReadCipher(std::move(zeroRttReadCipher));\n  }\n  if (zeroRttHeaderCipher) {\n    conn.readCodec->setZeroRttHeaderCipher(std::move(zeroRttHeaderCipher));\n  }\n  if (oneRttWriteHeaderCipher) {\n    conn.oneRttWriteHeaderCipher = std::move(oneRttWriteHeaderCipher);\n  }\n  if (oneRttReadHeaderCipher) {\n    conn.readCodec->setOneRttHeaderCipher(std::move(oneRttReadHeaderCipher));\n  }\n\n  if (oneRttWriteCipher) {\n    if (conn.qLogger) {\n      conn.qLogger->addTransportStateUpdate(kDerivedOneRttWriteCipher);\n    }\n    QUIC_TRACE(fst_trace, conn, \"derived 1-rtt write cipher\");\n    CHECK(!conn.oneRttWriteCipher.get());\n    conn.oneRttWriteCipher = std::move(oneRttWriteCipher);\n\n    updatePacingOnKeyEstablished(conn);\n\n    // We negotiate the transport parameters whenever we have the 1-RTT write\n    // keys available.\n    auto clientParams = handshakeLayer->getClientTransportParams();\n    if (!clientParams) {\n      throw QuicTransportException(\n          \"No client transport params\",\n          TransportErrorCode::TRANSPORT_PARAMETER_ERROR);\n    }\n    processClientInitialParams(conn, std::move(*clientParams));\n  }\n  if (oneRttReadCipher) {\n    if (conn.qLogger) {\n      conn.qLogger->addTransportStateUpdate(kDerivedOneRttReadCipher);\n    }\n    QUIC_TRACE(fst_trace, conn, \"derived 1-rtt read cipher\");\n    // Clear limit because CFIN is received at this point\n    conn.writableBytesLimit = folly::none;\n    conn.readCodec->setOneRttReadCipher(std::move(oneRttReadCipher));\n  }\n  auto handshakeReadCipher = handshakeLayer->getHandshakeReadCipher();\n  auto handshakeReadHeaderCipher =\n      handshakeLayer->getHandshakeReadHeaderCipher();\n  if (handshakeReadCipher) {\n    CHECK(handshakeReadHeaderCipher);\n    conn.readCodec->setHandshakeReadCipher(std::move(handshakeReadCipher));\n    conn.readCodec->setHandshakeHeaderCipher(\n        std::move(handshakeReadHeaderCipher));\n  }\n  if (handshakeLayer->isHandshakeDone()) {\n    CHECK(conn.oneRttWriteCipher);\n    if (conn.version != QuicVersion::MVFST_D24 && !conn.sentHandshakeDone) {\n      sendSimpleFrame(conn, HandshakeDoneFrame());\n      conn.sentHandshakeDone = true;\n    }\n  }\n}", "func_hash": 43735419078414129480912957086830640484, "file_name": "ServerStateMachine.cpp", "file_hash": 9223824505720776904271246874049398430, "cwe": ["CWE-703"], "cve": "CVE-2021-24029", "cve_desc": "A packet of death scenario is possible in mvfst via a specially crafted message during a QUIC session, which causes a crash via a failed assertion. Per QUIC specification, this particular message should be treated as a connection error. This issue affects mvfst versions prior to commit a67083ff4b8dcbb7ee2839da6338032030d712b0 and proxygen versions prior to v2021.03.15.00.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-24029"}
{"idx": 231710, "project": "mvfst", "commit_id": "a67083ff4b8dcbb7ee2839da6338032030d712b0", "project_url": "https://github.com/facebookincubator/mvfst", "commit_url": "https://github.com/facebookincubator/mvfst/commit/a67083ff4b8dcbb7ee2839da6338032030d712b0", "commit_message": "Close connection if we derive an extra 1-rtt write cipher\n\nSummary: Fixes CVE-2021-24029\n\nReviewed By: mjoras, lnicco\n\nDifferential Revision: D26613890\n\nfbshipit-source-id: 19bb2be2c731808144e1a074ece313fba11f1945", "target": 0, "func": "void updateHandshakeState(QuicServerConnectionState& conn) {\n  // Zero RTT read cipher is available after chlo is processed with the\n  // condition that early data attempt is accepted.\n  auto handshakeLayer = conn.serverHandshakeLayer;\n  auto zeroRttReadCipher = handshakeLayer->getZeroRttReadCipher();\n  auto zeroRttHeaderCipher = handshakeLayer->getZeroRttReadHeaderCipher();\n  // One RTT write cipher is available at Fizz layer after chlo is processed.\n  // However, the cipher is only exported to QUIC if early data attempt is\n  // accepted. Otherwise, the cipher will be available after cfin is\n  // processed.\n  auto oneRttWriteCipher = handshakeLayer->getOneRttWriteCipher();\n  // One RTT read cipher is available after cfin is processed.\n  auto oneRttReadCipher = handshakeLayer->getOneRttReadCipher();\n\n  auto oneRttWriteHeaderCipher = handshakeLayer->getOneRttWriteHeaderCipher();\n  auto oneRttReadHeaderCipher = handshakeLayer->getOneRttReadHeaderCipher();\n\n  if (zeroRttReadCipher) {\n    if (conn.qLogger) {\n      conn.qLogger->addTransportStateUpdate(kDerivedZeroRttReadCipher);\n    }\n    QUIC_TRACE(fst_trace, conn, \"derived 0-rtt read cipher\");\n    conn.readCodec->setZeroRttReadCipher(std::move(zeroRttReadCipher));\n  }\n  if (zeroRttHeaderCipher) {\n    conn.readCodec->setZeroRttHeaderCipher(std::move(zeroRttHeaderCipher));\n  }\n  if (oneRttWriteHeaderCipher) {\n    conn.oneRttWriteHeaderCipher = std::move(oneRttWriteHeaderCipher);\n  }\n  if (oneRttReadHeaderCipher) {\n    conn.readCodec->setOneRttHeaderCipher(std::move(oneRttReadHeaderCipher));\n  }\n\n  if (oneRttWriteCipher) {\n    if (conn.qLogger) {\n      conn.qLogger->addTransportStateUpdate(kDerivedOneRttWriteCipher);\n    }\n    QUIC_TRACE(fst_trace, conn, \"derived 1-rtt write cipher\");\n    if (conn.oneRttWriteCipher) {\n      throw QuicTransportException(\n          \"Duplicate 1-rtt write cipher\", TransportErrorCode::CRYPTO_ERROR);\n    }\n    conn.oneRttWriteCipher = std::move(oneRttWriteCipher);\n\n    updatePacingOnKeyEstablished(conn);\n\n    // We negotiate the transport parameters whenever we have the 1-RTT write\n    // keys available.\n    auto clientParams = handshakeLayer->getClientTransportParams();\n    if (!clientParams) {\n      throw QuicTransportException(\n          \"No client transport params\",\n          TransportErrorCode::TRANSPORT_PARAMETER_ERROR);\n    }\n    processClientInitialParams(conn, std::move(*clientParams));\n  }\n  if (oneRttReadCipher) {\n    if (conn.qLogger) {\n      conn.qLogger->addTransportStateUpdate(kDerivedOneRttReadCipher);\n    }\n    QUIC_TRACE(fst_trace, conn, \"derived 1-rtt read cipher\");\n    // Clear limit because CFIN is received at this point\n    conn.writableBytesLimit = folly::none;\n    conn.readCodec->setOneRttReadCipher(std::move(oneRttReadCipher));\n  }\n  auto handshakeReadCipher = handshakeLayer->getHandshakeReadCipher();\n  auto handshakeReadHeaderCipher =\n      handshakeLayer->getHandshakeReadHeaderCipher();\n  if (handshakeReadCipher) {\n    CHECK(handshakeReadHeaderCipher);\n    conn.readCodec->setHandshakeReadCipher(std::move(handshakeReadCipher));\n    conn.readCodec->setHandshakeHeaderCipher(\n        std::move(handshakeReadHeaderCipher));\n  }\n  if (handshakeLayer->isHandshakeDone()) {\n    CHECK(conn.oneRttWriteCipher);\n    if (conn.version != QuicVersion::MVFST_D24 && !conn.sentHandshakeDone) {\n      sendSimpleFrame(conn, HandshakeDoneFrame());\n      conn.sentHandshakeDone = true;\n    }\n  }\n}", "func_hash": 131573153342571823274301341051505058759, "file_name": "ServerStateMachine.cpp", "file_hash": 204614198627642259228820961859917931421, "cwe": ["CWE-703"], "cve": "CVE-2021-24029", "cve_desc": "A packet of death scenario is possible in mvfst via a specially crafted message during a QUIC session, which causes a crash via a failed assertion. Per QUIC specification, this particular message should be treated as a connection error. This issue affects mvfst versions prior to commit a67083ff4b8dcbb7ee2839da6338032030d712b0 and proxygen versions prior to v2021.03.15.00.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-24029"}
{"idx": 195740, "project": "libjpeg", "commit_id": "4746b577931e926a49e50de9720a4946de3069a7", "project_url": "https://github.com/thorfdbg/libjpeg", "commit_url": "https://github.com/thorfdbg/libjpeg/commit/4746b577931e926a49e50de9720a4946de3069a7", "commit_message": "Fixed handling of empty JPEG-LS scans.", "target": 1, "func": "bool SampleInterleavedLSScan::ParseMCU(void)\n{\n#if ACCUSOFT_CODE\n  int lines             = m_ulRemaining[0]; // total number of MCU lines processed.\n  UBYTE preshift        = m_ucLowBit + FractionalColorBitsOf();\n  struct Line *line[4];\n  UBYTE cx;\n\n  //\n  // If a DNL marker is present, the number of remaining lines is zero. Fix it.\n  if (m_pFrame->HeightOf() == 0) {\n    assert(lines == 0);\n    lines = 8;\n  }\n  //\n  // A \"MCU\" in respect to the code organization is eight lines.\n  if (lines > 8) {\n    lines = 8;\n  }\n  if (m_pFrame->HeightOf() > 0)\n    m_ulRemaining[0] -= lines;\n  assert(lines > 0);\n  assert(m_ucCount < 4);\n\n  //\n  // Fill the line pointers.\n  for(cx = 0;cx < m_ucCount;cx++) {\n    line[cx] = CurrentLine(cx);\n  }\n\n  // Loop over lines and columns\n  do {\n    LONG length = m_ulWidth[0];\n    LONG *lp[4];\n\n    // Get the line pointers and initialize the internal backup lines.\n    for(cx = 0;cx < m_ucCount;cx++) {\n      lp[cx] = line[cx]->m_pData;\n      StartLine(cx);\n    }\n\n    if (BeginReadMCU(m_Stream.ByteStreamOf())) { \n      // No error handling strategy. No RST in scans. Bummer!\n      do {\n        LONG a[4],b[4],c[4],d[4]; // neighbouring values.\n        LONG d1[4],d2[4],d3[4];   // local gradients.\n        bool isrun = true;\n      \n        for(cx = 0;cx < m_ucCount;cx++) {\n          GetContext(cx,a[cx],b[cx],c[cx],d[cx]);\n\n          d1[cx]  = d[cx] - b[cx];    // compute local gradients\n          d2[cx]  = b[cx] - c[cx];\n          d3[cx]  = c[cx] - a[cx];\n\n          //\n          // Run mode only if the run condition is met for all components\n          if (isrun && !isRunMode(d1[cx],d2[cx],d3[cx]))\n            isrun = false;\n        }\n        \n        if (isrun) {\n          LONG run = DecodeRun(length,m_lRunIndex[0]);\n          //\n          // Now fill the data.\n          while(run) {\n            // Update so that the next process gets the correct value.\n            // There is one sample per component.\n            for(cx = 0;cx < m_ucCount;cx++) {\n              UpdateContext(cx,a[cx]);\n              // And insert the value into the target line as well.\n              *lp[cx]++ = a[cx] << preshift;\n            }\n            run--,length--;\n            // As long as there are pixels on the line.\n          }\n          //\n          // More data on the line? I.e. the run did not cover the full m_lJ samples?\n          // Now decode the run interruption sample. The rtype is here always zero.\n          if (length) {\n            bool negative; // the sign variable\n            LONG errval;   // the prediction error\n            LONG merr;     // the mapped error (symbol)\n            LONG rx;       // the reconstructed value\n            UBYTE k;       // golomb parameter\n            //\n            // Decode the interrupting pixels.\n            for(cx = 0;cx < m_ucCount;cx++) {\n              // Get the neighbourhood.\n              GetContext(cx,a[cx],b[cx],c[cx],d[cx]);\n              // The prediction mode is always false, but the sign information\n              // is required.\n              negative = a[cx] > b[cx];\n              // Get the golomb parameter for run interruption coding.\n              k       = GolombParameter(false);\n              // Golomb-decode the error symbol. It is always using the common\n              // run index.\n              merr    = GolombDecode(k,m_lLimit - m_lJ[m_lRunIndex[0]] - 1);\n              // Inverse the error mapping procedure.\n              errval  = InverseErrorMapping(merr,ErrorMappingOffset(false,merr != 0,k));\n              // Compute the reconstructed value.\n              rx      = Reconstruct(negative,b[cx],errval);\n              // Update so that the next process gets the correct value.\n              UpdateContext(cx,rx);\n              // Fill in the value into the line\n              *lp[cx]++ = rx << preshift;\n              // Update the variables of the run mode.\n              UpdateState(false,errval);\n            }\n            // Update the run index now. This is not part of\n            // EncodeRun because the non-reduced run-index is\n            // required for the golomb coder length limit. \n            if (m_lRunIndex[0] > 0)\n              m_lRunIndex[0]--;\n          } else break; // end of line.\n        } else {\n          UWORD ctxt;\n          bool  negative; // the sign variable.\n          LONG  px;       // the predicted variable.\n          LONG  rx;       // the reconstructed value.\n          LONG  errval;   // the error value.\n          LONG  merr;     // the mapped error value.\n          UBYTE k;        // the Golomb parameter.\n          //\n          for(cx = 0;cx < m_ucCount;cx++) {\n            // Quantize the gradients.\n            d1[cx]  = QuantizedGradient(d1[cx]);\n            d2[cx]  = QuantizedGradient(d2[cx]);\n            d3[cx]  = QuantizedGradient(d3[cx]);\n            // Compute the context.\n            ctxt    = Context(negative,d1[cx],d2[cx],d3[cx]); \n            // Compute the predicted value.\n            px      = Predict(a[cx],b[cx],c[cx]);\n            // Correct the prediction.\n            px      = CorrectPrediction(ctxt,negative,px);\n            // Compute the golomb parameter k from the context.\n            k       = GolombParameter(ctxt);\n            // Decode the error symbol.\n            merr    = GolombDecode(k,m_lLimit);\n            // Inverse the error symbol into an error value.\n            errval  = InverseErrorMapping(merr,ErrorMappingOffset(ctxt,k));\n            // Update the variables.\n            UpdateState(ctxt,errval);\n            // Compute the reconstructed value.\n            rx      = Reconstruct(negative,px,errval);\n            // Update so that the next process gets the correct value.\n            UpdateContext(cx,rx);\n            // And insert the value into the target line as well.\n            *lp[cx]++ = rx << preshift;\n          }\n        }\n      } while(--length);\n    } // No error handling here.\n    //\n    // Advance the line pointers.\n    for(cx = 0;cx < m_ucCount;cx++) {\n      EndLine(cx);\n      line[cx] = line[cx]->m_pNext;\n    }\n    //\n  } while(--lines);\n  //\n  // If this is the last line, gobble up all the\n  // bits from bitstuffing the last byte may have left.\n  // As SkipStuffing is idempotent, we can also do that\n  // all the time.\n  m_Stream.SkipStuffing();\n#endif  \n  return false;\n}", "func_hash": 262161649015079801638874313151941212550, "file_name": "None", "file_hash": null, "cwe": ["CWE-703"], "cve": "CVE-2022-32978", "cve_desc": "There is an assertion failure in SingleComponentLSScan::ParseMCU in singlecomponentlsscan.cpp in libjpeg before 1.64 via an empty JPEG-LS scan.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32978"}
{"idx": 232289, "project": "libjpeg", "commit_id": "4746b577931e926a49e50de9720a4946de3069a7", "project_url": "https://github.com/thorfdbg/libjpeg", "commit_url": "https://github.com/thorfdbg/libjpeg/commit/4746b577931e926a49e50de9720a4946de3069a7", "commit_message": "Fixed handling of empty JPEG-LS scans.", "target": 0, "func": "bool SampleInterleavedLSScan::ParseMCU(void)\n{\n#if ACCUSOFT_CODE\n  int lines             = m_ulRemaining[0]; // total number of MCU lines processed.\n  UBYTE preshift        = m_ucLowBit + FractionalColorBitsOf();\n  struct Line *line[4];\n  UBYTE cx;\n\n  //\n  // If a DNL marker is present, the number of remaining lines is zero. Fix it.\n  if (m_pFrame->HeightOf() == 0) {\n    assert(lines == 0);\n    lines = 8;\n  }\n  //\n  // A \"MCU\" in respect to the code organization is eight lines.\n  if (lines > 8) {\n    lines = 8;\n  }\n\n  if (lines == 0)\n    return false;\n  \n  if (m_pFrame->HeightOf() > 0)\n    m_ulRemaining[0] -= lines;\n  assert(m_ucCount < 4);\n\n  //\n  // Fill the line pointers.\n  for(cx = 0;cx < m_ucCount;cx++) {\n    line[cx] = CurrentLine(cx);\n  }\n\n  // Loop over lines and columns\n  do {\n    LONG length = m_ulWidth[0];\n    LONG *lp[4];\n\n    // Get the line pointers and initialize the internal backup lines.\n    for(cx = 0;cx < m_ucCount;cx++) {\n      lp[cx] = line[cx]->m_pData;\n      StartLine(cx);\n    }\n\n    if (BeginReadMCU(m_Stream.ByteStreamOf())) { \n      // No error handling strategy. No RST in scans. Bummer!\n      do {\n        LONG a[4],b[4],c[4],d[4]; // neighbouring values.\n        LONG d1[4],d2[4],d3[4];   // local gradients.\n        bool isrun = true;\n      \n        for(cx = 0;cx < m_ucCount;cx++) {\n          GetContext(cx,a[cx],b[cx],c[cx],d[cx]);\n\n          d1[cx]  = d[cx] - b[cx];    // compute local gradients\n          d2[cx]  = b[cx] - c[cx];\n          d3[cx]  = c[cx] - a[cx];\n\n          //\n          // Run mode only if the run condition is met for all components\n          if (isrun && !isRunMode(d1[cx],d2[cx],d3[cx]))\n            isrun = false;\n        }\n        \n        if (isrun) {\n          LONG run = DecodeRun(length,m_lRunIndex[0]);\n          //\n          // Now fill the data.\n          while(run) {\n            // Update so that the next process gets the correct value.\n            // There is one sample per component.\n            for(cx = 0;cx < m_ucCount;cx++) {\n              UpdateContext(cx,a[cx]);\n              // And insert the value into the target line as well.\n              *lp[cx]++ = a[cx] << preshift;\n            }\n            run--,length--;\n            // As long as there are pixels on the line.\n          }\n          //\n          // More data on the line? I.e. the run did not cover the full m_lJ samples?\n          // Now decode the run interruption sample. The rtype is here always zero.\n          if (length) {\n            bool negative; // the sign variable\n            LONG errval;   // the prediction error\n            LONG merr;     // the mapped error (symbol)\n            LONG rx;       // the reconstructed value\n            UBYTE k;       // golomb parameter\n            //\n            // Decode the interrupting pixels.\n            for(cx = 0;cx < m_ucCount;cx++) {\n              // Get the neighbourhood.\n              GetContext(cx,a[cx],b[cx],c[cx],d[cx]);\n              // The prediction mode is always false, but the sign information\n              // is required.\n              negative = a[cx] > b[cx];\n              // Get the golomb parameter for run interruption coding.\n              k       = GolombParameter(false);\n              // Golomb-decode the error symbol. It is always using the common\n              // run index.\n              merr    = GolombDecode(k,m_lLimit - m_lJ[m_lRunIndex[0]] - 1);\n              // Inverse the error mapping procedure.\n              errval  = InverseErrorMapping(merr,ErrorMappingOffset(false,merr != 0,k));\n              // Compute the reconstructed value.\n              rx      = Reconstruct(negative,b[cx],errval);\n              // Update so that the next process gets the correct value.\n              UpdateContext(cx,rx);\n              // Fill in the value into the line\n              *lp[cx]++ = rx << preshift;\n              // Update the variables of the run mode.\n              UpdateState(false,errval);\n            }\n            // Update the run index now. This is not part of\n            // EncodeRun because the non-reduced run-index is\n            // required for the golomb coder length limit. \n            if (m_lRunIndex[0] > 0)\n              m_lRunIndex[0]--;\n          } else break; // end of line.\n        } else {\n          UWORD ctxt;\n          bool  negative; // the sign variable.\n          LONG  px;       // the predicted variable.\n          LONG  rx;       // the reconstructed value.\n          LONG  errval;   // the error value.\n          LONG  merr;     // the mapped error value.\n          UBYTE k;        // the Golomb parameter.\n          //\n          for(cx = 0;cx < m_ucCount;cx++) {\n            // Quantize the gradients.\n            d1[cx]  = QuantizedGradient(d1[cx]);\n            d2[cx]  = QuantizedGradient(d2[cx]);\n            d3[cx]  = QuantizedGradient(d3[cx]);\n            // Compute the context.\n            ctxt    = Context(negative,d1[cx],d2[cx],d3[cx]); \n            // Compute the predicted value.\n            px      = Predict(a[cx],b[cx],c[cx]);\n            // Correct the prediction.\n            px      = CorrectPrediction(ctxt,negative,px);\n            // Compute the golomb parameter k from the context.\n            k       = GolombParameter(ctxt);\n            // Decode the error symbol.\n            merr    = GolombDecode(k,m_lLimit);\n            // Inverse the error symbol into an error value.\n            errval  = InverseErrorMapping(merr,ErrorMappingOffset(ctxt,k));\n            // Update the variables.\n            UpdateState(ctxt,errval);\n            // Compute the reconstructed value.\n            rx      = Reconstruct(negative,px,errval);\n            // Update so that the next process gets the correct value.\n            UpdateContext(cx,rx);\n            // And insert the value into the target line as well.\n            *lp[cx]++ = rx << preshift;\n          }\n        }\n      } while(--length);\n    } // No error handling here.\n    //\n    // Advance the line pointers.\n    for(cx = 0;cx < m_ucCount;cx++) {\n      EndLine(cx);\n      line[cx] = line[cx]->m_pNext;\n    }\n    //\n  } while(--lines);\n  //\n  // If this is the last line, gobble up all the\n  // bits from bitstuffing the last byte may have left.\n  // As SkipStuffing is idempotent, we can also do that\n  // all the time.\n  m_Stream.SkipStuffing();\n#endif  \n  return false;\n}", "func_hash": 195933043393855107446070248148738301990, "file_name": "None", "file_hash": null, "cwe": ["CWE-703"], "cve": "CVE-2022-32978", "cve_desc": "There is an assertion failure in SingleComponentLSScan::ParseMCU in singlecomponentlsscan.cpp in libjpeg before 1.64 via an empty JPEG-LS scan.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32978"}
{"idx": 195741, "project": "libjpeg", "commit_id": "4746b577931e926a49e50de9720a4946de3069a7", "project_url": "https://github.com/thorfdbg/libjpeg", "commit_url": "https://github.com/thorfdbg/libjpeg/commit/4746b577931e926a49e50de9720a4946de3069a7", "commit_message": "Fixed handling of empty JPEG-LS scans.", "target": 1, "func": "bool SingleComponentLSScan::ParseMCU(void)\n{ \n#if ACCUSOFT_CODE\n  int lines             = m_ulRemaining[0]; // total number of MCU lines processed.\n  UBYTE preshift        = m_ucLowBit + FractionalColorBitsOf();\n  struct Line *line     = CurrentLine(0);\n  \n  //\n  // If a DNL marker is present, the number of remaining lines is zero. Fix it.\n  if (m_pFrame->HeightOf() == 0) {\n    assert(lines == 0);\n    lines = 8;\n  }\n\n  assert(m_ucCount == 1);\n\n  //\n  // A \"MCU\" in respect to the code organization is eight lines.\n  if (lines > 8) {\n    lines = 8;\n  }\n  if (m_pFrame->HeightOf() > 0)\n    m_ulRemaining[0] -= lines;\n  \n  assert(lines > 0);\n\n  // Loop over lines and columns\n  do {\n    LONG length = m_ulWidth[0];\n    LONG *lp    = line->m_pData;\n\n#ifdef DEBUG_LS\n    int xpos    = 0;\n    static int linenumber = 0;\n    printf(\"\\n%4d : \",++linenumber);\n#endif\n     \n    StartLine(0);\n    if (BeginReadMCU(m_Stream.ByteStreamOf())) { // No error handling strategy. No RST in scans. Bummer!\n      do {\n        LONG a,b,c,d;   // neighbouring values.\n        LONG d1,d2,d3;  // local gradients.\n      \n        GetContext(0,a,b,c,d);\n        d1  = d - b;    // compute local gradients\n        d2  = b - c;\n        d3  = c - a;\n        \n        if (isRunMode(d1,d2,d3)) {\n          LONG run = DecodeRun(length,m_lRunIndex[0]);\n          //\n          // Now fill the data.\n          while(run) {\n            // Update so that the next process gets the correct value.\n            UpdateContext(0,a);\n            // And insert the value into the target line as well.\n            *lp++ = a << preshift;\n#ifdef DEBUG_LS\n            printf(\"%4d:<%2x> \",xpos++,a);\n#endif\n            run--,length--;\n            // As long as there are pixels on the line.\n          }\n          //\n          // More data on the line? I.e. the run did not cover the full m_lJ samples?\n          // Now decode the run interruption sample.\n          if (length) {\n            bool negative; // the sign variable\n            bool rtype;    // run interruption type\n            LONG errval;   // the prediction error\n            LONG merr;     // the mapped error (symbol)\n            LONG rx;       // the reconstructed value\n            UBYTE k;       // golomb parameter\n            // Get the neighbourhood.\n            GetContext(0,a,b,c,d);\n            // Get the prediction mode.\n            rtype  = InterruptedPredictionMode(negative,a,b);\n            // Get the golomb parameter for run interruption coding.\n            k      = GolombParameter(rtype);\n            // Golomb-decode the error symbol.\n            merr   = GolombDecode(k,m_lLimit - m_lJ[m_lRunIndex[0]] - 1);\n            // Inverse the error mapping procedure.\n            errval = InverseErrorMapping(merr + rtype,ErrorMappingOffset(rtype,rtype || merr,k));\n            // Compute the reconstructed value.\n            rx     = Reconstruct(negative,rtype?a:b,errval);\n            // Update so that the next process gets the correct value.\n            UpdateContext(0,rx);\n            // Fill in the value into the line\n            *lp    = rx << preshift;\n#ifdef DEBUG_LS\n            printf(\"%4d:<%2x> \",xpos++,*lp);\n#endif\n            // Update the variables of the run mode.\n            UpdateState(rtype,errval);\n            // Update the run index now. This is not part of\n            // EncodeRun because the non-reduced run-index is\n            // required for the golomb coder length limit. \n            if (m_lRunIndex[0] > 0)\n              m_lRunIndex[0]--;\n          } else break; // end of line.\n        } else {\n          UWORD ctxt;\n          bool  negative; // the sign variable.\n          LONG  px;       // the predicted variable.\n          LONG  rx;       // the reconstructed value.\n          LONG  errval;   // the error value.\n          LONG  merr;     // the mapped error value.\n          UBYTE k;        // the Golomb parameter.\n          // Quantize the gradients.\n          d1     = QuantizedGradient(d1);\n          d2     = QuantizedGradient(d2);\n          d3     = QuantizedGradient(d3);\n          // Compute the context.\n          ctxt   = Context(negative,d1,d2,d3); \n          // Compute the predicted value.\n          px     = Predict(a,b,c);\n          // Correct the prediction.\n          px     = CorrectPrediction(ctxt,negative,px);\n          // Compute the golomb parameter k from the context.\n          k      = GolombParameter(ctxt);\n          // Decode the error symbol.\n          merr   = GolombDecode(k,m_lLimit);\n          // Inverse the error symbol into an error value.\n          errval = InverseErrorMapping(merr,ErrorMappingOffset(ctxt,k));\n          // Update the variables.\n          UpdateState(ctxt,errval);\n          // Compute the reconstructed value.\n          rx     = Reconstruct(negative,px,errval);\n          // Update so that the next process gets the correct value.\n          UpdateContext(0,rx);\n          // And insert the value into the target line as well.\n          *lp    = rx << preshift;\n#ifdef DEBUG_LS\n          printf(\"%4d:<%2x> \",xpos++,*lp);\n#endif\n        }\n      } while(++lp,--length);\n    } // No error handling here.\n    EndLine(0);\n    line = line->m_pNext;\n  } while(--lines); \n  //\n  // If this is the last line, gobble up all the\n  // bits from bitstuffing the last byte may have left.\n  // As SkipStuffing is idempotent, we can also do that\n  // all the time.\n  m_Stream.SkipStuffing();\n#endif  \n  return false;\n}", "func_hash": 62606079555374024593923514521759457355, "file_name": "None", "file_hash": null, "cwe": ["CWE-703"], "cve": "CVE-2022-32978", "cve_desc": "There is an assertion failure in SingleComponentLSScan::ParseMCU in singlecomponentlsscan.cpp in libjpeg before 1.64 via an empty JPEG-LS scan.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32978"}
{"idx": 232287, "project": "libjpeg", "commit_id": "4746b577931e926a49e50de9720a4946de3069a7", "project_url": "https://github.com/thorfdbg/libjpeg", "commit_url": "https://github.com/thorfdbg/libjpeg/commit/4746b577931e926a49e50de9720a4946de3069a7", "commit_message": "Fixed handling of empty JPEG-LS scans.", "target": 0, "func": "bool SingleComponentLSScan::ParseMCU(void)\n{ \n#if ACCUSOFT_CODE\n  int lines             = m_ulRemaining[0]; // total number of MCU lines processed.\n  UBYTE preshift        = m_ucLowBit + FractionalColorBitsOf();\n  struct Line *line     = CurrentLine(0);\n  \n  //\n  // If a DNL marker is present, the number of remaining lines is zero. Fix it.\n  if (m_pFrame->HeightOf() == 0) {\n    assert(lines == 0);\n    lines = 8;\n  }\n\n  assert(m_ucCount == 1);\n\n  //\n  // A \"MCU\" in respect to the code organization is eight lines.\n  if (lines > 8) {\n    lines = 8;\n  }\n  if (m_pFrame->HeightOf() > 0)\n    m_ulRemaining[0] -= lines;\n\n  if (lines == 0)\n    return false;\n\n  // Loop over lines and columns\n  do {\n    LONG length = m_ulWidth[0];\n    LONG *lp    = line->m_pData;\n\n#ifdef DEBUG_LS\n    int xpos    = 0;\n    static int linenumber = 0;\n    printf(\"\\n%4d : \",++linenumber);\n#endif\n     \n    StartLine(0);\n    if (BeginReadMCU(m_Stream.ByteStreamOf())) { // No error handling strategy. No RST in scans. Bummer!\n      do {\n        LONG a,b,c,d;   // neighbouring values.\n        LONG d1,d2,d3;  // local gradients.\n      \n        GetContext(0,a,b,c,d);\n        d1  = d - b;    // compute local gradients\n        d2  = b - c;\n        d3  = c - a;\n        \n        if (isRunMode(d1,d2,d3)) {\n          LONG run = DecodeRun(length,m_lRunIndex[0]);\n          //\n          // Now fill the data.\n          while(run) {\n            // Update so that the next process gets the correct value.\n            UpdateContext(0,a);\n            // And insert the value into the target line as well.\n            *lp++ = a << preshift;\n#ifdef DEBUG_LS\n            printf(\"%4d:<%2x> \",xpos++,a);\n#endif\n            run--,length--;\n            // As long as there are pixels on the line.\n          }\n          //\n          // More data on the line? I.e. the run did not cover the full m_lJ samples?\n          // Now decode the run interruption sample.\n          if (length) {\n            bool negative; // the sign variable\n            bool rtype;    // run interruption type\n            LONG errval;   // the prediction error\n            LONG merr;     // the mapped error (symbol)\n            LONG rx;       // the reconstructed value\n            UBYTE k;       // golomb parameter\n            // Get the neighbourhood.\n            GetContext(0,a,b,c,d);\n            // Get the prediction mode.\n            rtype  = InterruptedPredictionMode(negative,a,b);\n            // Get the golomb parameter for run interruption coding.\n            k      = GolombParameter(rtype);\n            // Golomb-decode the error symbol.\n            merr   = GolombDecode(k,m_lLimit - m_lJ[m_lRunIndex[0]] - 1);\n            // Inverse the error mapping procedure.\n            errval = InverseErrorMapping(merr + rtype,ErrorMappingOffset(rtype,rtype || merr,k));\n            // Compute the reconstructed value.\n            rx     = Reconstruct(negative,rtype?a:b,errval);\n            // Update so that the next process gets the correct value.\n            UpdateContext(0,rx);\n            // Fill in the value into the line\n            *lp    = rx << preshift;\n#ifdef DEBUG_LS\n            printf(\"%4d:<%2x> \",xpos++,*lp);\n#endif\n            // Update the variables of the run mode.\n            UpdateState(rtype,errval);\n            // Update the run index now. This is not part of\n            // EncodeRun because the non-reduced run-index is\n            // required for the golomb coder length limit. \n            if (m_lRunIndex[0] > 0)\n              m_lRunIndex[0]--;\n          } else break; // end of line.\n        } else {\n          UWORD ctxt;\n          bool  negative; // the sign variable.\n          LONG  px;       // the predicted variable.\n          LONG  rx;       // the reconstructed value.\n          LONG  errval;   // the error value.\n          LONG  merr;     // the mapped error value.\n          UBYTE k;        // the Golomb parameter.\n          // Quantize the gradients.\n          d1     = QuantizedGradient(d1);\n          d2     = QuantizedGradient(d2);\n          d3     = QuantizedGradient(d3);\n          // Compute the context.\n          ctxt   = Context(negative,d1,d2,d3); \n          // Compute the predicted value.\n          px     = Predict(a,b,c);\n          // Correct the prediction.\n          px     = CorrectPrediction(ctxt,negative,px);\n          // Compute the golomb parameter k from the context.\n          k      = GolombParameter(ctxt);\n          // Decode the error symbol.\n          merr   = GolombDecode(k,m_lLimit);\n          // Inverse the error symbol into an error value.\n          errval = InverseErrorMapping(merr,ErrorMappingOffset(ctxt,k));\n          // Update the variables.\n          UpdateState(ctxt,errval);\n          // Compute the reconstructed value.\n          rx     = Reconstruct(negative,px,errval);\n          // Update so that the next process gets the correct value.\n          UpdateContext(0,rx);\n          // And insert the value into the target line as well.\n          *lp    = rx << preshift;\n#ifdef DEBUG_LS\n          printf(\"%4d:<%2x> \",xpos++,*lp);\n#endif\n        }\n      } while(++lp,--length);\n    } // No error handling here.\n    EndLine(0);\n    line = line->m_pNext;\n  } while(--lines); \n  //\n  // If this is the last line, gobble up all the\n  // bits from bitstuffing the last byte may have left.\n  // As SkipStuffing is idempotent, we can also do that\n  // all the time.\n  m_Stream.SkipStuffing();\n#endif  \n  return false;\n}", "func_hash": 278625865669519268412189582687913030823, "file_name": "None", "file_hash": null, "cwe": ["CWE-703"], "cve": "CVE-2022-32978", "cve_desc": "There is an assertion failure in SingleComponentLSScan::ParseMCU in singlecomponentlsscan.cpp in libjpeg before 1.64 via an empty JPEG-LS scan.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32978"}
{"idx": 195742, "project": "gpac", "commit_id": "37592ad86c6ca934d34740012213e467acc4a3b0", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/37592ad86c6ca934d34740012213e467acc4a3b0", "commit_message": "fixed #2163", "target": 1, "func": "static GF_Err gf_isom_parse_movie_boxes_internal(GF_ISOFile *mov, u32 *boxType, u64 *bytesMissing, Bool progressive_mode)\n{\n\tGF_Box *a;\n\tu64 totSize, mdat_end=0;\n\tGF_Err e = GF_OK;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\tif (mov->single_moof_mode && mov->single_moof_state == 2) {\n\t\treturn e;\n\t}\n\n\t/*restart from where we stopped last*/\n\ttotSize = mov->current_top_box_start;\n\tif (mov->bytes_removed) {\n\t\tassert(totSize >= mov->bytes_removed);\n\t\ttotSize -= mov->bytes_removed;\n\t}\n\tgf_bs_seek(mov->movieFileMap->bs, totSize);\n#endif\n\n\n\t/*while we have some data, parse our boxes*/\n\twhile (gf_bs_available(mov->movieFileMap->bs)) {\n\t\t*bytesMissing = 0;\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Parsing a top-level box at position %d\\n\", mov->current_top_box_start));\n#endif\n\n\t\te = gf_isom_parse_root_box(&a, mov->movieFileMap->bs, boxType, bytesMissing, progressive_mode);\n\n\t\tif (e >= 0) {\n\n\t\t} else if (e == GF_ISOM_INCOMPLETE_FILE) {\n\t\t\t/*our mdat is uncomplete, only valid for READ ONLY files...*/\n\t\t\tif (mov->openMode != GF_ISOM_OPEN_READ) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete MDAT while file is not read-only\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tif ((mov->openMode == GF_ISOM_OPEN_READ) && !progressive_mode) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete file while reading for dump - aborting parsing\\n\"));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn e;\n\t\t} else {\n\t\t\treturn e;\n\t\t}\n\n\t\tswitch (a->type) {\n\t\t/*MOOV box*/\n\t\tcase GF_ISOM_BOX_TYPE_MOOV:\n\t\t\tif (mov->moov) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate MOOV detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->moov = (GF_MovieBox *)a;\n\t\t\tmov->original_moov_offset = mov->current_top_box_start;\n\t\t\t/*set our pointer to the movie*/\n\t\t\tmov->moov->mov = mov;\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (mov->moov->mvex) mov->moov->mvex->mov = mov;\n\n#ifdef GF_ENABLE_CTRN\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tgf_isom_setup_traf_inheritance(mov);\n\t\t\t}\n#endif\n\n#endif\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\n\t\t\ttotSize += a->size;\n\n            if (!mov->moov->mvhd) {\n                GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MovieHeaderBox\\n\"));\n                return GF_ISOM_INVALID_FILE;\n            }\n\n            if (mov->meta) {\n\t\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\t}\n\n\t\t\t//dump senc info in dump mode\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\n\t\t\t\t\tif (trak->sample_encryption) {\n\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, NULL, trak->sample_encryption);\n\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\t\t\t\t\tif (trak->Media->information->sampleTable->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(trak->Media->information->sampleTable->child_boxes, trak->Media->information->sampleTable->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n            if (mdat_end && mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n                gf_isom_push_mdat_end(mov, mdat_end);\n                mdat_end=0;\n            }\n\t\t\tbreak;\n\n\t\t/*META box*/\n\t\tcase GF_ISOM_BOX_TYPE_META:\n\t\t\tif (mov->meta) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate META detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->meta = (GF_MetaBox *)a;\n\t\t\tmov->original_meta_offset = mov->current_top_box_start;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) {\n\t\t\t\treturn e;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\tbreak;\n\n\t\t/*we only keep the MDAT in READ for dump purposes*/\n\t\tcase GF_ISOM_BOX_TYPE_MDAT:\n\t\t\tif (!mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (mov->emsgs) {\n\t\t\t\tgf_isom_box_array_del(mov->emsgs);\n\t\t\t\tmov->emsgs = NULL;\n\t\t\t}\n#endif\n\n\t\t\tif (mov->openMode == GF_ISOM_OPEN_READ) {\n\t\t\t\tif (!mov->mdat) {\n\t\t\t\t\tmov->mdat = (GF_MediaDataBox *) a;\n\t\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\treturn e;\n\t\t\t\t\t}\n\t\t\t\t}\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\t\telse if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) gf_list_add(mov->TopBoxes, a);\n#endif\n\t\t\t\telse gf_isom_box_del(a); //in other modes we don't care\n\n\n\t\t\t\tif (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n                    mdat_end = gf_bs_get_position(mov->movieFileMap->bs);\n                    if (mov->moov) {\n                        gf_isom_push_mdat_end(mov, mdat_end);\n                        mdat_end=0;\n                    }\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*if we don't have any MDAT yet, create one (edit-write mode)\n\t\t\tWe only work with one mdat, but we're puting it at the place\n\t\t\tof the first mdat found when opening a file for editing*/\n\t\t\telse if (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\t\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\tif (e) {\n\t\t\t\t\treturn e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GF_ISOM_BOX_TYPE_FTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->brand) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'ftyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->brand = (GF_FileTypeBox *)a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_OTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->otyp) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'otyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tmov->otyp = (GF_Box *)a;\n\t\t\t\ttotSize += a->size;\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else {\n\t\t\t\tGF_FileTypeBox *brand = (GF_FileTypeBox *) gf_isom_box_find_child(a->child_boxes, GF_ISOM_BOX_TYPE_FTYP);\n\t\t\t\tif (brand) {\n\t\t\t\t\ts32 pos;\n\t\t\t\t\tgf_list_del_item(a->child_boxes, brand);\n\t\t\t\t\tpos = gf_list_del_item(mov->TopBoxes, mov->brand);\n\t\t\t\t\tgf_isom_box_del((GF_Box *) mov->brand);\n\t\t\t\t\tmov->brand = brand;\n\t\t\t\t\tif (pos<0) pos=0;\n\t\t\t\t\tgf_list_insert(mov->TopBoxes, brand, pos);\n\t\t\t\t}\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PDIN:\n\t\t\t/*ONE AND ONLY ONE PDIN*/\n\t\t\tif (mov->pdin) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'pdin'' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->pdin = (GF_ProgressiveDownloadBox *) a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tcase GF_ISOM_BOX_TYPE_STYP:\n\t\t{\n\t\t\tu32 brand = ((GF_FileTypeBox *)a)->majorBrand;\n\t\t\tswitch (brand) {\n\t\t\tcase GF_ISOM_BRAND_SISX:\n\t\t\tcase GF_ISOM_BRAND_RISX:\n\t\t\tcase GF_ISOM_BRAND_SSSS:\n\t\t\t\tmov->is_index_segment = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t/*fall-through*/\n\n\t\tcase GF_ISOM_BOX_TYPE_SIDX:\n\t\tcase GF_ISOM_BOX_TYPE_SSIX:\n\t\t\tif (mov->moov && !mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else if (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)  && (mov->openMode!=GF_ISOM_OPEN_KEEP_FRAGMENTS)\n\t\t\t) {\n\t\t\t\tif (a->type==GF_ISOM_BOX_TYPE_SIDX) {\n\t\t\t\t\tif (mov->root_sidx) gf_isom_box_del( (GF_Box *) mov->root_sidx);\n\t\t\t\t\tmov->root_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\t\tmov->sidx_start_offset = mov->current_top_box_start;\n\t\t\t\t\tmov->sidx_end_offset = gf_bs_get_position(mov->movieFileMap->bs);\n\n\t\t\t\t}\n\t\t\t\telse if (a->type==GF_ISOM_BOX_TYPE_STYP) {\n\t\t\t\t\tmov->styp_start_offset = mov->current_top_box_start;\n\n\t\t\t\t\tif (mov->seg_styp) gf_isom_box_del(mov->seg_styp);\n\t\t\t\t\tmov->seg_styp = a;\n\t\t\t\t} else if (a->type==GF_ISOM_BOX_TYPE_SSIX) {\n\t\t\t\t\tif (mov->seg_ssix) gf_isom_box_del(mov->seg_ssix);\n\t\t\t\t\tmov->seg_ssix = a;\n\t\t\t\t} else {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t}\n\t\t\t\tgf_isom_push_mdat_end(mov, mov->current_top_box_start);\n\t\t\t} else if (!mov->NextMoofNumber && (a->type==GF_ISOM_BOX_TYPE_SIDX)) {\n\t\t\t\tif (mov->main_sidx) gf_isom_box_del( (GF_Box *) mov->main_sidx);\n\t\t\t\tmov->main_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\tmov->main_sidx_end_pos = mov->current_top_box_start + a->size;\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_MOOF:\n\t\t\t//no support for inplace rewrite for fragmented files\n\t\t\tgf_isom_disable_inplace_rewrite(mov);\n\t\t\tif (!mov->moov) {\n\t\t\t\tGF_LOG(mov->moof ? GF_LOG_DEBUG : GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Movie fragment but no moov (yet) - possibly broken parsing!\\n\"));\n\t\t\t}\n\t\t\tif (mov->single_moof_mode) {\n\t\t\t\tmov->single_moof_state++;\n\t\t\t\tif (mov->single_moof_state > 1) {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t}\n\t\t\t}\n\t\t\t((GF_MovieFragmentBox *)a)->mov = mov;\n\n\t\t\ttotSize += a->size;\n\t\t\tmov->moof = (GF_MovieFragmentBox *) a;\n\n\t\t\t/*some smooth streaming streams contain a SDTP under the TRAF: this is incorrect, convert it*/\n\t\t\tFixTrackID(mov);\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tFixSDTPInTRAF(mov->moof);\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\tGF_TrackFragmentBox *traf = (GF_TrackFragmentBox *)gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\tif (traf->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(traf->child_boxes, traf->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*read & debug: store at root level*/\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tgf_list_add(mov->TopBoxes, a);\n\t\t\t\t/*also update pointers to trex for debug*/\n\t\t\t\tif (mov->moov) {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->tfhd && mov->moov->mvex && mov->moov->mvex->TrackExList) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = gf_isom_get_track_from_id(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\tu32 j=0;\n\t\t\t\t\t\t\twhile ((traf->trex = (GF_TrackExtendsBox*)gf_list_enum(mov->moov->mvex->TrackExList, &j))) {\n\t\t\t\t\t\t\t\tif (traf->trex->trackID == traf->tfhd->trackID) {\n\t\t\t\t\t\t\t\t\tif (!traf->trex->track) traf->trex->track = trak;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttraf->trex = NULL;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//we should only parse senc/psec when no saiz/saio is present, otherwise we fetch the info directly\n\t\t\t\t\t\tif (traf->trex && traf->tfhd && traf->trex->track && traf->sample_encryption) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = GetTrackbyID(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\tif (trak) {\n\t\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = traf->tfhd->sample_desc_index ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;\n\t\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, traf, traf->sample_encryption);\n\t\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->sample_encryption) {\n\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, NULL, traf, traf->sample_encryption);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t} else if (mov->openMode==GF_ISOM_OPEN_KEEP_FRAGMENTS) {\n\t\t\t\tmov->NextMoofNumber = mov->moof->mfhd->sequence_number+1;\n\t\t\t\tmov->moof = NULL;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\t/*merge all info*/\n\t\t\t\te = MergeFragment((GF_MovieFragmentBox *)a, mov);\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\n\t\t\t//done with moov\n\t\t\tif (mov->root_sidx) {\n\t\t\t\tgf_isom_box_del((GF_Box *) mov->root_sidx);\n\t\t\t\tmov->root_sidx = NULL;\n\t\t\t}\n\t\t\tif (mov->root_ssix) {\n\t\t\t\tgf_isom_box_del(mov->seg_ssix);\n\t\t\t\tmov->root_ssix = NULL;\n\t\t\t}\n\t\t\tif (mov->seg_styp) {\n\t\t\t\tgf_isom_box_del(mov->seg_styp);\n\t\t\t\tmov->seg_styp = NULL;\n\t\t\t}\n\t\t\tmov->sidx_start_offset = 0;\n\t\t\tmov->sidx_end_offset = 0;\n\t\t\tmov->styp_start_offset = 0;\n\t\t\tbreak;\n#endif\n\t\tcase GF_ISOM_BOX_TYPE_UNKNOWN:\n\t\t{\n\t\t\tGF_UnknownBox *box = (GF_UnknownBox*)a;\n\t\t\tif (box->original_4cc == GF_ISOM_BOX_TYPE_JP) {\n\t\t\t\tu8 *c = (u8 *) box->data;\n\t\t\t\tif ((box->dataSize==4) && (GF_4CC(c[0],c[1],c[2],c[3])==(u32)0x0D0A870A))\n\t\t\t\t\tmov->is_jp2 = 1;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PRFT:\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (!(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\t//keep the last one read\n\t\t\t\tif (mov->last_producer_ref_time)\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\telse\n\t\t\t\t\tmov->last_producer_ref_time = (GF_ProducerReferenceTimeBox *)a;\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\t\t//fallthrough\n\t\tcase GF_ISOM_BOX_TYPE_EMSG:\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tif (!mov->emsgs) mov->emsgs = gf_list_new();\n\t\t\t\tgf_list_add(mov->emsgs, a);\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\t\tcase GF_ISOM_BOX_TYPE_MFRA:\n\t\tcase GF_ISOM_BOX_TYPE_MFRO:\n\t\t\t//only keep for dump mode, otherwise we ignore these boxes and we don't want to carry them over in non-fragmented file\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\ttotSize += a->size;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tbreak;\n\t\t\t}\n\t\tdefault:\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\t\t}\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*remember where we left, in case we append an entire number of movie fragments*/\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n#endif\n\t}\n\n\t/*we need at least moov or meta*/\n\tif (!mov->moov && !mov->meta\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t        && !mov->moof && !mov->is_index_segment\n#endif\n\t   ) {\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\t/*we MUST have movie header*/\n\tif (!gf_opts_get_bool(\"core\", \"no-check\")) {\n\t\tif (mov->moov && !mov->moov->mvhd) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MVHD in MOOV!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\t\t/*we MUST have meta handler*/\n\t\tif (mov->meta && !mov->meta->handler) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing handler in META!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\t}\n\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\n\tif (mov->moov) {\n\t\t/*set the default interleaving time*/\n\t\tmov->interleavingTime = mov->moov->mvhd->timeScale;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*in edit mode with successfully loaded fragments, delete all fragment signaling since\n\t\tfile is no longer fragmented*/\n\t\tif ((mov->openMode > GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS) && mov->moov->mvex) {\n\t\t\tgf_isom_box_del_parent(&mov->moov->child_boxes, (GF_Box *)mov->moov->mvex);\n\t\t\tmov->moov->mvex = NULL;\n\t\t}\n#endif\n\n\t}\n\n\t//create a default mdat if none was found\n\tif (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\tif (e) return e;\n\t}\n#endif /*GPAC_DISABLE_ISOM_WRITE*/\n\n\treturn GF_OK;\n}", "func_hash": 68912157747726016692935177449045975431, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2022-29340", "cve_desc": "GPAC 2.1-DEV-rev87-g053aae8-master. has a Null Pointer Dereference vulnerability in gf_isom_parse_movie_boxes_internal due to improper return value handling of GF_SKIP_BOX, which causes a Denial of Service. This vulnerability was fixed in commit 37592ad.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29340"}
{"idx": 232329, "project": "gpac", "commit_id": "37592ad86c6ca934d34740012213e467acc4a3b0", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/37592ad86c6ca934d34740012213e467acc4a3b0", "commit_message": "fixed #2163", "target": 0, "func": "static GF_Err gf_isom_parse_movie_boxes_internal(GF_ISOFile *mov, u32 *boxType, u64 *bytesMissing, Bool progressive_mode)\n{\n\tGF_Box *a;\n\tu64 totSize, mdat_end=0;\n\tGF_Err e = GF_OK;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\tif (mov->single_moof_mode && mov->single_moof_state == 2) {\n\t\treturn e;\n\t}\n\n\t/*restart from where we stopped last*/\n\ttotSize = mov->current_top_box_start;\n\tif (mov->bytes_removed) {\n\t\tassert(totSize >= mov->bytes_removed);\n\t\ttotSize -= mov->bytes_removed;\n\t}\n\tgf_bs_seek(mov->movieFileMap->bs, totSize);\n#endif\n\n\n\t/*while we have some data, parse our boxes*/\n\twhile (gf_bs_available(mov->movieFileMap->bs)) {\n\t\t*bytesMissing = 0;\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Parsing a top-level box at position %d\\n\", mov->current_top_box_start));\n#endif\n\n\t\te = gf_isom_parse_root_box(&a, mov->movieFileMap->bs, boxType, bytesMissing, progressive_mode);\n\n\t\tif (e >= 0) {\n\t\t\t//safety check, should never happen\n\t\t\tif (!a) return GF_ISOM_INVALID_FILE;\n\t\t} else if (e == GF_ISOM_INCOMPLETE_FILE) {\n\t\t\t/*our mdat is uncomplete, only valid for READ ONLY files...*/\n\t\t\tif (mov->openMode != GF_ISOM_OPEN_READ) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete MDAT while file is not read-only\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tif ((mov->openMode == GF_ISOM_OPEN_READ) && !progressive_mode) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete file while reading for dump - aborting parsing\\n\"));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn e;\n\t\t} else {\n\t\t\treturn e;\n\t\t}\n\n\t\tswitch (a->type) {\n\t\t/*MOOV box*/\n\t\tcase GF_ISOM_BOX_TYPE_MOOV:\n\t\t\tif (mov->moov) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate MOOV detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->moov = (GF_MovieBox *)a;\n\t\t\tmov->original_moov_offset = mov->current_top_box_start;\n\t\t\t/*set our pointer to the movie*/\n\t\t\tmov->moov->mov = mov;\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (mov->moov->mvex) mov->moov->mvex->mov = mov;\n\n#ifdef GF_ENABLE_CTRN\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tgf_isom_setup_traf_inheritance(mov);\n\t\t\t}\n#endif\n\n#endif\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\n\t\t\ttotSize += a->size;\n\n            if (!mov->moov->mvhd) {\n                GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MovieHeaderBox\\n\"));\n                return GF_ISOM_INVALID_FILE;\n            }\n\n            if (mov->meta) {\n\t\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\t}\n\n\t\t\t//dump senc info in dump mode\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\n\t\t\t\t\tif (trak->sample_encryption) {\n\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, NULL, trak->sample_encryption);\n\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\t\t\t\t\tif (trak->Media->information->sampleTable->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(trak->Media->information->sampleTable->child_boxes, trak->Media->information->sampleTable->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n            if (mdat_end && mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n                gf_isom_push_mdat_end(mov, mdat_end);\n                mdat_end=0;\n            }\n\t\t\tbreak;\n\n\t\t/*META box*/\n\t\tcase GF_ISOM_BOX_TYPE_META:\n\t\t\tif (mov->meta) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate META detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->meta = (GF_MetaBox *)a;\n\t\t\tmov->original_meta_offset = mov->current_top_box_start;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) {\n\t\t\t\treturn e;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\tbreak;\n\n\t\t/*we only keep the MDAT in READ for dump purposes*/\n\t\tcase GF_ISOM_BOX_TYPE_MDAT:\n\t\t\tif (!mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (mov->emsgs) {\n\t\t\t\tgf_isom_box_array_del(mov->emsgs);\n\t\t\t\tmov->emsgs = NULL;\n\t\t\t}\n#endif\n\n\t\t\tif (mov->openMode == GF_ISOM_OPEN_READ) {\n\t\t\t\tif (!mov->mdat) {\n\t\t\t\t\tmov->mdat = (GF_MediaDataBox *) a;\n\t\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\treturn e;\n\t\t\t\t\t}\n\t\t\t\t}\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\t\telse if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) gf_list_add(mov->TopBoxes, a);\n#endif\n\t\t\t\telse gf_isom_box_del(a); //in other modes we don't care\n\n\n\t\t\t\tif (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n                    mdat_end = gf_bs_get_position(mov->movieFileMap->bs);\n                    if (mov->moov) {\n                        gf_isom_push_mdat_end(mov, mdat_end);\n                        mdat_end=0;\n                    }\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*if we don't have any MDAT yet, create one (edit-write mode)\n\t\t\tWe only work with one mdat, but we're puting it at the place\n\t\t\tof the first mdat found when opening a file for editing*/\n\t\t\telse if (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\t\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\tif (e) {\n\t\t\t\t\treturn e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GF_ISOM_BOX_TYPE_FTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->brand) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'ftyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->brand = (GF_FileTypeBox *)a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_OTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->otyp) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'otyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tmov->otyp = (GF_Box *)a;\n\t\t\t\ttotSize += a->size;\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else {\n\t\t\t\tGF_FileTypeBox *brand = (GF_FileTypeBox *) gf_isom_box_find_child(a->child_boxes, GF_ISOM_BOX_TYPE_FTYP);\n\t\t\t\tif (brand) {\n\t\t\t\t\ts32 pos;\n\t\t\t\t\tgf_list_del_item(a->child_boxes, brand);\n\t\t\t\t\tpos = gf_list_del_item(mov->TopBoxes, mov->brand);\n\t\t\t\t\tgf_isom_box_del((GF_Box *) mov->brand);\n\t\t\t\t\tmov->brand = brand;\n\t\t\t\t\tif (pos<0) pos=0;\n\t\t\t\t\tgf_list_insert(mov->TopBoxes, brand, pos);\n\t\t\t\t}\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PDIN:\n\t\t\t/*ONE AND ONLY ONE PDIN*/\n\t\t\tif (mov->pdin) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'pdin'' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->pdin = (GF_ProgressiveDownloadBox *) a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tcase GF_ISOM_BOX_TYPE_STYP:\n\t\t{\n\t\t\tu32 brand = ((GF_FileTypeBox *)a)->majorBrand;\n\t\t\tswitch (brand) {\n\t\t\tcase GF_ISOM_BRAND_SISX:\n\t\t\tcase GF_ISOM_BRAND_RISX:\n\t\t\tcase GF_ISOM_BRAND_SSSS:\n\t\t\t\tmov->is_index_segment = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t/*fall-through*/\n\n\t\tcase GF_ISOM_BOX_TYPE_SIDX:\n\t\tcase GF_ISOM_BOX_TYPE_SSIX:\n\t\t\tif (mov->moov && !mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else if (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)  && (mov->openMode!=GF_ISOM_OPEN_KEEP_FRAGMENTS)\n\t\t\t) {\n\t\t\t\tif (a->type==GF_ISOM_BOX_TYPE_SIDX) {\n\t\t\t\t\tif (mov->root_sidx) gf_isom_box_del( (GF_Box *) mov->root_sidx);\n\t\t\t\t\tmov->root_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\t\tmov->sidx_start_offset = mov->current_top_box_start;\n\t\t\t\t\tmov->sidx_end_offset = gf_bs_get_position(mov->movieFileMap->bs);\n\n\t\t\t\t}\n\t\t\t\telse if (a->type==GF_ISOM_BOX_TYPE_STYP) {\n\t\t\t\t\tmov->styp_start_offset = mov->current_top_box_start;\n\n\t\t\t\t\tif (mov->seg_styp) gf_isom_box_del(mov->seg_styp);\n\t\t\t\t\tmov->seg_styp = a;\n\t\t\t\t} else if (a->type==GF_ISOM_BOX_TYPE_SSIX) {\n\t\t\t\t\tif (mov->seg_ssix) gf_isom_box_del(mov->seg_ssix);\n\t\t\t\t\tmov->seg_ssix = a;\n\t\t\t\t} else {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t}\n\t\t\t\tgf_isom_push_mdat_end(mov, mov->current_top_box_start);\n\t\t\t} else if (!mov->NextMoofNumber && (a->type==GF_ISOM_BOX_TYPE_SIDX)) {\n\t\t\t\tif (mov->main_sidx) gf_isom_box_del( (GF_Box *) mov->main_sidx);\n\t\t\t\tmov->main_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\tmov->main_sidx_end_pos = mov->current_top_box_start + a->size;\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_MOOF:\n\t\t\t//no support for inplace rewrite for fragmented files\n\t\t\tgf_isom_disable_inplace_rewrite(mov);\n\t\t\tif (!mov->moov) {\n\t\t\t\tGF_LOG(mov->moof ? GF_LOG_DEBUG : GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Movie fragment but no moov (yet) - possibly broken parsing!\\n\"));\n\t\t\t}\n\t\t\tif (mov->single_moof_mode) {\n\t\t\t\tmov->single_moof_state++;\n\t\t\t\tif (mov->single_moof_state > 1) {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t}\n\t\t\t}\n\t\t\t((GF_MovieFragmentBox *)a)->mov = mov;\n\n\t\t\ttotSize += a->size;\n\t\t\tmov->moof = (GF_MovieFragmentBox *) a;\n\n\t\t\t/*some smooth streaming streams contain a SDTP under the TRAF: this is incorrect, convert it*/\n\t\t\tFixTrackID(mov);\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tFixSDTPInTRAF(mov->moof);\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\tGF_TrackFragmentBox *traf = (GF_TrackFragmentBox *)gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\tif (traf->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(traf->child_boxes, traf->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*read & debug: store at root level*/\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tgf_list_add(mov->TopBoxes, a);\n\t\t\t\t/*also update pointers to trex for debug*/\n\t\t\t\tif (mov->moov) {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->tfhd && mov->moov->mvex && mov->moov->mvex->TrackExList) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = gf_isom_get_track_from_id(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\tu32 j=0;\n\t\t\t\t\t\t\twhile ((traf->trex = (GF_TrackExtendsBox*)gf_list_enum(mov->moov->mvex->TrackExList, &j))) {\n\t\t\t\t\t\t\t\tif (traf->trex->trackID == traf->tfhd->trackID) {\n\t\t\t\t\t\t\t\t\tif (!traf->trex->track) traf->trex->track = trak;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttraf->trex = NULL;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//we should only parse senc/psec when no saiz/saio is present, otherwise we fetch the info directly\n\t\t\t\t\t\tif (traf->trex && traf->tfhd && traf->trex->track && traf->sample_encryption) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = GetTrackbyID(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\tif (trak) {\n\t\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = traf->tfhd->sample_desc_index ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;\n\t\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, traf, traf->sample_encryption);\n\t\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->sample_encryption) {\n\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, NULL, traf, traf->sample_encryption);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t} else if (mov->openMode==GF_ISOM_OPEN_KEEP_FRAGMENTS) {\n\t\t\t\tmov->NextMoofNumber = mov->moof->mfhd->sequence_number+1;\n\t\t\t\tmov->moof = NULL;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\t/*merge all info*/\n\t\t\t\te = MergeFragment((GF_MovieFragmentBox *)a, mov);\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\n\t\t\t//done with moov\n\t\t\tif (mov->root_sidx) {\n\t\t\t\tgf_isom_box_del((GF_Box *) mov->root_sidx);\n\t\t\t\tmov->root_sidx = NULL;\n\t\t\t}\n\t\t\tif (mov->root_ssix) {\n\t\t\t\tgf_isom_box_del(mov->seg_ssix);\n\t\t\t\tmov->root_ssix = NULL;\n\t\t\t}\n\t\t\tif (mov->seg_styp) {\n\t\t\t\tgf_isom_box_del(mov->seg_styp);\n\t\t\t\tmov->seg_styp = NULL;\n\t\t\t}\n\t\t\tmov->sidx_start_offset = 0;\n\t\t\tmov->sidx_end_offset = 0;\n\t\t\tmov->styp_start_offset = 0;\n\t\t\tbreak;\n#endif\n\t\tcase GF_ISOM_BOX_TYPE_UNKNOWN:\n\t\t{\n\t\t\tGF_UnknownBox *box = (GF_UnknownBox*)a;\n\t\t\tif (box->original_4cc == GF_ISOM_BOX_TYPE_JP) {\n\t\t\t\tu8 *c = (u8 *) box->data;\n\t\t\t\tif ((box->dataSize==4) && (GF_4CC(c[0],c[1],c[2],c[3])==(u32)0x0D0A870A))\n\t\t\t\t\tmov->is_jp2 = 1;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PRFT:\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (!(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\t//keep the last one read\n\t\t\t\tif (mov->last_producer_ref_time)\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\telse\n\t\t\t\t\tmov->last_producer_ref_time = (GF_ProducerReferenceTimeBox *)a;\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\t\t//fallthrough\n\t\tcase GF_ISOM_BOX_TYPE_EMSG:\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tif (!mov->emsgs) mov->emsgs = gf_list_new();\n\t\t\t\tgf_list_add(mov->emsgs, a);\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\t\tcase GF_ISOM_BOX_TYPE_MFRA:\n\t\tcase GF_ISOM_BOX_TYPE_MFRO:\n\t\t\t//only keep for dump mode, otherwise we ignore these boxes and we don't want to carry them over in non-fragmented file\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\ttotSize += a->size;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tbreak;\n\t\t\t}\n\t\tdefault:\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\t\t}\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*remember where we left, in case we append an entire number of movie fragments*/\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n#endif\n\t}\n\n\t/*we need at least moov or meta*/\n\tif (!mov->moov && !mov->meta\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t        && !mov->moof && !mov->is_index_segment\n#endif\n\t   ) {\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\t/*we MUST have movie header*/\n\tif (!gf_opts_get_bool(\"core\", \"no-check\")) {\n\t\tif (mov->moov && !mov->moov->mvhd) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MVHD in MOOV!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\t\t/*we MUST have meta handler*/\n\t\tif (mov->meta && !mov->meta->handler) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing handler in META!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\t}\n\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\n\tif (mov->moov) {\n\t\t/*set the default interleaving time*/\n\t\tmov->interleavingTime = mov->moov->mvhd->timeScale;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*in edit mode with successfully loaded fragments, delete all fragment signaling since\n\t\tfile is no longer fragmented*/\n\t\tif ((mov->openMode > GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS) && mov->moov->mvex) {\n\t\t\tgf_isom_box_del_parent(&mov->moov->child_boxes, (GF_Box *)mov->moov->mvex);\n\t\t\tmov->moov->mvex = NULL;\n\t\t}\n#endif\n\n\t}\n\n\t//create a default mdat if none was found\n\tif (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\tif (e) return e;\n\t}\n#endif /*GPAC_DISABLE_ISOM_WRITE*/\n\n\treturn GF_OK;\n}", "func_hash": 33398552270127430256413281511092874838, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2022-29340", "cve_desc": "GPAC 2.1-DEV-rev87-g053aae8-master. has a Null Pointer Dereference vulnerability in gf_isom_parse_movie_boxes_internal due to improper return value handling of GF_SKIP_BOX, which causes a Denial of Service. This vulnerability was fixed in commit 37592ad.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29340"}
{"idx": 195752, "project": "tensorflow", "commit_id": "02cc160e29d20631de3859c6653184e3f876b9d7", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/02cc160e29d20631de3859c6653184e3f876b9d7", "commit_message": "Prevent nullptr deref in SparseTensorSliceDataset\n\nThe arguments must determine a valid sparse tensor. This means that when indices are empty then the values must be empty too (and the reverse).\n\nAlso added test, by modifying existing test with empty sparse tensor to now run with an invalid sparse tensor input.\n\nPiperOrigin-RevId: 388562757\nChange-Id: Id8b54cd7c2316025b4f9a77292c8fb5344d17609", "target": 1, "func": "  void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override {\n    // Create a new SparseTensorSliceDatasetOp::Dataset, insert it in\n    // the step container, and return it as the output.\n    const Tensor* indices;\n    OP_REQUIRES_OK(ctx, ctx->input(\"indices\", &indices));\n    const Tensor* values;\n    OP_REQUIRES_OK(ctx, ctx->input(\"values\", &values));\n    const Tensor* dense_shape;\n    OP_REQUIRES_OK(ctx, ctx->input(\"dense_shape\", &dense_shape));\n\n    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices->shape()),\n                errors::InvalidArgument(\n                    \"Input indices should be a matrix but received shape \",\n                    indices->shape().DebugString()));\n    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values->shape()),\n                errors::InvalidArgument(\n                    \"Input values should be a vector but received shape \",\n                    indices->shape().DebugString()));\n    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(dense_shape->shape()),\n                errors::InvalidArgument(\n                    \"Input shape should be a vector but received shape \",\n                    dense_shape->shape().DebugString()));\n\n    // We currently ensure that `sparse_tensor` is ordered in the\n    // batch dimension.\n    // TODO(mrry): Investigate ways to avoid this unconditional check\n    // if we can be sure that the sparse tensor was produced in an\n    // appropriate order (e.g. by `tf.parse_example()` or a Dataset\n    // that batches elements into rows of a SparseTensor).\n    int64_t previous_batch_index = -1;\n    for (int64_t i = 0; i < indices->dim_size(0); ++i) {\n      int64_t next_batch_index = indices->matrix()(i, 0);\n      OP_REQUIRES(\n          ctx, next_batch_index >= previous_batch_index,\n          errors::Unimplemented(\"The SparseTensor must be ordered in the batch \"\n                                \"dimension; handling arbitrarily ordered input \"\n                                \"is not currently supported.\"));\n      previous_batch_index = next_batch_index;\n    }\n    gtl::InlinedVector std_order(dense_shape->NumElements(), 0);\n    sparse::SparseTensor tensor;\n    OP_REQUIRES_OK(\n        ctx, sparse::SparseTensor::Create(\n                 *indices, *values, TensorShape(dense_shape->vec()),\n                 std_order, &tensor));\n    *output = new Dataset(ctx, std::move(tensor));\n  }", "func_hash": 111818826187244494245403789873500831419, "file_name": "sparse_tensor_slice_dataset_op.cc", "file_hash": 152047584060469134260687844063366554733, "cwe": ["CWE-476"], "cve": "CVE-2021-37647", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. When a user does not supply arguments that determine a valid sparse tensor, `tf.raw_ops.SparseTensorSliceDataset` implementation can be made to dereference a null pointer. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/data/sparse_tensor_slice_dataset_op.cc#L240-L251) has some argument validation but fails to consider the case when either `indices` or `values` are provided for an empty sparse tensor when the other is not. If `indices` is empty, then [code that performs validation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/data/sparse_tensor_slice_dataset_op.cc#L260-L261) (i.e., checking that the indices are monotonically increasing) results in a null pointer dereference. If `indices` as provided by the user is empty, then `indices` in the C++ code above is backed by an empty `std::vector`, hence calling `indices->dim_size(0)` results in null pointer dereferencing (same as calling `std::vector::at()` on an empty vector). We have patched the issue in GitHub commit 02cc160e29d20631de3859c6653184e3f876b9d7. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37647"}
{"idx": 232405, "project": "tensorflow", "commit_id": "02cc160e29d20631de3859c6653184e3f876b9d7", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/02cc160e29d20631de3859c6653184e3f876b9d7", "commit_message": "Prevent nullptr deref in SparseTensorSliceDataset\n\nThe arguments must determine a valid sparse tensor. This means that when indices are empty then the values must be empty too (and the reverse).\n\nAlso added test, by modifying existing test with empty sparse tensor to now run with an invalid sparse tensor input.\n\nPiperOrigin-RevId: 388562757\nChange-Id: Id8b54cd7c2316025b4f9a77292c8fb5344d17609", "target": 0, "func": "  void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override {\n    // Create a new SparseTensorSliceDatasetOp::Dataset, insert it in\n    // the step container, and return it as the output.\n    const Tensor* indices;\n    OP_REQUIRES_OK(ctx, ctx->input(\"indices\", &indices));\n    const Tensor* values;\n    OP_REQUIRES_OK(ctx, ctx->input(\"values\", &values));\n    const Tensor* dense_shape;\n    OP_REQUIRES_OK(ctx, ctx->input(\"dense_shape\", &dense_shape));\n\n    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices->shape()),\n                errors::InvalidArgument(\n                    \"Input indices should be a matrix but received shape \",\n                    indices->shape().DebugString()));\n\n    const auto num_indices = indices->NumElements();\n    const auto num_values = values->NumElements();\n    if (num_indices == 0 || num_values == 0) {\n      OP_REQUIRES(ctx, num_indices == num_values,\n                  errors::InvalidArgument(\n                      \"If indices or values are empty, the other one must also \"\n                      \"be. Got indices of shape \",\n                      indices->shape().DebugString(), \" and values of shape \",\n                      values->shape().DebugString()));\n    }\n    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values->shape()),\n                errors::InvalidArgument(\n                    \"Input values should be a vector but received shape \",\n                    indices->shape().DebugString()));\n    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(dense_shape->shape()),\n                errors::InvalidArgument(\n                    \"Input shape should be a vector but received shape \",\n                    dense_shape->shape().DebugString()));\n\n    // We currently ensure that `sparse_tensor` is ordered in the\n    // batch dimension.\n    // TODO(mrry): Investigate ways to avoid this unconditional check\n    // if we can be sure that the sparse tensor was produced in an\n    // appropriate order (e.g. by `tf.parse_example()` or a Dataset\n    // that batches elements into rows of a SparseTensor).\n    int64_t previous_batch_index = -1;\n    for (int64_t i = 0; i < indices->dim_size(0); ++i) {\n      int64_t next_batch_index = indices->matrix()(i, 0);\n      OP_REQUIRES(\n          ctx, next_batch_index >= previous_batch_index,\n          errors::Unimplemented(\"The SparseTensor must be ordered in the batch \"\n                                \"dimension; handling arbitrarily ordered input \"\n                                \"is not currently supported.\"));\n      previous_batch_index = next_batch_index;\n    }\n    gtl::InlinedVector std_order(dense_shape->NumElements(), 0);\n    sparse::SparseTensor tensor;\n    OP_REQUIRES_OK(\n        ctx, sparse::SparseTensor::Create(\n                 *indices, *values, TensorShape(dense_shape->vec()),\n                 std_order, &tensor));\n    *output = new Dataset(ctx, std::move(tensor));\n  }", "func_hash": 126239557450594194918340916106898261954, "file_name": "sparse_tensor_slice_dataset_op.cc", "file_hash": 188414793374606504588915566744198162485, "cwe": ["CWE-476"], "cve": "CVE-2021-37647", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. When a user does not supply arguments that determine a valid sparse tensor, `tf.raw_ops.SparseTensorSliceDataset` implementation can be made to dereference a null pointer. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/data/sparse_tensor_slice_dataset_op.cc#L240-L251) has some argument validation but fails to consider the case when either `indices` or `values` are provided for an empty sparse tensor when the other is not. If `indices` is empty, then [code that performs validation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/data/sparse_tensor_slice_dataset_op.cc#L260-L261) (i.e., checking that the indices are monotonically increasing) results in a null pointer dereference. If `indices` as provided by the user is empty, then `indices` in the C++ code above is backed by an empty `std::vector`, hence calling `indices->dim_size(0)` results in null pointer dereferencing (same as calling `std::vector::at()` on an empty vector). We have patched the issue in GitHub commit 02cc160e29d20631de3859c6653184e3f876b9d7. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37647"}
{"idx": 195768, "project": "tensorflow", "commit_id": "8a84f7a2b5a2b27ecf88d25bad9ac777cd2f7992", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/8a84f7a2b5a2b27ecf88d25bad9ac777cd2f7992", "commit_message": "Ensure num_streams >= 0 in tf.raw_ops.BoostedTreesCreateQuantileStreamResource\n\nPiperOrigin-RevId: 387452765\nChange-Id: I9990c760e177fabca6a3b9b4612ceeaeeba51495", "target": 1, "func": "  void Compute(OpKernelContext* context) override {\n    // Only create one, if one does not exist already. Report status for all\n    // other exceptions. If one already exists, it unrefs the new one.\n    // An epsilon value of zero could cause performance issues and is therefore,\n    // disallowed.\n    const Tensor* epsilon_t;\n    OP_REQUIRES_OK(context, context->input(kEpsilonName, &epsilon_t));\n    float epsilon = epsilon_t->scalar()();\n    OP_REQUIRES(\n        context, epsilon > 0,\n        errors::InvalidArgument(\"An epsilon value of zero is not allowed.\"));\n\n    const Tensor* num_streams_t;\n    OP_REQUIRES_OK(context, context->input(kNumStreamsName, &num_streams_t));\n    int64_t num_streams = num_streams_t->scalar()();\n\n    auto result =\n        new QuantileStreamResource(epsilon, max_elements_, num_streams);\n    auto status = CreateResource(context, HandleFromInput(context, 0), result);\n    if (!status.ok() && status.code() != tensorflow::error::ALREADY_EXISTS) {\n      OP_REQUIRES(context, false, status);\n    }\n  }", "func_hash": 313445736659793184747687838118492710807, "file_name": "quantile_ops.cc", "file_hash": 107616464713850423069668018637690909159, "cwe": ["CWE-703"], "cve": "CVE-2021-37661", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can cause a denial of service in `boosted_trees_create_quantile_stream_resource` by using negative arguments. The [implementation](https://github.com/tensorflow/tensorflow/blob/84d053187cb80d975ef2b9684d4b61981bca0c41/tensorflow/core/kernels/boosted_trees/quantile_ops.cc#L96) does not validate that `num_streams` only contains non-negative numbers. In turn, [this results in using this value to allocate memory](https://github.com/tensorflow/tensorflow/blob/84d053187cb80d975ef2b9684d4b61981bca0c41/tensorflow/core/kernels/boosted_trees/quantiles/quantile_stream_resource.h#L31-L40). However, `reserve` receives an unsigned integer so there is an implicit conversion from a negative value to a large positive unsigned. This results in a crash from the standard library. We have patched the issue in GitHub commit 8a84f7a2b5a2b27ecf88d25bad9ac777cd2f7992. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37661"}
{"idx": 232839, "project": "tensorflow", "commit_id": "8a84f7a2b5a2b27ecf88d25bad9ac777cd2f7992", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/8a84f7a2b5a2b27ecf88d25bad9ac777cd2f7992", "commit_message": "Ensure num_streams >= 0 in tf.raw_ops.BoostedTreesCreateQuantileStreamResource\n\nPiperOrigin-RevId: 387452765\nChange-Id: I9990c760e177fabca6a3b9b4612ceeaeeba51495", "target": 0, "func": "  void Compute(OpKernelContext* context) override {\n    // Only create one, if one does not exist already. Report status for all\n    // other exceptions. If one already exists, it unrefs the new one.\n    // An epsilon value of zero could cause performance issues and is therefore,\n    // disallowed.\n    const Tensor* epsilon_t;\n    OP_REQUIRES_OK(context, context->input(kEpsilonName, &epsilon_t));\n    float epsilon = epsilon_t->scalar()();\n    OP_REQUIRES(\n        context, epsilon > 0,\n        errors::InvalidArgument(\"An epsilon value of zero is not allowed.\"));\n\n    const Tensor* num_streams_t;\n    OP_REQUIRES_OK(context, context->input(kNumStreamsName, &num_streams_t));\n    int64_t num_streams = num_streams_t->scalar()();\n    OP_REQUIRES(context, num_streams >= 0,\n                errors::InvalidArgument(\n                    \"Num_streams input cannot be a negative integer\"));\n\n    auto result =\n        new QuantileStreamResource(epsilon, max_elements_, num_streams);\n    auto status = CreateResource(context, HandleFromInput(context, 0), result);\n    if (!status.ok() && status.code() != tensorflow::error::ALREADY_EXISTS) {\n      OP_REQUIRES(context, false, status);\n    }\n  }", "func_hash": 211706993180687307698189182900649131515, "file_name": "quantile_ops.cc", "file_hash": 2460463357913626818723111707864043881, "cwe": ["CWE-703"], "cve": "CVE-2021-37661", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can cause a denial of service in `boosted_trees_create_quantile_stream_resource` by using negative arguments. The [implementation](https://github.com/tensorflow/tensorflow/blob/84d053187cb80d975ef2b9684d4b61981bca0c41/tensorflow/core/kernels/boosted_trees/quantile_ops.cc#L96) does not validate that `num_streams` only contains non-negative numbers. In turn, [this results in using this value to allocate memory](https://github.com/tensorflow/tensorflow/blob/84d053187cb80d975ef2b9684d4b61981bca0c41/tensorflow/core/kernels/boosted_trees/quantiles/quantile_stream_resource.h#L31-L40). However, `reserve` receives an unsigned integer so there is an implicit conversion from a negative value to a large positive unsigned. This results in a crash from the standard library. We have patched the issue in GitHub commit 8a84f7a2b5a2b27ecf88d25bad9ac777cd2f7992. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37661"}
{"idx": 195800, "project": "deark", "commit_id": "62acb7753b0e3c0d3ab3c15057b0a65222313334", "project_url": "https://github.com/jsummers/deark", "commit_url": "https://github.com/jsummers/deark/commit/62acb7753b0e3c0d3ab3c15057b0a65222313334", "commit_message": "pict,macrsrc: Fixed a bug that could cause division by 0\n\nFound by F. \u00c7elik.", "target": 1, "func": "void fmtutil_macbitmap_read_pixmap_only_fields(deark *c, dbuf *f, struct fmtutil_macbitmap_info *bi,\n\ti64 pos)\n{\n\ti64 pixmap_version;\n\ti64 pack_size;\n\ti64 plane_bytes;\n\ti64 n;\n\n\tde_dbg(c, \"additional PixMap header fields, at %d\", (int)pos);\n\tde_dbg_indent(c, 1);\n\n\tpixmap_version = dbuf_getu16be(f, pos+0);\n\tde_dbg(c, \"pixmap version: %d\", (int)pixmap_version);\n\n\tbi->packing_type = dbuf_getu16be(f, pos+2);\n\tde_dbg(c, \"packing type: %d\", (int)bi->packing_type);\n\n\tpack_size = dbuf_getu32be(f, pos+4);\n\tde_dbg(c, \"pixel data length: %d\", (int)pack_size);\n\n\tbi->hdpi = pict_read_fixed(f, pos+8);\n\tbi->vdpi = pict_read_fixed(f, pos+12);\n\tde_dbg(c, \"dpi: %.2f\"DE_CHAR_TIMES\"%.2f\", bi->hdpi, bi->vdpi);\n\n\tbi->pixeltype = dbuf_getu16be(f, pos+16);\n\tbi->pixelsize = dbuf_getu16be(f, pos+18);\n\tbi->cmpcount = dbuf_getu16be(f, pos+20);\n\tbi->cmpsize = dbuf_getu16be(f, pos+22);\n\tde_dbg(c, \"pixel type=%d, bits/pixel=%d, components/pixel=%d, bits/comp=%d\",\n\t\t(int)bi->pixeltype, (int)bi->pixelsize, (int)bi->cmpcount, (int)bi->cmpsize);\n\n\tbi->pdwidth = (bi->rowbytes*8)/bi->pixelsize;\n\tif(bi->pdwidth < bi->npwidth) {\n\t\tbi->pdwidth = bi->npwidth;\n\t}\n\n\tplane_bytes = dbuf_getu32be(f, pos+24);\n\tde_dbg(c, \"plane bytes: %d\", (int)plane_bytes);\n\n\tbi->pmTable = (u32)dbuf_getu32be(f, pos+28);\n\tde_dbg(c, \"pmTable: 0x%08x\", (unsigned int)bi->pmTable);\n\n\tn = dbuf_getu32be(f, pos+32);\n\tde_dbg(c, \"pmReserved: 0x%08x\", (unsigned int)n);\n\n\tde_dbg_indent(c, -1);\n}", "func_hash": 203544519943268578056087775697493086183, "file_name": "fmtutil.c", "file_hash": 198892381443353894699781903058114971913, "cwe": ["CWE-369"], "cve": "CVE-2021-28856", "cve_desc": "In Deark before v1.5.8, a specially crafted input file can cause a division by zero in (src/fmtutil.c) because of the value of pixelsize.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28856"}
{"idx": 233862, "project": "deark", "commit_id": "62acb7753b0e3c0d3ab3c15057b0a65222313334", "project_url": "https://github.com/jsummers/deark", "commit_url": "https://github.com/jsummers/deark/commit/62acb7753b0e3c0d3ab3c15057b0a65222313334", "commit_message": "pict,macrsrc: Fixed a bug that could cause division by 0\n\nFound by F. \u00c7elik.", "target": 0, "func": "void fmtutil_macbitmap_read_pixmap_only_fields(deark *c, dbuf *f, struct fmtutil_macbitmap_info *bi,\n\ti64 pos)\n{\n\ti64 pixmap_version;\n\ti64 pack_size;\n\ti64 plane_bytes;\n\ti64 n;\n\n\tde_dbg(c, \"additional PixMap header fields, at %d\", (int)pos);\n\tde_dbg_indent(c, 1);\n\n\tpixmap_version = dbuf_getu16be(f, pos+0);\n\tde_dbg(c, \"pixmap version: %d\", (int)pixmap_version);\n\n\tbi->packing_type = dbuf_getu16be(f, pos+2);\n\tde_dbg(c, \"packing type: %d\", (int)bi->packing_type);\n\n\tpack_size = dbuf_getu32be(f, pos+4);\n\tde_dbg(c, \"pixel data length: %d\", (int)pack_size);\n\n\tbi->hdpi = pict_read_fixed(f, pos+8);\n\tbi->vdpi = pict_read_fixed(f, pos+12);\n\tde_dbg(c, \"dpi: %.2f\"DE_CHAR_TIMES\"%.2f\", bi->hdpi, bi->vdpi);\n\n\tbi->pixeltype = dbuf_getu16be(f, pos+16);\n\tbi->pixelsize = dbuf_getu16be(f, pos+18);\n\tbi->cmpcount = dbuf_getu16be(f, pos+20);\n\tbi->cmpsize = dbuf_getu16be(f, pos+22);\n\tde_dbg(c, \"pixel type=%d, bits/pixel=%d, components/pixel=%d, bits/comp=%d\",\n\t\t(int)bi->pixeltype, (int)bi->pixelsize, (int)bi->cmpcount, (int)bi->cmpsize);\n\n\tif(bi->pixelsize>0) {\n\t\tbi->pdwidth = (bi->rowbytes*8)/bi->pixelsize;\n\t}\n\tif(bi->pdwidth < bi->npwidth) {\n\t\tbi->pdwidth = bi->npwidth;\n\t}\n\n\tplane_bytes = dbuf_getu32be(f, pos+24);\n\tde_dbg(c, \"plane bytes: %d\", (int)plane_bytes);\n\n\tbi->pmTable = (u32)dbuf_getu32be(f, pos+28);\n\tde_dbg(c, \"pmTable: 0x%08x\", (unsigned int)bi->pmTable);\n\n\tn = dbuf_getu32be(f, pos+32);\n\tde_dbg(c, \"pmReserved: 0x%08x\", (unsigned int)n);\n\n\tde_dbg_indent(c, -1);\n}", "func_hash": 165750695801886950946994956858448129756, "file_name": "fmtutil.c", "file_hash": 134744298134309373748233562166931104409, "cwe": ["CWE-369"], "cve": "CVE-2021-28856", "cve_desc": "In Deark before v1.5.8, a specially crafted input file can cause a division by zero in (src/fmtutil.c) because of the value of pixelsize.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28856"}
{"idx": 195801, "project": "php-src", "commit_id": "0c8a2a2cd1056b7dc403eacb5d2c0eec6ce47c6f", "project_url": "https://github.com/php/php-src", "commit_url": "https://github.com/php/php-src/commit/0c8a2a2cd1056b7dc403eacb5d2c0eec6ce47c6f", "commit_message": "Fix for bug #72790 and bug #72799\n\n(cherry picked from commit a14fdb9746262549bbbb96abb87338bacd147e1b)\n\nConflicts:\n\text/wddx/wddx.c", "target": 1, "func": " */\nstatic void php_wddx_pop_element(void *user_data, const XML_Char *name)\n{\n\tst_entry \t\t\t*ent1, *ent2;\n\twddx_stack \t\t\t*stack = (wddx_stack *)user_data;\n\tHashTable \t\t\t*target_hash;\n\tzend_class_entry \t*pce;\n\tzval\t\t\t\tobj;\n\n/* OBJECTS_FIXME */\n\tif (stack->top == 0) {\n\t\treturn;\n\t}\n\n\tif (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) ||\n\t\t!strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) ||\n\t  \t!strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) ||\n\t\t!strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) ||\n\t\t!strcmp((char *)name, EL_DATETIME)) {\n\t\twddx_stack_top(stack, (void**)&ent1);\n\n\t\tif (Z_TYPE(ent1->data) == IS_UNDEF) {\n\t\t\tif (stack->top > 1) {\n\t\t\t\tstack->top--;\n\t\t\t} else {\n\t\t\t\tstack->done = 1;\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!strcmp((char *)name, EL_BINARY)) {\n\t\t\tzend_string *new_str = php_base64_decode(\n\t\t\t\t(unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));\n\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\tZVAL_STR(&ent1->data, new_str);\n\t\t}\n\n\t\t/* Call __wakeup() method on the object. */\n\t\tif (Z_TYPE(ent1->data) == IS_OBJECT) {\n\t\t\tzval fname, retval;\n\n\t\t\tZVAL_STRING(&fname, \"__wakeup\");\n\n\t\t\tcall_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL);\n\n\t\t\tzval_ptr_dtor(&fname);\n\t\t\tzval_ptr_dtor(&retval);\n\t\t}\n\n\t\tif (stack->top > 1) {\n\t\t\tstack->top--;\n\t\t\twddx_stack_top(stack, (void**)&ent2);\n\n\t\t\t/* if non-existent field */\n\t\t\tif (ent2->type == ST_FIELD && Z_ISUNDEF(ent2->data)) {\n\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\tefree(ent1);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) {\n\t\t\t\ttarget_hash = HASH_OF(&ent2->data);\n\n\t\t\t\tif (ent1->varname) {\n\t\t\t\t\tif (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&\n\t\t\t\t\t\tZ_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) &&\n\t\t\t\t\t\tent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) {\n\t\t\t\t\t\tzend_bool incomplete_class = 0;\n\n\t\t\t\t\t\tzend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));\n\t\t\t\t\t\tzend_string_forget_hash_val(Z_STR(ent1->data));\n\t\t\t\t\t\tif ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) {\n\t\t\t\t\t\t\tincomplete_class = 1;\n\t\t\t\t\t\t\tpce = PHP_IC_ENTRY;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Initialize target object */\n\t\t\t\t\t\tobject_init_ex(&obj, pce);\n\n\t\t\t\t\t\t/* Merge current hashtable with object's default properties */\n\t\t\t\t\t\tzend_hash_merge(Z_OBJPROP(obj),\n\t\t\t\t\t\t\t\t\t\tZ_ARRVAL(ent2->data),\n\t\t\t\t\t\t\t\t\t\tzval_add_ref, 0);\n\n\t\t\t\t\t\tif (incomplete_class) {\n\t\t\t\t\t\t\tphp_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Clean up old array entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent2->data);\n\n\t\t\t\t\t\t/* Set stack entry to point to the newly created object */\n\t\t\t\t\t\tZVAL_COPY_VALUE(&ent2->data, &obj);\n\n\t\t\t\t\t\t/* Clean up class name var entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\t\t} else if (Z_TYPE(ent2->data) == IS_OBJECT) {\n\t\t\t\t\t\tzend_class_entry *old_scope = EG(scope);\n\n\t\t\t\t\t\tEG(scope) = Z_OBJCE(ent2->data);\n\t\t\t\t\t\tadd_property_zval(&ent2->data, ent1->varname, &ent1->data);\n\t\t\t\t\t\tif Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data);\n\t\t\t\t\t\tEG(scope) = old_scope;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tzend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data);\n\t\t\t\t\t}\n\t\t\t\t\tefree(ent1->varname);\n\t\t\t\t} else\t{\n\t\t\t\t\tzend_hash_next_index_insert(target_hash, &ent1->data);\n\t\t\t\t}\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t} else {\n\t\t\tstack->done = 1;\n\t\t}\n\t} else if (!strcmp((char *)name, EL_VAR) && stack->varname) {\n\t\tefree(stack->varname);\n\t\tstack->varname = NULL;\n\t} else if (!strcmp((char *)name, EL_FIELD)) {\n\t\tst_entry *ent;\n\t\twddx_stack_top(stack, (void **)&ent);\n\t\tefree(ent);\n\t\tstack->top--;\n\t}", "func_hash": 195456627139063255714886732829389598772, "file_name": "wddx.c", "file_hash": 202333767268853724294318351879930678985, "cwe": ["CWE-476"], "cve": "CVE-2016-7132", "cve_desc": "ext/wddx/wddx.c in PHP before 5.6.25 and 7.x before 7.0.10 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) or possibly have unspecified other impact via an invalid wddxPacket XML document that is mishandled in a wddx_deserialize call, as demonstrated by a stray element inside a boolean element, leading to incorrect pop processing.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-7132"}
{"idx": 233867, "project": "php-src", "commit_id": "0c8a2a2cd1056b7dc403eacb5d2c0eec6ce47c6f", "project_url": "https://github.com/php/php-src", "commit_url": "https://github.com/php/php-src/commit/0c8a2a2cd1056b7dc403eacb5d2c0eec6ce47c6f", "commit_message": "Fix for bug #72790 and bug #72799\n\n(cherry picked from commit a14fdb9746262549bbbb96abb87338bacd147e1b)\n\nConflicts:\n\text/wddx/wddx.c", "target": 0, "func": " */\nstatic void php_wddx_pop_element(void *user_data, const XML_Char *name)\n{\n\tst_entry \t\t\t*ent1, *ent2;\n\twddx_stack \t\t\t*stack = (wddx_stack *)user_data;\n\tHashTable \t\t\t*target_hash;\n\tzend_class_entry \t*pce;\n\tzval\t\t\t\tobj;\n\n/* OBJECTS_FIXME */\n\tif (stack->top == 0) {\n\t\treturn;\n\t}\n\n\tif (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) ||\n\t\t!strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) ||\n\t  \t!strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) ||\n\t\t!strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) ||\n\t\t!strcmp((char *)name, EL_DATETIME)) {\n\t\twddx_stack_top(stack, (void**)&ent1);\n\n\t\tif (Z_TYPE(ent1->data) == IS_UNDEF) {\n\t\t\tif (stack->top > 1) {\n\t\t\t\tstack->top--;\n\t\t\t\tefree(ent1);\n\t\t\t} else {\n\t\t\t\tstack->done = 1;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (!strcmp((char *)name, EL_BINARY)) {\n\t\t\tzend_string *new_str = php_base64_decode(\n\t\t\t\t(unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));\n\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\tZVAL_STR(&ent1->data, new_str);\n\t\t}\n\n\t\t/* Call __wakeup() method on the object. */\n\t\tif (Z_TYPE(ent1->data) == IS_OBJECT) {\n\t\t\tzval fname, retval;\n\n\t\t\tZVAL_STRING(&fname, \"__wakeup\");\n\n\t\t\tcall_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL);\n\n\t\t\tzval_ptr_dtor(&fname);\n\t\t\tzval_ptr_dtor(&retval);\n\t\t}\n\n\t\tif (stack->top > 1) {\n\t\t\tstack->top--;\n\t\t\twddx_stack_top(stack, (void**)&ent2);\n\n\t\t\t/* if non-existent field */\n\t\t\tif (ent2->type == ST_FIELD && Z_ISUNDEF(ent2->data)) {\n\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\tefree(ent1);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) {\n\t\t\t\ttarget_hash = HASH_OF(&ent2->data);\n\n\t\t\t\tif (ent1->varname) {\n\t\t\t\t\tif (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&\n\t\t\t\t\t\tZ_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) &&\n\t\t\t\t\t\tent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) {\n\t\t\t\t\t\tzend_bool incomplete_class = 0;\n\n\t\t\t\t\t\tzend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));\n\t\t\t\t\t\tzend_string_forget_hash_val(Z_STR(ent1->data));\n\t\t\t\t\t\tif ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) {\n\t\t\t\t\t\t\tincomplete_class = 1;\n\t\t\t\t\t\t\tpce = PHP_IC_ENTRY;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Initialize target object */\n\t\t\t\t\t\tobject_init_ex(&obj, pce);\n\n\t\t\t\t\t\t/* Merge current hashtable with object's default properties */\n\t\t\t\t\t\tzend_hash_merge(Z_OBJPROP(obj),\n\t\t\t\t\t\t\t\t\t\tZ_ARRVAL(ent2->data),\n\t\t\t\t\t\t\t\t\t\tzval_add_ref, 0);\n\n\t\t\t\t\t\tif (incomplete_class) {\n\t\t\t\t\t\t\tphp_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Clean up old array entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent2->data);\n\n\t\t\t\t\t\t/* Set stack entry to point to the newly created object */\n\t\t\t\t\t\tZVAL_COPY_VALUE(&ent2->data, &obj);\n\n\t\t\t\t\t\t/* Clean up class name var entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\t\t} else if (Z_TYPE(ent2->data) == IS_OBJECT) {\n\t\t\t\t\t\tzend_class_entry *old_scope = EG(scope);\n\n\t\t\t\t\t\tEG(scope) = Z_OBJCE(ent2->data);\n\t\t\t\t\t\tadd_property_zval(&ent2->data, ent1->varname, &ent1->data);\n\t\t\t\t\t\tif Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data);\n\t\t\t\t\t\tEG(scope) = old_scope;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tzend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data);\n\t\t\t\t\t}\n\t\t\t\t\tefree(ent1->varname);\n\t\t\t\t} else\t{\n\t\t\t\t\tzend_hash_next_index_insert(target_hash, &ent1->data);\n\t\t\t\t}\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t} else {\n\t\t\tstack->done = 1;\n\t\t}\n\t} else if (!strcmp((char *)name, EL_VAR) && stack->varname) {\n\t\tefree(stack->varname);\n\t\tstack->varname = NULL;\n\t} else if (!strcmp((char *)name, EL_FIELD)) {\n\t\tst_entry *ent;\n\t\twddx_stack_top(stack, (void **)&ent);\n\t\tefree(ent);\n\t\tstack->top--;\n\t}", "func_hash": 31470175015119113662948688342343260077, "file_name": "wddx.c", "file_hash": 138061260196786413886706259778202745956, "cwe": ["CWE-476"], "cve": "CVE-2016-7132", "cve_desc": "ext/wddx/wddx.c in PHP before 5.6.25 and 7.x before 7.0.10 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) or possibly have unspecified other impact via an invalid wddxPacket XML document that is mishandled in a wddx_deserialize call, as demonstrated by a stray element inside a boolean element, leading to incorrect pop processing.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-7132"}
{"idx": 195908, "project": "linux", "commit_id": "e4571b8c5e9ffa1e85c0c671995bd4dcc5c75091", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/e4571b8c5e9ffa1e85c0c671995bd4dcc5c75091", "commit_message": "btrfs: fix NULL pointer dereference when deleting device by invalid id\n\n[BUG]\nIt's easy to trigger NULL pointer dereference, just by removing a\nnon-existing device id:\n\n # mkfs.btrfs -f -m single -d single /dev/test/scratch1 \\\n\t\t\t\t     /dev/test/scratch2\n # mount /dev/test/scratch1 /mnt/btrfs\n # btrfs device remove 3 /mnt/btrfs\n\nThen we have the following kernel NULL pointer dereference:\n\n BUG: kernel NULL pointer dereference, address: 0000000000000000\n #PF: supervisor read access in kernel mode\n #PF: error_code(0x0000) - not-present page\n PGD 0 P4D 0\n Oops: 0000 [#1] PREEMPT SMP NOPTI\n CPU: 9 PID: 649 Comm: btrfs Not tainted 5.14.0-rc3-custom+ #35\n Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 0.0.0 02/06/2015\n RIP: 0010:btrfs_rm_device+0x4de/0x6b0 [btrfs]\n  btrfs_ioctl+0x18bb/0x3190 [btrfs]\n  ? lock_is_held_type+0xa5/0x120\n  ? find_held_lock.constprop.0+0x2b/0x80\n  ? do_user_addr_fault+0x201/0x6a0\n  ? lock_release+0xd2/0x2d0\n  ? __x64_sys_ioctl+0x83/0xb0\n  __x64_sys_ioctl+0x83/0xb0\n  do_syscall_64+0x3b/0x90\n  entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n[CAUSE]\nCommit a27a94c2b0c7 (\"btrfs: Make btrfs_find_device_by_devspec return\nbtrfs_device directly\") moves the \"missing\" device path check into\nbtrfs_rm_device().\n\nBut btrfs_rm_device() itself can have case where it only receives\n@devid, with NULL as @device_path.\n\nIn that case, calling strcmp() on NULL will trigger the NULL pointer\ndereference.\n\nBefore that commit, we handle the \"missing\" case inside\nbtrfs_find_device_by_devspec(), which will not check @device_path at all\nif @devid is provided, thus no way to trigger the bug.\n\n[FIX]\nBefore calling strcmp(), also make sure @device_path is not NULL.\n\nFixes: a27a94c2b0c7 (\"btrfs: Make btrfs_find_device_by_devspec return btrfs_device directly\")\nCC: stable@vger.kernel.org # 5.4+\nReported-by: butt3rflyh4ck \nReviewed-by: Anand Jain \nSigned-off-by: Qu Wenruo \nReviewed-by: David Sterba \nSigned-off-by: David Sterba ", "target": 1, "func": "int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,\n\t\t    u64 devid)\n{\n\tstruct btrfs_device *device;\n\tstruct btrfs_fs_devices *cur_devices;\n\tstruct btrfs_fs_devices *fs_devices = fs_info->fs_devices;\n\tu64 num_devices;\n\tint ret = 0;\n\n\tmutex_lock(&uuid_mutex);\n\n\tnum_devices = btrfs_num_devices(fs_info);\n\n\tret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);\n\tif (ret)\n\t\tgoto out;\n\n\tdevice = btrfs_find_device_by_devspec(fs_info, devid, device_path);\n\n\tif (IS_ERR(device)) {\n\t\tif (PTR_ERR(device) == -ENOENT &&\n\t\t    strcmp(device_path, \"missing\") == 0)\n\t\t\tret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;\n\t\telse\n\t\t\tret = PTR_ERR(device);\n\t\tgoto out;\n\t}\n\n\tif (btrfs_pinned_by_swapfile(fs_info, device)) {\n\t\tbtrfs_warn_in_rcu(fs_info,\n\t\t  \"cannot remove device %s (devid %llu) due to active swapfile\",\n\t\t\t\t  rcu_str_deref(device->name), device->devid);\n\t\tret = -ETXTBSY;\n\t\tgoto out;\n\t}\n\n\tif (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {\n\t\tret = BTRFS_ERROR_DEV_TGT_REPLACE;\n\t\tgoto out;\n\t}\n\n\tif (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&\n\t    fs_info->fs_devices->rw_devices == 1) {\n\t\tret = BTRFS_ERROR_DEV_ONLY_WRITABLE;\n\t\tgoto out;\n\t}\n\n\tif (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {\n\t\tmutex_lock(&fs_info->chunk_mutex);\n\t\tlist_del_init(&device->dev_alloc_list);\n\t\tdevice->fs_devices->rw_devices--;\n\t\tmutex_unlock(&fs_info->chunk_mutex);\n\t}\n\n\tmutex_unlock(&uuid_mutex);\n\tret = btrfs_shrink_device(device, 0);\n\tif (!ret)\n\t\tbtrfs_reada_remove_dev(device);\n\tmutex_lock(&uuid_mutex);\n\tif (ret)\n\t\tgoto error_undo;\n\n\t/*\n\t * TODO: the superblock still includes this device in its num_devices\n\t * counter although write_all_supers() is not locked out. This\n\t * could give a filesystem state which requires a degraded mount.\n\t */\n\tret = btrfs_rm_dev_item(device);\n\tif (ret)\n\t\tgoto error_undo;\n\n\tclear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);\n\tbtrfs_scrub_cancel_dev(device);\n\n\t/*\n\t * the device list mutex makes sure that we don't change\n\t * the device list while someone else is writing out all\n\t * the device supers. Whoever is writing all supers, should\n\t * lock the device list mutex before getting the number of\n\t * devices in the super block (super_copy). Conversely,\n\t * whoever updates the number of devices in the super block\n\t * (super_copy) should hold the device list mutex.\n\t */\n\n\t/*\n\t * In normal cases the cur_devices == fs_devices. But in case\n\t * of deleting a seed device, the cur_devices should point to\n\t * its own fs_devices listed under the fs_devices->seed.\n\t */\n\tcur_devices = device->fs_devices;\n\tmutex_lock(&fs_devices->device_list_mutex);\n\tlist_del_rcu(&device->dev_list);\n\n\tcur_devices->num_devices--;\n\tcur_devices->total_devices--;\n\t/* Update total_devices of the parent fs_devices if it's seed */\n\tif (cur_devices != fs_devices)\n\t\tfs_devices->total_devices--;\n\n\tif (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))\n\t\tcur_devices->missing_devices--;\n\n\tbtrfs_assign_next_active_device(device, NULL);\n\n\tif (device->bdev) {\n\t\tcur_devices->open_devices--;\n\t\t/* remove sysfs entry */\n\t\tbtrfs_sysfs_remove_device(device);\n\t}\n\n\tnum_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;\n\tbtrfs_set_super_num_devices(fs_info->super_copy, num_devices);\n\tmutex_unlock(&fs_devices->device_list_mutex);\n\n\t/*\n\t * at this point, the device is zero sized and detached from\n\t * the devices list.  All that's left is to zero out the old\n\t * supers and free the device.\n\t */\n\tif (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))\n\t\tbtrfs_scratch_superblocks(fs_info, device->bdev,\n\t\t\t\t\t  device->name->str);\n\n\tbtrfs_close_bdev(device);\n\tsynchronize_rcu();\n\tbtrfs_free_device(device);\n\n\tif (cur_devices->open_devices == 0) {\n\t\tlist_del_init(&cur_devices->seed_list);\n\t\tclose_fs_devices(cur_devices);\n\t\tfree_fs_devices(cur_devices);\n\t}\n\nout:\n\tmutex_unlock(&uuid_mutex);\n\treturn ret;\n\nerror_undo:\n\tbtrfs_reada_undo_remove_dev(device);\n\tif (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {\n\t\tmutex_lock(&fs_info->chunk_mutex);\n\t\tlist_add(&device->dev_alloc_list,\n\t\t\t &fs_devices->alloc_list);\n\t\tdevice->fs_devices->rw_devices++;\n\t\tmutex_unlock(&fs_info->chunk_mutex);\n\t}\n\tgoto out;\n}", "func_hash": 109862119097507194285189243526662049352, "file_name": "volumes.c", "file_hash": 327977751785202812455417482244318484271, "cwe": ["CWE-703"], "cve": "CVE-2021-3739", "cve_desc": "A NULL pointer dereference flaw was found in the btrfs_rm_device function in fs/btrfs/volumes.c in the Linux Kernel, where triggering the bug requires \u2018CAP_SYS_ADMIN\u2019. This flaw allows a local attacker to crash the system or leak kernel internal information. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3739"}
{"idx": 234731, "project": "linux", "commit_id": "e4571b8c5e9ffa1e85c0c671995bd4dcc5c75091", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/e4571b8c5e9ffa1e85c0c671995bd4dcc5c75091", "commit_message": "btrfs: fix NULL pointer dereference when deleting device by invalid id\n\n[BUG]\nIt's easy to trigger NULL pointer dereference, just by removing a\nnon-existing device id:\n\n # mkfs.btrfs -f -m single -d single /dev/test/scratch1 \\\n\t\t\t\t     /dev/test/scratch2\n # mount /dev/test/scratch1 /mnt/btrfs\n # btrfs device remove 3 /mnt/btrfs\n\nThen we have the following kernel NULL pointer dereference:\n\n BUG: kernel NULL pointer dereference, address: 0000000000000000\n #PF: supervisor read access in kernel mode\n #PF: error_code(0x0000) - not-present page\n PGD 0 P4D 0\n Oops: 0000 [#1] PREEMPT SMP NOPTI\n CPU: 9 PID: 649 Comm: btrfs Not tainted 5.14.0-rc3-custom+ #35\n Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 0.0.0 02/06/2015\n RIP: 0010:btrfs_rm_device+0x4de/0x6b0 [btrfs]\n  btrfs_ioctl+0x18bb/0x3190 [btrfs]\n  ? lock_is_held_type+0xa5/0x120\n  ? find_held_lock.constprop.0+0x2b/0x80\n  ? do_user_addr_fault+0x201/0x6a0\n  ? lock_release+0xd2/0x2d0\n  ? __x64_sys_ioctl+0x83/0xb0\n  __x64_sys_ioctl+0x83/0xb0\n  do_syscall_64+0x3b/0x90\n  entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n[CAUSE]\nCommit a27a94c2b0c7 (\"btrfs: Make btrfs_find_device_by_devspec return\nbtrfs_device directly\") moves the \"missing\" device path check into\nbtrfs_rm_device().\n\nBut btrfs_rm_device() itself can have case where it only receives\n@devid, with NULL as @device_path.\n\nIn that case, calling strcmp() on NULL will trigger the NULL pointer\ndereference.\n\nBefore that commit, we handle the \"missing\" case inside\nbtrfs_find_device_by_devspec(), which will not check @device_path at all\nif @devid is provided, thus no way to trigger the bug.\n\n[FIX]\nBefore calling strcmp(), also make sure @device_path is not NULL.\n\nFixes: a27a94c2b0c7 (\"btrfs: Make btrfs_find_device_by_devspec return btrfs_device directly\")\nCC: stable@vger.kernel.org # 5.4+\nReported-by: butt3rflyh4ck \nReviewed-by: Anand Jain \nSigned-off-by: Qu Wenruo \nReviewed-by: David Sterba \nSigned-off-by: David Sterba ", "target": 0, "func": "int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,\n\t\t    u64 devid)\n{\n\tstruct btrfs_device *device;\n\tstruct btrfs_fs_devices *cur_devices;\n\tstruct btrfs_fs_devices *fs_devices = fs_info->fs_devices;\n\tu64 num_devices;\n\tint ret = 0;\n\n\tmutex_lock(&uuid_mutex);\n\n\tnum_devices = btrfs_num_devices(fs_info);\n\n\tret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);\n\tif (ret)\n\t\tgoto out;\n\n\tdevice = btrfs_find_device_by_devspec(fs_info, devid, device_path);\n\n\tif (IS_ERR(device)) {\n\t\tif (PTR_ERR(device) == -ENOENT &&\n\t\t    device_path && strcmp(device_path, \"missing\") == 0)\n\t\t\tret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;\n\t\telse\n\t\t\tret = PTR_ERR(device);\n\t\tgoto out;\n\t}\n\n\tif (btrfs_pinned_by_swapfile(fs_info, device)) {\n\t\tbtrfs_warn_in_rcu(fs_info,\n\t\t  \"cannot remove device %s (devid %llu) due to active swapfile\",\n\t\t\t\t  rcu_str_deref(device->name), device->devid);\n\t\tret = -ETXTBSY;\n\t\tgoto out;\n\t}\n\n\tif (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {\n\t\tret = BTRFS_ERROR_DEV_TGT_REPLACE;\n\t\tgoto out;\n\t}\n\n\tif (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&\n\t    fs_info->fs_devices->rw_devices == 1) {\n\t\tret = BTRFS_ERROR_DEV_ONLY_WRITABLE;\n\t\tgoto out;\n\t}\n\n\tif (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {\n\t\tmutex_lock(&fs_info->chunk_mutex);\n\t\tlist_del_init(&device->dev_alloc_list);\n\t\tdevice->fs_devices->rw_devices--;\n\t\tmutex_unlock(&fs_info->chunk_mutex);\n\t}\n\n\tmutex_unlock(&uuid_mutex);\n\tret = btrfs_shrink_device(device, 0);\n\tif (!ret)\n\t\tbtrfs_reada_remove_dev(device);\n\tmutex_lock(&uuid_mutex);\n\tif (ret)\n\t\tgoto error_undo;\n\n\t/*\n\t * TODO: the superblock still includes this device in its num_devices\n\t * counter although write_all_supers() is not locked out. This\n\t * could give a filesystem state which requires a degraded mount.\n\t */\n\tret = btrfs_rm_dev_item(device);\n\tif (ret)\n\t\tgoto error_undo;\n\n\tclear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);\n\tbtrfs_scrub_cancel_dev(device);\n\n\t/*\n\t * the device list mutex makes sure that we don't change\n\t * the device list while someone else is writing out all\n\t * the device supers. Whoever is writing all supers, should\n\t * lock the device list mutex before getting the number of\n\t * devices in the super block (super_copy). Conversely,\n\t * whoever updates the number of devices in the super block\n\t * (super_copy) should hold the device list mutex.\n\t */\n\n\t/*\n\t * In normal cases the cur_devices == fs_devices. But in case\n\t * of deleting a seed device, the cur_devices should point to\n\t * its own fs_devices listed under the fs_devices->seed.\n\t */\n\tcur_devices = device->fs_devices;\n\tmutex_lock(&fs_devices->device_list_mutex);\n\tlist_del_rcu(&device->dev_list);\n\n\tcur_devices->num_devices--;\n\tcur_devices->total_devices--;\n\t/* Update total_devices of the parent fs_devices if it's seed */\n\tif (cur_devices != fs_devices)\n\t\tfs_devices->total_devices--;\n\n\tif (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))\n\t\tcur_devices->missing_devices--;\n\n\tbtrfs_assign_next_active_device(device, NULL);\n\n\tif (device->bdev) {\n\t\tcur_devices->open_devices--;\n\t\t/* remove sysfs entry */\n\t\tbtrfs_sysfs_remove_device(device);\n\t}\n\n\tnum_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;\n\tbtrfs_set_super_num_devices(fs_info->super_copy, num_devices);\n\tmutex_unlock(&fs_devices->device_list_mutex);\n\n\t/*\n\t * at this point, the device is zero sized and detached from\n\t * the devices list.  All that's left is to zero out the old\n\t * supers and free the device.\n\t */\n\tif (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))\n\t\tbtrfs_scratch_superblocks(fs_info, device->bdev,\n\t\t\t\t\t  device->name->str);\n\n\tbtrfs_close_bdev(device);\n\tsynchronize_rcu();\n\tbtrfs_free_device(device);\n\n\tif (cur_devices->open_devices == 0) {\n\t\tlist_del_init(&cur_devices->seed_list);\n\t\tclose_fs_devices(cur_devices);\n\t\tfree_fs_devices(cur_devices);\n\t}\n\nout:\n\tmutex_unlock(&uuid_mutex);\n\treturn ret;\n\nerror_undo:\n\tbtrfs_reada_undo_remove_dev(device);\n\tif (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {\n\t\tmutex_lock(&fs_info->chunk_mutex);\n\t\tlist_add(&device->dev_alloc_list,\n\t\t\t &fs_devices->alloc_list);\n\t\tdevice->fs_devices->rw_devices++;\n\t\tmutex_unlock(&fs_info->chunk_mutex);\n\t}\n\tgoto out;\n}", "func_hash": 150119639172350576972778244740451645198, "file_name": "volumes.c", "file_hash": 142275211219518353290156650917746742888, "cwe": ["CWE-703"], "cve": "CVE-2021-3739", "cve_desc": "A NULL pointer dereference flaw was found in the btrfs_rm_device function in fs/btrfs/volumes.c in the Linux Kernel, where triggering the bug requires \u2018CAP_SYS_ADMIN\u2019. This flaw allows a local attacker to crash the system or leak kernel internal information. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3739"}
{"idx": 195909, "project": "ImageMagick", "commit_id": "d072ed6aff835c174e856ce3a428163c0da9e8f4", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/d072ed6aff835c174e856ce3a428163c0da9e8f4", "commit_message": "Skip MNG CLIP chunk with out-of-range object IDs", "target": 1, "func": "static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,\n     ExceptionInfo *exception)\n{\n  char\n    page_geometry[MagickPathExtent];\n\n  Image\n    *image;\n\n  MagickBooleanType\n    logging;\n\n  volatile int\n    first_mng_object,\n    object_id,\n    term_chunk_found,\n    skip_to_iend;\n\n  volatile ssize_t\n    image_count=0;\n\n  MagickBooleanType\n    status;\n\n  MagickOffsetType\n    offset;\n\n  MngBox\n    default_fb,\n    fb,\n    previous_fb;\n\n#if defined(MNG_INSERT_LAYERS)\n  PixelInfo\n    mng_background_color;\n#endif\n\n  register unsigned char\n    *p;\n\n  register ssize_t\n    i;\n\n  size_t\n    count;\n\n  ssize_t\n    loop_level;\n\n  volatile short\n    skipping_loop;\n\n#if defined(MNG_INSERT_LAYERS)\n  unsigned int\n    mandatory_back=0;\n#endif\n\n  volatile unsigned int\n#ifdef MNG_OBJECT_BUFFERS\n    mng_background_object=0,\n#endif\n    mng_type=0;   /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */\n\n  size_t\n    default_frame_timeout,\n    frame_timeout,\n#if defined(MNG_INSERT_LAYERS)\n    image_height,\n    image_width,\n#endif\n    length;\n\n  /* These delays are all measured in image ticks_per_second,\n   * not in MNG ticks_per_second\n   */\n  volatile size_t\n    default_frame_delay,\n    final_delay,\n    final_image_delay,\n    frame_delay,\n#if defined(MNG_INSERT_LAYERS)\n    insert_layers,\n#endif\n    mng_iterations=1,\n    simplicity=0,\n    subframe_height=0,\n    subframe_width=0;\n\n  previous_fb.top=0;\n  previous_fb.bottom=0;\n  previous_fb.left=0;\n  previous_fb.right=0;\n  default_fb.top=0;\n  default_fb.bottom=0;\n  default_fb.left=0;\n  default_fb.right=0;\n\n  logging=LogMagickEvent(CoderEvent,GetMagickModule(),\n    \"  Enter ReadOneMNGImage()\");\n\n  image=mng_info->image;\n\n  if (LocaleCompare(image_info->magick,\"MNG\") == 0)\n    {\n      char\n        magic_number[MagickPathExtent];\n\n      /* Verify MNG signature.  */\n      count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);\n      if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0)\n        ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n      /* Initialize some nonzero members of the MngInfo structure.  */\n      for (i=0; i < MNG_MAX_OBJECTS; i++)\n      {\n        mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;\n        mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;\n      }\n      mng_info->exists[0]=MagickTrue;\n    }\n\n  skipping_loop=(-1);\n  first_mng_object=MagickTrue;\n  mng_type=0;\n#if defined(MNG_INSERT_LAYERS)\n  insert_layers=MagickFalse; /* should be False during convert or mogrify */\n#endif\n  default_frame_delay=0;\n  default_frame_timeout=0;\n  frame_delay=0;\n  final_delay=1;\n  mng_info->ticks_per_second=1UL*image->ticks_per_second;\n  object_id=0;\n  skip_to_iend=MagickFalse;\n  term_chunk_found=MagickFalse;\n  mng_info->framing_mode=1;\n#if defined(MNG_INSERT_LAYERS)\n  mandatory_back=MagickFalse;\n#endif\n#if defined(MNG_INSERT_LAYERS)\n  mng_background_color=image->background_color;\n#endif\n  default_fb=mng_info->frame;\n  previous_fb=mng_info->frame;\n  do\n  {\n    char\n      type[MagickPathExtent];\n\n    if (LocaleCompare(image_info->magick,\"MNG\") == 0)\n      {\n        unsigned char\n          *chunk;\n\n        /*\n          Read a new chunk.\n        */\n        type[0]='\\0';\n        (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent);\n        length=ReadBlobMSBLong(image);\n        count=(size_t) ReadBlob(image,4,(unsigned char *) type);\n\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n           \"  Reading MNG chunk type %c%c%c%c, length: %.20g\",\n           type[0],type[1],type[2],type[3],(double) length);\n\n        if (length > PNG_UINT_31_MAX)\n          {\n            status=MagickFalse;\n            break;\n          }\n\n        if (count == 0)\n          ThrowReaderException(CorruptImageError,\"CorruptImage\");\n\n        p=NULL;\n        chunk=(unsigned char *) NULL;\n\n        if (length != 0)\n          {\n            if (length > GetBlobSize(image))\n              ThrowReaderException(CorruptImageError,\n                \"InsufficientImageDataInFile\");\n            chunk=(unsigned char *) AcquireQuantumMemory(length+\n             MagickPathExtent,sizeof(*chunk));\n\n            if (chunk == (unsigned char *) NULL)\n              ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n            for (i=0; i < (ssize_t) length; i++)\n            {\n              int\n                c;\n\n              c=ReadBlobByte(image);\n              if (c == EOF)\n                break;\n              chunk[i]=(unsigned char) c;\n            }\n\n            p=chunk;\n          }\n\n        (void) ReadBlobMSBLong(image);  /* read crc word */\n\n#if !defined(JNG_SUPPORTED)\n        if (memcmp(type,mng_JHDR,4) == 0)\n          {\n            skip_to_iend=MagickTrue;\n\n            if (mng_info->jhdr_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename);\n\n            mng_info->jhdr_warning++;\n          }\n#endif\n        if (memcmp(type,mng_DHDR,4) == 0)\n          {\n            skip_to_iend=MagickTrue;\n\n            if (mng_info->dhdr_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename);\n\n            mng_info->dhdr_warning++;\n          }\n        if (memcmp(type,mng_MEND,4) == 0)\n          break;\n\n        if (skip_to_iend)\n          {\n            if (memcmp(type,mng_IEND,4) == 0)\n              skip_to_iend=MagickFalse;\n\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Skip to IEND.\");\n\n            continue;\n          }\n\n        if (memcmp(type,mng_MHDR,4) == 0)\n          {\n            if (length != 28)\n              {\n                chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n                ThrowReaderException(CorruptImageError,\"CorruptImage\");\n              }\n\n            mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |\n                (p[2] << 8) | p[3]);\n\n            mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |\n                (p[6] << 8) | p[7]);\n\n            if (logging != MagickFalse)\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  MNG width: %.20g\",(double) mng_info->mng_width);\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  MNG height: %.20g\",(double) mng_info->mng_height);\n              }\n\n            p+=8;\n            mng_info->ticks_per_second=(size_t) mng_get_long(p);\n\n            if (mng_info->ticks_per_second == 0)\n              default_frame_delay=0;\n\n            else\n              default_frame_delay=1UL*image->ticks_per_second/\n                mng_info->ticks_per_second;\n\n            frame_delay=default_frame_delay;\n            simplicity=0;\n\n            p+=16;\n            simplicity=(size_t) mng_get_long(p);\n\n            mng_type=1;    /* Full MNG */\n\n            if ((simplicity != 0) && ((simplicity | 11) == 11))\n              mng_type=2; /* LC */\n\n            if ((simplicity != 0) && ((simplicity | 9) == 9))\n              mng_type=3; /* VLC */\n\n#if defined(MNG_INSERT_LAYERS)\n            if (mng_type != 3)\n              insert_layers=MagickTrue;\n#endif\n            if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n              {\n                /* Allocate next image structure.  */\n                AcquireNextImage(image_info,image,exception);\n\n                if (GetNextImageInList(image) == (Image *) NULL)\n                  return((Image *) NULL);\n\n                image=SyncNextImageInList(image);\n                mng_info->image=image;\n              }\n\n            if ((mng_info->mng_width > 65535L) ||\n                (mng_info->mng_height > 65535L))\n              {\n                chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n                ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\");\n              }\n\n            (void) FormatLocaleString(page_geometry,MagickPathExtent,\n              \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double)\n              mng_info->mng_height);\n\n            mng_info->frame.left=0;\n            mng_info->frame.right=(ssize_t) mng_info->mng_width;\n            mng_info->frame.top=0;\n            mng_info->frame.bottom=(ssize_t) mng_info->mng_height;\n            mng_info->clip=default_fb=previous_fb=mng_info->frame;\n\n            for (i=0; i < MNG_MAX_OBJECTS; i++)\n              mng_info->object_clip[i]=mng_info->frame;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_TERM,4) == 0)\n          {\n            int\n              repeat=0;\n\n            if (length != 0)\n              repeat=p[0];\n\n            if (repeat == 3)\n              {\n                final_delay=(png_uint_32) mng_get_long(&p[2]);\n                mng_iterations=(png_uint_32) mng_get_long(&p[6]);\n\n                if (mng_iterations == PNG_UINT_31_MAX)\n                  mng_iterations=0;\n\n                image->iterations=mng_iterations;\n                term_chunk_found=MagickTrue;\n              }\n\n            if (logging != MagickFalse)\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"    repeat=%d,  final_delay=%.20g,  iterations=%.20g\",\n                  repeat,(double) final_delay, (double) image->iterations);\n              }\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n        if (memcmp(type,mng_DEFI,4) == 0)\n          {\n            if (mng_type == 3)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\",\n                image->filename);\n\n            if (length < 2)\n              {\n                if (chunk)\n                  chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n                ThrowReaderException(CorruptImageError,\"CorruptImage\");\n              }\n\n            object_id=(p[0] << 8) | p[1];\n\n            if (mng_type == 2 && object_id != 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\",\n                image->filename);\n\n            if (object_id > MNG_MAX_OBJECTS)\n              {\n                /*\n                  Instead of using a warning we should allocate a larger\n                  MngInfo structure and continue.\n                */\n                (void) ThrowMagickException(exception,GetMagickModule(),\n                  CoderError,\"object id too large\",\"`%s'\",image->filename);\n                object_id=MNG_MAX_OBJECTS;\n              }\n\n            if (mng_info->exists[object_id])\n              if (mng_info->frozen[object_id])\n                {\n                  chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n                  (void) ThrowMagickException(exception,\n                    GetMagickModule(),CoderError,\n                    \"DEFI cannot redefine a frozen MNG object\",\"`%s'\",\n                    image->filename);\n                  continue;\n                }\n\n            mng_info->exists[object_id]=MagickTrue;\n\n            if (length > 2)\n              mng_info->invisible[object_id]=p[2];\n\n            /*\n              Extract object offset info.\n            */\n            if (length > 11)\n              {\n                mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) |\n                    (p[5] << 16) | (p[6] << 8) | p[7]);\n\n                mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) |\n                    (p[9] << 16) | (p[10] << 8) | p[11]);\n\n                if (logging != MagickFalse)\n                  {\n                    (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                      \"  x_off[%d]: %.20g,  y_off[%d]: %.20g\",\n                      object_id,(double) mng_info->x_off[object_id],\n                      object_id,(double) mng_info->y_off[object_id]);\n                  }\n              }\n\n            /*\n              Extract object clipping info.\n            */\n            if (length > 27)\n              mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0,\n                &p[12]);\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n        if (memcmp(type,mng_bKGD,4) == 0)\n          {\n            mng_info->have_global_bkgd=MagickFalse;\n\n            if (length > 5)\n              {\n                mng_info->mng_global_bkgd.red=\n                  ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));\n\n                mng_info->mng_global_bkgd.green=\n                  ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));\n\n                mng_info->mng_global_bkgd.blue=\n                  ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));\n\n                mng_info->have_global_bkgd=MagickTrue;\n              }\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n        if (memcmp(type,mng_BACK,4) == 0)\n          {\n#if defined(MNG_INSERT_LAYERS)\n            if (length > 6)\n              mandatory_back=p[6];\n\n            else\n              mandatory_back=0;\n\n            if (mandatory_back && length > 5)\n              {\n                mng_background_color.red=\n                    ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));\n\n                mng_background_color.green=\n                    ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));\n\n                mng_background_color.blue=\n                    ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));\n\n                mng_background_color.alpha=OpaqueAlpha;\n              }\n\n#ifdef MNG_OBJECT_BUFFERS\n            if (length > 8)\n              mng_background_object=(p[7] << 8) | p[8];\n#endif\n#endif\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_PLTE,4) == 0)\n          {\n            /* Read global PLTE.  */\n\n            if (length && (length < 769))\n              {\n                if (mng_info->global_plte == (png_colorp) NULL)\n                  mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,\n                    sizeof(*mng_info->global_plte));\n\n                for (i=0; i < (ssize_t) (length/3); i++)\n                {\n                  mng_info->global_plte[i].red=p[3*i];\n                  mng_info->global_plte[i].green=p[3*i+1];\n                  mng_info->global_plte[i].blue=p[3*i+2];\n                }\n\n                mng_info->global_plte_length=(unsigned int) (length/3);\n              }\n#ifdef MNG_LOOSE\n            for ( ; i < 256; i++)\n            {\n              mng_info->global_plte[i].red=i;\n              mng_info->global_plte[i].green=i;\n              mng_info->global_plte[i].blue=i;\n            }\n\n            if (length != 0)\n              mng_info->global_plte_length=256;\n#endif\n            else\n              mng_info->global_plte_length=0;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_tRNS,4) == 0)\n          {\n            /* read global tRNS */\n\n            if (length > 0 && length < 257)\n              for (i=0; i < (ssize_t) length; i++)\n                mng_info->global_trns[i]=p[i];\n\n#ifdef MNG_LOOSE\n            for ( ; i < 256; i++)\n              mng_info->global_trns[i]=255;\n#endif\n            mng_info->global_trns_length=(unsigned int) length;\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n        if (memcmp(type,mng_gAMA,4) == 0)\n          {\n            if (length == 4)\n              {\n                ssize_t\n                  igamma;\n\n                igamma=mng_get_long(p);\n                mng_info->global_gamma=((float) igamma)*0.00001;\n                mng_info->have_global_gama=MagickTrue;\n              }\n\n            else\n              mng_info->have_global_gama=MagickFalse;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_cHRM,4) == 0)\n          {\n            /* Read global cHRM */\n\n            if (length == 32)\n              {\n                mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);\n                mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);\n                mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);\n                mng_info->global_chrm.red_primary.y=0.00001*\n                  mng_get_long(&p[12]);\n                mng_info->global_chrm.green_primary.x=0.00001*\n                  mng_get_long(&p[16]);\n                mng_info->global_chrm.green_primary.y=0.00001*\n                  mng_get_long(&p[20]);\n                mng_info->global_chrm.blue_primary.x=0.00001*\n                  mng_get_long(&p[24]);\n                mng_info->global_chrm.blue_primary.y=0.00001*\n                  mng_get_long(&p[28]);\n                mng_info->have_global_chrm=MagickTrue;\n              }\n            else\n              mng_info->have_global_chrm=MagickFalse;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_sRGB,4) == 0)\n          {\n            /*\n              Read global sRGB.\n            */\n            if (length != 0)\n              {\n                mng_info->global_srgb_intent=\n                  Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);\n                mng_info->have_global_srgb=MagickTrue;\n              }\n            else\n              mng_info->have_global_srgb=MagickFalse;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_iCCP,4) == 0)\n          {\n            /* To do: */\n\n            /*\n              Read global iCCP.\n            */\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            continue;\n          }\n\n        if (memcmp(type,mng_FRAM,4) == 0)\n          {\n            if (mng_type == 3)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\",\n                image->filename);\n\n            if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))\n              image->delay=frame_delay;\n\n            frame_delay=default_frame_delay;\n            frame_timeout=default_frame_timeout;\n            fb=default_fb;\n\n            if (length != 0)\n              if (p[0])\n                mng_info->framing_mode=p[0];\n\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"    Framing_mode=%d\",mng_info->framing_mode);\n\n            if (length > 6)\n              {\n                /* Note the delay and frame clipping boundaries.  */\n\n                p++; /* framing mode */\n\n                while (*p && ((p-chunk) < (ssize_t) length))\n                  p++;  /* frame name */\n\n                p++;  /* frame name terminator */\n\n                if ((p-chunk) < (ssize_t) (length-4))\n                  {\n                    int\n                      change_delay,\n                      change_timeout,\n                      change_clipping;\n\n                    change_delay=(*p++);\n                    change_timeout=(*p++);\n                    change_clipping=(*p++);\n                    p++; /* change_sync */\n\n                    if (change_delay)\n                      {\n                        frame_delay=1UL*image->ticks_per_second*\n                          mng_get_long(p);\n\n                        if (mng_info->ticks_per_second != 0)\n                          frame_delay/=mng_info->ticks_per_second;\n\n                        else\n                          frame_delay=PNG_UINT_31_MAX;\n\n                        if (change_delay == 2)\n                          default_frame_delay=frame_delay;\n\n                        p+=4;\n\n                        if (logging != MagickFalse)\n                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                            \"    Framing_delay=%.20g\",(double) frame_delay);\n                      }\n\n                    if (change_timeout)\n                      {\n                        frame_timeout=1UL*image->ticks_per_second*\n                          mng_get_long(p);\n\n                        if (mng_info->ticks_per_second != 0)\n                          frame_timeout/=mng_info->ticks_per_second;\n\n                        else\n                          frame_timeout=PNG_UINT_31_MAX;\n\n                        if (change_timeout == 2)\n                          default_frame_timeout=frame_timeout;\n\n                        p+=4;\n\n                        if (logging != MagickFalse)\n                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                            \"    Framing_timeout=%.20g\",(double) frame_timeout);\n                      }\n\n                    if (change_clipping)\n                      {\n                        fb=mng_read_box(previous_fb,(char) p[0],&p[1]);\n                        p+=17;\n                        previous_fb=fb;\n\n                        if (logging != MagickFalse)\n                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                            \"    Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\",\n                            (double) fb.left,(double) fb.right,(double) fb.top,\n                            (double) fb.bottom);\n\n                        if (change_clipping == 2)\n                          default_fb=fb;\n                      }\n                  }\n              }\n            mng_info->clip=fb;\n            mng_info->clip=mng_minimum_box(fb,mng_info->frame);\n\n            subframe_width=(size_t) (mng_info->clip.right\n               -mng_info->clip.left);\n\n            subframe_height=(size_t) (mng_info->clip.bottom\n               -mng_info->clip.top);\n            /*\n              Insert a background layer behind the frame if framing_mode is 4.\n            */\n#if defined(MNG_INSERT_LAYERS)\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"   subframe_width=%.20g, subframe_height=%.20g\",(double)\n                subframe_width,(double) subframe_height);\n\n            if (insert_layers && (mng_info->framing_mode == 4) &&\n                (subframe_width) && (subframe_height))\n              {\n                /* Allocate next image structure.  */\n                if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n                  {\n                    AcquireNextImage(image_info,image,exception);\n\n                    if (GetNextImageInList(image) == (Image *) NULL)\n                      return(DestroyImageList(image));\n\n                    image=SyncNextImageInList(image);\n                  }\n\n                mng_info->image=image;\n\n                if (term_chunk_found)\n                  {\n                    image->start_loop=MagickTrue;\n                    image->iterations=mng_iterations;\n                    term_chunk_found=MagickFalse;\n                  }\n\n                else\n                    image->start_loop=MagickFalse;\n\n                image->columns=subframe_width;\n                image->rows=subframe_height;\n                image->page.width=subframe_width;\n                image->page.height=subframe_height;\n                image->page.x=mng_info->clip.left;\n                image->page.y=mng_info->clip.top;\n                image->background_color=mng_background_color;\n                image->alpha_trait=UndefinedPixelTrait;\n                image->delay=0;\n                (void) SetImageBackgroundColor(image,exception);\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\",\n                    (double) mng_info->clip.left,\n                    (double) mng_info->clip.right,\n                    (double) mng_info->clip.top,\n                    (double) mng_info->clip.bottom);\n              }\n#endif\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_CLIP,4) == 0)\n          {\n            unsigned int\n              first_object,\n              last_object;\n\n            /*\n              Read CLIP.\n            */\n            if (length > 3)\n              {\n                first_object=(p[0] << 8) | p[1];\n                last_object=(p[2] << 8) | p[3];\n                p+=4;\n\n                for (i=(int) first_object; i <= (int) last_object; i++)\n                {\n                  if (mng_info->exists[i] && !mng_info->frozen[i])\n                    {\n                      MngBox\n                        box;\n\n                      box=mng_info->object_clip[i];\n                      if ((p-chunk) < (ssize_t) (length-17))\n                        mng_info->object_clip[i]=\n                           mng_read_box(box,(char) p[0],&p[1]);\n                    }\n                }\n\n              }\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_SAVE,4) == 0)\n          {\n            for (i=1; i < MNG_MAX_OBJECTS; i++)\n              if (mng_info->exists[i])\n                {\n                 mng_info->frozen[i]=MagickTrue;\n#ifdef MNG_OBJECT_BUFFERS\n                 if (mng_info->ob[i] != (MngBuffer *) NULL)\n                    mng_info->ob[i]->frozen=MagickTrue;\n#endif\n                }\n\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            continue;\n          }\n\n        if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))\n          {\n            /* Read DISC or SEEK.  */\n\n            if ((length == 0) || !memcmp(type,mng_SEEK,4))\n              {\n                for (i=1; i < MNG_MAX_OBJECTS; i++)\n                  MngInfoDiscardObject(mng_info,i);\n              }\n\n            else\n              {\n                register ssize_t\n                  j;\n\n                for (j=1; j < (ssize_t) length; j+=2)\n                {\n                  i=p[j-1] << 8 | p[j];\n                  MngInfoDiscardObject(mng_info,i);\n                }\n              }\n\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            continue;\n          }\n\n        if (memcmp(type,mng_MOVE,4) == 0)\n          {\n            size_t\n              first_object,\n              last_object;\n\n            /* read MOVE */\n\n            if (length > 3)\n            {\n              first_object=(p[0] << 8) | p[1];\n              last_object=(p[2] << 8) | p[3];\n              p+=4;\n\n              for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)\n              {\n                if ((i < 0) || (i >= MNG_MAX_OBJECTS))\n                  continue;\n\n                if (mng_info->exists[i] && !mng_info->frozen[i] &&\n                    (p-chunk) < (ssize_t) (length-8))\n                  {\n                    MngPair\n                      new_pair;\n\n                    MngPair\n                      old_pair;\n\n                    old_pair.a=mng_info->x_off[i];\n                    old_pair.b=mng_info->y_off[i];\n                    new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);\n                    mng_info->x_off[i]=new_pair.a;\n                    mng_info->y_off[i]=new_pair.b;\n                  }\n              }\n            }\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_LOOP,4) == 0)\n          {\n            ssize_t loop_iters=1;\n            if (length > 4)\n              {\n                loop_level=chunk[0];\n                mng_info->loop_active[loop_level]=1;  /* mark loop active */\n\n                /* Record starting point.  */\n                loop_iters=mng_get_long(&chunk[1]);\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  LOOP level %.20g has %.20g iterations \",\n                    (double) loop_level, (double) loop_iters);\n\n                if (loop_iters == 0)\n                  skipping_loop=loop_level;\n\n                else\n                  {\n                    mng_info->loop_jump[loop_level]=TellBlob(image);\n                    mng_info->loop_count[loop_level]=loop_iters;\n                  }\n\n                mng_info->loop_iteration[loop_level]=0;\n              }\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_ENDL,4) == 0)\n          {\n            if (length > 0)\n              {\n                loop_level=chunk[0];\n\n                if (skipping_loop > 0)\n                  {\n                    if (skipping_loop == loop_level)\n                      {\n                        /*\n                          Found end of zero-iteration loop.\n                        */\n                        skipping_loop=(-1);\n                        mng_info->loop_active[loop_level]=0;\n                      }\n                  }\n\n                else\n                  {\n                    if (mng_info->loop_active[loop_level] == 1)\n                      {\n                        mng_info->loop_count[loop_level]--;\n                        mng_info->loop_iteration[loop_level]++;\n\n                        if (logging != MagickFalse)\n                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                          \"  ENDL: LOOP level %.20g has %.20g remaining iters\",\n                            (double) loop_level,(double)\n                            mng_info->loop_count[loop_level]);\n\n                        if (mng_info->loop_count[loop_level] != 0)\n                          {\n                            offset=\n                              SeekBlob(image,mng_info->loop_jump[loop_level],\n                              SEEK_SET);\n\n                            if (offset < 0)\n                              {\n                                chunk=(unsigned char *) RelinquishMagickMemory(\n                                  chunk);\n                                ThrowReaderException(CorruptImageError,\n                                  \"ImproperImageHeader\");\n                              }\n                          }\n\n                        else\n                          {\n                            short\n                              last_level;\n\n                            /*\n                              Finished loop.\n                            */\n                            mng_info->loop_active[loop_level]=0;\n                            last_level=(-1);\n                            for (i=0; i < loop_level; i++)\n                              if (mng_info->loop_active[i] == 1)\n                                last_level=(short) i;\n                            loop_level=last_level;\n                          }\n                      }\n                  }\n              }\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_CLON,4) == 0)\n          {\n            if (mng_info->clon_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"CLON is not implemented yet\",\"`%s'\",\n                image->filename);\n\n            mng_info->clon_warning++;\n          }\n\n        if (memcmp(type,mng_MAGN,4) == 0)\n          {\n            png_uint_16\n              magn_first,\n              magn_last,\n              magn_mb,\n              magn_ml,\n              magn_mr,\n              magn_mt,\n              magn_mx,\n              magn_my,\n              magn_methx,\n              magn_methy;\n\n            if (length > 1)\n              magn_first=(p[0] << 8) | p[1];\n\n            else\n              magn_first=0;\n\n            if (length > 3)\n              magn_last=(p[2] << 8) | p[3];\n\n            else\n              magn_last=magn_first;\n#ifndef MNG_OBJECT_BUFFERS\n            if (magn_first || magn_last)\n              if (mng_info->magn_warning == 0)\n                {\n                  (void) ThrowMagickException(exception,\n                     GetMagickModule(),CoderError,\n                     \"MAGN is not implemented yet for nonzero objects\",\n                     \"`%s'\",image->filename);\n\n                   mng_info->magn_warning++;\n                }\n#endif\n            if (length > 4)\n              magn_methx=p[4];\n\n            else\n              magn_methx=0;\n\n            if (length > 6)\n              magn_mx=(p[5] << 8) | p[6];\n\n            else\n              magn_mx=1;\n\n            if (magn_mx == 0)\n              magn_mx=1;\n\n            if (length > 8)\n              magn_my=(p[7] << 8) | p[8];\n\n            else\n              magn_my=magn_mx;\n\n            if (magn_my == 0)\n              magn_my=1;\n\n            if (length > 10)\n              magn_ml=(p[9] << 8) | p[10];\n\n            else\n              magn_ml=magn_mx;\n\n            if (magn_ml == 0)\n              magn_ml=1;\n\n            if (length > 12)\n              magn_mr=(p[11] << 8) | p[12];\n\n            else\n              magn_mr=magn_mx;\n\n            if (magn_mr == 0)\n              magn_mr=1;\n\n            if (length > 14)\n              magn_mt=(p[13] << 8) | p[14];\n\n            else\n              magn_mt=magn_my;\n\n            if (magn_mt == 0)\n              magn_mt=1;\n\n            if (length > 16)\n              magn_mb=(p[15] << 8) | p[16];\n\n            else\n              magn_mb=magn_my;\n\n            if (magn_mb == 0)\n              magn_mb=1;\n\n            if (length > 17)\n              magn_methy=p[17];\n\n            else\n              magn_methy=magn_methx;\n\n\n            if (magn_methx > 5 || magn_methy > 5)\n              if (mng_info->magn_warning == 0)\n                {\n                  (void) ThrowMagickException(exception,\n                     GetMagickModule(),CoderError,\n                     \"Unknown MAGN method in MNG datastream\",\"`%s'\",\n                     image->filename);\n\n                   mng_info->magn_warning++;\n                }\n#ifdef MNG_OBJECT_BUFFERS\n          /* Magnify existing objects in the range magn_first to magn_last */\n#endif\n            if (magn_first == 0 || magn_last == 0)\n              {\n                /* Save the magnification factors for object 0 */\n                mng_info->magn_mb=magn_mb;\n                mng_info->magn_ml=magn_ml;\n                mng_info->magn_mr=magn_mr;\n                mng_info->magn_mt=magn_mt;\n                mng_info->magn_mx=magn_mx;\n                mng_info->magn_my=magn_my;\n                mng_info->magn_methx=magn_methx;\n                mng_info->magn_methy=magn_methy;\n              }\n          }\n\n        if (memcmp(type,mng_PAST,4) == 0)\n          {\n            if (mng_info->past_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"PAST is not implemented yet\",\"`%s'\",\n                image->filename);\n\n            mng_info->past_warning++;\n          }\n\n        if (memcmp(type,mng_SHOW,4) == 0)\n          {\n            if (mng_info->show_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"SHOW is not implemented yet\",\"`%s'\",\n                image->filename);\n\n            mng_info->show_warning++;\n          }\n\n        if (memcmp(type,mng_sBIT,4) == 0)\n          {\n            if (length < 4)\n              mng_info->have_global_sbit=MagickFalse;\n\n            else\n              {\n                mng_info->global_sbit.gray=p[0];\n                mng_info->global_sbit.red=p[0];\n                mng_info->global_sbit.green=p[1];\n                mng_info->global_sbit.blue=p[2];\n                mng_info->global_sbit.alpha=p[3];\n                mng_info->have_global_sbit=MagickTrue;\n             }\n          }\n        if (memcmp(type,mng_pHYs,4) == 0)\n          {\n            if (length > 8)\n              {\n                mng_info->global_x_pixels_per_unit=\n                    (size_t) mng_get_long(p);\n                mng_info->global_y_pixels_per_unit=\n                    (size_t) mng_get_long(&p[4]);\n                mng_info->global_phys_unit_type=p[8];\n                mng_info->have_global_phys=MagickTrue;\n              }\n\n            else\n              mng_info->have_global_phys=MagickFalse;\n          }\n        if (memcmp(type,mng_pHYg,4) == 0)\n          {\n            if (mng_info->phyg_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename);\n\n            mng_info->phyg_warning++;\n          }\n        if (memcmp(type,mng_BASI,4) == 0)\n          {\n            skip_to_iend=MagickTrue;\n\n            if (mng_info->basi_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"BASI is not implemented yet\",\"`%s'\",\n                image->filename);\n\n            mng_info->basi_warning++;\n#ifdef MNG_BASI_SUPPORTED\n            basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) |\n               (p[2] << 8) | p[3]);\n            basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) |\n               (p[6] << 8) | p[7]);\n            basi_color_type=p[8];\n            basi_compression_method=p[9];\n            basi_filter_type=p[10];\n            basi_interlace_method=p[11];\n            if (length > 11)\n              basi_red=(p[12] << 8) & p[13];\n\n            else\n              basi_red=0;\n\n            if (length > 13)\n              basi_green=(p[14] << 8) & p[15];\n\n            else\n              basi_green=0;\n\n            if (length > 15)\n              basi_blue=(p[16] << 8) & p[17];\n\n            else\n              basi_blue=0;\n\n            if (length > 17)\n              basi_alpha=(p[18] << 8) & p[19];\n\n            else\n              {\n                if (basi_sample_depth == 16)\n                  basi_alpha=65535L;\n                else\n                  basi_alpha=255;\n              }\n\n            if (length > 19)\n              basi_viewable=p[20];\n\n            else\n              basi_viewable=0;\n\n#endif\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_IHDR,4)\n#if defined(JNG_SUPPORTED)\n            && memcmp(type,mng_JHDR,4)\n#endif\n            )\n          {\n            /* Not an IHDR or JHDR chunk */\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            continue;\n          }\n/* Process IHDR */\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]);\n\n        mng_info->exists[object_id]=MagickTrue;\n        mng_info->viewable[object_id]=MagickTrue;\n\n        if (mng_info->invisible[object_id])\n          {\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Skipping invisible object\");\n\n            skip_to_iend=MagickTrue;\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n#if defined(MNG_INSERT_LAYERS)\n        if (length < 8)\n          {\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n          }\n\n        image_width=(size_t) mng_get_long(p);\n        image_height=(size_t) mng_get_long(&p[4]);\n#endif\n        chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n        /*\n          Insert a transparent background layer behind the entire animation\n          if it is not full screen.\n        */\n#if defined(MNG_INSERT_LAYERS)\n        if (insert_layers && mng_type && first_mng_object)\n          {\n            if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||\n                (image_width < mng_info->mng_width) ||\n                (mng_info->clip.right < (ssize_t) mng_info->mng_width) ||\n                (image_height < mng_info->mng_height) ||\n                (mng_info->clip.bottom < (ssize_t) mng_info->mng_height))\n              {\n                if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n                  {\n                    /*\n                      Allocate next image structure.\n                    */\n                    AcquireNextImage(image_info,image,exception);\n\n                    if (GetNextImageInList(image) == (Image *) NULL)\n                      return(DestroyImageList(image));\n\n                    image=SyncNextImageInList(image);\n                  }\n                mng_info->image=image;\n\n                if (term_chunk_found)\n                  {\n                    image->start_loop=MagickTrue;\n                    image->iterations=mng_iterations;\n                    term_chunk_found=MagickFalse;\n                  }\n\n                else\n                    image->start_loop=MagickFalse;\n\n                /* Make a background rectangle.  */\n\n                image->delay=0;\n                image->columns=mng_info->mng_width;\n                image->rows=mng_info->mng_height;\n                image->page.width=mng_info->mng_width;\n                image->page.height=mng_info->mng_height;\n                image->page.x=0;\n                image->page.y=0;\n                image->background_color=mng_background_color;\n                (void) SetImageBackgroundColor(image,exception);\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  Inserted transparent background layer, W=%.20g, H=%.20g\",\n                    (double) mng_info->mng_width,(double) mng_info->mng_height);\n              }\n          }\n        /*\n          Insert a background layer behind the upcoming image if\n          framing_mode is 3, and we haven't already inserted one.\n        */\n        if (insert_layers && (mng_info->framing_mode == 3) &&\n                (subframe_width) && (subframe_height) && (simplicity == 0 ||\n                (simplicity & 0x08)))\n          {\n            if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n            {\n              /*\n                Allocate next image structure.\n              */\n              AcquireNextImage(image_info,image,exception);\n\n              if (GetNextImageInList(image) == (Image *) NULL)\n                return(DestroyImageList(image));\n\n              image=SyncNextImageInList(image);\n            }\n\n            mng_info->image=image;\n\n            if (term_chunk_found)\n              {\n                image->start_loop=MagickTrue;\n                image->iterations=mng_iterations;\n                term_chunk_found=MagickFalse;\n              }\n\n            else\n                image->start_loop=MagickFalse;\n\n            image->delay=0;\n            image->columns=subframe_width;\n            image->rows=subframe_height;\n            image->page.width=subframe_width;\n            image->page.height=subframe_height;\n            image->page.x=mng_info->clip.left;\n            image->page.y=mng_info->clip.top;\n            image->background_color=mng_background_color;\n            image->alpha_trait=UndefinedPixelTrait;\n            (void) SetImageBackgroundColor(image,exception);\n\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\",\n                (double) mng_info->clip.left,(double) mng_info->clip.right,\n                (double) mng_info->clip.top,(double) mng_info->clip.bottom);\n          }\n#endif /* MNG_INSERT_LAYERS */\n        first_mng_object=MagickFalse;\n\n        if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n          {\n            /*\n              Allocate next image structure.\n            */\n            AcquireNextImage(image_info,image,exception);\n\n            if (GetNextImageInList(image) == (Image *) NULL)\n              return(DestroyImageList(image));\n\n            image=SyncNextImageInList(image);\n          }\n        mng_info->image=image;\n        status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n          GetBlobSize(image));\n\n        if (status == MagickFalse)\n          break;\n\n        if (term_chunk_found)\n          {\n            image->start_loop=MagickTrue;\n            term_chunk_found=MagickFalse;\n          }\n\n        else\n            image->start_loop=MagickFalse;\n\n        if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)\n          {\n            image->delay=frame_delay;\n            frame_delay=default_frame_delay;\n          }\n\n        else\n          image->delay=0;\n\n        image->page.width=mng_info->mng_width;\n        image->page.height=mng_info->mng_height;\n        image->page.x=mng_info->x_off[object_id];\n        image->page.y=mng_info->y_off[object_id];\n        image->iterations=mng_iterations;\n\n        /*\n          Seek back to the beginning of the IHDR or JHDR chunk's length field.\n        */\n\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1],\n            type[2],type[3]);\n\n        offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);\n\n        if (offset < 0)\n          ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n\n    mng_info->image=image;\n    mng_info->mng_type=mng_type;\n    mng_info->object_id=object_id;\n\n    if (memcmp(type,mng_IHDR,4) == 0)\n      image=ReadOnePNGImage(mng_info,image_info,exception);\n\n#if defined(JNG_SUPPORTED)\n    else\n      image=ReadOneJNGImage(mng_info,image_info,exception);\n#endif\n\n    if (image == (Image *) NULL)\n      {\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"exit ReadJNGImage() with error\");\n\n        return((Image *) NULL);\n      }\n\n    if (image->columns == 0 || image->rows == 0)\n      {\n        (void) CloseBlob(image);\n        return(DestroyImageList(image));\n      }\n\n    mng_info->image=image;\n\n    if (mng_type)\n      {\n        MngBox\n          crop_box;\n\n        if (mng_info->magn_methx || mng_info->magn_methy)\n          {\n            png_uint_32\n               magnified_height,\n               magnified_width;\n\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Processing MNG MAGN chunk\");\n\n            if (mng_info->magn_methx == 1)\n              {\n                magnified_width=mng_info->magn_ml;\n\n                if (image->columns > 1)\n                   magnified_width += mng_info->magn_mr;\n\n                if (image->columns > 2)\n                   magnified_width += (png_uint_32)\n                      ((image->columns-2)*(mng_info->magn_mx));\n              }\n\n            else\n              {\n                magnified_width=(png_uint_32) image->columns;\n\n                if (image->columns > 1)\n                   magnified_width += mng_info->magn_ml-1;\n\n                if (image->columns > 2)\n                   magnified_width += mng_info->magn_mr-1;\n\n                if (image->columns > 3)\n                   magnified_width += (png_uint_32)\n                      ((image->columns-3)*(mng_info->magn_mx-1));\n              }\n\n            if (mng_info->magn_methy == 1)\n              {\n                magnified_height=mng_info->magn_mt;\n\n                if (image->rows > 1)\n                   magnified_height += mng_info->magn_mb;\n\n                if (image->rows > 2)\n                   magnified_height += (png_uint_32)\n                      ((image->rows-2)*(mng_info->magn_my));\n              }\n\n            else\n              {\n                magnified_height=(png_uint_32) image->rows;\n\n                if (image->rows > 1)\n                   magnified_height += mng_info->magn_mt-1;\n\n                if (image->rows > 2)\n                   magnified_height += mng_info->magn_mb-1;\n\n                if (image->rows > 3)\n                   magnified_height += (png_uint_32)\n                      ((image->rows-3)*(mng_info->magn_my-1));\n              }\n\n            if (magnified_height > image->rows ||\n                magnified_width > image->columns)\n              {\n                Image\n                  *large_image;\n\n                int\n                  yy;\n\n                Quantum\n                  *next,\n                  *prev;\n\n                png_uint_16\n                  magn_methx,\n                  magn_methy;\n\n                ssize_t\n                  m,\n                  y;\n\n                register Quantum\n                  *n,\n                  *q;\n\n                register ssize_t\n                  x;\n\n                /* Allocate next image structure.  */\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"    Allocate magnified image\");\n\n                AcquireNextImage(image_info,image,exception);\n\n                if (GetNextImageInList(image) == (Image *) NULL)\n                  return(DestroyImageList(image));\n\n                large_image=SyncNextImageInList(image);\n\n                large_image->columns=magnified_width;\n                large_image->rows=magnified_height;\n\n                magn_methx=mng_info->magn_methx;\n                magn_methy=mng_info->magn_methy;\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n#define QM unsigned short\n                if (magn_methx != 1 || magn_methy != 1)\n                  {\n                  /*\n                     Scale pixels to unsigned shorts to prevent\n                     overflow of intermediate values of interpolations\n                  */\n                     for (y=0; y < (ssize_t) image->rows; y++)\n                     {\n                       q=GetAuthenticPixels(image,0,y,image->columns,1,\n                          exception);\n\n                       for (x=(ssize_t) image->columns-1; x >= 0; x--)\n                       {\n                          SetPixelRed(image,ScaleQuantumToShort(\n                            GetPixelRed(image,q)),q);\n                          SetPixelGreen(image,ScaleQuantumToShort(\n                            GetPixelGreen(image,q)),q);\n                          SetPixelBlue(image,ScaleQuantumToShort(\n                            GetPixelBlue(image,q)),q);\n                          SetPixelAlpha(image,ScaleQuantumToShort(\n                            GetPixelAlpha(image,q)),q);\n                          q+=GetPixelChannels(image);\n                       }\n\n                       if (SyncAuthenticPixels(image,exception) == MagickFalse)\n                         break;\n                     }\n                  }\n#else\n#define QM Quantum\n#endif\n\n                if (image->alpha_trait != UndefinedPixelTrait)\n                   (void) SetImageBackgroundColor(large_image,exception);\n\n                else\n                  {\n                    large_image->background_color.alpha=OpaqueAlpha;\n                    (void) SetImageBackgroundColor(large_image,exception);\n\n                    if (magn_methx == 4)\n                      magn_methx=2;\n\n                    if (magn_methx == 5)\n                      magn_methx=3;\n\n                    if (magn_methy == 4)\n                      magn_methy=2;\n\n                    if (magn_methy == 5)\n                      magn_methy=3;\n                  }\n\n                /* magnify the rows into the right side of the large image */\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"    Magnify the rows to %.20g\",\n                    (double) large_image->rows);\n                m=(ssize_t) mng_info->magn_mt;\n                yy=0;\n                length=(size_t) GetPixelChannels(image)*image->columns;\n                next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next));\n                prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev));\n\n                if ((prev == (Quantum *) NULL) ||\n                    (next == (Quantum *) NULL))\n                  {\n                     image=DestroyImageList(image);\n                     ThrowReaderException(ResourceLimitError,\n                       \"MemoryAllocationFailed\");\n                  }\n\n                n=GetAuthenticPixels(image,0,0,image->columns,1,exception);\n                (void) CopyMagickMemory(next,n,length);\n\n                for (y=0; y < (ssize_t) image->rows; y++)\n                {\n                  if (y == 0)\n                    m=(ssize_t) mng_info->magn_mt;\n\n                  else if (magn_methy > 1 && y == (ssize_t) image->rows-2)\n                    m=(ssize_t) mng_info->magn_mb;\n\n                  else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)\n                    m=(ssize_t) mng_info->magn_mb;\n\n                  else if (magn_methy > 1 && y == (ssize_t) image->rows-1)\n                    m=1;\n\n                  else\n                    m=(ssize_t) mng_info->magn_my;\n\n                  n=prev;\n                  prev=next;\n                  next=n;\n\n                  if (y < (ssize_t) image->rows-1)\n                    {\n                      n=GetAuthenticPixels(image,0,y+1,image->columns,1,\n                          exception);\n                      (void) CopyMagickMemory(next,n,length);\n                    }\n\n                  for (i=0; i < m; i++, yy++)\n                  {\n                    register Quantum\n                      *pixels;\n\n                    assert(yy < (ssize_t) large_image->rows);\n                    pixels=prev;\n                    n=next;\n                    q=GetAuthenticPixels(large_image,0,yy,large_image->columns,\n                      1,exception);\n                    q+=(large_image->columns-image->columns)*\n                      GetPixelChannels(large_image);\n\n                    for (x=(ssize_t) image->columns-1; x >= 0; x--)\n                    {\n                      /* To do: get color as function of indexes[x] */\n                      /*\n                      if (image->storage_class == PseudoClass)\n                        {\n                        }\n                      */\n\n                      if (magn_methy <= 1)\n                        {\n                          /* replicate previous */\n                          SetPixelRed(large_image,GetPixelRed(image,pixels),q);\n                          SetPixelGreen(large_image,GetPixelGreen(image,\n                             pixels),q);\n                          SetPixelBlue(large_image,GetPixelBlue(image,\n                             pixels),q);\n                          SetPixelAlpha(large_image,GetPixelAlpha(image,\n                             pixels),q);\n                        }\n\n                      else if (magn_methy == 2 || magn_methy == 4)\n                        {\n                          if (i == 0)\n                            {\n                              SetPixelRed(large_image,GetPixelRed(image,\n                                 pixels),q);\n                              SetPixelGreen(large_image,GetPixelGreen(image,\n                                 pixels),q);\n                              SetPixelBlue(large_image,GetPixelBlue(image,\n                                 pixels),q);\n                              SetPixelAlpha(large_image,GetPixelAlpha(image,\n                                 pixels),q);\n                            }\n\n                          else\n                            {\n                              /* Interpolate */\n                              SetPixelRed(large_image,((QM) (((ssize_t)\n                                 (2*i*(GetPixelRed(image,n)\n                                 -GetPixelRed(image,pixels)+m))/\n                                 ((ssize_t) (m*2))\n                                 +GetPixelRed(image,pixels)))),q);\n                              SetPixelGreen(large_image,((QM) (((ssize_t)\n                                 (2*i*(GetPixelGreen(image,n)\n                                 -GetPixelGreen(image,pixels)+m))/\n                                 ((ssize_t) (m*2))\n                                 +GetPixelGreen(image,pixels)))),q);\n                              SetPixelBlue(large_image,((QM) (((ssize_t)\n                                 (2*i*(GetPixelBlue(image,n)\n                                 -GetPixelBlue(image,pixels)+m))/\n                                 ((ssize_t) (m*2))\n                                 +GetPixelBlue(image,pixels)))),q);\n\n                              if (image->alpha_trait != UndefinedPixelTrait)\n                                 SetPixelAlpha(large_image, ((QM) (((ssize_t)\n                                    (2*i*(GetPixelAlpha(image,n)\n                                    -GetPixelAlpha(image,pixels)+m))\n                                    /((ssize_t) (m*2))+\n                                   GetPixelAlpha(image,pixels)))),q);\n                            }\n\n                          if (magn_methy == 4)\n                            {\n                              /* Replicate nearest */\n                              if (i <= ((m+1) << 1))\n                                 SetPixelAlpha(large_image,GetPixelAlpha(image,\n                                    pixels),q);\n                              else\n                                 SetPixelAlpha(large_image,GetPixelAlpha(image,\n                                    n),q);\n                            }\n                        }\n\n                      else /* if (magn_methy == 3 || magn_methy == 5) */\n                        {\n                          /* Replicate nearest */\n                          if (i <= ((m+1) << 1))\n                          {\n                             SetPixelRed(large_image,GetPixelRed(image,\n                                    pixels),q);\n                             SetPixelGreen(large_image,GetPixelGreen(image,\n                                    pixels),q);\n                             SetPixelBlue(large_image,GetPixelBlue(image,\n                                    pixels),q);\n                             SetPixelAlpha(large_image,GetPixelAlpha(image,\n                                    pixels),q);\n                          }\n\n                          else\n                          {\n                             SetPixelRed(large_image,GetPixelRed(image,n),q);\n                             SetPixelGreen(large_image,GetPixelGreen(image,n),\n                                    q);\n                             SetPixelBlue(large_image,GetPixelBlue(image,n),\n                                    q);\n                             SetPixelAlpha(large_image,GetPixelAlpha(image,n),\n                                    q);\n                          }\n\n                          if (magn_methy == 5)\n                            {\n                              SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i*\n                                 (GetPixelAlpha(image,n)\n                                 -GetPixelAlpha(image,pixels))\n                                 +m))/((ssize_t) (m*2))\n                                 +GetPixelAlpha(image,pixels)),q);\n                            }\n                        }\n                      n+=GetPixelChannels(image);\n                      q+=GetPixelChannels(large_image);\n                      pixels+=GetPixelChannels(image);\n                    } /* x */\n\n                    if (SyncAuthenticPixels(large_image,exception) == 0)\n                      break;\n\n                  } /* i */\n                } /* y */\n\n                prev=(Quantum *) RelinquishMagickMemory(prev);\n                next=(Quantum *) RelinquishMagickMemory(next);\n\n                length=image->columns;\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"    Delete original image\");\n\n                DeleteImageFromList(&image);\n\n                image=large_image;\n\n                mng_info->image=image;\n\n                /* magnify the columns */\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"    Magnify the columns to %.20g\",\n                    (double) image->columns);\n\n                for (y=0; y < (ssize_t) image->rows; y++)\n                {\n                  register Quantum\n                    *pixels;\n\n                  q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n                  pixels=q+(image->columns-length)*GetPixelChannels(image);\n                  n=pixels+GetPixelChannels(image);\n\n                  for (x=(ssize_t) (image->columns-length);\n                    x < (ssize_t) image->columns; x++)\n                  {\n                    /* To do: Rewrite using Get/Set***PixelChannel() */\n\n                    if (x == (ssize_t) (image->columns-length))\n                      m=(ssize_t) mng_info->magn_ml;\n\n                    else if (magn_methx > 1 && x == (ssize_t) image->columns-2)\n                      m=(ssize_t) mng_info->magn_mr;\n\n                    else if (magn_methx <= 1 &&\n                        x == (ssize_t) image->columns-1)\n                      m=(ssize_t) mng_info->magn_mr;\n\n                    else if (magn_methx > 1 && x == (ssize_t) image->columns-1)\n                      m=1;\n\n                    else\n                      m=(ssize_t) mng_info->magn_mx;\n\n                    for (i=0; i < m; i++)\n                    {\n                      if (magn_methx <= 1)\n                        {\n                          /* replicate previous */\n                          SetPixelRed(image,GetPixelRed(image,pixels),q);\n                          SetPixelGreen(image,GetPixelGreen(image,pixels),q);\n                          SetPixelBlue(image,GetPixelBlue(image,pixels),q);\n                          SetPixelAlpha(image,GetPixelAlpha(image,pixels),q);\n                        }\n\n                      else if (magn_methx == 2 || magn_methx == 4)\n                        {\n                          if (i == 0)\n                          {\n                            SetPixelRed(image,GetPixelRed(image,pixels),q);\n                            SetPixelGreen(image,GetPixelGreen(image,pixels),q);\n                            SetPixelBlue(image,GetPixelBlue(image,pixels),q);\n                            SetPixelAlpha(image,GetPixelAlpha(image,pixels),q);\n                          }\n\n                          /* To do: Rewrite using Get/Set***PixelChannel() */\n                          else\n                            {\n                              /* Interpolate */\n                              SetPixelRed(image,(QM) ((2*i*(\n                                 GetPixelRed(image,n)\n                                 -GetPixelRed(image,pixels))+m)\n                                 /((ssize_t) (m*2))+\n                                 GetPixelRed(image,pixels)),q);\n\n                              SetPixelGreen(image,(QM) ((2*i*(\n                                 GetPixelGreen(image,n)\n                                 -GetPixelGreen(image,pixels))+m)\n                                 /((ssize_t) (m*2))+\n                                 GetPixelGreen(image,pixels)),q);\n\n                              SetPixelBlue(image,(QM) ((2*i*(\n                                 GetPixelBlue(image,n)\n                                 -GetPixelBlue(image,pixels))+m)\n                                 /((ssize_t) (m*2))+\n                                 GetPixelBlue(image,pixels)),q);\n                              if (image->alpha_trait != UndefinedPixelTrait)\n                                 SetPixelAlpha(image,(QM) ((2*i*(\n                                   GetPixelAlpha(image,n)\n                                   -GetPixelAlpha(image,pixels))+m)\n                                   /((ssize_t) (m*2))+\n                                   GetPixelAlpha(image,pixels)),q);\n                            }\n\n                          if (magn_methx == 4)\n                            {\n                              /* Replicate nearest */\n                              if (i <= ((m+1) << 1))\n                              {\n                                 SetPixelAlpha(image,\n                                   GetPixelAlpha(image,pixels)+0,q);\n                              }\n                              else\n                              {\n                                 SetPixelAlpha(image,\n                                   GetPixelAlpha(image,n)+0,q);\n                              }\n                            }\n                        }\n\n                      else /* if (magn_methx == 3 || magn_methx == 5) */\n                        {\n                          /* Replicate nearest */\n                          if (i <= ((m+1) << 1))\n                          {\n                             SetPixelRed(image,GetPixelRed(image,pixels),q);\n                             SetPixelGreen(image,GetPixelGreen(image,\n                                 pixels),q);\n                             SetPixelBlue(image,GetPixelBlue(image,pixels),q);\n                             SetPixelAlpha(image,GetPixelAlpha(image,\n                                 pixels),q);\n                          }\n\n                          else\n                          {\n                             SetPixelRed(image,GetPixelRed(image,n),q);\n                             SetPixelGreen(image,GetPixelGreen(image,n),q);\n                             SetPixelBlue(image,GetPixelBlue(image,n),q);\n                             SetPixelAlpha(image,GetPixelAlpha(image,n),q);\n                          }\n\n                          if (magn_methx == 5)\n                            {\n                              /* Interpolate */\n                              SetPixelAlpha(image,\n                                 (QM) ((2*i*( GetPixelAlpha(image,n)\n                                 -GetPixelAlpha(image,pixels))+m)/\n                                 ((ssize_t) (m*2))\n                                 +GetPixelAlpha(image,pixels)),q);\n                            }\n                        }\n                      q+=GetPixelChannels(image);\n                    }\n                    n+=GetPixelChannels(image);\n                  }\n\n                  if (SyncAuthenticPixels(image,exception) == MagickFalse)\n                    break;\n                }\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n              if (magn_methx != 1 || magn_methy != 1)\n                {\n                /*\n                   Rescale pixels to Quantum\n                */\n                   for (y=0; y < (ssize_t) image->rows; y++)\n                   {\n                     q=GetAuthenticPixels(image,0,y,image->columns,1,\n                       exception);\n\n                     for (x=(ssize_t) image->columns-1; x >= 0; x--)\n                     {\n                        SetPixelRed(image,ScaleShortToQuantum(\n                          GetPixelRed(image,q)),q);\n                        SetPixelGreen(image,ScaleShortToQuantum(\n                          GetPixelGreen(image,q)),q);\n                        SetPixelBlue(image,ScaleShortToQuantum(\n                          GetPixelBlue(image,q)),q);\n                        SetPixelAlpha(image,ScaleShortToQuantum(\n                          GetPixelAlpha(image,q)),q);\n                        q+=GetPixelChannels(image);\n                     }\n\n                     if (SyncAuthenticPixels(image,exception) == MagickFalse)\n                       break;\n                   }\n                }\n#endif\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  Finished MAGN processing\");\n              }\n          }\n\n        /*\n          Crop_box is with respect to the upper left corner of the MNG.\n        */\n        crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];\n        crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];\n        crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];\n        crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];\n        crop_box=mng_minimum_box(crop_box,mng_info->clip);\n        crop_box=mng_minimum_box(crop_box,mng_info->frame);\n        crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);\n        if ((crop_box.left != (mng_info->image_box.left\n            +mng_info->x_off[object_id])) ||\n            (crop_box.right != (mng_info->image_box.right\n            +mng_info->x_off[object_id])) ||\n            (crop_box.top != (mng_info->image_box.top\n            +mng_info->y_off[object_id])) ||\n            (crop_box.bottom != (mng_info->image_box.bottom\n            +mng_info->y_off[object_id])))\n          {\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Crop the PNG image\");\n\n            if ((crop_box.left < crop_box.right) &&\n                (crop_box.top < crop_box.bottom))\n              {\n                Image\n                  *im;\n\n                RectangleInfo\n                  crop_info;\n\n                /*\n                  Crop_info is with respect to the upper left corner of\n                  the image.\n                */\n                crop_info.x=(crop_box.left-mng_info->x_off[object_id]);\n                crop_info.y=(crop_box.top-mng_info->y_off[object_id]);\n                crop_info.width=(size_t) (crop_box.right-crop_box.left);\n                crop_info.height=(size_t) (crop_box.bottom-crop_box.top);\n                image->page.width=image->columns;\n                image->page.height=image->rows;\n                image->page.x=0;\n                image->page.y=0;\n                im=CropImage(image,&crop_info,exception);\n\n                if (im != (Image *) NULL)\n                  {\n                    image->columns=im->columns;\n                    image->rows=im->rows;\n                    im=DestroyImage(im);\n                    image->page.width=image->columns;\n                    image->page.height=image->rows;\n                    image->page.x=crop_box.left;\n                    image->page.y=crop_box.top;\n                  }\n              }\n\n            else\n              {\n                /*\n                  No pixels in crop area.  The MNG spec still requires\n                  a layer, though, so make a single transparent pixel in\n                  the top left corner.\n                */\n                image->columns=1;\n                image->rows=1;\n                image->colors=2;\n                (void) SetImageBackgroundColor(image,exception);\n                image->page.width=1;\n                image->page.height=1;\n                image->page.x=0;\n                image->page.y=0;\n              }\n          }\n#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED\n        image=mng_info->image;\n#endif\n      }\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n      /* PNG does not handle depths greater than 16 so reduce it even\n       * if lossy.\n       */\n      if (image->depth > 16)\n         image->depth=16;\n#endif\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 8)\n      if (image->depth > 8)\n        {\n          /* To do: fill low byte properly */\n          image->depth=16;\n        }\n\n      if (LosslessReduceDepthOK(image,exception) != MagickFalse)\n         image->depth = 8;\n#endif\n\n      if (image_info->number_scenes != 0)\n        {\n          if (mng_info->scenes_found >\n             (ssize_t) (image_info->first_scene+image_info->number_scenes))\n            break;\n        }\n\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"  Finished reading image datastream.\");\n\n  } while (LocaleCompare(image_info->magick,\"MNG\") == 0);\n\n  (void) CloseBlob(image);\n\n  if (logging != MagickFalse)\n    (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n      \"  Finished reading all image datastreams.\");\n\n#if defined(MNG_INSERT_LAYERS)\n  if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&\n       (mng_info->mng_height))\n    {\n      /*\n        Insert a background layer if nothing else was found.\n      */\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"  No images found.  Inserting a background layer.\");\n\n      if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n        {\n          /*\n            Allocate next image structure.\n          */\n          AcquireNextImage(image_info,image,exception);\n          if (GetNextImageInList(image) == (Image *) NULL)\n            {\n              if (logging != MagickFalse)\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Allocation failed, returning NULL.\");\n\n              return(DestroyImageList(image));;\n            }\n          image=SyncNextImageInList(image);\n        }\n      image->columns=mng_info->mng_width;\n      image->rows=mng_info->mng_height;\n      image->page.width=mng_info->mng_width;\n      image->page.height=mng_info->mng_height;\n      image->page.x=0;\n      image->page.y=0;\n      image->background_color=mng_background_color;\n      image->alpha_trait=UndefinedPixelTrait;\n\n      if (image_info->ping == MagickFalse)\n        (void) SetImageBackgroundColor(image,exception);\n\n      mng_info->image_found++;\n    }\n#endif\n  image->iterations=mng_iterations;\n\n  if (mng_iterations == 1)\n    image->start_loop=MagickTrue;\n\n  while (GetPreviousImageInList(image) != (Image *) NULL)\n  {\n    image_count++;\n    if (image_count > 10*mng_info->image_found)\n      {\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  No beginning\");\n\n        (void) ThrowMagickException(exception,GetMagickModule(),\n          CoderError,\"Linked list is corrupted, beginning of list not found\",\n          \"`%s'\",image_info->filename);\n\n        return(DestroyImageList(image));\n      }\n\n    image=GetPreviousImageInList(image);\n\n    if (GetNextImageInList(image) == (Image *) NULL)\n      {\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  Corrupt list\");\n\n        (void) ThrowMagickException(exception,GetMagickModule(),\n          CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\",\n          image_info->filename);\n      }\n  }\n\n  if (mng_info->ticks_per_second && mng_info->image_found > 1 &&\n             GetNextImageInList(image) ==\n     (Image *) NULL)\n    {\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  First image null\");\n\n      (void) ThrowMagickException(exception,GetMagickModule(),\n        CoderError,\"image->next for first image is NULL but shouldn't be.\",\n        \"`%s'\",image_info->filename);\n    }\n\n  if (mng_info->image_found == 0)\n    {\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"  No visible images found.\");\n\n      (void) ThrowMagickException(exception,GetMagickModule(),\n        CoderError,\"No visible images in file\",\"`%s'\",image_info->filename);\n\n      return(DestroyImageList(image));\n    }\n\n  if (mng_info->ticks_per_second)\n    final_delay=1UL*MagickMax(image->ticks_per_second,1L)*\n            final_delay/mng_info->ticks_per_second;\n\n  else\n    image->start_loop=MagickTrue;\n\n  /* Find final nonzero image delay */\n  final_image_delay=0;\n\n  while (GetNextImageInList(image) != (Image *) NULL)\n    {\n      if (image->delay)\n        final_image_delay=image->delay;\n\n      image=GetNextImageInList(image);\n    }\n\n  if (final_delay < final_image_delay)\n    final_delay=final_image_delay;\n\n  image->delay=final_delay;\n\n  if (logging != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"  image->delay=%.20g, final_delay=%.20g\",(double) image->delay,\n        (double) final_delay);\n\n  if (logging != MagickFalse)\n    {\n      int\n        scene;\n\n      scene=0;\n      image=GetFirstImageInList(image);\n\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"  Before coalesce:\");\n\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"    scene 0 delay=%.20g\",(double) image->delay);\n\n      while (GetNextImageInList(image) != (Image *) NULL)\n      {\n        image=GetNextImageInList(image);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"    scene %.20g delay=%.20g\",(double) scene++,\n          (double) image->delay);\n      }\n    }\n\n  image=GetFirstImageInList(image);\n#ifdef MNG_COALESCE_LAYERS\n  if (insert_layers)\n    {\n      Image\n        *next_image,\n        *next;\n\n      size_t\n        scene;\n\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"  Coalesce Images\");\n\n      scene=image->scene;\n      next_image=CoalesceImages(image,exception);\n\n      if (next_image == (Image *) NULL)\n        ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n      image=DestroyImageList(image);\n      image=next_image;\n\n      for (next=image; next != (Image *) NULL; next=next_image)\n      {\n         next->page.width=mng_info->mng_width;\n         next->page.height=mng_info->mng_height;\n         next->page.x=0;\n         next->page.y=0;\n         next->scene=scene++;\n         next_image=GetNextImageInList(next);\n\n         if (next_image == (Image *) NULL)\n           break;\n\n         if (next->delay == 0)\n           {\n             scene--;\n             next_image->previous=GetPreviousImageInList(next);\n             if (GetPreviousImageInList(next) == (Image *) NULL)\n               image=next_image;\n             else\n               next->previous->next=next_image;\n             next=DestroyImage(next);\n           }\n      }\n    }\n#endif\n\n  while (GetNextImageInList(image) != (Image *) NULL)\n      image=GetNextImageInList(image);\n\n  image->dispose=BackgroundDispose;\n\n  if (logging != MagickFalse)\n    {\n      int\n        scene;\n\n      scene=0;\n      image=GetFirstImageInList(image);\n\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"  After coalesce:\");\n\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"    scene 0 delay=%.20g dispose=%.20g\",(double) image->delay,\n        (double) image->dispose);\n\n      while (GetNextImageInList(image) != (Image *) NULL)\n      {\n        image=GetNextImageInList(image);\n\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"    scene %.20g delay=%.20g dispose=%.20g\",(double) scene++,\n          (double) image->delay,(double) image->dispose);\n      }\n   }\n\n  if (logging != MagickFalse)\n    (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n      \"  exit ReadOneMNGImage();\");\n\n  return(image);\n}", "func_hash": 112335411773175147602521832461985951659, "file_name": "png.c", "file_hash": 320300249685897026258566713334395171716, "cwe": ["CWE-125"], "cve": "CVE-2017-13139", "cve_desc": "In ImageMagick before 6.9.9-0 and 7.x before 7.0.6-1, the ReadOneMNGImage function in coders/png.c has an out-of-bounds read with the MNG CLIP chunk.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-13139"}
{"idx": 234875, "project": "ImageMagick", "commit_id": "d072ed6aff835c174e856ce3a428163c0da9e8f4", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/d072ed6aff835c174e856ce3a428163c0da9e8f4", "commit_message": "Skip MNG CLIP chunk with out-of-range object IDs", "target": 0, "func": "static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,\n     ExceptionInfo *exception)\n{\n  char\n    page_geometry[MagickPathExtent];\n\n  Image\n    *image;\n\n  MagickBooleanType\n    logging;\n\n  volatile int\n    first_mng_object,\n    object_id,\n    term_chunk_found,\n    skip_to_iend;\n\n  volatile ssize_t\n    image_count=0;\n\n  MagickBooleanType\n    status;\n\n  MagickOffsetType\n    offset;\n\n  MngBox\n    default_fb,\n    fb,\n    previous_fb;\n\n#if defined(MNG_INSERT_LAYERS)\n  PixelInfo\n    mng_background_color;\n#endif\n\n  register unsigned char\n    *p;\n\n  register ssize_t\n    i;\n\n  size_t\n    count;\n\n  ssize_t\n    loop_level;\n\n  volatile short\n    skipping_loop;\n\n#if defined(MNG_INSERT_LAYERS)\n  unsigned int\n    mandatory_back=0;\n#endif\n\n  volatile unsigned int\n#ifdef MNG_OBJECT_BUFFERS\n    mng_background_object=0,\n#endif\n    mng_type=0;   /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */\n\n  size_t\n    default_frame_timeout,\n    frame_timeout,\n#if defined(MNG_INSERT_LAYERS)\n    image_height,\n    image_width,\n#endif\n    length;\n\n  /* These delays are all measured in image ticks_per_second,\n   * not in MNG ticks_per_second\n   */\n  volatile size_t\n    default_frame_delay,\n    final_delay,\n    final_image_delay,\n    frame_delay,\n#if defined(MNG_INSERT_LAYERS)\n    insert_layers,\n#endif\n    mng_iterations=1,\n    simplicity=0,\n    subframe_height=0,\n    subframe_width=0;\n\n  previous_fb.top=0;\n  previous_fb.bottom=0;\n  previous_fb.left=0;\n  previous_fb.right=0;\n  default_fb.top=0;\n  default_fb.bottom=0;\n  default_fb.left=0;\n  default_fb.right=0;\n\n  logging=LogMagickEvent(CoderEvent,GetMagickModule(),\n    \"  Enter ReadOneMNGImage()\");\n\n  image=mng_info->image;\n\n  if (LocaleCompare(image_info->magick,\"MNG\") == 0)\n    {\n      char\n        magic_number[MagickPathExtent];\n\n      /* Verify MNG signature.  */\n      count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);\n      if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0)\n        ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n      /* Initialize some nonzero members of the MngInfo structure.  */\n      for (i=0; i < MNG_MAX_OBJECTS; i++)\n      {\n        mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;\n        mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;\n      }\n      mng_info->exists[0]=MagickTrue;\n    }\n\n  skipping_loop=(-1);\n  first_mng_object=MagickTrue;\n  mng_type=0;\n#if defined(MNG_INSERT_LAYERS)\n  insert_layers=MagickFalse; /* should be False during convert or mogrify */\n#endif\n  default_frame_delay=0;\n  default_frame_timeout=0;\n  frame_delay=0;\n  final_delay=1;\n  mng_info->ticks_per_second=1UL*image->ticks_per_second;\n  object_id=0;\n  skip_to_iend=MagickFalse;\n  term_chunk_found=MagickFalse;\n  mng_info->framing_mode=1;\n#if defined(MNG_INSERT_LAYERS)\n  mandatory_back=MagickFalse;\n#endif\n#if defined(MNG_INSERT_LAYERS)\n  mng_background_color=image->background_color;\n#endif\n  default_fb=mng_info->frame;\n  previous_fb=mng_info->frame;\n  do\n  {\n    char\n      type[MagickPathExtent];\n\n    if (LocaleCompare(image_info->magick,\"MNG\") == 0)\n      {\n        unsigned char\n          *chunk;\n\n        /*\n          Read a new chunk.\n        */\n        type[0]='\\0';\n        (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent);\n        length=ReadBlobMSBLong(image);\n        count=(size_t) ReadBlob(image,4,(unsigned char *) type);\n\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n           \"  Reading MNG chunk type %c%c%c%c, length: %.20g\",\n           type[0],type[1],type[2],type[3],(double) length);\n\n        if (length > PNG_UINT_31_MAX)\n          {\n            status=MagickFalse;\n            break;\n          }\n\n        if (count == 0)\n          ThrowReaderException(CorruptImageError,\"CorruptImage\");\n\n        p=NULL;\n        chunk=(unsigned char *) NULL;\n\n        if (length != 0)\n          {\n            if (length > GetBlobSize(image))\n              ThrowReaderException(CorruptImageError,\n                \"InsufficientImageDataInFile\");\n            chunk=(unsigned char *) AcquireQuantumMemory(length+\n             MagickPathExtent,sizeof(*chunk));\n\n            if (chunk == (unsigned char *) NULL)\n              ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n            for (i=0; i < (ssize_t) length; i++)\n            {\n              int\n                c;\n\n              c=ReadBlobByte(image);\n              if (c == EOF)\n                break;\n              chunk[i]=(unsigned char) c;\n            }\n\n            p=chunk;\n          }\n\n        (void) ReadBlobMSBLong(image);  /* read crc word */\n\n#if !defined(JNG_SUPPORTED)\n        if (memcmp(type,mng_JHDR,4) == 0)\n          {\n            skip_to_iend=MagickTrue;\n\n            if (mng_info->jhdr_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename);\n\n            mng_info->jhdr_warning++;\n          }\n#endif\n        if (memcmp(type,mng_DHDR,4) == 0)\n          {\n            skip_to_iend=MagickTrue;\n\n            if (mng_info->dhdr_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename);\n\n            mng_info->dhdr_warning++;\n          }\n        if (memcmp(type,mng_MEND,4) == 0)\n          break;\n\n        if (skip_to_iend)\n          {\n            if (memcmp(type,mng_IEND,4) == 0)\n              skip_to_iend=MagickFalse;\n\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Skip to IEND.\");\n\n            continue;\n          }\n\n        if (memcmp(type,mng_MHDR,4) == 0)\n          {\n            if (length != 28)\n              {\n                chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n                ThrowReaderException(CorruptImageError,\"CorruptImage\");\n              }\n\n            mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |\n                (p[2] << 8) | p[3]);\n\n            mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |\n                (p[6] << 8) | p[7]);\n\n            if (logging != MagickFalse)\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  MNG width: %.20g\",(double) mng_info->mng_width);\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  MNG height: %.20g\",(double) mng_info->mng_height);\n              }\n\n            p+=8;\n            mng_info->ticks_per_second=(size_t) mng_get_long(p);\n\n            if (mng_info->ticks_per_second == 0)\n              default_frame_delay=0;\n\n            else\n              default_frame_delay=1UL*image->ticks_per_second/\n                mng_info->ticks_per_second;\n\n            frame_delay=default_frame_delay;\n            simplicity=0;\n\n            p+=16;\n            simplicity=(size_t) mng_get_long(p);\n\n            mng_type=1;    /* Full MNG */\n\n            if ((simplicity != 0) && ((simplicity | 11) == 11))\n              mng_type=2; /* LC */\n\n            if ((simplicity != 0) && ((simplicity | 9) == 9))\n              mng_type=3; /* VLC */\n\n#if defined(MNG_INSERT_LAYERS)\n            if (mng_type != 3)\n              insert_layers=MagickTrue;\n#endif\n            if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n              {\n                /* Allocate next image structure.  */\n                AcquireNextImage(image_info,image,exception);\n\n                if (GetNextImageInList(image) == (Image *) NULL)\n                  return((Image *) NULL);\n\n                image=SyncNextImageInList(image);\n                mng_info->image=image;\n              }\n\n            if ((mng_info->mng_width > 65535L) ||\n                (mng_info->mng_height > 65535L))\n              {\n                chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n                ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\");\n              }\n\n            (void) FormatLocaleString(page_geometry,MagickPathExtent,\n              \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double)\n              mng_info->mng_height);\n\n            mng_info->frame.left=0;\n            mng_info->frame.right=(ssize_t) mng_info->mng_width;\n            mng_info->frame.top=0;\n            mng_info->frame.bottom=(ssize_t) mng_info->mng_height;\n            mng_info->clip=default_fb=previous_fb=mng_info->frame;\n\n            for (i=0; i < MNG_MAX_OBJECTS; i++)\n              mng_info->object_clip[i]=mng_info->frame;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_TERM,4) == 0)\n          {\n            int\n              repeat=0;\n\n            if (length != 0)\n              repeat=p[0];\n\n            if (repeat == 3)\n              {\n                final_delay=(png_uint_32) mng_get_long(&p[2]);\n                mng_iterations=(png_uint_32) mng_get_long(&p[6]);\n\n                if (mng_iterations == PNG_UINT_31_MAX)\n                  mng_iterations=0;\n\n                image->iterations=mng_iterations;\n                term_chunk_found=MagickTrue;\n              }\n\n            if (logging != MagickFalse)\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"    repeat=%d,  final_delay=%.20g,  iterations=%.20g\",\n                  repeat,(double) final_delay, (double) image->iterations);\n              }\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n        if (memcmp(type,mng_DEFI,4) == 0)\n          {\n            if (mng_type == 3)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\",\n                image->filename);\n\n            if (length < 2)\n              {\n                if (chunk)\n                  chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n                ThrowReaderException(CorruptImageError,\"CorruptImage\");\n              }\n\n            object_id=(p[0] << 8) | p[1];\n\n            if (mng_type == 2 && object_id != 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\",\n                image->filename);\n\n            if (object_id > MNG_MAX_OBJECTS)\n              {\n                /*\n                  Instead of using a warning we should allocate a larger\n                  MngInfo structure and continue.\n                */\n                (void) ThrowMagickException(exception,GetMagickModule(),\n                  CoderError,\"object id too large\",\"`%s'\",image->filename);\n                object_id=MNG_MAX_OBJECTS;\n              }\n\n            if (mng_info->exists[object_id])\n              if (mng_info->frozen[object_id])\n                {\n                  chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n                  (void) ThrowMagickException(exception,\n                    GetMagickModule(),CoderError,\n                    \"DEFI cannot redefine a frozen MNG object\",\"`%s'\",\n                    image->filename);\n                  continue;\n                }\n\n            mng_info->exists[object_id]=MagickTrue;\n\n            if (length > 2)\n              mng_info->invisible[object_id]=p[2];\n\n            /*\n              Extract object offset info.\n            */\n            if (length > 11)\n              {\n                mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) |\n                    (p[5] << 16) | (p[6] << 8) | p[7]);\n\n                mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) |\n                    (p[9] << 16) | (p[10] << 8) | p[11]);\n\n                if (logging != MagickFalse)\n                  {\n                    (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                      \"  x_off[%d]: %.20g,  y_off[%d]: %.20g\",\n                      object_id,(double) mng_info->x_off[object_id],\n                      object_id,(double) mng_info->y_off[object_id]);\n                  }\n              }\n\n            /*\n              Extract object clipping info.\n            */\n            if (length > 27)\n              mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0,\n                &p[12]);\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n        if (memcmp(type,mng_bKGD,4) == 0)\n          {\n            mng_info->have_global_bkgd=MagickFalse;\n\n            if (length > 5)\n              {\n                mng_info->mng_global_bkgd.red=\n                  ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));\n\n                mng_info->mng_global_bkgd.green=\n                  ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));\n\n                mng_info->mng_global_bkgd.blue=\n                  ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));\n\n                mng_info->have_global_bkgd=MagickTrue;\n              }\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n        if (memcmp(type,mng_BACK,4) == 0)\n          {\n#if defined(MNG_INSERT_LAYERS)\n            if (length > 6)\n              mandatory_back=p[6];\n\n            else\n              mandatory_back=0;\n\n            if (mandatory_back && length > 5)\n              {\n                mng_background_color.red=\n                    ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));\n\n                mng_background_color.green=\n                    ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));\n\n                mng_background_color.blue=\n                    ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));\n\n                mng_background_color.alpha=OpaqueAlpha;\n              }\n\n#ifdef MNG_OBJECT_BUFFERS\n            if (length > 8)\n              mng_background_object=(p[7] << 8) | p[8];\n#endif\n#endif\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_PLTE,4) == 0)\n          {\n            /* Read global PLTE.  */\n\n            if (length && (length < 769))\n              {\n                if (mng_info->global_plte == (png_colorp) NULL)\n                  mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,\n                    sizeof(*mng_info->global_plte));\n\n                for (i=0; i < (ssize_t) (length/3); i++)\n                {\n                  mng_info->global_plte[i].red=p[3*i];\n                  mng_info->global_plte[i].green=p[3*i+1];\n                  mng_info->global_plte[i].blue=p[3*i+2];\n                }\n\n                mng_info->global_plte_length=(unsigned int) (length/3);\n              }\n#ifdef MNG_LOOSE\n            for ( ; i < 256; i++)\n            {\n              mng_info->global_plte[i].red=i;\n              mng_info->global_plte[i].green=i;\n              mng_info->global_plte[i].blue=i;\n            }\n\n            if (length != 0)\n              mng_info->global_plte_length=256;\n#endif\n            else\n              mng_info->global_plte_length=0;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_tRNS,4) == 0)\n          {\n            /* read global tRNS */\n\n            if (length > 0 && length < 257)\n              for (i=0; i < (ssize_t) length; i++)\n                mng_info->global_trns[i]=p[i];\n\n#ifdef MNG_LOOSE\n            for ( ; i < 256; i++)\n              mng_info->global_trns[i]=255;\n#endif\n            mng_info->global_trns_length=(unsigned int) length;\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n        if (memcmp(type,mng_gAMA,4) == 0)\n          {\n            if (length == 4)\n              {\n                ssize_t\n                  igamma;\n\n                igamma=mng_get_long(p);\n                mng_info->global_gamma=((float) igamma)*0.00001;\n                mng_info->have_global_gama=MagickTrue;\n              }\n\n            else\n              mng_info->have_global_gama=MagickFalse;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_cHRM,4) == 0)\n          {\n            /* Read global cHRM */\n\n            if (length == 32)\n              {\n                mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);\n                mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);\n                mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);\n                mng_info->global_chrm.red_primary.y=0.00001*\n                  mng_get_long(&p[12]);\n                mng_info->global_chrm.green_primary.x=0.00001*\n                  mng_get_long(&p[16]);\n                mng_info->global_chrm.green_primary.y=0.00001*\n                  mng_get_long(&p[20]);\n                mng_info->global_chrm.blue_primary.x=0.00001*\n                  mng_get_long(&p[24]);\n                mng_info->global_chrm.blue_primary.y=0.00001*\n                  mng_get_long(&p[28]);\n                mng_info->have_global_chrm=MagickTrue;\n              }\n            else\n              mng_info->have_global_chrm=MagickFalse;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_sRGB,4) == 0)\n          {\n            /*\n              Read global sRGB.\n            */\n            if (length != 0)\n              {\n                mng_info->global_srgb_intent=\n                  Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);\n                mng_info->have_global_srgb=MagickTrue;\n              }\n            else\n              mng_info->have_global_srgb=MagickFalse;\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_iCCP,4) == 0)\n          {\n            /* To do: */\n\n            /*\n              Read global iCCP.\n            */\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            continue;\n          }\n\n        if (memcmp(type,mng_FRAM,4) == 0)\n          {\n            if (mng_type == 3)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\",\n                image->filename);\n\n            if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))\n              image->delay=frame_delay;\n\n            frame_delay=default_frame_delay;\n            frame_timeout=default_frame_timeout;\n            fb=default_fb;\n\n            if (length != 0)\n              if (p[0])\n                mng_info->framing_mode=p[0];\n\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"    Framing_mode=%d\",mng_info->framing_mode);\n\n            if (length > 6)\n              {\n                /* Note the delay and frame clipping boundaries.  */\n\n                p++; /* framing mode */\n\n                while (*p && ((p-chunk) < (ssize_t) length))\n                  p++;  /* frame name */\n\n                p++;  /* frame name terminator */\n\n                if ((p-chunk) < (ssize_t) (length-4))\n                  {\n                    int\n                      change_delay,\n                      change_timeout,\n                      change_clipping;\n\n                    change_delay=(*p++);\n                    change_timeout=(*p++);\n                    change_clipping=(*p++);\n                    p++; /* change_sync */\n\n                    if (change_delay)\n                      {\n                        frame_delay=1UL*image->ticks_per_second*\n                          mng_get_long(p);\n\n                        if (mng_info->ticks_per_second != 0)\n                          frame_delay/=mng_info->ticks_per_second;\n\n                        else\n                          frame_delay=PNG_UINT_31_MAX;\n\n                        if (change_delay == 2)\n                          default_frame_delay=frame_delay;\n\n                        p+=4;\n\n                        if (logging != MagickFalse)\n                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                            \"    Framing_delay=%.20g\",(double) frame_delay);\n                      }\n\n                    if (change_timeout)\n                      {\n                        frame_timeout=1UL*image->ticks_per_second*\n                          mng_get_long(p);\n\n                        if (mng_info->ticks_per_second != 0)\n                          frame_timeout/=mng_info->ticks_per_second;\n\n                        else\n                          frame_timeout=PNG_UINT_31_MAX;\n\n                        if (change_timeout == 2)\n                          default_frame_timeout=frame_timeout;\n\n                        p+=4;\n\n                        if (logging != MagickFalse)\n                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                            \"    Framing_timeout=%.20g\",(double) frame_timeout);\n                      }\n\n                    if (change_clipping)\n                      {\n                        fb=mng_read_box(previous_fb,(char) p[0],&p[1]);\n                        p+=17;\n                        previous_fb=fb;\n\n                        if (logging != MagickFalse)\n                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                            \"    Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\",\n                            (double) fb.left,(double) fb.right,(double) fb.top,\n                            (double) fb.bottom);\n\n                        if (change_clipping == 2)\n                          default_fb=fb;\n                      }\n                  }\n              }\n            mng_info->clip=fb;\n            mng_info->clip=mng_minimum_box(fb,mng_info->frame);\n\n            subframe_width=(size_t) (mng_info->clip.right\n               -mng_info->clip.left);\n\n            subframe_height=(size_t) (mng_info->clip.bottom\n               -mng_info->clip.top);\n            /*\n              Insert a background layer behind the frame if framing_mode is 4.\n            */\n#if defined(MNG_INSERT_LAYERS)\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"   subframe_width=%.20g, subframe_height=%.20g\",(double)\n                subframe_width,(double) subframe_height);\n\n            if (insert_layers && (mng_info->framing_mode == 4) &&\n                (subframe_width) && (subframe_height))\n              {\n                /* Allocate next image structure.  */\n                if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n                  {\n                    AcquireNextImage(image_info,image,exception);\n\n                    if (GetNextImageInList(image) == (Image *) NULL)\n                      return(DestroyImageList(image));\n\n                    image=SyncNextImageInList(image);\n                  }\n\n                mng_info->image=image;\n\n                if (term_chunk_found)\n                  {\n                    image->start_loop=MagickTrue;\n                    image->iterations=mng_iterations;\n                    term_chunk_found=MagickFalse;\n                  }\n\n                else\n                    image->start_loop=MagickFalse;\n\n                image->columns=subframe_width;\n                image->rows=subframe_height;\n                image->page.width=subframe_width;\n                image->page.height=subframe_height;\n                image->page.x=mng_info->clip.left;\n                image->page.y=mng_info->clip.top;\n                image->background_color=mng_background_color;\n                image->alpha_trait=UndefinedPixelTrait;\n                image->delay=0;\n                (void) SetImageBackgroundColor(image,exception);\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\",\n                    (double) mng_info->clip.left,\n                    (double) mng_info->clip.right,\n                    (double) mng_info->clip.top,\n                    (double) mng_info->clip.bottom);\n              }\n#endif\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_CLIP,4) == 0)\n          {\n            unsigned int\n              first_object,\n              last_object;\n\n            /*\n              Read CLIP.\n            */\n            if (length > 3)\n              {\n                first_object=(p[0] << 8) | p[1];\n                last_object=(p[2] << 8) | p[3];\n                p+=4;\n\n                for (i=(int) first_object; i <= (int) last_object; i++)\n                {\n                  if ((i < 0) || (i >= MNG_MAX_OBJECTS))\n                    continue;\n\n                  if (mng_info->exists[i] && !mng_info->frozen[i])\n                    {\n                      MngBox\n                        box;\n\n                      box=mng_info->object_clip[i];\n                      if ((p-chunk) < (ssize_t) (length-17))\n                        mng_info->object_clip[i]=\n                           mng_read_box(box,(char) p[0],&p[1]);\n                    }\n                }\n\n              }\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_SAVE,4) == 0)\n          {\n            for (i=1; i < MNG_MAX_OBJECTS; i++)\n              if (mng_info->exists[i])\n                {\n                 mng_info->frozen[i]=MagickTrue;\n#ifdef MNG_OBJECT_BUFFERS\n                 if (mng_info->ob[i] != (MngBuffer *) NULL)\n                    mng_info->ob[i]->frozen=MagickTrue;\n#endif\n                }\n\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            continue;\n          }\n\n        if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))\n          {\n            /* Read DISC or SEEK.  */\n\n            if ((length == 0) || !memcmp(type,mng_SEEK,4))\n              {\n                for (i=1; i < MNG_MAX_OBJECTS; i++)\n                  MngInfoDiscardObject(mng_info,i);\n              }\n\n            else\n              {\n                register ssize_t\n                  j;\n\n                for (j=1; j < (ssize_t) length; j+=2)\n                {\n                  i=p[j-1] << 8 | p[j];\n                  MngInfoDiscardObject(mng_info,i);\n                }\n              }\n\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            continue;\n          }\n\n        if (memcmp(type,mng_MOVE,4) == 0)\n          {\n            size_t\n              first_object,\n              last_object;\n\n            /* read MOVE */\n\n            if (length > 3)\n            {\n              first_object=(p[0] << 8) | p[1];\n              last_object=(p[2] << 8) | p[3];\n              p+=4;\n\n              for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)\n              {\n                if ((i < 0) || (i >= MNG_MAX_OBJECTS))\n                  continue;\n\n                if (mng_info->exists[i] && !mng_info->frozen[i] &&\n                    (p-chunk) < (ssize_t) (length-8))\n                  {\n                    MngPair\n                      new_pair;\n\n                    MngPair\n                      old_pair;\n\n                    old_pair.a=mng_info->x_off[i];\n                    old_pair.b=mng_info->y_off[i];\n                    new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);\n                    mng_info->x_off[i]=new_pair.a;\n                    mng_info->y_off[i]=new_pair.b;\n                  }\n              }\n            }\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_LOOP,4) == 0)\n          {\n            ssize_t loop_iters=1;\n            if (length > 4)\n              {\n                loop_level=chunk[0];\n                mng_info->loop_active[loop_level]=1;  /* mark loop active */\n\n                /* Record starting point.  */\n                loop_iters=mng_get_long(&chunk[1]);\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  LOOP level %.20g has %.20g iterations \",\n                    (double) loop_level, (double) loop_iters);\n\n                if (loop_iters == 0)\n                  skipping_loop=loop_level;\n\n                else\n                  {\n                    mng_info->loop_jump[loop_level]=TellBlob(image);\n                    mng_info->loop_count[loop_level]=loop_iters;\n                  }\n\n                mng_info->loop_iteration[loop_level]=0;\n              }\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_ENDL,4) == 0)\n          {\n            if (length > 0)\n              {\n                loop_level=chunk[0];\n\n                if (skipping_loop > 0)\n                  {\n                    if (skipping_loop == loop_level)\n                      {\n                        /*\n                          Found end of zero-iteration loop.\n                        */\n                        skipping_loop=(-1);\n                        mng_info->loop_active[loop_level]=0;\n                      }\n                  }\n\n                else\n                  {\n                    if (mng_info->loop_active[loop_level] == 1)\n                      {\n                        mng_info->loop_count[loop_level]--;\n                        mng_info->loop_iteration[loop_level]++;\n\n                        if (logging != MagickFalse)\n                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                          \"  ENDL: LOOP level %.20g has %.20g remaining iters\",\n                            (double) loop_level,(double)\n                            mng_info->loop_count[loop_level]);\n\n                        if (mng_info->loop_count[loop_level] != 0)\n                          {\n                            offset=\n                              SeekBlob(image,mng_info->loop_jump[loop_level],\n                              SEEK_SET);\n\n                            if (offset < 0)\n                              {\n                                chunk=(unsigned char *) RelinquishMagickMemory(\n                                  chunk);\n                                ThrowReaderException(CorruptImageError,\n                                  \"ImproperImageHeader\");\n                              }\n                          }\n\n                        else\n                          {\n                            short\n                              last_level;\n\n                            /*\n                              Finished loop.\n                            */\n                            mng_info->loop_active[loop_level]=0;\n                            last_level=(-1);\n                            for (i=0; i < loop_level; i++)\n                              if (mng_info->loop_active[i] == 1)\n                                last_level=(short) i;\n                            loop_level=last_level;\n                          }\n                      }\n                  }\n              }\n\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_CLON,4) == 0)\n          {\n            if (mng_info->clon_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"CLON is not implemented yet\",\"`%s'\",\n                image->filename);\n\n            mng_info->clon_warning++;\n          }\n\n        if (memcmp(type,mng_MAGN,4) == 0)\n          {\n            png_uint_16\n              magn_first,\n              magn_last,\n              magn_mb,\n              magn_ml,\n              magn_mr,\n              magn_mt,\n              magn_mx,\n              magn_my,\n              magn_methx,\n              magn_methy;\n\n            if (length > 1)\n              magn_first=(p[0] << 8) | p[1];\n\n            else\n              magn_first=0;\n\n            if (length > 3)\n              magn_last=(p[2] << 8) | p[3];\n\n            else\n              magn_last=magn_first;\n#ifndef MNG_OBJECT_BUFFERS\n            if (magn_first || magn_last)\n              if (mng_info->magn_warning == 0)\n                {\n                  (void) ThrowMagickException(exception,\n                     GetMagickModule(),CoderError,\n                     \"MAGN is not implemented yet for nonzero objects\",\n                     \"`%s'\",image->filename);\n\n                   mng_info->magn_warning++;\n                }\n#endif\n            if (length > 4)\n              magn_methx=p[4];\n\n            else\n              magn_methx=0;\n\n            if (length > 6)\n              magn_mx=(p[5] << 8) | p[6];\n\n            else\n              magn_mx=1;\n\n            if (magn_mx == 0)\n              magn_mx=1;\n\n            if (length > 8)\n              magn_my=(p[7] << 8) | p[8];\n\n            else\n              magn_my=magn_mx;\n\n            if (magn_my == 0)\n              magn_my=1;\n\n            if (length > 10)\n              magn_ml=(p[9] << 8) | p[10];\n\n            else\n              magn_ml=magn_mx;\n\n            if (magn_ml == 0)\n              magn_ml=1;\n\n            if (length > 12)\n              magn_mr=(p[11] << 8) | p[12];\n\n            else\n              magn_mr=magn_mx;\n\n            if (magn_mr == 0)\n              magn_mr=1;\n\n            if (length > 14)\n              magn_mt=(p[13] << 8) | p[14];\n\n            else\n              magn_mt=magn_my;\n\n            if (magn_mt == 0)\n              magn_mt=1;\n\n            if (length > 16)\n              magn_mb=(p[15] << 8) | p[16];\n\n            else\n              magn_mb=magn_my;\n\n            if (magn_mb == 0)\n              magn_mb=1;\n\n            if (length > 17)\n              magn_methy=p[17];\n\n            else\n              magn_methy=magn_methx;\n\n\n            if (magn_methx > 5 || magn_methy > 5)\n              if (mng_info->magn_warning == 0)\n                {\n                  (void) ThrowMagickException(exception,\n                     GetMagickModule(),CoderError,\n                     \"Unknown MAGN method in MNG datastream\",\"`%s'\",\n                     image->filename);\n\n                   mng_info->magn_warning++;\n                }\n#ifdef MNG_OBJECT_BUFFERS\n          /* Magnify existing objects in the range magn_first to magn_last */\n#endif\n            if (magn_first == 0 || magn_last == 0)\n              {\n                /* Save the magnification factors for object 0 */\n                mng_info->magn_mb=magn_mb;\n                mng_info->magn_ml=magn_ml;\n                mng_info->magn_mr=magn_mr;\n                mng_info->magn_mt=magn_mt;\n                mng_info->magn_mx=magn_mx;\n                mng_info->magn_my=magn_my;\n                mng_info->magn_methx=magn_methx;\n                mng_info->magn_methy=magn_methy;\n              }\n          }\n\n        if (memcmp(type,mng_PAST,4) == 0)\n          {\n            if (mng_info->past_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"PAST is not implemented yet\",\"`%s'\",\n                image->filename);\n\n            mng_info->past_warning++;\n          }\n\n        if (memcmp(type,mng_SHOW,4) == 0)\n          {\n            if (mng_info->show_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"SHOW is not implemented yet\",\"`%s'\",\n                image->filename);\n\n            mng_info->show_warning++;\n          }\n\n        if (memcmp(type,mng_sBIT,4) == 0)\n          {\n            if (length < 4)\n              mng_info->have_global_sbit=MagickFalse;\n\n            else\n              {\n                mng_info->global_sbit.gray=p[0];\n                mng_info->global_sbit.red=p[0];\n                mng_info->global_sbit.green=p[1];\n                mng_info->global_sbit.blue=p[2];\n                mng_info->global_sbit.alpha=p[3];\n                mng_info->have_global_sbit=MagickTrue;\n             }\n          }\n        if (memcmp(type,mng_pHYs,4) == 0)\n          {\n            if (length > 8)\n              {\n                mng_info->global_x_pixels_per_unit=\n                    (size_t) mng_get_long(p);\n                mng_info->global_y_pixels_per_unit=\n                    (size_t) mng_get_long(&p[4]);\n                mng_info->global_phys_unit_type=p[8];\n                mng_info->have_global_phys=MagickTrue;\n              }\n\n            else\n              mng_info->have_global_phys=MagickFalse;\n          }\n        if (memcmp(type,mng_pHYg,4) == 0)\n          {\n            if (mng_info->phyg_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename);\n\n            mng_info->phyg_warning++;\n          }\n        if (memcmp(type,mng_BASI,4) == 0)\n          {\n            skip_to_iend=MagickTrue;\n\n            if (mng_info->basi_warning == 0)\n              (void) ThrowMagickException(exception,GetMagickModule(),\n                CoderError,\"BASI is not implemented yet\",\"`%s'\",\n                image->filename);\n\n            mng_info->basi_warning++;\n#ifdef MNG_BASI_SUPPORTED\n            basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) |\n               (p[2] << 8) | p[3]);\n            basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) |\n               (p[6] << 8) | p[7]);\n            basi_color_type=p[8];\n            basi_compression_method=p[9];\n            basi_filter_type=p[10];\n            basi_interlace_method=p[11];\n            if (length > 11)\n              basi_red=(p[12] << 8) & p[13];\n\n            else\n              basi_red=0;\n\n            if (length > 13)\n              basi_green=(p[14] << 8) & p[15];\n\n            else\n              basi_green=0;\n\n            if (length > 15)\n              basi_blue=(p[16] << 8) & p[17];\n\n            else\n              basi_blue=0;\n\n            if (length > 17)\n              basi_alpha=(p[18] << 8) & p[19];\n\n            else\n              {\n                if (basi_sample_depth == 16)\n                  basi_alpha=65535L;\n                else\n                  basi_alpha=255;\n              }\n\n            if (length > 19)\n              basi_viewable=p[20];\n\n            else\n              basi_viewable=0;\n\n#endif\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n\n        if (memcmp(type,mng_IHDR,4)\n#if defined(JNG_SUPPORTED)\n            && memcmp(type,mng_JHDR,4)\n#endif\n            )\n          {\n            /* Not an IHDR or JHDR chunk */\n            if (length != 0)\n              chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n            continue;\n          }\n/* Process IHDR */\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]);\n\n        mng_info->exists[object_id]=MagickTrue;\n        mng_info->viewable[object_id]=MagickTrue;\n\n        if (mng_info->invisible[object_id])\n          {\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Skipping invisible object\");\n\n            skip_to_iend=MagickTrue;\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            continue;\n          }\n#if defined(MNG_INSERT_LAYERS)\n        if (length < 8)\n          {\n            chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n            ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n          }\n\n        image_width=(size_t) mng_get_long(p);\n        image_height=(size_t) mng_get_long(&p[4]);\n#endif\n        chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n        /*\n          Insert a transparent background layer behind the entire animation\n          if it is not full screen.\n        */\n#if defined(MNG_INSERT_LAYERS)\n        if (insert_layers && mng_type && first_mng_object)\n          {\n            if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||\n                (image_width < mng_info->mng_width) ||\n                (mng_info->clip.right < (ssize_t) mng_info->mng_width) ||\n                (image_height < mng_info->mng_height) ||\n                (mng_info->clip.bottom < (ssize_t) mng_info->mng_height))\n              {\n                if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n                  {\n                    /*\n                      Allocate next image structure.\n                    */\n                    AcquireNextImage(image_info,image,exception);\n\n                    if (GetNextImageInList(image) == (Image *) NULL)\n                      return(DestroyImageList(image));\n\n                    image=SyncNextImageInList(image);\n                  }\n                mng_info->image=image;\n\n                if (term_chunk_found)\n                  {\n                    image->start_loop=MagickTrue;\n                    image->iterations=mng_iterations;\n                    term_chunk_found=MagickFalse;\n                  }\n\n                else\n                    image->start_loop=MagickFalse;\n\n                /* Make a background rectangle.  */\n\n                image->delay=0;\n                image->columns=mng_info->mng_width;\n                image->rows=mng_info->mng_height;\n                image->page.width=mng_info->mng_width;\n                image->page.height=mng_info->mng_height;\n                image->page.x=0;\n                image->page.y=0;\n                image->background_color=mng_background_color;\n                (void) SetImageBackgroundColor(image,exception);\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  Inserted transparent background layer, W=%.20g, H=%.20g\",\n                    (double) mng_info->mng_width,(double) mng_info->mng_height);\n              }\n          }\n        /*\n          Insert a background layer behind the upcoming image if\n          framing_mode is 3, and we haven't already inserted one.\n        */\n        if (insert_layers && (mng_info->framing_mode == 3) &&\n                (subframe_width) && (subframe_height) && (simplicity == 0 ||\n                (simplicity & 0x08)))\n          {\n            if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n            {\n              /*\n                Allocate next image structure.\n              */\n              AcquireNextImage(image_info,image,exception);\n\n              if (GetNextImageInList(image) == (Image *) NULL)\n                return(DestroyImageList(image));\n\n              image=SyncNextImageInList(image);\n            }\n\n            mng_info->image=image;\n\n            if (term_chunk_found)\n              {\n                image->start_loop=MagickTrue;\n                image->iterations=mng_iterations;\n                term_chunk_found=MagickFalse;\n              }\n\n            else\n                image->start_loop=MagickFalse;\n\n            image->delay=0;\n            image->columns=subframe_width;\n            image->rows=subframe_height;\n            image->page.width=subframe_width;\n            image->page.height=subframe_height;\n            image->page.x=mng_info->clip.left;\n            image->page.y=mng_info->clip.top;\n            image->background_color=mng_background_color;\n            image->alpha_trait=UndefinedPixelTrait;\n            (void) SetImageBackgroundColor(image,exception);\n\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\",\n                (double) mng_info->clip.left,(double) mng_info->clip.right,\n                (double) mng_info->clip.top,(double) mng_info->clip.bottom);\n          }\n#endif /* MNG_INSERT_LAYERS */\n        first_mng_object=MagickFalse;\n\n        if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n          {\n            /*\n              Allocate next image structure.\n            */\n            AcquireNextImage(image_info,image,exception);\n\n            if (GetNextImageInList(image) == (Image *) NULL)\n              return(DestroyImageList(image));\n\n            image=SyncNextImageInList(image);\n          }\n        mng_info->image=image;\n        status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n          GetBlobSize(image));\n\n        if (status == MagickFalse)\n          break;\n\n        if (term_chunk_found)\n          {\n            image->start_loop=MagickTrue;\n            term_chunk_found=MagickFalse;\n          }\n\n        else\n            image->start_loop=MagickFalse;\n\n        if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)\n          {\n            image->delay=frame_delay;\n            frame_delay=default_frame_delay;\n          }\n\n        else\n          image->delay=0;\n\n        image->page.width=mng_info->mng_width;\n        image->page.height=mng_info->mng_height;\n        image->page.x=mng_info->x_off[object_id];\n        image->page.y=mng_info->y_off[object_id];\n        image->iterations=mng_iterations;\n\n        /*\n          Seek back to the beginning of the IHDR or JHDR chunk's length field.\n        */\n\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1],\n            type[2],type[3]);\n\n        offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);\n\n        if (offset < 0)\n          ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n\n    mng_info->image=image;\n    mng_info->mng_type=mng_type;\n    mng_info->object_id=object_id;\n\n    if (memcmp(type,mng_IHDR,4) == 0)\n      image=ReadOnePNGImage(mng_info,image_info,exception);\n\n#if defined(JNG_SUPPORTED)\n    else\n      image=ReadOneJNGImage(mng_info,image_info,exception);\n#endif\n\n    if (image == (Image *) NULL)\n      {\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"exit ReadJNGImage() with error\");\n\n        return((Image *) NULL);\n      }\n\n    if (image->columns == 0 || image->rows == 0)\n      {\n        (void) CloseBlob(image);\n        return(DestroyImageList(image));\n      }\n\n    mng_info->image=image;\n\n    if (mng_type)\n      {\n        MngBox\n          crop_box;\n\n        if (mng_info->magn_methx || mng_info->magn_methy)\n          {\n            png_uint_32\n               magnified_height,\n               magnified_width;\n\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Processing MNG MAGN chunk\");\n\n            if (mng_info->magn_methx == 1)\n              {\n                magnified_width=mng_info->magn_ml;\n\n                if (image->columns > 1)\n                   magnified_width += mng_info->magn_mr;\n\n                if (image->columns > 2)\n                   magnified_width += (png_uint_32)\n                      ((image->columns-2)*(mng_info->magn_mx));\n              }\n\n            else\n              {\n                magnified_width=(png_uint_32) image->columns;\n\n                if (image->columns > 1)\n                   magnified_width += mng_info->magn_ml-1;\n\n                if (image->columns > 2)\n                   magnified_width += mng_info->magn_mr-1;\n\n                if (image->columns > 3)\n                   magnified_width += (png_uint_32)\n                      ((image->columns-3)*(mng_info->magn_mx-1));\n              }\n\n            if (mng_info->magn_methy == 1)\n              {\n                magnified_height=mng_info->magn_mt;\n\n                if (image->rows > 1)\n                   magnified_height += mng_info->magn_mb;\n\n                if (image->rows > 2)\n                   magnified_height += (png_uint_32)\n                      ((image->rows-2)*(mng_info->magn_my));\n              }\n\n            else\n              {\n                magnified_height=(png_uint_32) image->rows;\n\n                if (image->rows > 1)\n                   magnified_height += mng_info->magn_mt-1;\n\n                if (image->rows > 2)\n                   magnified_height += mng_info->magn_mb-1;\n\n                if (image->rows > 3)\n                   magnified_height += (png_uint_32)\n                      ((image->rows-3)*(mng_info->magn_my-1));\n              }\n\n            if (magnified_height > image->rows ||\n                magnified_width > image->columns)\n              {\n                Image\n                  *large_image;\n\n                int\n                  yy;\n\n                Quantum\n                  *next,\n                  *prev;\n\n                png_uint_16\n                  magn_methx,\n                  magn_methy;\n\n                ssize_t\n                  m,\n                  y;\n\n                register Quantum\n                  *n,\n                  *q;\n\n                register ssize_t\n                  x;\n\n                /* Allocate next image structure.  */\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"    Allocate magnified image\");\n\n                AcquireNextImage(image_info,image,exception);\n\n                if (GetNextImageInList(image) == (Image *) NULL)\n                  return(DestroyImageList(image));\n\n                large_image=SyncNextImageInList(image);\n\n                large_image->columns=magnified_width;\n                large_image->rows=magnified_height;\n\n                magn_methx=mng_info->magn_methx;\n                magn_methy=mng_info->magn_methy;\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n#define QM unsigned short\n                if (magn_methx != 1 || magn_methy != 1)\n                  {\n                  /*\n                     Scale pixels to unsigned shorts to prevent\n                     overflow of intermediate values of interpolations\n                  */\n                     for (y=0; y < (ssize_t) image->rows; y++)\n                     {\n                       q=GetAuthenticPixels(image,0,y,image->columns,1,\n                          exception);\n\n                       for (x=(ssize_t) image->columns-1; x >= 0; x--)\n                       {\n                          SetPixelRed(image,ScaleQuantumToShort(\n                            GetPixelRed(image,q)),q);\n                          SetPixelGreen(image,ScaleQuantumToShort(\n                            GetPixelGreen(image,q)),q);\n                          SetPixelBlue(image,ScaleQuantumToShort(\n                            GetPixelBlue(image,q)),q);\n                          SetPixelAlpha(image,ScaleQuantumToShort(\n                            GetPixelAlpha(image,q)),q);\n                          q+=GetPixelChannels(image);\n                       }\n\n                       if (SyncAuthenticPixels(image,exception) == MagickFalse)\n                         break;\n                     }\n                  }\n#else\n#define QM Quantum\n#endif\n\n                if (image->alpha_trait != UndefinedPixelTrait)\n                   (void) SetImageBackgroundColor(large_image,exception);\n\n                else\n                  {\n                    large_image->background_color.alpha=OpaqueAlpha;\n                    (void) SetImageBackgroundColor(large_image,exception);\n\n                    if (magn_methx == 4)\n                      magn_methx=2;\n\n                    if (magn_methx == 5)\n                      magn_methx=3;\n\n                    if (magn_methy == 4)\n                      magn_methy=2;\n\n                    if (magn_methy == 5)\n                      magn_methy=3;\n                  }\n\n                /* magnify the rows into the right side of the large image */\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"    Magnify the rows to %.20g\",\n                    (double) large_image->rows);\n                m=(ssize_t) mng_info->magn_mt;\n                yy=0;\n                length=(size_t) GetPixelChannels(image)*image->columns;\n                next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next));\n                prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev));\n\n                if ((prev == (Quantum *) NULL) ||\n                    (next == (Quantum *) NULL))\n                  {\n                     image=DestroyImageList(image);\n                     ThrowReaderException(ResourceLimitError,\n                       \"MemoryAllocationFailed\");\n                  }\n\n                n=GetAuthenticPixels(image,0,0,image->columns,1,exception);\n                (void) CopyMagickMemory(next,n,length);\n\n                for (y=0; y < (ssize_t) image->rows; y++)\n                {\n                  if (y == 0)\n                    m=(ssize_t) mng_info->magn_mt;\n\n                  else if (magn_methy > 1 && y == (ssize_t) image->rows-2)\n                    m=(ssize_t) mng_info->magn_mb;\n\n                  else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)\n                    m=(ssize_t) mng_info->magn_mb;\n\n                  else if (magn_methy > 1 && y == (ssize_t) image->rows-1)\n                    m=1;\n\n                  else\n                    m=(ssize_t) mng_info->magn_my;\n\n                  n=prev;\n                  prev=next;\n                  next=n;\n\n                  if (y < (ssize_t) image->rows-1)\n                    {\n                      n=GetAuthenticPixels(image,0,y+1,image->columns,1,\n                          exception);\n                      (void) CopyMagickMemory(next,n,length);\n                    }\n\n                  for (i=0; i < m; i++, yy++)\n                  {\n                    register Quantum\n                      *pixels;\n\n                    assert(yy < (ssize_t) large_image->rows);\n                    pixels=prev;\n                    n=next;\n                    q=GetAuthenticPixels(large_image,0,yy,large_image->columns,\n                      1,exception);\n                    q+=(large_image->columns-image->columns)*\n                      GetPixelChannels(large_image);\n\n                    for (x=(ssize_t) image->columns-1; x >= 0; x--)\n                    {\n                      /* To do: get color as function of indexes[x] */\n                      /*\n                      if (image->storage_class == PseudoClass)\n                        {\n                        }\n                      */\n\n                      if (magn_methy <= 1)\n                        {\n                          /* replicate previous */\n                          SetPixelRed(large_image,GetPixelRed(image,pixels),q);\n                          SetPixelGreen(large_image,GetPixelGreen(image,\n                             pixels),q);\n                          SetPixelBlue(large_image,GetPixelBlue(image,\n                             pixels),q);\n                          SetPixelAlpha(large_image,GetPixelAlpha(image,\n                             pixels),q);\n                        }\n\n                      else if (magn_methy == 2 || magn_methy == 4)\n                        {\n                          if (i == 0)\n                            {\n                              SetPixelRed(large_image,GetPixelRed(image,\n                                 pixels),q);\n                              SetPixelGreen(large_image,GetPixelGreen(image,\n                                 pixels),q);\n                              SetPixelBlue(large_image,GetPixelBlue(image,\n                                 pixels),q);\n                              SetPixelAlpha(large_image,GetPixelAlpha(image,\n                                 pixels),q);\n                            }\n\n                          else\n                            {\n                              /* Interpolate */\n                              SetPixelRed(large_image,((QM) (((ssize_t)\n                                 (2*i*(GetPixelRed(image,n)\n                                 -GetPixelRed(image,pixels)+m))/\n                                 ((ssize_t) (m*2))\n                                 +GetPixelRed(image,pixels)))),q);\n                              SetPixelGreen(large_image,((QM) (((ssize_t)\n                                 (2*i*(GetPixelGreen(image,n)\n                                 -GetPixelGreen(image,pixels)+m))/\n                                 ((ssize_t) (m*2))\n                                 +GetPixelGreen(image,pixels)))),q);\n                              SetPixelBlue(large_image,((QM) (((ssize_t)\n                                 (2*i*(GetPixelBlue(image,n)\n                                 -GetPixelBlue(image,pixels)+m))/\n                                 ((ssize_t) (m*2))\n                                 +GetPixelBlue(image,pixels)))),q);\n\n                              if (image->alpha_trait != UndefinedPixelTrait)\n                                 SetPixelAlpha(large_image, ((QM) (((ssize_t)\n                                    (2*i*(GetPixelAlpha(image,n)\n                                    -GetPixelAlpha(image,pixels)+m))\n                                    /((ssize_t) (m*2))+\n                                   GetPixelAlpha(image,pixels)))),q);\n                            }\n\n                          if (magn_methy == 4)\n                            {\n                              /* Replicate nearest */\n                              if (i <= ((m+1) << 1))\n                                 SetPixelAlpha(large_image,GetPixelAlpha(image,\n                                    pixels),q);\n                              else\n                                 SetPixelAlpha(large_image,GetPixelAlpha(image,\n                                    n),q);\n                            }\n                        }\n\n                      else /* if (magn_methy == 3 || magn_methy == 5) */\n                        {\n                          /* Replicate nearest */\n                          if (i <= ((m+1) << 1))\n                          {\n                             SetPixelRed(large_image,GetPixelRed(image,\n                                    pixels),q);\n                             SetPixelGreen(large_image,GetPixelGreen(image,\n                                    pixels),q);\n                             SetPixelBlue(large_image,GetPixelBlue(image,\n                                    pixels),q);\n                             SetPixelAlpha(large_image,GetPixelAlpha(image,\n                                    pixels),q);\n                          }\n\n                          else\n                          {\n                             SetPixelRed(large_image,GetPixelRed(image,n),q);\n                             SetPixelGreen(large_image,GetPixelGreen(image,n),\n                                    q);\n                             SetPixelBlue(large_image,GetPixelBlue(image,n),\n                                    q);\n                             SetPixelAlpha(large_image,GetPixelAlpha(image,n),\n                                    q);\n                          }\n\n                          if (magn_methy == 5)\n                            {\n                              SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i*\n                                 (GetPixelAlpha(image,n)\n                                 -GetPixelAlpha(image,pixels))\n                                 +m))/((ssize_t) (m*2))\n                                 +GetPixelAlpha(image,pixels)),q);\n                            }\n                        }\n                      n+=GetPixelChannels(image);\n                      q+=GetPixelChannels(large_image);\n                      pixels+=GetPixelChannels(image);\n                    } /* x */\n\n                    if (SyncAuthenticPixels(large_image,exception) == 0)\n                      break;\n\n                  } /* i */\n                } /* y */\n\n                prev=(Quantum *) RelinquishMagickMemory(prev);\n                next=(Quantum *) RelinquishMagickMemory(next);\n\n                length=image->columns;\n\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"    Delete original image\");\n\n                DeleteImageFromList(&image);\n\n                image=large_image;\n\n                mng_info->image=image;\n\n                /* magnify the columns */\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"    Magnify the columns to %.20g\",\n                    (double) image->columns);\n\n                for (y=0; y < (ssize_t) image->rows; y++)\n                {\n                  register Quantum\n                    *pixels;\n\n                  q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n                  pixels=q+(image->columns-length)*GetPixelChannels(image);\n                  n=pixels+GetPixelChannels(image);\n\n                  for (x=(ssize_t) (image->columns-length);\n                    x < (ssize_t) image->columns; x++)\n                  {\n                    /* To do: Rewrite using Get/Set***PixelChannel() */\n\n                    if (x == (ssize_t) (image->columns-length))\n                      m=(ssize_t) mng_info->magn_ml;\n\n                    else if (magn_methx > 1 && x == (ssize_t) image->columns-2)\n                      m=(ssize_t) mng_info->magn_mr;\n\n                    else if (magn_methx <= 1 &&\n                        x == (ssize_t) image->columns-1)\n                      m=(ssize_t) mng_info->magn_mr;\n\n                    else if (magn_methx > 1 && x == (ssize_t) image->columns-1)\n                      m=1;\n\n                    else\n                      m=(ssize_t) mng_info->magn_mx;\n\n                    for (i=0; i < m; i++)\n                    {\n                      if (magn_methx <= 1)\n                        {\n                          /* replicate previous */\n                          SetPixelRed(image,GetPixelRed(image,pixels),q);\n                          SetPixelGreen(image,GetPixelGreen(image,pixels),q);\n                          SetPixelBlue(image,GetPixelBlue(image,pixels),q);\n                          SetPixelAlpha(image,GetPixelAlpha(image,pixels),q);\n                        }\n\n                      else if (magn_methx == 2 || magn_methx == 4)\n                        {\n                          if (i == 0)\n                          {\n                            SetPixelRed(image,GetPixelRed(image,pixels),q);\n                            SetPixelGreen(image,GetPixelGreen(image,pixels),q);\n                            SetPixelBlue(image,GetPixelBlue(image,pixels),q);\n                            SetPixelAlpha(image,GetPixelAlpha(image,pixels),q);\n                          }\n\n                          /* To do: Rewrite using Get/Set***PixelChannel() */\n                          else\n                            {\n                              /* Interpolate */\n                              SetPixelRed(image,(QM) ((2*i*(\n                                 GetPixelRed(image,n)\n                                 -GetPixelRed(image,pixels))+m)\n                                 /((ssize_t) (m*2))+\n                                 GetPixelRed(image,pixels)),q);\n\n                              SetPixelGreen(image,(QM) ((2*i*(\n                                 GetPixelGreen(image,n)\n                                 -GetPixelGreen(image,pixels))+m)\n                                 /((ssize_t) (m*2))+\n                                 GetPixelGreen(image,pixels)),q);\n\n                              SetPixelBlue(image,(QM) ((2*i*(\n                                 GetPixelBlue(image,n)\n                                 -GetPixelBlue(image,pixels))+m)\n                                 /((ssize_t) (m*2))+\n                                 GetPixelBlue(image,pixels)),q);\n                              if (image->alpha_trait != UndefinedPixelTrait)\n                                 SetPixelAlpha(image,(QM) ((2*i*(\n                                   GetPixelAlpha(image,n)\n                                   -GetPixelAlpha(image,pixels))+m)\n                                   /((ssize_t) (m*2))+\n                                   GetPixelAlpha(image,pixels)),q);\n                            }\n\n                          if (magn_methx == 4)\n                            {\n                              /* Replicate nearest */\n                              if (i <= ((m+1) << 1))\n                              {\n                                 SetPixelAlpha(image,\n                                   GetPixelAlpha(image,pixels)+0,q);\n                              }\n                              else\n                              {\n                                 SetPixelAlpha(image,\n                                   GetPixelAlpha(image,n)+0,q);\n                              }\n                            }\n                        }\n\n                      else /* if (magn_methx == 3 || magn_methx == 5) */\n                        {\n                          /* Replicate nearest */\n                          if (i <= ((m+1) << 1))\n                          {\n                             SetPixelRed(image,GetPixelRed(image,pixels),q);\n                             SetPixelGreen(image,GetPixelGreen(image,\n                                 pixels),q);\n                             SetPixelBlue(image,GetPixelBlue(image,pixels),q);\n                             SetPixelAlpha(image,GetPixelAlpha(image,\n                                 pixels),q);\n                          }\n\n                          else\n                          {\n                             SetPixelRed(image,GetPixelRed(image,n),q);\n                             SetPixelGreen(image,GetPixelGreen(image,n),q);\n                             SetPixelBlue(image,GetPixelBlue(image,n),q);\n                             SetPixelAlpha(image,GetPixelAlpha(image,n),q);\n                          }\n\n                          if (magn_methx == 5)\n                            {\n                              /* Interpolate */\n                              SetPixelAlpha(image,\n                                 (QM) ((2*i*( GetPixelAlpha(image,n)\n                                 -GetPixelAlpha(image,pixels))+m)/\n                                 ((ssize_t) (m*2))\n                                 +GetPixelAlpha(image,pixels)),q);\n                            }\n                        }\n                      q+=GetPixelChannels(image);\n                    }\n                    n+=GetPixelChannels(image);\n                  }\n\n                  if (SyncAuthenticPixels(image,exception) == MagickFalse)\n                    break;\n                }\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n              if (magn_methx != 1 || magn_methy != 1)\n                {\n                /*\n                   Rescale pixels to Quantum\n                */\n                   for (y=0; y < (ssize_t) image->rows; y++)\n                   {\n                     q=GetAuthenticPixels(image,0,y,image->columns,1,\n                       exception);\n\n                     for (x=(ssize_t) image->columns-1; x >= 0; x--)\n                     {\n                        SetPixelRed(image,ScaleShortToQuantum(\n                          GetPixelRed(image,q)),q);\n                        SetPixelGreen(image,ScaleShortToQuantum(\n                          GetPixelGreen(image,q)),q);\n                        SetPixelBlue(image,ScaleShortToQuantum(\n                          GetPixelBlue(image,q)),q);\n                        SetPixelAlpha(image,ScaleShortToQuantum(\n                          GetPixelAlpha(image,q)),q);\n                        q+=GetPixelChannels(image);\n                     }\n\n                     if (SyncAuthenticPixels(image,exception) == MagickFalse)\n                       break;\n                   }\n                }\n#endif\n                if (logging != MagickFalse)\n                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                    \"  Finished MAGN processing\");\n              }\n          }\n\n        /*\n          Crop_box is with respect to the upper left corner of the MNG.\n        */\n        crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];\n        crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];\n        crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];\n        crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];\n        crop_box=mng_minimum_box(crop_box,mng_info->clip);\n        crop_box=mng_minimum_box(crop_box,mng_info->frame);\n        crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);\n        if ((crop_box.left != (mng_info->image_box.left\n            +mng_info->x_off[object_id])) ||\n            (crop_box.right != (mng_info->image_box.right\n            +mng_info->x_off[object_id])) ||\n            (crop_box.top != (mng_info->image_box.top\n            +mng_info->y_off[object_id])) ||\n            (crop_box.bottom != (mng_info->image_box.bottom\n            +mng_info->y_off[object_id])))\n          {\n            if (logging != MagickFalse)\n              (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                \"  Crop the PNG image\");\n\n            if ((crop_box.left < crop_box.right) &&\n                (crop_box.top < crop_box.bottom))\n              {\n                Image\n                  *im;\n\n                RectangleInfo\n                  crop_info;\n\n                /*\n                  Crop_info is with respect to the upper left corner of\n                  the image.\n                */\n                crop_info.x=(crop_box.left-mng_info->x_off[object_id]);\n                crop_info.y=(crop_box.top-mng_info->y_off[object_id]);\n                crop_info.width=(size_t) (crop_box.right-crop_box.left);\n                crop_info.height=(size_t) (crop_box.bottom-crop_box.top);\n                image->page.width=image->columns;\n                image->page.height=image->rows;\n                image->page.x=0;\n                image->page.y=0;\n                im=CropImage(image,&crop_info,exception);\n\n                if (im != (Image *) NULL)\n                  {\n                    image->columns=im->columns;\n                    image->rows=im->rows;\n                    im=DestroyImage(im);\n                    image->page.width=image->columns;\n                    image->page.height=image->rows;\n                    image->page.x=crop_box.left;\n                    image->page.y=crop_box.top;\n                  }\n              }\n\n            else\n              {\n                /*\n                  No pixels in crop area.  The MNG spec still requires\n                  a layer, though, so make a single transparent pixel in\n                  the top left corner.\n                */\n                image->columns=1;\n                image->rows=1;\n                image->colors=2;\n                (void) SetImageBackgroundColor(image,exception);\n                image->page.width=1;\n                image->page.height=1;\n                image->page.x=0;\n                image->page.y=0;\n              }\n          }\n#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED\n        image=mng_info->image;\n#endif\n      }\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n      /* PNG does not handle depths greater than 16 so reduce it even\n       * if lossy.\n       */\n      if (image->depth > 16)\n         image->depth=16;\n#endif\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 8)\n      if (image->depth > 8)\n        {\n          /* To do: fill low byte properly */\n          image->depth=16;\n        }\n\n      if (LosslessReduceDepthOK(image,exception) != MagickFalse)\n         image->depth = 8;\n#endif\n\n      if (image_info->number_scenes != 0)\n        {\n          if (mng_info->scenes_found >\n             (ssize_t) (image_info->first_scene+image_info->number_scenes))\n            break;\n        }\n\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"  Finished reading image datastream.\");\n\n  } while (LocaleCompare(image_info->magick,\"MNG\") == 0);\n\n  (void) CloseBlob(image);\n\n  if (logging != MagickFalse)\n    (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n      \"  Finished reading all image datastreams.\");\n\n#if defined(MNG_INSERT_LAYERS)\n  if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&\n       (mng_info->mng_height))\n    {\n      /*\n        Insert a background layer if nothing else was found.\n      */\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"  No images found.  Inserting a background layer.\");\n\n      if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n        {\n          /*\n            Allocate next image structure.\n          */\n          AcquireNextImage(image_info,image,exception);\n          if (GetNextImageInList(image) == (Image *) NULL)\n            {\n              if (logging != MagickFalse)\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Allocation failed, returning NULL.\");\n\n              return(DestroyImageList(image));;\n            }\n          image=SyncNextImageInList(image);\n        }\n      image->columns=mng_info->mng_width;\n      image->rows=mng_info->mng_height;\n      image->page.width=mng_info->mng_width;\n      image->page.height=mng_info->mng_height;\n      image->page.x=0;\n      image->page.y=0;\n      image->background_color=mng_background_color;\n      image->alpha_trait=UndefinedPixelTrait;\n\n      if (image_info->ping == MagickFalse)\n        (void) SetImageBackgroundColor(image,exception);\n\n      mng_info->image_found++;\n    }\n#endif\n  image->iterations=mng_iterations;\n\n  if (mng_iterations == 1)\n    image->start_loop=MagickTrue;\n\n  while (GetPreviousImageInList(image) != (Image *) NULL)\n  {\n    image_count++;\n    if (image_count > 10*mng_info->image_found)\n      {\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  No beginning\");\n\n        (void) ThrowMagickException(exception,GetMagickModule(),\n          CoderError,\"Linked list is corrupted, beginning of list not found\",\n          \"`%s'\",image_info->filename);\n\n        return(DestroyImageList(image));\n      }\n\n    image=GetPreviousImageInList(image);\n\n    if (GetNextImageInList(image) == (Image *) NULL)\n      {\n        if (logging != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  Corrupt list\");\n\n        (void) ThrowMagickException(exception,GetMagickModule(),\n          CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\",\n          image_info->filename);\n      }\n  }\n\n  if (mng_info->ticks_per_second && mng_info->image_found > 1 &&\n             GetNextImageInList(image) ==\n     (Image *) NULL)\n    {\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  First image null\");\n\n      (void) ThrowMagickException(exception,GetMagickModule(),\n        CoderError,\"image->next for first image is NULL but shouldn't be.\",\n        \"`%s'\",image_info->filename);\n    }\n\n  if (mng_info->image_found == 0)\n    {\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"  No visible images found.\");\n\n      (void) ThrowMagickException(exception,GetMagickModule(),\n        CoderError,\"No visible images in file\",\"`%s'\",image_info->filename);\n\n      return(DestroyImageList(image));\n    }\n\n  if (mng_info->ticks_per_second)\n    final_delay=1UL*MagickMax(image->ticks_per_second,1L)*\n            final_delay/mng_info->ticks_per_second;\n\n  else\n    image->start_loop=MagickTrue;\n\n  /* Find final nonzero image delay */\n  final_image_delay=0;\n\n  while (GetNextImageInList(image) != (Image *) NULL)\n    {\n      if (image->delay)\n        final_image_delay=image->delay;\n\n      image=GetNextImageInList(image);\n    }\n\n  if (final_delay < final_image_delay)\n    final_delay=final_image_delay;\n\n  image->delay=final_delay;\n\n  if (logging != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"  image->delay=%.20g, final_delay=%.20g\",(double) image->delay,\n        (double) final_delay);\n\n  if (logging != MagickFalse)\n    {\n      int\n        scene;\n\n      scene=0;\n      image=GetFirstImageInList(image);\n\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"  Before coalesce:\");\n\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"    scene 0 delay=%.20g\",(double) image->delay);\n\n      while (GetNextImageInList(image) != (Image *) NULL)\n      {\n        image=GetNextImageInList(image);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"    scene %.20g delay=%.20g\",(double) scene++,\n          (double) image->delay);\n      }\n    }\n\n  image=GetFirstImageInList(image);\n#ifdef MNG_COALESCE_LAYERS\n  if (insert_layers)\n    {\n      Image\n        *next_image,\n        *next;\n\n      size_t\n        scene;\n\n      if (logging != MagickFalse)\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"  Coalesce Images\");\n\n      scene=image->scene;\n      next_image=CoalesceImages(image,exception);\n\n      if (next_image == (Image *) NULL)\n        ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n      image=DestroyImageList(image);\n      image=next_image;\n\n      for (next=image; next != (Image *) NULL; next=next_image)\n      {\n         next->page.width=mng_info->mng_width;\n         next->page.height=mng_info->mng_height;\n         next->page.x=0;\n         next->page.y=0;\n         next->scene=scene++;\n         next_image=GetNextImageInList(next);\n\n         if (next_image == (Image *) NULL)\n           break;\n\n         if (next->delay == 0)\n           {\n             scene--;\n             next_image->previous=GetPreviousImageInList(next);\n             if (GetPreviousImageInList(next) == (Image *) NULL)\n               image=next_image;\n             else\n               next->previous->next=next_image;\n             next=DestroyImage(next);\n           }\n      }\n    }\n#endif\n\n  while (GetNextImageInList(image) != (Image *) NULL)\n      image=GetNextImageInList(image);\n\n  image->dispose=BackgroundDispose;\n\n  if (logging != MagickFalse)\n    {\n      int\n        scene;\n\n      scene=0;\n      image=GetFirstImageInList(image);\n\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"  After coalesce:\");\n\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"    scene 0 delay=%.20g dispose=%.20g\",(double) image->delay,\n        (double) image->dispose);\n\n      while (GetNextImageInList(image) != (Image *) NULL)\n      {\n        image=GetNextImageInList(image);\n\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"    scene %.20g delay=%.20g dispose=%.20g\",(double) scene++,\n          (double) image->delay,(double) image->dispose);\n      }\n   }\n\n  if (logging != MagickFalse)\n    (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n      \"  exit ReadOneMNGImage();\");\n\n  return(image);\n}", "func_hash": 158627527242372232555718474097358340968, "file_name": "png.c", "file_hash": 308141979970390112779858157014940687903, "cwe": ["CWE-125"], "cve": "CVE-2017-13139", "cve_desc": "In ImageMagick before 6.9.9-0 and 7.x before 7.0.6-1, the ReadOneMNGImage function in coders/png.c has an out-of-bounds read with the MNG CLIP chunk.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-13139"}
{"idx": 195954, "project": "pjproject", "commit_id": "9fae8f43accef8ea65d4a8ae9cdf297c46cfe29a", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/9fae8f43accef8ea65d4a8ae9cdf297c46cfe29a", "commit_message": "Merge pull request from GHSA-p6g5-v97c-w5q4\n\n* Prevent heap buffer overflow when parsing DNS packets\n\n* Make sure packet parsing doesn't advance beyond max/end\n\n* Update checks\n\n* Remove  check\n\nCo-authored-by: sauwming ", "target": 1, "func": "static pj_status_t parse_query(pj_dns_parsed_query *q, pj_pool_t *pool,\n\t\t\t       const pj_uint8_t *pkt, const pj_uint8_t *start,\n\t\t\t       const pj_uint8_t *max, int *parsed_len)\n{\n    const pj_uint8_t *p = start;\n    int name_len, name_part_len;\n    pj_status_t status;\n\n    /* Get the length of the name */\n    status = get_name_len(0, pkt, start, max, &name_part_len, &name_len);\n    if (status != PJ_SUCCESS)\n\treturn status;\n\n    /* Allocate memory for the name */\n    q->name.ptr = (char*) pj_pool_alloc(pool, name_len+4);\n    q->name.slen = 0;\n\n    /* Get the name */\n    status = get_name(0, pkt, start, max, &q->name);\n    if (status != PJ_SUCCESS)\n\treturn status;\n\n    p = (start + name_part_len);\n\n    /* Get the type */\n    pj_memcpy(&q->type, p, 2);\n    q->type = pj_ntohs(q->type);\n    p += 2;\n\n    /* Get the class */\n    pj_memcpy(&q->dnsclass, p, 2);\n    q->dnsclass = pj_ntohs(q->dnsclass);\n    p += 2;\n\n    *parsed_len = (int)(p - start);\n\n    return PJ_SUCCESS;\n}", "func_hash": 135450072303259419822933820270333517166, "file_name": "dns.c", "file_hash": 253652259492393007596255371845847130395, "cwe": ["CWE-787"], "cve": "CVE-2022-24793", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C. A buffer overflow vulnerability in versions 2.12 and prior affects applications that use PJSIP DNS resolution. It doesn't affect PJSIP users who utilize an external resolver. This vulnerability is related to CVE-2023-27585. The difference is that this issue is in parsing the query record `parse_rr()`, while the issue in CVE-2023-27585 is in `parse_query()`. A patch is available in the `master` branch of the `pjsip/pjproject` GitHub repository. A workaround is to disable DNS resolution in PJSIP config (by setting `nameserver_count` to zero) or use an external resolver instead.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24793"}
{"idx": 235642, "project": "pjproject", "commit_id": "9fae8f43accef8ea65d4a8ae9cdf297c46cfe29a", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/9fae8f43accef8ea65d4a8ae9cdf297c46cfe29a", "commit_message": "Merge pull request from GHSA-p6g5-v97c-w5q4\n\n* Prevent heap buffer overflow when parsing DNS packets\n\n* Make sure packet parsing doesn't advance beyond max/end\n\n* Update checks\n\n* Remove  check\n\nCo-authored-by: sauwming ", "target": 0, "func": "static pj_status_t parse_query(pj_dns_parsed_query *q, pj_pool_t *pool,\n\t\t\t       const pj_uint8_t *pkt, const pj_uint8_t *start,\n\t\t\t       const pj_uint8_t *max, int *parsed_len)\n{\n    const pj_uint8_t *p = start;\n    int name_len, name_part_len;\n    pj_status_t status;\n\n    /* Get the length of the name */\n    status = get_name_len(0, pkt, start, max, &name_part_len, &name_len);\n    if (status != PJ_SUCCESS)\n\treturn status;\n\n    /* Allocate memory for the name */\n    q->name.ptr = (char*) pj_pool_alloc(pool, name_len+4);\n    q->name.slen = 0;\n\n    /* Get the name */\n    status = get_name(0, pkt, start, max, &q->name);\n    if (status != PJ_SUCCESS)\n\treturn status;\n\n    p = (start + name_part_len);\n\n    /* Check the size can accomodate next few fields. */\n    if (p + 4 > max)\n    \treturn PJLIB_UTIL_EDNSINSIZE;\n\n    /* Get the type */\n    pj_memcpy(&q->type, p, 2);\n    q->type = pj_ntohs(q->type);\n    p += 2;\n\n    /* Get the class */\n    pj_memcpy(&q->dnsclass, p, 2);\n    q->dnsclass = pj_ntohs(q->dnsclass);\n    p += 2;\n\n    *parsed_len = (int)(p - start);\n\n    return PJ_SUCCESS;\n}", "func_hash": 182542196466721409447058148432122336027, "file_name": "dns.c", "file_hash": 267684295944312304672181273486771812087, "cwe": ["CWE-787"], "cve": "CVE-2022-24793", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C. A buffer overflow vulnerability in versions 2.12 and prior affects applications that use PJSIP DNS resolution. It doesn't affect PJSIP users who utilize an external resolver. This vulnerability is related to CVE-2023-27585. The difference is that this issue is in parsing the query record `parse_rr()`, while the issue in CVE-2023-27585 is in `parse_query()`. A patch is available in the `master` branch of the `pjsip/pjproject` GitHub repository. A workaround is to disable DNS resolution in PJSIP config (by setting `nameserver_count` to zero) or use an external resolver instead.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24793"}
{"idx": 195965, "project": "tensorflow", "commit_id": "30721cf564cb029d34535446d6a5a6357bebc8e7", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/30721cf564cb029d34535446d6a5a6357bebc8e7", "commit_message": "Fix tf.raw_ops.EditDistance vulnerability with negative indices.\n\nCheck that indices are non-negative. Fix several identical code sites.\nClean up grammar in error message.\n\nPiperOrigin-RevId: 445442017", "target": 1, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor* hypothesis_indices;\n    const Tensor* hypothesis_values;\n    const Tensor* hypothesis_shape;\n    const Tensor* truth_indices;\n    const Tensor* truth_values;\n    const Tensor* truth_shape;\n    OP_REQUIRES_OK(ctx, ctx->input(\"hypothesis_indices\", &hypothesis_indices));\n    OP_REQUIRES_OK(ctx, ctx->input(\"hypothesis_values\", &hypothesis_values));\n    OP_REQUIRES_OK(ctx, ctx->input(\"hypothesis_shape\", &hypothesis_shape));\n    OP_REQUIRES_OK(ctx, ctx->input(\"truth_indices\", &truth_indices));\n    OP_REQUIRES_OK(ctx, ctx->input(\"truth_values\", &truth_values));\n    OP_REQUIRES_OK(ctx, ctx->input(\"truth_shape\", &truth_shape));\n\n    OP_REQUIRES_OK(\n        ctx, ValidateShapes(ctx, *hypothesis_indices, *hypothesis_values,\n                            *hypothesis_shape, *truth_indices, *truth_values,\n                            *truth_shape));\n\n    TensorShape hypothesis_st_shape;\n    OP_REQUIRES_OK(ctx,\n                   TensorShapeUtils::MakeShape(\n                       hypothesis_shape->vec().data(),\n                       hypothesis_shape->NumElements(), &hypothesis_st_shape));\n    TensorShape truth_st_shape;\n    OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(\n                            truth_shape->vec().data(),\n                            truth_shape->NumElements(), &truth_st_shape));\n\n    // Assume indices are sorted in row-major order.\n    std::vector sorted_order(truth_st_shape.dims());\n    std::iota(sorted_order.begin(), sorted_order.end(), 0);\n\n    sparse::SparseTensor hypothesis;\n    OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create(\n                            *hypothesis_indices, *hypothesis_values,\n                            hypothesis_st_shape, sorted_order, &hypothesis));\n\n    sparse::SparseTensor truth;\n    OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create(\n                            *truth_indices, *truth_values, truth_st_shape,\n                            sorted_order, &truth));\n\n    // Group dims 0, 1, ..., RANK - 1.  The very last dim is assumed\n    // to store the variable length sequences.\n    std::vector group_dims(truth_st_shape.dims() - 1);\n    std::iota(group_dims.begin(), group_dims.end(), 0);\n\n    TensorShape output_shape;\n    for (int d = 0; d < static_cast(group_dims.size()); ++d) {\n      output_shape.AddDim(std::max(hypothesis_st_shape.dim_size(d),\n                                   truth_st_shape.dim_size(d)));\n    }\n    const auto output_elements = output_shape.num_elements();\n    OP_REQUIRES(\n        ctx, output_elements > 0,\n        errors::InvalidArgument(\"Got output shape \", output_shape.DebugString(),\n                                \" which has 0 elements\"));\n\n    Tensor* output = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(\"output\", output_shape, &output));\n    auto output_t = output->flat();\n    output_t.setZero();\n\n    std::vector output_strides(output_shape.dims());\n    output_strides[output_shape.dims() - 1] = 1;\n    for (int d = output_shape.dims() - 2; d >= 0; --d) {\n      output_strides[d] = output_strides[d + 1] * output_shape.dim_size(d + 1);\n    }\n\n    auto hypothesis_grouper = hypothesis.group(group_dims);\n    auto truth_grouper = truth.group(group_dims);\n\n    auto hypothesis_iter = hypothesis_grouper.begin();\n    auto truth_iter = truth_grouper.begin();\n\n    auto cmp = std::equal_to();\n\n    while (hypothesis_iter != hypothesis_grouper.end() &&\n           truth_iter != truth_grouper.end()) {\n      sparse::Group truth_i = *truth_iter;\n      sparse::Group hypothesis_j = *hypothesis_iter;\n      std::vector g_truth = truth_i.group();\n      std::vector g_hypothesis = hypothesis_j.group();\n      auto truth_seq = truth_i.values();\n      auto hypothesis_seq = hypothesis_j.values();\n\n      if (g_truth == g_hypothesis) {\n        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),\n                                      output_strides.begin(), int64_t{0});\n        OP_REQUIRES(\n            ctx, loc < output_elements,\n            errors::Internal(\"Got an inner product \", loc,\n                             \" which would require in writing to outside of \"\n                             \"the buffer for the output tensor (max elements \",\n                             output_elements, \")\"));\n        output_t(loc) =\n            gtl::LevenshteinDistance(truth_seq, hypothesis_seq, cmp);\n        if (normalize_) output_t(loc) /= truth_seq.size();\n\n        ++hypothesis_iter;\n        ++truth_iter;\n      } else if (g_truth > g_hypothesis) {  // zero-length truth\n        auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),\n                                      output_strides.begin(), int64_t{0});\n        OP_REQUIRES(\n            ctx, loc < output_elements,\n            errors::Internal(\"Got an inner product \", loc,\n                             \" which would require in writing to outside of \"\n                             \"the buffer for the output tensor (max elements \",\n                             output_elements, \")\"));\n        output_t(loc) = hypothesis_seq.size();\n        if (normalize_ && output_t(loc) != 0.0f) {\n          output_t(loc) = std::numeric_limits::infinity();\n        }\n        ++hypothesis_iter;\n      } else {  // zero-length hypothesis\n        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),\n                                      output_strides.begin(), int64_t{0});\n        OP_REQUIRES(\n            ctx, loc < output_elements,\n            errors::Internal(\"Got an inner product \", loc,\n                             \" which would require in writing to outside of \"\n                             \"the buffer for the output tensor (max elements \",\n                             output_elements, \")\"));\n        output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();\n        ++truth_iter;\n      }\n    }\n    while (hypothesis_iter != hypothesis_grouper.end()) {  // zero-length truths\n      sparse::Group hypothesis_j = *hypothesis_iter;\n      std::vector g_hypothesis = hypothesis_j.group();\n      auto hypothesis_seq = hypothesis_j.values();\n      auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),\n                                    output_strides.begin(), int64_t{0});\n      OP_REQUIRES(\n          ctx, loc < output_elements,\n          errors::Internal(\"Got an inner product \", loc,\n                           \" which would require in writing to outside of the \"\n                           \"buffer for the output tensor (max elements \",\n                           output_elements, \")\"));\n      output_t(loc) = hypothesis_seq.size();\n      if (normalize_ && output_t(loc) != 0.0f) {\n        output_t(loc) = std::numeric_limits::infinity();\n      }\n      ++hypothesis_iter;\n    }\n    while (truth_iter != truth_grouper.end()) {  // missing hypotheses\n      sparse::Group truth_i = *truth_iter;\n      std::vector g_truth = truth_i.group();\n      auto truth_seq = truth_i.values();\n      auto loc = std::inner_product(g_truth.begin(), g_truth.end(),\n                                    output_strides.begin(), int64_t{0});\n      OP_REQUIRES(\n          ctx, loc < output_elements,\n          errors::Internal(\"Got an inner product \", loc,\n                           \" which would require in writing to outside of the \"\n                           \"buffer for the output tensor (max elements \",\n                           output_elements, \")\"));\n      output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();\n      ++truth_iter;\n    }\n  }", "func_hash": 330908344605810468129440704571471984591, "file_name": "edit_distance_op.cc", "file_hash": 218278977682570302037113861275408263141, "cwe": ["CWE-787"], "cve": "CVE-2022-29208", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.EditDistance` has incomplete validation. Users can pass negative values to cause a segmentation fault based denial of service. In multiple places throughout the code, one may compute an index for a write operation. However, the existing validation only checks against the upper bound of the array. Hence, it is possible to write before the array by massaging the input to generate negative values for `loc`. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29208"}
{"idx": 235765, "project": "tensorflow", "commit_id": "30721cf564cb029d34535446d6a5a6357bebc8e7", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/30721cf564cb029d34535446d6a5a6357bebc8e7", "commit_message": "Fix tf.raw_ops.EditDistance vulnerability with negative indices.\n\nCheck that indices are non-negative. Fix several identical code sites.\nClean up grammar in error message.\n\nPiperOrigin-RevId: 445442017", "target": 0, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor* hypothesis_indices;\n    const Tensor* hypothesis_values;\n    const Tensor* hypothesis_shape;\n    const Tensor* truth_indices;\n    const Tensor* truth_values;\n    const Tensor* truth_shape;\n    OP_REQUIRES_OK(ctx, ctx->input(\"hypothesis_indices\", &hypothesis_indices));\n    OP_REQUIRES_OK(ctx, ctx->input(\"hypothesis_values\", &hypothesis_values));\n    OP_REQUIRES_OK(ctx, ctx->input(\"hypothesis_shape\", &hypothesis_shape));\n    OP_REQUIRES_OK(ctx, ctx->input(\"truth_indices\", &truth_indices));\n    OP_REQUIRES_OK(ctx, ctx->input(\"truth_values\", &truth_values));\n    OP_REQUIRES_OK(ctx, ctx->input(\"truth_shape\", &truth_shape));\n\n    OP_REQUIRES_OK(\n        ctx, ValidateShapes(ctx, *hypothesis_indices, *hypothesis_values,\n                            *hypothesis_shape, *truth_indices, *truth_values,\n                            *truth_shape));\n\n    TensorShape hypothesis_st_shape;\n    OP_REQUIRES_OK(ctx,\n                   TensorShapeUtils::MakeShape(\n                       hypothesis_shape->vec().data(),\n                       hypothesis_shape->NumElements(), &hypothesis_st_shape));\n    TensorShape truth_st_shape;\n    OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(\n                            truth_shape->vec().data(),\n                            truth_shape->NumElements(), &truth_st_shape));\n\n    // Assume indices are sorted in row-major order.\n    std::vector sorted_order(truth_st_shape.dims());\n    std::iota(sorted_order.begin(), sorted_order.end(), 0);\n\n    sparse::SparseTensor hypothesis;\n    OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create(\n                            *hypothesis_indices, *hypothesis_values,\n                            hypothesis_st_shape, sorted_order, &hypothesis));\n\n    sparse::SparseTensor truth;\n    OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create(\n                            *truth_indices, *truth_values, truth_st_shape,\n                            sorted_order, &truth));\n\n    // Group dims 0, 1, ..., RANK - 1.  The very last dim is assumed\n    // to store the variable length sequences.\n    std::vector group_dims(truth_st_shape.dims() - 1);\n    std::iota(group_dims.begin(), group_dims.end(), 0);\n\n    TensorShape output_shape;\n    for (int d = 0; d < static_cast(group_dims.size()); ++d) {\n      output_shape.AddDim(std::max(hypothesis_st_shape.dim_size(d),\n                                   truth_st_shape.dim_size(d)));\n    }\n    const auto output_elements = output_shape.num_elements();\n    OP_REQUIRES(\n        ctx, output_elements > 0,\n        errors::InvalidArgument(\"Got output shape \", output_shape.DebugString(),\n                                \" which has 0 elements\"));\n\n    Tensor* output = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(\"output\", output_shape, &output));\n    auto output_t = output->flat();\n    output_t.setZero();\n\n    std::vector output_strides(output_shape.dims());\n    output_strides[output_shape.dims() - 1] = 1;\n    for (int d = output_shape.dims() - 2; d >= 0; --d) {\n      output_strides[d] = output_strides[d + 1] * output_shape.dim_size(d + 1);\n    }\n\n    auto hypothesis_grouper = hypothesis.group(group_dims);\n    auto truth_grouper = truth.group(group_dims);\n\n    auto hypothesis_iter = hypothesis_grouper.begin();\n    auto truth_iter = truth_grouper.begin();\n\n    auto cmp = std::equal_to();\n\n    while (hypothesis_iter != hypothesis_grouper.end() &&\n           truth_iter != truth_grouper.end()) {\n      sparse::Group truth_i = *truth_iter;\n      sparse::Group hypothesis_j = *hypothesis_iter;\n      std::vector g_truth = truth_i.group();\n      std::vector g_hypothesis = hypothesis_j.group();\n      auto truth_seq = truth_i.values();\n      auto hypothesis_seq = hypothesis_j.values();\n\n      if (g_truth == g_hypothesis) {\n        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),\n                                      output_strides.begin(), int64_t{0});\n        OP_REQUIRES(\n            ctx, 0 <= loc && loc < output_elements,\n            errors::Internal(\"Got an inner product \", loc,\n                             \" which would require writing to outside of \"\n                             \"the buffer for the output tensor (max elements \",\n                             output_elements, \")\"));\n        output_t(loc) =\n            gtl::LevenshteinDistance(truth_seq, hypothesis_seq, cmp);\n        if (normalize_) output_t(loc) /= truth_seq.size();\n\n        ++hypothesis_iter;\n        ++truth_iter;\n      } else if (g_truth > g_hypothesis) {  // zero-length truth\n        auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),\n                                      output_strides.begin(), int64_t{0});\n        OP_REQUIRES(\n            ctx, 0 <= loc && loc < output_elements,\n            errors::Internal(\"Got an inner product \", loc,\n                             \" which would require writing to outside of \"\n                             \"the buffer for the output tensor (max elements \",\n                             output_elements, \")\"));\n        output_t(loc) = hypothesis_seq.size();\n        if (normalize_ && output_t(loc) != 0.0f) {\n          output_t(loc) = std::numeric_limits::infinity();\n        }\n        ++hypothesis_iter;\n      } else {  // zero-length hypothesis\n        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),\n                                      output_strides.begin(), int64_t{0});\n        OP_REQUIRES(\n            ctx, 0 <= loc && loc < output_elements,\n            errors::Internal(\"Got an inner product \", loc,\n                             \" which would require writing to outside of \"\n                             \"the buffer for the output tensor (max elements \",\n                             output_elements, \")\"));\n        output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();\n        ++truth_iter;\n      }\n    }\n    while (hypothesis_iter != hypothesis_grouper.end()) {  // zero-length truths\n      sparse::Group hypothesis_j = *hypothesis_iter;\n      std::vector g_hypothesis = hypothesis_j.group();\n      auto hypothesis_seq = hypothesis_j.values();\n      auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),\n                                    output_strides.begin(), int64_t{0});\n      OP_REQUIRES(\n          ctx, 0 <= loc && loc < output_elements,\n          errors::Internal(\"Got an inner product \", loc,\n                           \" which would require writing to outside of the \"\n                           \"buffer for the output tensor (max elements \",\n                           output_elements, \")\"));\n      output_t(loc) = hypothesis_seq.size();\n      if (normalize_ && output_t(loc) != 0.0f) {\n        output_t(loc) = std::numeric_limits::infinity();\n      }\n      ++hypothesis_iter;\n    }\n    while (truth_iter != truth_grouper.end()) {  // missing hypotheses\n      sparse::Group truth_i = *truth_iter;\n      std::vector g_truth = truth_i.group();\n      auto truth_seq = truth_i.values();\n      auto loc = std::inner_product(g_truth.begin(), g_truth.end(),\n                                    output_strides.begin(), int64_t{0});\n      OP_REQUIRES(\n          ctx, 0 <= loc && loc < output_elements,\n          errors::Internal(\"Got an inner product \", loc,\n                           \" which would require writing to outside of the \"\n                           \"buffer for the output tensor (max elements \",\n                           output_elements, \")\"));\n      output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();\n      ++truth_iter;\n    }\n  }", "func_hash": 248166369480919859740493813092777127281, "file_name": "edit_distance_op.cc", "file_hash": 224900034498319197270351200055296266799, "cwe": ["CWE-787"], "cve": "CVE-2022-29208", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.EditDistance` has incomplete validation. Users can pass negative values to cause a segmentation fault based denial of service. In multiple places throughout the code, one may compute an index for a write operation. However, the existing validation only checks against the upper bound of the array. Hence, it is possible to write before the array by massaging the input to generate negative values for `loc`. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29208"}
{"idx": 195984, "project": "gpac", "commit_id": "3dbe11b37d65c8472faf0654410068e5500b3adb", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/3dbe11b37d65c8472faf0654410068e5500b3adb", "commit_message": "fixed #2175", "target": 1, "func": "GF_Err diST_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tu32 i;\n\tchar str[1024];\n\tGF_DIMSScriptTypesBox *p = (GF_DIMSScriptTypesBox *)s;\n\n\ti=0;\n\tstr[0]=0;\n\twhile (1) {\n\t\tstr[i] = gf_bs_read_u8(bs);\n\t\tif (!str[i]) break;\n\t\ti++;\n\t}\n\tISOM_DECREASE_SIZE(p, i);\n\n\tp->content_script_types = gf_strdup(str);\n\treturn GF_OK;\n}", "func_hash": 337508066102203205232219987774332438264, "file_name": "box_code_3gpp.c", "file_hash": 236995747067078276861335410375287788449, "cwe": ["CWE-703"], "cve": "CVE-2022-1441", "cve_desc": "MP4Box is a component of GPAC-2.0.0, which is a widely-used third-party package on RPM Fusion. When MP4Box tries to parse a MP4 file, it calls the function `diST_box_read()` to read from video. In this function, it allocates a buffer `str` with fixed length. However, content read from `bs` is controllable by user, so is the length, which causes a buffer overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1441"}
{"idx": 236125, "project": "gpac", "commit_id": "3dbe11b37d65c8472faf0654410068e5500b3adb", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/3dbe11b37d65c8472faf0654410068e5500b3adb", "commit_message": "fixed #2175", "target": 0, "func": "GF_Err diST_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tGF_DIMSScriptTypesBox *p = (GF_DIMSScriptTypesBox *)s;\n\n\tp->content_script_types = gf_malloc(sizeof(char) * (s->size+1));\n\tif (!p->content_script_types) return GF_OUT_OF_MEM;\n\tgf_bs_read_data(bs, p->content_script_types, s->size);\n\tp->content_script_types[s->size] = 0;\n\treturn GF_OK;\n}", "func_hash": 296645158113148498272091333023062986276, "file_name": "box_code_3gpp.c", "file_hash": 53964259103061248299506412136196602333, "cwe": ["CWE-703"], "cve": "CVE-2022-1441", "cve_desc": "MP4Box is a component of GPAC-2.0.0, which is a widely-used third-party package on RPM Fusion. When MP4Box tries to parse a MP4 file, it calls the function `diST_box_read()` to read from video. In this function, it allocates a buffer `str` with fixed length. However, content read from `bs` is controllable by user, so is the length, which causes a buffer overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1441"}
{"idx": 196276, "project": "lsquic", "commit_id": "a74702c630e108125e71898398737baec8f02238", "project_url": "https://github.com/litespeedtech/lsquic", "commit_url": "https://github.com/litespeedtech/lsquic/commit/a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "target": 1, "func": "lsquic_qeh_settings (struct qpack_enc_hdl *qeh, unsigned max_table_size,\n             unsigned dyn_table_size, unsigned max_risked_streams, int server)\n{\n    enum lsqpack_enc_opts enc_opts;\n\n    assert(qeh->qeh_flags & QEH_INITIALIZED);\n\n    if (qeh->qeh_flags & QEH_HAVE_SETTINGS)\n    {\n        LSQ_WARN(\"settings already set\");\n        return -1;\n    }\n\n    enc_opts = LSQPACK_ENC_OPT_STAGE_2\n             | (server ? LSQPACK_ENC_OPT_SERVER : 0);\n    qeh->qeh_tsu_sz = sizeof(qeh->qeh_tsu_buf);\n    if (0 != lsqpack_enc_init(&qeh->qeh_encoder, (void *) qeh->qeh_conn,\n                max_table_size, dyn_table_size, max_risked_streams, enc_opts,\n                qeh->qeh_tsu_buf, &qeh->qeh_tsu_sz))\n    {\n        LSQ_INFO(\"could not initialize QPACK encoder\");\n        return -1;\n    }\n    LSQ_DEBUG(\"%zu-byte post-init TSU\", qeh->qeh_tsu_sz);\n    qeh->qeh_flags |= QEH_HAVE_SETTINGS;\n    qeh->qeh_max_prefix_size =\n                        lsqpack_enc_header_block_prefix_size(&qeh->qeh_encoder);\n    LSQ_DEBUG(\"have settings: max table size=%u; dyn table size=%u; max risked \"\n        \"streams=%u\", max_table_size, dyn_table_size, max_risked_streams);\n    if (qeh->qeh_enc_sm_out)\n        qeh_begin_out(qeh);\n    return 0;\n}", "func_hash": 304358665951404548699605657299704903588, "file_name": "None", "file_hash": null, "cwe": ["CWE-269"], "cve": "CVE-2022-30592", "cve_desc": "liblsquic/lsquic_qenc_hdl.c in LiteSpeed QUIC (aka LSQUIC) before 3.1.0 mishandles MAX_TABLE_CAPACITY.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-30592"}
{"idx": 237885, "project": "lsquic", "commit_id": "a74702c630e108125e71898398737baec8f02238", "project_url": "https://github.com/litespeedtech/lsquic", "commit_url": "https://github.com/litespeedtech/lsquic/commit/a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "target": 0, "func": "lsquic_qeh_settings (struct qpack_enc_hdl *qeh, unsigned max_table_size,\n             unsigned dyn_table_size, unsigned max_risked_streams, int server)\n{\n    enum lsqpack_enc_opts enc_opts;\n\n    assert(qeh->qeh_flags & QEH_INITIALIZED);\n\n    if (qeh->qeh_flags & QEH_HAVE_SETTINGS)\n    {\n        LSQ_WARN(\"settings already set\");\n        return -1;\n    }\n\n    enc_opts = LSQPACK_ENC_OPT_STAGE_2\n             | (server ? LSQPACK_ENC_OPT_SERVER : 0);\n    qeh->qeh_tsu_sz = sizeof(qeh->qeh_tsu_buf);\n    if (QENC_MIN_DYN_TABLE_SIZE > dyn_table_size)\n        dyn_table_size = 0;\n    if (0 != lsqpack_enc_init(&qeh->qeh_encoder, (void *) qeh->qeh_conn,\n                max_table_size, dyn_table_size, max_risked_streams, enc_opts,\n                qeh->qeh_tsu_buf, &qeh->qeh_tsu_sz))\n    {\n        LSQ_INFO(\"could not initialize QPACK encoder\");\n        return -1;\n    }\n    LSQ_DEBUG(\"%zu-byte post-init TSU\", qeh->qeh_tsu_sz);\n    qeh->qeh_flags |= QEH_HAVE_SETTINGS;\n    qeh->qeh_max_prefix_size =\n                        lsqpack_enc_header_block_prefix_size(&qeh->qeh_encoder);\n    LSQ_DEBUG(\"have settings: max table size=%u; dyn table size=%u; max risked \"\n        \"streams=%u\", max_table_size, dyn_table_size, max_risked_streams);\n    if (qeh->qeh_enc_sm_out)\n        qeh_begin_out(qeh);\n    return 0;\n}", "func_hash": 213495580933926260913554982368628219722, "file_name": "None", "file_hash": null, "cwe": ["CWE-269"], "cve": "CVE-2022-30592", "cve_desc": "liblsquic/lsquic_qenc_hdl.c in LiteSpeed QUIC (aka LSQUIC) before 3.1.0 mishandles MAX_TABLE_CAPACITY.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-30592"}
{"idx": 196316, "project": "barebox", "commit_id": "0a9f9a7410681e55362f8311537ebc7be9ad0fbe", "project_url": "https://github.com/saschahauer/barebox", "commit_url": "https://github.com/saschahauer/barebox/commit/0a9f9a7410681e55362f8311537ebc7be9ad0fbe", "commit_message": "crypto: digest: use crypto_memneq()\n\nWhen verifying a digest it is important not to leak timing information\nthrough memcmp(). Use crypto_memneq() instead.\n\nSigned-off-by: Sascha Hauer ", "target": 1, "func": "int digest_generic_verify(struct digest *d, const unsigned char *md)\n{\n\tint ret;\n\tint len = digest_length(d);\n\tunsigned char *tmp;\n\n\ttmp = xmalloc(len);\n\n\tret = digest_final(d, tmp);\n\tif (ret)\n\t\tgoto end;\n\n\tret = memcmp(md, tmp, len);\n\tret = ret ? -EINVAL : 0;\nend:\n\tfree(tmp);\n\treturn ret;\n}", "func_hash": 71480685616976545176363965575731858659, "file_name": "digest.c", "file_hash": 309636649404648894565051311749383985179, "cwe": ["CWE-200"], "cve": "CVE-2021-37847", "cve_desc": "crypto/digest.c in Pengutronix barebox through 2021.07.0 leaks timing information because memcmp is used during digest verification.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37847"}
{"idx": 238322, "project": "barebox", "commit_id": "0a9f9a7410681e55362f8311537ebc7be9ad0fbe", "project_url": "https://github.com/saschahauer/barebox", "commit_url": "https://github.com/saschahauer/barebox/commit/0a9f9a7410681e55362f8311537ebc7be9ad0fbe", "commit_message": "crypto: digest: use crypto_memneq()\n\nWhen verifying a digest it is important not to leak timing information\nthrough memcmp(). Use crypto_memneq() instead.\n\nSigned-off-by: Sascha Hauer ", "target": 0, "func": "int digest_generic_verify(struct digest *d, const unsigned char *md)\n{\n\tint ret;\n\tint len = digest_length(d);\n\tunsigned char *tmp;\n\n\ttmp = xmalloc(len);\n\n\tret = digest_final(d, tmp);\n\tif (ret)\n\t\tgoto end;\n\n\tif (crypto_memneq(md, tmp, len))\n\t\tret = -EINVAL;\n\telse\n\t\tret = 0;\nend:\n\tfree(tmp);\n\treturn ret;\n}", "func_hash": 320239189684468072245266956547158344510, "file_name": "digest.c", "file_hash": 195235961590850585727206932057971391683, "cwe": ["CWE-200"], "cve": "CVE-2021-37847", "cve_desc": "crypto/digest.c in Pengutronix barebox through 2021.07.0 leaks timing information because memcmp is used during digest verification.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37847"}
{"idx": 196328, "project": "vim", "commit_id": "409510c588b1eec1ae33511ae97a21eb8e110895", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/409510c588b1eec1ae33511ae97a21eb8e110895", "commit_message": "patch 8.2.5050: using freed memory when searching for pattern in path\n\nProblem:    Using freed memory when searching for pattern in path.\nSolution:   Make a copy of the line.", "target": 1, "func": "find_pattern_in_path(\n    char_u\t*ptr,\t\t// pointer to search pattern\n    int\t\tdir UNUSED,\t// direction of expansion\n    int\t\tlen,\t\t// length of search pattern\n    int\t\twhole,\t\t// match whole words only\n    int\t\tskip_comments,\t// don't match inside comments\n    int\t\ttype,\t\t// Type of search; are we looking for a type?\n\t\t\t\t// a macro?\n    long\tcount,\n    int\t\taction,\t\t// What to do when we find it\n    linenr_T\tstart_lnum,\t// first line to start searching\n    linenr_T\tend_lnum)\t// last line for searching\n{\n    SearchedFile *files;\t\t// Stack of included files\n    SearchedFile *bigger;\t\t// When we need more space\n    int\t\tmax_path_depth = 50;\n    long\tmatch_count = 1;\n\n    char_u\t*pat;\n    char_u\t*new_fname;\n    char_u\t*curr_fname = curbuf->b_fname;\n    char_u\t*prev_fname = NULL;\n    linenr_T\tlnum;\n    int\t\tdepth;\n    int\t\tdepth_displayed;\t// For type==CHECK_PATH\n    int\t\told_files;\n    int\t\talready_searched;\n    char_u\t*file_line;\n    char_u\t*line;\n    char_u\t*p;\n    char_u\tsave_char;\n    int\t\tdefine_matched;\n    regmatch_T\tregmatch;\n    regmatch_T\tincl_regmatch;\n    regmatch_T\tdef_regmatch;\n    int\t\tmatched = FALSE;\n    int\t\tdid_show = FALSE;\n    int\t\tfound = FALSE;\n    int\t\ti;\n    char_u\t*already = NULL;\n    char_u\t*startp = NULL;\n    char_u\t*inc_opt = NULL;\n#if defined(FEAT_QUICKFIX)\n    win_T\t*curwin_save = NULL;\n#endif\n\n    regmatch.regprog = NULL;\n    incl_regmatch.regprog = NULL;\n    def_regmatch.regprog = NULL;\n\n    file_line = alloc(LSIZE);\n    if (file_line == NULL)\n\treturn;\n\n    if (type != CHECK_PATH && type != FIND_DEFINE\n\t    // when CONT_SOL is set compare \"ptr\" with the beginning of the\n\t    // line is faster than quote_meta/regcomp/regexec \"ptr\" -- Acevedo\n\t    && !compl_status_sol())\n    {\n\tpat = alloc(len + 5);\n\tif (pat == NULL)\n\t    goto fpip_end;\n\tsprintf((char *)pat, whole ? \"\\\\<%.*s\\\\>\" : \"%.*s\", len, ptr);\n\t// ignore case according to p_ic, p_scs and pat\n\tregmatch.rm_ic = ignorecase(pat);\n\tregmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);\n\tvim_free(pat);\n\tif (regmatch.regprog == NULL)\n\t    goto fpip_end;\n    }\n    inc_opt = (*curbuf->b_p_inc == NUL) ? p_inc : curbuf->b_p_inc;\n    if (*inc_opt != NUL)\n    {\n\tincl_regmatch.regprog = vim_regcomp(inc_opt,\n\t\t\t\t\t\t magic_isset() ? RE_MAGIC : 0);\n\tif (incl_regmatch.regprog == NULL)\n\t    goto fpip_end;\n\tincl_regmatch.rm_ic = FALSE;\t// don't ignore case in incl. pat.\n    }\n    if (type == FIND_DEFINE && (*curbuf->b_p_def != NUL || *p_def != NUL))\n    {\n\tdef_regmatch.regprog = vim_regcomp(*curbuf->b_p_def == NUL\n\t\t\t   ? p_def : curbuf->b_p_def,\n\t\t\t\t\t\t magic_isset() ? RE_MAGIC : 0);\n\tif (def_regmatch.regprog == NULL)\n\t    goto fpip_end;\n\tdef_regmatch.rm_ic = FALSE;\t// don't ignore case in define pat.\n    }\n    files = lalloc_clear(max_path_depth * sizeof(SearchedFile), TRUE);\n    if (files == NULL)\n\tgoto fpip_end;\n    old_files = max_path_depth;\n    depth = depth_displayed = -1;\n\n    lnum = start_lnum;\n    if (end_lnum > curbuf->b_ml.ml_line_count)\n\tend_lnum = curbuf->b_ml.ml_line_count;\n    if (lnum > end_lnum)\t\t// do at least one line\n\tlnum = end_lnum;\n    line = ml_get(lnum);\n\n    for (;;)\n    {\n\tif (incl_regmatch.regprog != NULL\n\t\t&& vim_regexec(&incl_regmatch, line, (colnr_T)0))\n\t{\n\t    char_u *p_fname = (curr_fname == curbuf->b_fname)\n\t\t\t\t\t      ? curbuf->b_ffname : curr_fname;\n\n\t    if (inc_opt != NULL && strstr((char *)inc_opt, \"\\\\zs\") != NULL)\n\t\t// Use text from '\\zs' to '\\ze' (or end) of 'include'.\n\t\tnew_fname = find_file_name_in_path(incl_regmatch.startp[0],\n\t\t       (int)(incl_regmatch.endp[0] - incl_regmatch.startp[0]),\n\t\t\t\t FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname);\n\t    else\n\t\t// Use text after match with 'include'.\n\t\tnew_fname = file_name_in_line(incl_regmatch.endp[0], 0,\n\t\t\t     FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL);\n\t    already_searched = FALSE;\n\t    if (new_fname != NULL)\n\t    {\n\t\t// Check whether we have already searched in this file\n\t\tfor (i = 0;; i++)\n\t\t{\n\t\t    if (i == depth + 1)\n\t\t\ti = old_files;\n\t\t    if (i == max_path_depth)\n\t\t\tbreak;\n\t\t    if (fullpathcmp(new_fname, files[i].name, TRUE, TRUE)\n\t\t\t\t\t\t\t\t    & FPC_SAME)\n\t\t    {\n\t\t\tif (type != CHECK_PATH\n\t\t\t\t&& action == ACTION_SHOW_ALL\n\t\t\t\t&& files[i].matched)\n\t\t\t{\n\t\t\t    msg_putchar('\\n');\t    // cursor below last one\n\t\t\t    if (!got_int)\t    // don't display if 'q'\n\t\t\t\t\t\t    // typed at \"--more--\"\n\t\t\t\t\t\t    // message\n\t\t\t    {\n\t\t\t\tmsg_home_replace_hl(new_fname);\n\t\t\t\tmsg_puts(_(\" (includes previously listed match)\"));\n\t\t\t\tprev_fname = NULL;\n\t\t\t    }\n\t\t\t}\n\t\t\tVIM_CLEAR(new_fname);\n\t\t\talready_searched = TRUE;\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t    }\n\n\t    if (type == CHECK_PATH && (action == ACTION_SHOW_ALL\n\t\t\t\t || (new_fname == NULL && !already_searched)))\n\t    {\n\t\tif (did_show)\n\t\t    msg_putchar('\\n');\t    // cursor below last one\n\t\telse\n\t\t{\n\t\t    gotocmdline(TRUE);\t    // cursor at status line\n\t\t    msg_puts_title(_(\"--- Included files \"));\n\t\t    if (action != ACTION_SHOW_ALL)\n\t\t\tmsg_puts_title(_(\"not found \"));\n\t\t    msg_puts_title(_(\"in path ---\\n\"));\n\t\t}\n\t\tdid_show = TRUE;\n\t\twhile (depth_displayed < depth && !got_int)\n\t\t{\n\t\t    ++depth_displayed;\n\t\t    for (i = 0; i < depth_displayed; i++)\n\t\t\tmsg_puts(\"  \");\n\t\t    msg_home_replace(files[depth_displayed].name);\n\t\t    msg_puts(\" -->\\n\");\n\t\t}\n\t\tif (!got_int)\t\t    // don't display if 'q' typed\n\t\t\t\t\t    // for \"--more--\" message\n\t\t{\n\t\t    for (i = 0; i <= depth_displayed; i++)\n\t\t\tmsg_puts(\"  \");\n\t\t    if (new_fname != NULL)\n\t\t    {\n\t\t\t// using \"new_fname\" is more reliable, e.g., when\n\t\t\t// 'includeexpr' is set.\n\t\t\tmsg_outtrans_attr(new_fname, HL_ATTR(HLF_D));\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\t/*\n\t\t\t * Isolate the file name.\n\t\t\t * Include the surrounding \"\" or <> if present.\n\t\t\t */\n\t\t\tif (inc_opt != NULL\n\t\t\t\t   && strstr((char *)inc_opt, \"\\\\zs\") != NULL)\n\t\t\t{\n\t\t\t    // pattern contains \\zs, use the match\n\t\t\t    p = incl_regmatch.startp[0];\n\t\t\t    i = (int)(incl_regmatch.endp[0]\n\t\t\t\t\t\t   - incl_regmatch.startp[0]);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t    // find the file name after the end of the match\n\t\t\t    for (p = incl_regmatch.endp[0];\n\t\t\t\t\t\t  *p && !vim_isfilec(*p); p++)\n\t\t\t\t;\n\t\t\t    for (i = 0; vim_isfilec(p[i]); i++)\n\t\t\t\t;\n\t\t\t}\n\n\t\t\tif (i == 0)\n\t\t\t{\n\t\t\t    // Nothing found, use the rest of the line.\n\t\t\t    p = incl_regmatch.endp[0];\n\t\t\t    i = (int)STRLEN(p);\n\t\t\t}\n\t\t\t// Avoid checking before the start of the line, can\n\t\t\t// happen if \\zs appears in the regexp.\n\t\t\telse if (p > line)\n\t\t\t{\n\t\t\t    if (p[-1] == '\"' || p[-1] == '<')\n\t\t\t    {\n\t\t\t\t--p;\n\t\t\t\t++i;\n\t\t\t    }\n\t\t\t    if (p[i] == '\"' || p[i] == '>')\n\t\t\t\t++i;\n\t\t\t}\n\t\t\tsave_char = p[i];\n\t\t\tp[i] = NUL;\n\t\t\tmsg_outtrans_attr(p, HL_ATTR(HLF_D));\n\t\t\tp[i] = save_char;\n\t\t    }\n\n\t\t    if (new_fname == NULL && action == ACTION_SHOW_ALL)\n\t\t    {\n\t\t\tif (already_searched)\n\t\t\t    msg_puts(_(\"  (Already listed)\"));\n\t\t\telse\n\t\t\t    msg_puts(_(\"  NOT FOUND\"));\n\t\t    }\n\t\t}\n\t\tout_flush();\t    // output each line directly\n\t    }\n\n\t    if (new_fname != NULL)\n\t    {\n\t\t// Push the new file onto the file stack\n\t\tif (depth + 1 == old_files)\n\t\t{\n\t\t    bigger = ALLOC_MULT(SearchedFile, max_path_depth * 2);\n\t\t    if (bigger != NULL)\n\t\t    {\n\t\t\tfor (i = 0; i <= depth; i++)\n\t\t\t    bigger[i] = files[i];\n\t\t\tfor (i = depth + 1; i < old_files + max_path_depth; i++)\n\t\t\t{\n\t\t\t    bigger[i].fp = NULL;\n\t\t\t    bigger[i].name = NULL;\n\t\t\t    bigger[i].lnum = 0;\n\t\t\t    bigger[i].matched = FALSE;\n\t\t\t}\n\t\t\tfor (i = old_files; i < max_path_depth; i++)\n\t\t\t    bigger[i + max_path_depth] = files[i];\n\t\t\told_files += max_path_depth;\n\t\t\tmax_path_depth *= 2;\n\t\t\tvim_free(files);\n\t\t\tfiles = bigger;\n\t\t    }\n\t\t}\n\t\tif ((files[depth + 1].fp = mch_fopen((char *)new_fname, \"r\"))\n\t\t\t\t\t\t\t\t    == NULL)\n\t\t    vim_free(new_fname);\n\t\telse\n\t\t{\n\t\t    if (++depth == old_files)\n\t\t    {\n\t\t\t/*\n\t\t\t * lalloc() for 'bigger' must have failed above.  We\n\t\t\t * will forget one of our already visited files now.\n\t\t\t */\n\t\t\tvim_free(files[old_files].name);\n\t\t\t++old_files;\n\t\t    }\n\t\t    files[depth].name = curr_fname = new_fname;\n\t\t    files[depth].lnum = 0;\n\t\t    files[depth].matched = FALSE;\n\t\t    if (action == ACTION_EXPAND)\n\t\t    {\n\t\t\tmsg_hist_off = TRUE;\t// reset in msg_trunc_attr()\n\t\t\tvim_snprintf((char*)IObuff, IOSIZE,\n\t\t\t\t_(\"Scanning included file: %s\"),\n\t\t\t\t(char *)new_fname);\n\t\t\tmsg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));\n\t\t    }\n\t\t    else if (p_verbose >= 5)\n\t\t    {\n\t\t\tverbose_enter();\n\t\t\tsmsg(_(\"Searching included file %s\"),\n\t\t\t\t\t\t\t   (char *)new_fname);\n\t\t\tverbose_leave();\n\t\t    }\n\n\t\t}\n\t    }\n\t}\n\telse\n\t{\n\t    /*\n\t     * Check if the line is a define (type == FIND_DEFINE)\n\t     */\n\t    p = line;\nsearch_line:\n\t    define_matched = FALSE;\n\t    if (def_regmatch.regprog != NULL\n\t\t\t      && vim_regexec(&def_regmatch, line, (colnr_T)0))\n\t    {\n\t\t/*\n\t\t * Pattern must be first identifier after 'define', so skip\n\t\t * to that position before checking for match of pattern.  Also\n\t\t * don't let it match beyond the end of this identifier.\n\t\t */\n\t\tp = def_regmatch.endp[0];\n\t\twhile (*p && !vim_iswordc(*p))\n\t\t    p++;\n\t\tdefine_matched = TRUE;\n\t    }\n\n\t    /*\n\t     * Look for a match.  Don't do this if we are looking for a\n\t     * define and this line didn't match define_prog above.\n\t     */\n\t    if (def_regmatch.regprog == NULL || define_matched)\n\t    {\n\t\tif (define_matched || compl_status_sol())\n\t\t{\n\t\t    // compare the first \"len\" chars from \"ptr\"\n\t\t    startp = skipwhite(p);\n\t\t    if (p_ic)\n\t\t\tmatched = !MB_STRNICMP(startp, ptr, len);\n\t\t    else\n\t\t\tmatched = !STRNCMP(startp, ptr, len);\n\t\t    if (matched && define_matched && whole\n\t\t\t\t\t\t  && vim_iswordc(startp[len]))\n\t\t\tmatched = FALSE;\n\t\t}\n\t\telse if (regmatch.regprog != NULL\n\t\t\t && vim_regexec(®match, line, (colnr_T)(p - line)))\n\t\t{\n\t\t    matched = TRUE;\n\t\t    startp = regmatch.startp[0];\n\t\t    /*\n\t\t     * Check if the line is not a comment line (unless we are\n\t\t     * looking for a define).  A line starting with \"# define\"\n\t\t     * is not considered to be a comment line.\n\t\t     */\n\t\t    if (!define_matched && skip_comments)\n\t\t    {\n\t\t\tif ((*line != '#' ||\n\t\t\t\tSTRNCMP(skipwhite(line + 1), \"define\", 6) != 0)\n\t\t\t\t&& get_leader_len(line, NULL, FALSE, TRUE))\n\t\t\t    matched = FALSE;\n\n\t\t\t/*\n\t\t\t * Also check for a \"/ *\" or \"/ /\" before the match.\n\t\t\t * Skips lines like \"int backwards;  / * normal index\n\t\t\t * * /\" when looking for \"normal\".\n\t\t\t * Note: Doesn't skip \"/ *\" in comments.\n\t\t\t */\n\t\t\tp = skipwhite(line);\n\t\t\tif (matched\n\t\t\t\t|| (p[0] == '/' && p[1] == '*') || p[0] == '*')\n\t\t\t    for (p = line; *p && p < startp; ++p)\n\t\t\t    {\n\t\t\t\tif (matched\n\t\t\t\t\t&& p[0] == '/'\n\t\t\t\t\t&& (p[1] == '*' || p[1] == '/'))\n\t\t\t\t{\n\t\t\t\t    matched = FALSE;\n\t\t\t\t    // After \"//\" all text is comment\n\t\t\t\t    if (p[1] == '/')\n\t\t\t\t\tbreak;\n\t\t\t\t    ++p;\n\t\t\t\t}\n\t\t\t\telse if (!matched && p[0] == '*' && p[1] == '/')\n\t\t\t\t{\n\t\t\t\t    // Can find match after \"* /\".\n\t\t\t\t    matched = TRUE;\n\t\t\t\t    ++p;\n\t\t\t\t}\n\t\t\t    }\n\t\t    }\n\t\t}\n\t    }\n\t}\n\tif (matched)\n\t{\n\t    if (action == ACTION_EXPAND)\n\t    {\n\t\tint\tcont_s_ipos = FALSE;\n\t\tint\tadd_r;\n\t\tchar_u\t*aux;\n\n\t\tif (depth == -1 && lnum == curwin->w_cursor.lnum)\n\t\t    break;\n\t\tfound = TRUE;\n\t\taux = p = startp;\n\t\tif (compl_status_adding())\n\t\t{\n\t\t    p += ins_compl_len();\n\t\t    if (vim_iswordp(p))\n\t\t\tgoto exit_matched;\n\t\t    p = find_word_start(p);\n\t\t}\n\t\tp = find_word_end(p);\n\t\ti = (int)(p - aux);\n\n\t\tif (compl_status_adding() && i == ins_compl_len())\n\t\t{\n\t\t    // IOSIZE > compl_length, so the STRNCPY works\n\t\t    STRNCPY(IObuff, aux, i);\n\n\t\t    // Get the next line: when \"depth\" < 0  from the current\n\t\t    // buffer, otherwise from the included file.  Jump to\n\t\t    // exit_matched when past the last line.\n\t\t    if (depth < 0)\n\t\t    {\n\t\t\tif (lnum >= end_lnum)\n\t\t\t    goto exit_matched;\n\t\t\tline = ml_get(++lnum);\n\t\t    }\n\t\t    else if (vim_fgets(line = file_line,\n\t\t\t\t\t\t      LSIZE, files[depth].fp))\n\t\t\tgoto exit_matched;\n\n\t\t    // we read a line, set \"already\" to check this \"line\" later\n\t\t    // if depth >= 0 we'll increase files[depth].lnum far\n\t\t    // below  -- Acevedo\n\t\t    already = aux = p = skipwhite(line);\n\t\t    p = find_word_start(p);\n\t\t    p = find_word_end(p);\n\t\t    if (p > aux)\n\t\t    {\n\t\t\tif (*aux != ')' && IObuff[i-1] != TAB)\n\t\t\t{\n\t\t\t    if (IObuff[i-1] != ' ')\n\t\t\t\tIObuff[i++] = ' ';\n\t\t\t    // IObuf =~ \"\\(\\k\\|\\i\\).* \", thus i >= 2\n\t\t\t    if (p_js\n\t\t\t\t&& (IObuff[i-2] == '.'\n\t\t\t\t    || (vim_strchr(p_cpo, CPO_JOINSP) == NULL\n\t\t\t\t\t&& (IObuff[i-2] == '?'\n\t\t\t\t\t    || IObuff[i-2] == '!'))))\n\t\t\t\tIObuff[i++] = ' ';\n\t\t\t}\n\t\t\t// copy as much as possible of the new word\n\t\t\tif (p - aux >= IOSIZE - i)\n\t\t\t    p = aux + IOSIZE - i - 1;\n\t\t\tSTRNCPY(IObuff + i, aux, p - aux);\n\t\t\ti += (int)(p - aux);\n\t\t\tcont_s_ipos = TRUE;\n\t\t    }\n\t\t    IObuff[i] = NUL;\n\t\t    aux = IObuff;\n\n\t\t    if (i == ins_compl_len())\n\t\t\tgoto exit_matched;\n\t\t}\n\n\t\tadd_r = ins_compl_add_infercase(aux, i, p_ic,\n\t\t\tcurr_fname == curbuf->b_fname ? NULL : curr_fname,\n\t\t\tdir, cont_s_ipos);\n\t\tif (add_r == OK)\n\t\t    // if dir was BACKWARD then honor it just once\n\t\t    dir = FORWARD;\n\t\telse if (add_r == FAIL)\n\t\t    break;\n\t    }\n\t    else if (action == ACTION_SHOW_ALL)\n\t    {\n\t\tfound = TRUE;\n\t\tif (!did_show)\n\t\t    gotocmdline(TRUE);\t\t// cursor at status line\n\t\tif (curr_fname != prev_fname)\n\t\t{\n\t\t    if (did_show)\n\t\t\tmsg_putchar('\\n');\t// cursor below last one\n\t\t    if (!got_int)\t\t// don't display if 'q' typed\n\t\t\t\t\t\t// at \"--more--\" message\n\t\t\tmsg_home_replace_hl(curr_fname);\n\t\t    prev_fname = curr_fname;\n\t\t}\n\t\tdid_show = TRUE;\n\t\tif (!got_int)\n\t\t    show_pat_in_path(line, type, TRUE, action,\n\t\t\t    (depth == -1) ? NULL : files[depth].fp,\n\t\t\t    (depth == -1) ? &lnum : &files[depth].lnum,\n\t\t\t    match_count++);\n\n\t\t// Set matched flag for this file and all the ones that\n\t\t// include it\n\t\tfor (i = 0; i <= depth; ++i)\n\t\t    files[i].matched = TRUE;\n\t    }\n\t    else if (--count <= 0)\n\t    {\n\t\tfound = TRUE;\n\t\tif (depth == -1 && lnum == curwin->w_cursor.lnum\n#if defined(FEAT_QUICKFIX)\n\t\t\t\t\t\t      && g_do_tagpreview == 0\n#endif\n\t\t\t\t\t\t      )\n\t\t    emsg(_(e_match_is_on_current_line));\n\t\telse if (action == ACTION_SHOW)\n\t\t{\n\t\t    show_pat_in_path(line, type, did_show, action,\n\t\t\t(depth == -1) ? NULL : files[depth].fp,\n\t\t\t(depth == -1) ? &lnum : &files[depth].lnum, 1L);\n\t\t    did_show = TRUE;\n\t\t}\n\t\telse\n\t\t{\n#ifdef FEAT_GUI\n\t\t    need_mouse_correct = TRUE;\n#endif\n#if defined(FEAT_QUICKFIX)\n\t\t    // \":psearch\" uses the preview window\n\t\t    if (g_do_tagpreview != 0)\n\t\t    {\n\t\t\tcurwin_save = curwin;\n\t\t\tprepare_tagpreview(TRUE, TRUE, FALSE);\n\t\t    }\n#endif\n\t\t    if (action == ACTION_SPLIT)\n\t\t    {\n\t\t\tif (win_split(0, 0) == FAIL)\n\t\t\t    break;\n\t\t\tRESET_BINDING(curwin);\n\t\t    }\n\t\t    if (depth == -1)\n\t\t    {\n\t\t\t// match in current file\n#if defined(FEAT_QUICKFIX)\n\t\t\tif (g_do_tagpreview != 0)\n\t\t\t{\n\t\t\t    if (!win_valid(curwin_save))\n\t\t\t\tbreak;\n\t\t\t    if (!GETFILE_SUCCESS(getfile(\n\t\t\t\t\t   curwin_save->w_buffer->b_fnum, NULL,\n\t\t\t\t\t\t     NULL, TRUE, lnum, FALSE)))\n\t\t\t\tbreak;\t// failed to jump to file\n\t\t\t}\n\t\t\telse\n#endif\n\t\t\t    setpcmark();\n\t\t\tcurwin->w_cursor.lnum = lnum;\n\t\t\tcheck_cursor();\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\tif (!GETFILE_SUCCESS(getfile(\n\t\t\t\t\t0, files[depth].name, NULL, TRUE,\n\t\t\t\t\t\t    files[depth].lnum, FALSE)))\n\t\t\t    break;\t// failed to jump to file\n\t\t\t// autocommands may have changed the lnum, we don't\n\t\t\t// want that here\n\t\t\tcurwin->w_cursor.lnum = files[depth].lnum;\n\t\t    }\n\t\t}\n\t\tif (action != ACTION_SHOW)\n\t\t{\n\t\t    curwin->w_cursor.col = (colnr_T)(startp - line);\n\t\t    curwin->w_set_curswant = TRUE;\n\t\t}\n\n#if defined(FEAT_QUICKFIX)\n\t\tif (g_do_tagpreview != 0\n\t\t\t   && curwin != curwin_save && win_valid(curwin_save))\n\t\t{\n\t\t    // Return cursor to where we were\n\t\t    validate_cursor();\n\t\t    redraw_later(VALID);\n\t\t    win_enter(curwin_save, TRUE);\n\t\t}\n# ifdef FEAT_PROP_POPUP\n\t\telse if (WIN_IS_POPUP(curwin))\n\t\t    // can't keep focus in popup window\n\t\t    win_enter(firstwin, TRUE);\n# endif\n#endif\n\t\tbreak;\n\t    }\nexit_matched:\n\t    matched = FALSE;\n\t    // look for other matches in the rest of the line if we\n\t    // are not at the end of it already\n\t    if (def_regmatch.regprog == NULL\n\t\t    && action == ACTION_EXPAND\n\t\t    && !compl_status_sol()\n\t\t    && *startp != NUL\n\t\t    && *(p = startp + mb_ptr2len(startp)) != NUL)\n\t\tgoto search_line;\n\t}\n\tline_breakcheck();\n\tif (action == ACTION_EXPAND)\n\t    ins_compl_check_keys(30, FALSE);\n\tif (got_int || ins_compl_interrupted())\n\t    break;\n\n\t/*\n\t * Read the next line.  When reading an included file and encountering\n\t * end-of-file, close the file and continue in the file that included\n\t * it.\n\t */\n\twhile (depth >= 0 && !already\n\t\t&& vim_fgets(line = file_line, LSIZE, files[depth].fp))\n\t{\n\t    fclose(files[depth].fp);\n\t    --old_files;\n\t    files[old_files].name = files[depth].name;\n\t    files[old_files].matched = files[depth].matched;\n\t    --depth;\n\t    curr_fname = (depth == -1) ? curbuf->b_fname\n\t\t\t\t       : files[depth].name;\n\t    if (depth < depth_displayed)\n\t\tdepth_displayed = depth;\n\t}\n\tif (depth >= 0)\t\t// we could read the line\n\t{\n\t    files[depth].lnum++;\n\t    // Remove any CR and LF from the line.\n\t    i = (int)STRLEN(line);\n\t    if (i > 0 && line[i - 1] == '\\n')\n\t\tline[--i] = NUL;\n\t    if (i > 0 && line[i - 1] == '\\r')\n\t\tline[--i] = NUL;\n\t}\n\telse if (!already)\n\t{\n\t    if (++lnum > end_lnum)\n\t\tbreak;\n\t    line = ml_get(lnum);\n\t}\n\talready = NULL;\n    }\n    // End of big for (;;) loop.\n\n    // Close any files that are still open.\n    for (i = 0; i <= depth; i++)\n    {\n\tfclose(files[i].fp);\n\tvim_free(files[i].name);\n    }\n    for (i = old_files; i < max_path_depth; i++)\n\tvim_free(files[i].name);\n    vim_free(files);\n\n    if (type == CHECK_PATH)\n    {\n\tif (!did_show)\n\t{\n\t    if (action != ACTION_SHOW_ALL)\n\t\tmsg(_(\"All included files were found\"));\n\t    else\n\t\tmsg(_(\"No included files\"));\n\t}\n    }\n    else if (!found && action != ACTION_EXPAND)\n    {\n\tif (got_int || ins_compl_interrupted())\n\t    emsg(_(e_interrupted));\n\telse if (type == FIND_DEFINE)\n\t    emsg(_(e_couldnt_find_definition));\n\telse\n\t    emsg(_(e_couldnt_find_pattern));\n    }\n    if (action == ACTION_SHOW || action == ACTION_SHOW_ALL)\n\tmsg_end();\n\nfpip_end:\n    vim_free(file_line);\n    vim_regfree(regmatch.regprog);\n    vim_regfree(incl_regmatch.regprog);\n    vim_regfree(def_regmatch.regprog);\n}", "func_hash": 123923862521809134964983633516065480238, "file_name": "search.c", "file_hash": 229512534202460810065416633781657256150, "cwe": ["CWE-416"], "cve": "CVE-2022-1968", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1968"}
{"idx": 238803, "project": "vim", "commit_id": "409510c588b1eec1ae33511ae97a21eb8e110895", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/409510c588b1eec1ae33511ae97a21eb8e110895", "commit_message": "patch 8.2.5050: using freed memory when searching for pattern in path\n\nProblem:    Using freed memory when searching for pattern in path.\nSolution:   Make a copy of the line.", "target": 0, "func": "find_pattern_in_path(\n    char_u\t*ptr,\t\t// pointer to search pattern\n    int\t\tdir UNUSED,\t// direction of expansion\n    int\t\tlen,\t\t// length of search pattern\n    int\t\twhole,\t\t// match whole words only\n    int\t\tskip_comments,\t// don't match inside comments\n    int\t\ttype,\t\t// Type of search; are we looking for a type?\n\t\t\t\t// a macro?\n    long\tcount,\n    int\t\taction,\t\t// What to do when we find it\n    linenr_T\tstart_lnum,\t// first line to start searching\n    linenr_T\tend_lnum)\t// last line for searching\n{\n    SearchedFile *files;\t\t// Stack of included files\n    SearchedFile *bigger;\t\t// When we need more space\n    int\t\tmax_path_depth = 50;\n    long\tmatch_count = 1;\n\n    char_u\t*pat;\n    char_u\t*new_fname;\n    char_u\t*curr_fname = curbuf->b_fname;\n    char_u\t*prev_fname = NULL;\n    linenr_T\tlnum;\n    int\t\tdepth;\n    int\t\tdepth_displayed;\t// For type==CHECK_PATH\n    int\t\told_files;\n    int\t\talready_searched;\n    char_u\t*file_line;\n    char_u\t*line;\n    char_u\t*p;\n    char_u\tsave_char;\n    int\t\tdefine_matched;\n    regmatch_T\tregmatch;\n    regmatch_T\tincl_regmatch;\n    regmatch_T\tdef_regmatch;\n    int\t\tmatched = FALSE;\n    int\t\tdid_show = FALSE;\n    int\t\tfound = FALSE;\n    int\t\ti;\n    char_u\t*already = NULL;\n    char_u\t*startp = NULL;\n    char_u\t*inc_opt = NULL;\n#if defined(FEAT_QUICKFIX)\n    win_T\t*curwin_save = NULL;\n#endif\n\n    regmatch.regprog = NULL;\n    incl_regmatch.regprog = NULL;\n    def_regmatch.regprog = NULL;\n\n    file_line = alloc(LSIZE);\n    if (file_line == NULL)\n\treturn;\n\n    if (type != CHECK_PATH && type != FIND_DEFINE\n\t    // when CONT_SOL is set compare \"ptr\" with the beginning of the\n\t    // line is faster than quote_meta/regcomp/regexec \"ptr\" -- Acevedo\n\t    && !compl_status_sol())\n    {\n\tpat = alloc(len + 5);\n\tif (pat == NULL)\n\t    goto fpip_end;\n\tsprintf((char *)pat, whole ? \"\\\\<%.*s\\\\>\" : \"%.*s\", len, ptr);\n\t// ignore case according to p_ic, p_scs and pat\n\tregmatch.rm_ic = ignorecase(pat);\n\tregmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);\n\tvim_free(pat);\n\tif (regmatch.regprog == NULL)\n\t    goto fpip_end;\n    }\n    inc_opt = (*curbuf->b_p_inc == NUL) ? p_inc : curbuf->b_p_inc;\n    if (*inc_opt != NUL)\n    {\n\tincl_regmatch.regprog = vim_regcomp(inc_opt,\n\t\t\t\t\t\t magic_isset() ? RE_MAGIC : 0);\n\tif (incl_regmatch.regprog == NULL)\n\t    goto fpip_end;\n\tincl_regmatch.rm_ic = FALSE;\t// don't ignore case in incl. pat.\n    }\n    if (type == FIND_DEFINE && (*curbuf->b_p_def != NUL || *p_def != NUL))\n    {\n\tdef_regmatch.regprog = vim_regcomp(*curbuf->b_p_def == NUL\n\t\t\t   ? p_def : curbuf->b_p_def,\n\t\t\t\t\t\t magic_isset() ? RE_MAGIC : 0);\n\tif (def_regmatch.regprog == NULL)\n\t    goto fpip_end;\n\tdef_regmatch.rm_ic = FALSE;\t// don't ignore case in define pat.\n    }\n    files = lalloc_clear(max_path_depth * sizeof(SearchedFile), TRUE);\n    if (files == NULL)\n\tgoto fpip_end;\n    old_files = max_path_depth;\n    depth = depth_displayed = -1;\n\n    lnum = start_lnum;\n    if (end_lnum > curbuf->b_ml.ml_line_count)\n\tend_lnum = curbuf->b_ml.ml_line_count;\n    if (lnum > end_lnum)\t\t// do at least one line\n\tlnum = end_lnum;\n    line = get_line_and_copy(lnum, file_line);\n\n    for (;;)\n    {\n\tif (incl_regmatch.regprog != NULL\n\t\t&& vim_regexec(&incl_regmatch, line, (colnr_T)0))\n\t{\n\t    char_u *p_fname = (curr_fname == curbuf->b_fname)\n\t\t\t\t\t      ? curbuf->b_ffname : curr_fname;\n\n\t    if (inc_opt != NULL && strstr((char *)inc_opt, \"\\\\zs\") != NULL)\n\t\t// Use text from '\\zs' to '\\ze' (or end) of 'include'.\n\t\tnew_fname = find_file_name_in_path(incl_regmatch.startp[0],\n\t\t       (int)(incl_regmatch.endp[0] - incl_regmatch.startp[0]),\n\t\t\t\t FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname);\n\t    else\n\t\t// Use text after match with 'include'.\n\t\tnew_fname = file_name_in_line(incl_regmatch.endp[0], 0,\n\t\t\t     FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL);\n\t    already_searched = FALSE;\n\t    if (new_fname != NULL)\n\t    {\n\t\t// Check whether we have already searched in this file\n\t\tfor (i = 0;; i++)\n\t\t{\n\t\t    if (i == depth + 1)\n\t\t\ti = old_files;\n\t\t    if (i == max_path_depth)\n\t\t\tbreak;\n\t\t    if (fullpathcmp(new_fname, files[i].name, TRUE, TRUE)\n\t\t\t\t\t\t\t\t    & FPC_SAME)\n\t\t    {\n\t\t\tif (type != CHECK_PATH\n\t\t\t\t&& action == ACTION_SHOW_ALL\n\t\t\t\t&& files[i].matched)\n\t\t\t{\n\t\t\t    msg_putchar('\\n');\t    // cursor below last one\n\t\t\t    if (!got_int)\t    // don't display if 'q'\n\t\t\t\t\t\t    // typed at \"--more--\"\n\t\t\t\t\t\t    // message\n\t\t\t    {\n\t\t\t\tmsg_home_replace_hl(new_fname);\n\t\t\t\tmsg_puts(_(\" (includes previously listed match)\"));\n\t\t\t\tprev_fname = NULL;\n\t\t\t    }\n\t\t\t}\n\t\t\tVIM_CLEAR(new_fname);\n\t\t\talready_searched = TRUE;\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t    }\n\n\t    if (type == CHECK_PATH && (action == ACTION_SHOW_ALL\n\t\t\t\t || (new_fname == NULL && !already_searched)))\n\t    {\n\t\tif (did_show)\n\t\t    msg_putchar('\\n');\t    // cursor below last one\n\t\telse\n\t\t{\n\t\t    gotocmdline(TRUE);\t    // cursor at status line\n\t\t    msg_puts_title(_(\"--- Included files \"));\n\t\t    if (action != ACTION_SHOW_ALL)\n\t\t\tmsg_puts_title(_(\"not found \"));\n\t\t    msg_puts_title(_(\"in path ---\\n\"));\n\t\t}\n\t\tdid_show = TRUE;\n\t\twhile (depth_displayed < depth && !got_int)\n\t\t{\n\t\t    ++depth_displayed;\n\t\t    for (i = 0; i < depth_displayed; i++)\n\t\t\tmsg_puts(\"  \");\n\t\t    msg_home_replace(files[depth_displayed].name);\n\t\t    msg_puts(\" -->\\n\");\n\t\t}\n\t\tif (!got_int)\t\t    // don't display if 'q' typed\n\t\t\t\t\t    // for \"--more--\" message\n\t\t{\n\t\t    for (i = 0; i <= depth_displayed; i++)\n\t\t\tmsg_puts(\"  \");\n\t\t    if (new_fname != NULL)\n\t\t    {\n\t\t\t// using \"new_fname\" is more reliable, e.g., when\n\t\t\t// 'includeexpr' is set.\n\t\t\tmsg_outtrans_attr(new_fname, HL_ATTR(HLF_D));\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\t/*\n\t\t\t * Isolate the file name.\n\t\t\t * Include the surrounding \"\" or <> if present.\n\t\t\t */\n\t\t\tif (inc_opt != NULL\n\t\t\t\t   && strstr((char *)inc_opt, \"\\\\zs\") != NULL)\n\t\t\t{\n\t\t\t    // pattern contains \\zs, use the match\n\t\t\t    p = incl_regmatch.startp[0];\n\t\t\t    i = (int)(incl_regmatch.endp[0]\n\t\t\t\t\t\t   - incl_regmatch.startp[0]);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t    // find the file name after the end of the match\n\t\t\t    for (p = incl_regmatch.endp[0];\n\t\t\t\t\t\t  *p && !vim_isfilec(*p); p++)\n\t\t\t\t;\n\t\t\t    for (i = 0; vim_isfilec(p[i]); i++)\n\t\t\t\t;\n\t\t\t}\n\n\t\t\tif (i == 0)\n\t\t\t{\n\t\t\t    // Nothing found, use the rest of the line.\n\t\t\t    p = incl_regmatch.endp[0];\n\t\t\t    i = (int)STRLEN(p);\n\t\t\t}\n\t\t\t// Avoid checking before the start of the line, can\n\t\t\t// happen if \\zs appears in the regexp.\n\t\t\telse if (p > line)\n\t\t\t{\n\t\t\t    if (p[-1] == '\"' || p[-1] == '<')\n\t\t\t    {\n\t\t\t\t--p;\n\t\t\t\t++i;\n\t\t\t    }\n\t\t\t    if (p[i] == '\"' || p[i] == '>')\n\t\t\t\t++i;\n\t\t\t}\n\t\t\tsave_char = p[i];\n\t\t\tp[i] = NUL;\n\t\t\tmsg_outtrans_attr(p, HL_ATTR(HLF_D));\n\t\t\tp[i] = save_char;\n\t\t    }\n\n\t\t    if (new_fname == NULL && action == ACTION_SHOW_ALL)\n\t\t    {\n\t\t\tif (already_searched)\n\t\t\t    msg_puts(_(\"  (Already listed)\"));\n\t\t\telse\n\t\t\t    msg_puts(_(\"  NOT FOUND\"));\n\t\t    }\n\t\t}\n\t\tout_flush();\t    // output each line directly\n\t    }\n\n\t    if (new_fname != NULL)\n\t    {\n\t\t// Push the new file onto the file stack\n\t\tif (depth + 1 == old_files)\n\t\t{\n\t\t    bigger = ALLOC_MULT(SearchedFile, max_path_depth * 2);\n\t\t    if (bigger != NULL)\n\t\t    {\n\t\t\tfor (i = 0; i <= depth; i++)\n\t\t\t    bigger[i] = files[i];\n\t\t\tfor (i = depth + 1; i < old_files + max_path_depth; i++)\n\t\t\t{\n\t\t\t    bigger[i].fp = NULL;\n\t\t\t    bigger[i].name = NULL;\n\t\t\t    bigger[i].lnum = 0;\n\t\t\t    bigger[i].matched = FALSE;\n\t\t\t}\n\t\t\tfor (i = old_files; i < max_path_depth; i++)\n\t\t\t    bigger[i + max_path_depth] = files[i];\n\t\t\told_files += max_path_depth;\n\t\t\tmax_path_depth *= 2;\n\t\t\tvim_free(files);\n\t\t\tfiles = bigger;\n\t\t    }\n\t\t}\n\t\tif ((files[depth + 1].fp = mch_fopen((char *)new_fname, \"r\"))\n\t\t\t\t\t\t\t\t    == NULL)\n\t\t    vim_free(new_fname);\n\t\telse\n\t\t{\n\t\t    if (++depth == old_files)\n\t\t    {\n\t\t\t/*\n\t\t\t * lalloc() for 'bigger' must have failed above.  We\n\t\t\t * will forget one of our already visited files now.\n\t\t\t */\n\t\t\tvim_free(files[old_files].name);\n\t\t\t++old_files;\n\t\t    }\n\t\t    files[depth].name = curr_fname = new_fname;\n\t\t    files[depth].lnum = 0;\n\t\t    files[depth].matched = FALSE;\n\t\t    if (action == ACTION_EXPAND)\n\t\t    {\n\t\t\tmsg_hist_off = TRUE;\t// reset in msg_trunc_attr()\n\t\t\tvim_snprintf((char*)IObuff, IOSIZE,\n\t\t\t\t_(\"Scanning included file: %s\"),\n\t\t\t\t(char *)new_fname);\n\t\t\tmsg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));\n\t\t    }\n\t\t    else if (p_verbose >= 5)\n\t\t    {\n\t\t\tverbose_enter();\n\t\t\tsmsg(_(\"Searching included file %s\"),\n\t\t\t\t\t\t\t   (char *)new_fname);\n\t\t\tverbose_leave();\n\t\t    }\n\n\t\t}\n\t    }\n\t}\n\telse\n\t{\n\t    /*\n\t     * Check if the line is a define (type == FIND_DEFINE)\n\t     */\n\t    p = line;\nsearch_line:\n\t    define_matched = FALSE;\n\t    if (def_regmatch.regprog != NULL\n\t\t\t      && vim_regexec(&def_regmatch, line, (colnr_T)0))\n\t    {\n\t\t/*\n\t\t * Pattern must be first identifier after 'define', so skip\n\t\t * to that position before checking for match of pattern.  Also\n\t\t * don't let it match beyond the end of this identifier.\n\t\t */\n\t\tp = def_regmatch.endp[0];\n\t\twhile (*p && !vim_iswordc(*p))\n\t\t    p++;\n\t\tdefine_matched = TRUE;\n\t    }\n\n\t    /*\n\t     * Look for a match.  Don't do this if we are looking for a\n\t     * define and this line didn't match define_prog above.\n\t     */\n\t    if (def_regmatch.regprog == NULL || define_matched)\n\t    {\n\t\tif (define_matched || compl_status_sol())\n\t\t{\n\t\t    // compare the first \"len\" chars from \"ptr\"\n\t\t    startp = skipwhite(p);\n\t\t    if (p_ic)\n\t\t\tmatched = !MB_STRNICMP(startp, ptr, len);\n\t\t    else\n\t\t\tmatched = !STRNCMP(startp, ptr, len);\n\t\t    if (matched && define_matched && whole\n\t\t\t\t\t\t  && vim_iswordc(startp[len]))\n\t\t\tmatched = FALSE;\n\t\t}\n\t\telse if (regmatch.regprog != NULL\n\t\t\t && vim_regexec(®match, line, (colnr_T)(p - line)))\n\t\t{\n\t\t    matched = TRUE;\n\t\t    startp = regmatch.startp[0];\n\t\t    /*\n\t\t     * Check if the line is not a comment line (unless we are\n\t\t     * looking for a define).  A line starting with \"# define\"\n\t\t     * is not considered to be a comment line.\n\t\t     */\n\t\t    if (!define_matched && skip_comments)\n\t\t    {\n\t\t\tif ((*line != '#' ||\n\t\t\t\tSTRNCMP(skipwhite(line + 1), \"define\", 6) != 0)\n\t\t\t\t&& get_leader_len(line, NULL, FALSE, TRUE))\n\t\t\t    matched = FALSE;\n\n\t\t\t/*\n\t\t\t * Also check for a \"/ *\" or \"/ /\" before the match.\n\t\t\t * Skips lines like \"int backwards;  / * normal index\n\t\t\t * * /\" when looking for \"normal\".\n\t\t\t * Note: Doesn't skip \"/ *\" in comments.\n\t\t\t */\n\t\t\tp = skipwhite(line);\n\t\t\tif (matched\n\t\t\t\t|| (p[0] == '/' && p[1] == '*') || p[0] == '*')\n\t\t\t    for (p = line; *p && p < startp; ++p)\n\t\t\t    {\n\t\t\t\tif (matched\n\t\t\t\t\t&& p[0] == '/'\n\t\t\t\t\t&& (p[1] == '*' || p[1] == '/'))\n\t\t\t\t{\n\t\t\t\t    matched = FALSE;\n\t\t\t\t    // After \"//\" all text is comment\n\t\t\t\t    if (p[1] == '/')\n\t\t\t\t\tbreak;\n\t\t\t\t    ++p;\n\t\t\t\t}\n\t\t\t\telse if (!matched && p[0] == '*' && p[1] == '/')\n\t\t\t\t{\n\t\t\t\t    // Can find match after \"* /\".\n\t\t\t\t    matched = TRUE;\n\t\t\t\t    ++p;\n\t\t\t\t}\n\t\t\t    }\n\t\t    }\n\t\t}\n\t    }\n\t}\n\tif (matched)\n\t{\n\t    if (action == ACTION_EXPAND)\n\t    {\n\t\tint\tcont_s_ipos = FALSE;\n\t\tint\tadd_r;\n\t\tchar_u\t*aux;\n\n\t\tif (depth == -1 && lnum == curwin->w_cursor.lnum)\n\t\t    break;\n\t\tfound = TRUE;\n\t\taux = p = startp;\n\t\tif (compl_status_adding())\n\t\t{\n\t\t    p += ins_compl_len();\n\t\t    if (vim_iswordp(p))\n\t\t\tgoto exit_matched;\n\t\t    p = find_word_start(p);\n\t\t}\n\t\tp = find_word_end(p);\n\t\ti = (int)(p - aux);\n\n\t\tif (compl_status_adding() && i == ins_compl_len())\n\t\t{\n\t\t    // IOSIZE > compl_length, so the STRNCPY works\n\t\t    STRNCPY(IObuff, aux, i);\n\n\t\t    // Get the next line: when \"depth\" < 0  from the current\n\t\t    // buffer, otherwise from the included file.  Jump to\n\t\t    // exit_matched when past the last line.\n\t\t    if (depth < 0)\n\t\t    {\n\t\t\tif (lnum >= end_lnum)\n\t\t\t    goto exit_matched;\n\t\t\tline = get_line_and_copy(++lnum, file_line);\n\t\t    }\n\t\t    else if (vim_fgets(line = file_line,\n\t\t\t\t\t\t      LSIZE, files[depth].fp))\n\t\t\tgoto exit_matched;\n\n\t\t    // we read a line, set \"already\" to check this \"line\" later\n\t\t    // if depth >= 0 we'll increase files[depth].lnum far\n\t\t    // below  -- Acevedo\n\t\t    already = aux = p = skipwhite(line);\n\t\t    p = find_word_start(p);\n\t\t    p = find_word_end(p);\n\t\t    if (p > aux)\n\t\t    {\n\t\t\tif (*aux != ')' && IObuff[i-1] != TAB)\n\t\t\t{\n\t\t\t    if (IObuff[i-1] != ' ')\n\t\t\t\tIObuff[i++] = ' ';\n\t\t\t    // IObuf =~ \"\\(\\k\\|\\i\\).* \", thus i >= 2\n\t\t\t    if (p_js\n\t\t\t\t&& (IObuff[i-2] == '.'\n\t\t\t\t    || (vim_strchr(p_cpo, CPO_JOINSP) == NULL\n\t\t\t\t\t&& (IObuff[i-2] == '?'\n\t\t\t\t\t    || IObuff[i-2] == '!'))))\n\t\t\t\tIObuff[i++] = ' ';\n\t\t\t}\n\t\t\t// copy as much as possible of the new word\n\t\t\tif (p - aux >= IOSIZE - i)\n\t\t\t    p = aux + IOSIZE - i - 1;\n\t\t\tSTRNCPY(IObuff + i, aux, p - aux);\n\t\t\ti += (int)(p - aux);\n\t\t\tcont_s_ipos = TRUE;\n\t\t    }\n\t\t    IObuff[i] = NUL;\n\t\t    aux = IObuff;\n\n\t\t    if (i == ins_compl_len())\n\t\t\tgoto exit_matched;\n\t\t}\n\n\t\tadd_r = ins_compl_add_infercase(aux, i, p_ic,\n\t\t\tcurr_fname == curbuf->b_fname ? NULL : curr_fname,\n\t\t\tdir, cont_s_ipos);\n\t\tif (add_r == OK)\n\t\t    // if dir was BACKWARD then honor it just once\n\t\t    dir = FORWARD;\n\t\telse if (add_r == FAIL)\n\t\t    break;\n\t    }\n\t    else if (action == ACTION_SHOW_ALL)\n\t    {\n\t\tfound = TRUE;\n\t\tif (!did_show)\n\t\t    gotocmdline(TRUE);\t\t// cursor at status line\n\t\tif (curr_fname != prev_fname)\n\t\t{\n\t\t    if (did_show)\n\t\t\tmsg_putchar('\\n');\t// cursor below last one\n\t\t    if (!got_int)\t\t// don't display if 'q' typed\n\t\t\t\t\t\t// at \"--more--\" message\n\t\t\tmsg_home_replace_hl(curr_fname);\n\t\t    prev_fname = curr_fname;\n\t\t}\n\t\tdid_show = TRUE;\n\t\tif (!got_int)\n\t\t    show_pat_in_path(line, type, TRUE, action,\n\t\t\t    (depth == -1) ? NULL : files[depth].fp,\n\t\t\t    (depth == -1) ? &lnum : &files[depth].lnum,\n\t\t\t    match_count++);\n\n\t\t// Set matched flag for this file and all the ones that\n\t\t// include it\n\t\tfor (i = 0; i <= depth; ++i)\n\t\t    files[i].matched = TRUE;\n\t    }\n\t    else if (--count <= 0)\n\t    {\n\t\tfound = TRUE;\n\t\tif (depth == -1 && lnum == curwin->w_cursor.lnum\n#if defined(FEAT_QUICKFIX)\n\t\t\t\t\t\t      && g_do_tagpreview == 0\n#endif\n\t\t\t\t\t\t      )\n\t\t    emsg(_(e_match_is_on_current_line));\n\t\telse if (action == ACTION_SHOW)\n\t\t{\n\t\t    show_pat_in_path(line, type, did_show, action,\n\t\t\t(depth == -1) ? NULL : files[depth].fp,\n\t\t\t(depth == -1) ? &lnum : &files[depth].lnum, 1L);\n\t\t    did_show = TRUE;\n\t\t}\n\t\telse\n\t\t{\n#ifdef FEAT_GUI\n\t\t    need_mouse_correct = TRUE;\n#endif\n#if defined(FEAT_QUICKFIX)\n\t\t    // \":psearch\" uses the preview window\n\t\t    if (g_do_tagpreview != 0)\n\t\t    {\n\t\t\tcurwin_save = curwin;\n\t\t\tprepare_tagpreview(TRUE, TRUE, FALSE);\n\t\t    }\n#endif\n\t\t    if (action == ACTION_SPLIT)\n\t\t    {\n\t\t\tif (win_split(0, 0) == FAIL)\n\t\t\t    break;\n\t\t\tRESET_BINDING(curwin);\n\t\t    }\n\t\t    if (depth == -1)\n\t\t    {\n\t\t\t// match in current file\n#if defined(FEAT_QUICKFIX)\n\t\t\tif (g_do_tagpreview != 0)\n\t\t\t{\n\t\t\t    if (!win_valid(curwin_save))\n\t\t\t\tbreak;\n\t\t\t    if (!GETFILE_SUCCESS(getfile(\n\t\t\t\t\t   curwin_save->w_buffer->b_fnum, NULL,\n\t\t\t\t\t\t     NULL, TRUE, lnum, FALSE)))\n\t\t\t\tbreak;\t// failed to jump to file\n\t\t\t}\n\t\t\telse\n#endif\n\t\t\t    setpcmark();\n\t\t\tcurwin->w_cursor.lnum = lnum;\n\t\t\tcheck_cursor();\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\tif (!GETFILE_SUCCESS(getfile(\n\t\t\t\t\t0, files[depth].name, NULL, TRUE,\n\t\t\t\t\t\t    files[depth].lnum, FALSE)))\n\t\t\t    break;\t// failed to jump to file\n\t\t\t// autocommands may have changed the lnum, we don't\n\t\t\t// want that here\n\t\t\tcurwin->w_cursor.lnum = files[depth].lnum;\n\t\t    }\n\t\t}\n\t\tif (action != ACTION_SHOW)\n\t\t{\n\t\t    curwin->w_cursor.col = (colnr_T)(startp - line);\n\t\t    curwin->w_set_curswant = TRUE;\n\t\t}\n\n#if defined(FEAT_QUICKFIX)\n\t\tif (g_do_tagpreview != 0\n\t\t\t   && curwin != curwin_save && win_valid(curwin_save))\n\t\t{\n\t\t    // Return cursor to where we were\n\t\t    validate_cursor();\n\t\t    redraw_later(VALID);\n\t\t    win_enter(curwin_save, TRUE);\n\t\t}\n# ifdef FEAT_PROP_POPUP\n\t\telse if (WIN_IS_POPUP(curwin))\n\t\t    // can't keep focus in popup window\n\t\t    win_enter(firstwin, TRUE);\n# endif\n#endif\n\t\tbreak;\n\t    }\nexit_matched:\n\t    matched = FALSE;\n\t    // look for other matches in the rest of the line if we\n\t    // are not at the end of it already\n\t    if (def_regmatch.regprog == NULL\n\t\t    && action == ACTION_EXPAND\n\t\t    && !compl_status_sol()\n\t\t    && *startp != NUL\n\t\t    && *(p = startp + mb_ptr2len(startp)) != NUL)\n\t\tgoto search_line;\n\t}\n\tline_breakcheck();\n\tif (action == ACTION_EXPAND)\n\t    ins_compl_check_keys(30, FALSE);\n\tif (got_int || ins_compl_interrupted())\n\t    break;\n\n\t/*\n\t * Read the next line.  When reading an included file and encountering\n\t * end-of-file, close the file and continue in the file that included\n\t * it.\n\t */\n\twhile (depth >= 0 && !already\n\t\t&& vim_fgets(line = file_line, LSIZE, files[depth].fp))\n\t{\n\t    fclose(files[depth].fp);\n\t    --old_files;\n\t    files[old_files].name = files[depth].name;\n\t    files[old_files].matched = files[depth].matched;\n\t    --depth;\n\t    curr_fname = (depth == -1) ? curbuf->b_fname\n\t\t\t\t       : files[depth].name;\n\t    if (depth < depth_displayed)\n\t\tdepth_displayed = depth;\n\t}\n\tif (depth >= 0)\t\t// we could read the line\n\t{\n\t    files[depth].lnum++;\n\t    // Remove any CR and LF from the line.\n\t    i = (int)STRLEN(line);\n\t    if (i > 0 && line[i - 1] == '\\n')\n\t\tline[--i] = NUL;\n\t    if (i > 0 && line[i - 1] == '\\r')\n\t\tline[--i] = NUL;\n\t}\n\telse if (!already)\n\t{\n\t    if (++lnum > end_lnum)\n\t\tbreak;\n\t    line = get_line_and_copy(lnum, file_line);\n\t}\n\talready = NULL;\n    }\n    // End of big for (;;) loop.\n\n    // Close any files that are still open.\n    for (i = 0; i <= depth; i++)\n    {\n\tfclose(files[i].fp);\n\tvim_free(files[i].name);\n    }\n    for (i = old_files; i < max_path_depth; i++)\n\tvim_free(files[i].name);\n    vim_free(files);\n\n    if (type == CHECK_PATH)\n    {\n\tif (!did_show)\n\t{\n\t    if (action != ACTION_SHOW_ALL)\n\t\tmsg(_(\"All included files were found\"));\n\t    else\n\t\tmsg(_(\"No included files\"));\n\t}\n    }\n    else if (!found && action != ACTION_EXPAND)\n    {\n\tif (got_int || ins_compl_interrupted())\n\t    emsg(_(e_interrupted));\n\telse if (type == FIND_DEFINE)\n\t    emsg(_(e_couldnt_find_definition));\n\telse\n\t    emsg(_(e_couldnt_find_pattern));\n    }\n    if (action == ACTION_SHOW || action == ACTION_SHOW_ALL)\n\tmsg_end();\n\nfpip_end:\n    vim_free(file_line);\n    vim_regfree(regmatch.regprog);\n    vim_regfree(incl_regmatch.regprog);\n    vim_regfree(def_regmatch.regprog);\n}", "func_hash": 332560855806865581562523893033870446906, "file_name": "search.c", "file_hash": 30662263767422374466151794140989574879, "cwe": ["CWE-416"], "cve": "CVE-2022-1968", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1968"}
{"idx": 196578, "project": "vim", "commit_id": "44db8213d38c39877d2148eff6a72f4beccfb94e", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/44db8213d38c39877d2148eff6a72f4beccfb94e", "commit_message": "patch 8.2.4219: reading before the start of the line\n\nProblem:    Reading before the start of the line.\nSolution:   Check boundary before trying to read the character.", "target": 1, "func": "yank_copy_line(struct block_def *bd, long y_idx, int exclude_trailing_space)\n{\n    char_u\t*pnew;\n\n    if (exclude_trailing_space)\n\tbd->endspaces = 0;\n    if ((pnew = alloc(bd->startspaces + bd->endspaces + bd->textlen + 1))\n\t\t\t\t\t\t\t\t      == NULL)\n\treturn FAIL;\n    y_current->y_array[y_idx] = pnew;\n    vim_memset(pnew, ' ', (size_t)bd->startspaces);\n    pnew += bd->startspaces;\n    mch_memmove(pnew, bd->textstart, (size_t)bd->textlen);\n    pnew += bd->textlen;\n    vim_memset(pnew, ' ', (size_t)bd->endspaces);\n    pnew += bd->endspaces;\n    if (exclude_trailing_space)\n    {\n\tint s = bd->textlen + bd->endspaces;\n\n\twhile (VIM_ISWHITE(*(bd->textstart + s - 1)) && s > 0)\n\t{\n\t    s = s - (*mb_head_off)(bd->textstart, bd->textstart + s - 1) - 1;\n\t    pnew--;\n\t}\n    }\n    *pnew = NUL;\n    return OK;\n}", "func_hash": 329046653104270093704788517563971777510, "file_name": "register.c", "file_hash": 197045442768005159362544298682780980387, "cwe": ["CWE-787"], "cve": "CVE-2022-0407", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0407"}
{"idx": 240276, "project": "vim", "commit_id": "44db8213d38c39877d2148eff6a72f4beccfb94e", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/44db8213d38c39877d2148eff6a72f4beccfb94e", "commit_message": "patch 8.2.4219: reading before the start of the line\n\nProblem:    Reading before the start of the line.\nSolution:   Check boundary before trying to read the character.", "target": 0, "func": "yank_copy_line(struct block_def *bd, long y_idx, int exclude_trailing_space)\n{\n    char_u\t*pnew;\n\n    if (exclude_trailing_space)\n\tbd->endspaces = 0;\n    if ((pnew = alloc(bd->startspaces + bd->endspaces + bd->textlen + 1))\n\t\t\t\t\t\t\t\t      == NULL)\n\treturn FAIL;\n    y_current->y_array[y_idx] = pnew;\n    vim_memset(pnew, ' ', (size_t)bd->startspaces);\n    pnew += bd->startspaces;\n    mch_memmove(pnew, bd->textstart, (size_t)bd->textlen);\n    pnew += bd->textlen;\n    vim_memset(pnew, ' ', (size_t)bd->endspaces);\n    pnew += bd->endspaces;\n    if (exclude_trailing_space)\n    {\n\tint s = bd->textlen + bd->endspaces;\n\n\twhile (s > 0 && VIM_ISWHITE(*(bd->textstart + s - 1)))\n\t{\n\t    s = s - (*mb_head_off)(bd->textstart, bd->textstart + s - 1) - 1;\n\t    pnew--;\n\t}\n    }\n    *pnew = NUL;\n    return OK;\n}", "func_hash": 215111577434116975174543951046273639484, "file_name": "register.c", "file_hash": 303069020104340496076924952267660178460, "cwe": ["CWE-787"], "cve": "CVE-2022-0407", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0407"}
{"idx": 196587, "project": "tensorflow", "commit_id": "4aacb30888638da75023e6601149415b39763d76", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4aacb30888638da75023e6601149415b39763d76", "commit_message": "Disallow division by zero FPE in `tf.raw_ops.ResourceScatterDiv`\n\nHad to update a test that was broken.\n\nPiperOrigin-RevId: 388516976\nChange-Id: Ic358e6bf0559e011539974d453fc7aa18b427e9c", "target": 1, "func": "  void DoCompute(OpKernelContext* c) {\n    core::RefCountPtr v;\n    OP_REQUIRES_OK(c, LookupResource(c, HandleFromInput(c, 0), &v));\n    Tensor* params = v->tensor();\n    const Tensor& indices = c->input(1);\n    const Tensor& updates = c->input(2);\n\n    // Check that rank(updates.shape) = rank(indices.shape + params.shape[1:])\n    OP_REQUIRES(c,\n                updates.dims() == 0 ||\n                    updates.dims() == indices.dims() + params->dims() - 1,\n                errors::InvalidArgument(\n                    \"Must have updates.shape = indices.shape + \"\n                    \"params.shape[1:] or updates.shape = [], got \",\n                    \"updates.shape \", updates.shape().DebugString(),\n                    \", indices.shape \", indices.shape().DebugString(),\n                    \", params.shape \", params->shape().DebugString()));\n\n    // Check that we have enough index space\n    const int64_t N_big = indices.NumElements();\n    OP_REQUIRES(\n        c, N_big <= std::numeric_limits::max(),\n        errors::InvalidArgument(\"indices has too many elements for \",\n                                DataTypeString(DataTypeToEnum::v()),\n                                \" indexing: \", N_big, \" > \",\n                                std::numeric_limits::max()));\n    const Index N = static_cast(N_big);\n    OP_REQUIRES(\n        c, params->dim_size(0) <= std::numeric_limits::max(),\n        errors::InvalidArgument(\"params.shape[0] too large for \",\n                                DataTypeString(DataTypeToEnum::v()),\n                                \" indexing: \", params->dim_size(0), \" > \",\n                                std::numeric_limits::max()));\n\n    if (N > 0) {\n      auto indices_flat = indices.flat();\n      auto params_flat = params->flat_outer_dims();\n      if (TensorShapeUtils::IsScalar(updates.shape())) {\n        const auto update = updates.scalar();\n\n        functor::ScatterScalarFunctor functor;\n        const Index bad_i = functor(c, c->template eigen_device(),\n                                    params_flat, update, indices_flat);\n        OP_REQUIRES(c, bad_i < 0,\n                    errors::InvalidArgument(\n                        \"indices\", SliceDebugString(indices.shape(), bad_i),\n                        \" = \", indices_flat(bad_i), \" is not in [0, \",\n                        params->dim_size(0), \")\"));\n      } else {\n        int64_t num_updates = updates.NumElements();\n        OP_REQUIRES(\n            c, TensorShapeUtils::StartsWith(updates.shape(), indices.shape()),\n            errors::InvalidArgument(\n                \"The shape of indices (\", indices.shape().DebugString(),\n                \") must be a prefix of the shape of updates (\",\n                updates.shape().DebugString(), \")\"));\n        auto updates_flat = updates.shaped({N, num_updates / N});\n\n        functor::ScatterFunctor functor;\n        const Index bad_i = functor(c, c->template eigen_device(),\n                                    params_flat, updates_flat, indices_flat);\n        OP_REQUIRES(c, bad_i < 0,\n                    errors::InvalidArgument(\n                        \"indices\", SliceDebugString(indices.shape(), bad_i),\n                        \" = \", indices_flat(bad_i), \" is not in [0, \",\n                        params->dim_size(0), \")\"));\n      }\n    }\n  }", "func_hash": 322924980951140877428129021875471736973, "file_name": "resource_variable_ops.cc", "file_hash": 290989719174845979221072798512679804902, "cwe": ["CWE-369"], "cve": "CVE-2021-37642", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of `tf.raw_ops.ResourceScatterDiv` is vulnerable to a division by 0 error. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/resource_variable_ops.cc#L865) uses a common class for all binary operations but fails to treat the division by 0 case separately. We have patched the issue in GitHub commit 4aacb30888638da75023e6601149415b39763d76. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37642"}
{"idx": 240595, "project": "tensorflow", "commit_id": "4aacb30888638da75023e6601149415b39763d76", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4aacb30888638da75023e6601149415b39763d76", "commit_message": "Disallow division by zero FPE in `tf.raw_ops.ResourceScatterDiv`\n\nHad to update a test that was broken.\n\nPiperOrigin-RevId: 388516976\nChange-Id: Ic358e6bf0559e011539974d453fc7aa18b427e9c", "target": 0, "func": "  void DoCompute(OpKernelContext* c) {\n    core::RefCountPtr v;\n    OP_REQUIRES_OK(c, LookupResource(c, HandleFromInput(c, 0), &v));\n    Tensor* params = v->tensor();\n    const Tensor& indices = c->input(1);\n    const Tensor& updates = c->input(2);\n\n    // Check that rank(updates.shape) = rank(indices.shape + params.shape[1:])\n    OP_REQUIRES(c,\n                updates.dims() == 0 ||\n                    updates.dims() == indices.dims() + params->dims() - 1,\n                errors::InvalidArgument(\n                    \"Must have updates.shape = indices.shape + \"\n                    \"params.shape[1:] or updates.shape = [], got \",\n                    \"updates.shape \", updates.shape().DebugString(),\n                    \", indices.shape \", indices.shape().DebugString(),\n                    \", params.shape \", params->shape().DebugString()));\n\n    // Check that we have enough index space\n    const int64_t N_big = indices.NumElements();\n    OP_REQUIRES(\n        c, N_big <= std::numeric_limits::max(),\n        errors::InvalidArgument(\"indices has too many elements for \",\n                                DataTypeString(DataTypeToEnum::v()),\n                                \" indexing: \", N_big, \" > \",\n                                std::numeric_limits::max()));\n    const Index N = static_cast(N_big);\n    OP_REQUIRES(\n        c, params->dim_size(0) <= std::numeric_limits::max(),\n        errors::InvalidArgument(\"params.shape[0] too large for \",\n                                DataTypeString(DataTypeToEnum::v()),\n                                \" indexing: \", params->dim_size(0), \" > \",\n                                std::numeric_limits::max()));\n\n    // Prevent division by 0\n    if (isCPUDevice() && op == tensorflow::scatter_op::UpdateOp::DIV) {\n      OP_REQUIRES(c, ValidateInput(updates),\n                  errors::InvalidArgument(\"updates must not contain 0\"));\n    }\n\n    if (N > 0) {\n      auto indices_flat = indices.flat();\n      auto params_flat = params->flat_outer_dims();\n      if (TensorShapeUtils::IsScalar(updates.shape())) {\n        const auto update = updates.scalar();\n\n        functor::ScatterScalarFunctor functor;\n        const Index bad_i = functor(c, c->template eigen_device(),\n                                    params_flat, update, indices_flat);\n        OP_REQUIRES(c, bad_i < 0,\n                    errors::InvalidArgument(\n                        \"indices\", SliceDebugString(indices.shape(), bad_i),\n                        \" = \", indices_flat(bad_i), \" is not in [0, \",\n                        params->dim_size(0), \")\"));\n      } else {\n        int64_t num_updates = updates.NumElements();\n        OP_REQUIRES(\n            c, TensorShapeUtils::StartsWith(updates.shape(), indices.shape()),\n            errors::InvalidArgument(\n                \"The shape of indices (\", indices.shape().DebugString(),\n                \") must be a prefix of the shape of updates (\",\n                updates.shape().DebugString(), \")\"));\n        auto updates_flat = updates.shaped({N, num_updates / N});\n\n        functor::ScatterFunctor functor;\n        const Index bad_i = functor(c, c->template eigen_device(),\n                                    params_flat, updates_flat, indices_flat);\n        OP_REQUIRES(c, bad_i < 0,\n                    errors::InvalidArgument(\n                        \"indices\", SliceDebugString(indices.shape(), bad_i),\n                        \" = \", indices_flat(bad_i), \" is not in [0, \",\n                        params->dim_size(0), \")\"));\n      }\n    }\n  }", "func_hash": 249042864160254570036396062378524137135, "file_name": "resource_variable_ops.cc", "file_hash": 303304073982532975843126024441239469279, "cwe": ["CWE-369"], "cve": "CVE-2021-37642", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of `tf.raw_ops.ResourceScatterDiv` is vulnerable to a division by 0 error. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/resource_variable_ops.cc#L865) uses a common class for all binary operations but fails to treat the division by 0 case separately. We have patched the issue in GitHub commit 4aacb30888638da75023e6601149415b39763d76. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37642"}
{"idx": 196611, "project": "booth", "commit_id": "35bf0b7b048d715f671eb68974fb6b4af6528c67", "project_url": "https://github.com/ClusterLabs/booth", "commit_url": "https://github.com/ClusterLabs/booth/commit/35bf0b7b048d715f671eb68974fb6b4af6528c67", "commit_message": "Revert \"Refactor: main: substitute is_auth_req macro\"\n\nThis reverts commit da79b8ba28ad4837a0fee13e5f8fb6f89fe0e24c.\n\nauthfile != authkey\n\nSigned-off-by: Jan Friesse ", "target": 1, "func": "static int setup_config(int type)\n{\n\tint rv;\n\n\trv = read_config(cl.configfile, type);\n\tif (rv < 0)\n\t\tgoto out;\n\n\tif (is_auth_req()) {\n\t\trv = read_authkey();\n\t\tif (rv < 0)\n\t\t\tgoto out;\n#if HAVE_LIBGCRYPT\n\t\tif (!gcry_check_version(NULL)) {\n\t\t\tlog_error(\"gcry_check_version\");\n\t\t\trv = -ENOENT;\n\t\t\tgoto out;\n\t\t}\n\t\tgcry_control(GCRYCTL_DISABLE_SECMEM, 0);\n\t\tgcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);\n#endif\n\t}\n\n\t/* Set \"local\" pointer, ignoring errors. */\n\tif (cl.type == DAEMON && cl.site[0]) {\n\t\tif (!find_site_by_name(cl.site, &local, 1)) {\n\t\t\tlog_error(\"Cannot find \\\"%s\\\" in the configuration.\",\n\t\t\t\t\tcl.site);\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tlocal->local = 1;\n\t} else\n\t\tfind_myself(NULL, type == CLIENT || type == GEOSTORE);\n\n\n\trv = check_config(type);\n\tif (rv < 0)\n\t\tgoto out;\n\n\n\t/* Per default the PID file name is derived from the\n\t * configuration name. */\n\tif (!cl.lockfile[0]) {\n\t\tsnprintf(cl.lockfile, sizeof(cl.lockfile)-1,\n\t\t\t\t\"%s/%s.pid\", BOOTH_RUN_DIR, booth_conf->name);\n\t}\n\nout:\n\treturn rv;\n}", "func_hash": 170997267947585139967201027163993257008, "file_name": "main.c", "file_hash": 4814718832295442874488153140310945385, "cwe": ["CWE-284"], "cve": "CVE-2022-2553", "cve_desc": "The authfile directive in the booth config file is ignored, preventing use of authentication in communications from node to node. As a result, nodes that do not have the correct authentication key are not prevented from communicating with other nodes in the cluster.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2553"}
{"idx": 241040, "project": "booth", "commit_id": "35bf0b7b048d715f671eb68974fb6b4af6528c67", "project_url": "https://github.com/ClusterLabs/booth", "commit_url": "https://github.com/ClusterLabs/booth/commit/35bf0b7b048d715f671eb68974fb6b4af6528c67", "commit_message": "Revert \"Refactor: main: substitute is_auth_req macro\"\n\nThis reverts commit da79b8ba28ad4837a0fee13e5f8fb6f89fe0e24c.\n\nauthfile != authkey\n\nSigned-off-by: Jan Friesse ", "target": 0, "func": "static int setup_config(int type)\n{\n\tint rv;\n\n\trv = read_config(cl.configfile, type);\n\tif (rv < 0)\n\t\tgoto out;\n\n\tif (booth_conf->authfile[0] != '\\0') {\n\t\trv = read_authkey();\n\t\tif (rv < 0)\n\t\t\tgoto out;\n#if HAVE_LIBGCRYPT\n\t\tif (!gcry_check_version(NULL)) {\n\t\t\tlog_error(\"gcry_check_version\");\n\t\t\trv = -ENOENT;\n\t\t\tgoto out;\n\t\t}\n\t\tgcry_control(GCRYCTL_DISABLE_SECMEM, 0);\n\t\tgcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);\n#endif\n\t}\n\n\t/* Set \"local\" pointer, ignoring errors. */\n\tif (cl.type == DAEMON && cl.site[0]) {\n\t\tif (!find_site_by_name(cl.site, &local, 1)) {\n\t\t\tlog_error(\"Cannot find \\\"%s\\\" in the configuration.\",\n\t\t\t\t\tcl.site);\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tlocal->local = 1;\n\t} else\n\t\tfind_myself(NULL, type == CLIENT || type == GEOSTORE);\n\n\n\trv = check_config(type);\n\tif (rv < 0)\n\t\tgoto out;\n\n\n\t/* Per default the PID file name is derived from the\n\t * configuration name. */\n\tif (!cl.lockfile[0]) {\n\t\tsnprintf(cl.lockfile, sizeof(cl.lockfile)-1,\n\t\t\t\t\"%s/%s.pid\", BOOTH_RUN_DIR, booth_conf->name);\n\t}\n\nout:\n\treturn rv;\n}", "func_hash": 89622919560301199125405967494920550093, "file_name": "main.c", "file_hash": 219733327123326706215521846542751103807, "cwe": ["CWE-284"], "cve": "CVE-2022-2553", "cve_desc": "The authfile directive in the booth config file is ignored, preventing use of authentication in communications from node to node. As a result, nodes that do not have the correct authentication key are not prevented from communicating with other nodes in the cluster.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2553"}
{"idx": 196621, "project": "mruby", "commit_id": "b1d0296a937fe278239bdfac840a3fd0e93b3ee9", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/b1d0296a937fe278239bdfac840a3fd0e93b3ee9", "commit_message": "class.c: clear method cache after `remove_method`.", "target": 1, "func": "mrb_remove_method(mrb_state *mrb, struct RClass *c, mrb_sym mid)\n{\n  mt_tbl *h;\n\n  MRB_CLASS_ORIGIN(c);\n  h = c->mt;\n\n  if (h && mt_del(mrb, h, mid)) return;\n  mrb_name_error(mrb, mid, \"method '%n' not defined in %C\", mid, c);\n}", "func_hash": 310092184444521797404238692578019888834, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-1286", "cve_desc": "heap-buffer-overflow in mrb_vm_exec in mruby/mruby in GitHub repository mruby/mruby prior to 3.2. Possible arbitrary code execution if being exploited.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1286"}
{"idx": 241311, "project": "mruby", "commit_id": "b1d0296a937fe278239bdfac840a3fd0e93b3ee9", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/b1d0296a937fe278239bdfac840a3fd0e93b3ee9", "commit_message": "class.c: clear method cache after `remove_method`.", "target": 0, "func": "mrb_remove_method(mrb_state *mrb, struct RClass *c, mrb_sym mid)\n{\n  mt_tbl *h;\n\n  MRB_CLASS_ORIGIN(c);\n  h = c->mt;\n\n  if (h && mt_del(mrb, h, mid)) {\n    mrb_mc_clear_by_class(mrb, c);\n    return;\n  }\n  mrb_name_error(mrb, mid, \"method '%n' not defined in %C\", mid, c);\n}", "func_hash": 224777801914266123479513901810152701375, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-1286", "cve_desc": "heap-buffer-overflow in mrb_vm_exec in mruby/mruby in GitHub repository mruby/mruby prior to 3.2. Possible arbitrary code execution if being exploited.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1286"}
{"idx": 196629, "project": "tensorflow", "commit_id": "579261dcd446385831fe4f7457d802a59685121d", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/579261dcd446385831fe4f7457d802a59685121d", "commit_message": "Fix crash in MatrixSolve when inputs have different batch dimensions.\n\nBefore, the process would crash or certain elements would be silently ignored. Now an InvalidArgument is raised.\n\nPiperOrigin-RevId: 384844020\nChange-Id: Iba44417e383bdd0e1abc4012bfca83b2377dd335", "target": 1, "func": "  void ComputeAsync(OpKernelContext* context, DoneCallback done) final {\n    const Tensor& input = context->input(0);\n    const Tensor& rhs = context->input(1);\n    const int ndims = input.dims();\n    const int64 n = input.dim_size(ndims - 1);\n    const int64 nrhs = rhs.dim_size(ndims - 1);\n    // Validate inputs.\n    OP_REQUIRES_ASYNC(\n        context, ndims >= 2,\n        errors::InvalidArgument(\"Input must have rank >= 2, got \", ndims),\n        done);\n    OP_REQUIRES_ASYNC(context, rhs.dims() == ndims,\n                      errors::InvalidArgument(\n                          \"Input and right-hand side must have same rank, got \",\n                          ndims, \" != \", rhs.dims()),\n                      done);\n    OP_REQUIRES_ASYNC(\n        context, input.dim_size(ndims - 2) == n,\n        errors::InvalidArgument(\"Input matrices must be squares, got\",\n                                input.dim_size(ndims - 2), \" != \", n),\n        done);\n    OP_REQUIRES_ASYNC(context, rhs.dim_size(ndims - 2) == n,\n                      errors::InvalidArgument(\n                          \"Input matrix and right-hand side must have the \"\n                          \"same number of rows, got\",\n                          n, \" != \", rhs.dim_size(ndims - 2)),\n                      done);\n\n    // Allocate output.\n    Tensor* output;\n    OP_REQUIRES_OK_ASYNC(\n        context,\n        context->forward_input_or_allocate_output({1}, 0, rhs.shape(), &output),\n        done);\n\n    // To be consistent with the MatrixInverse op, we define the solution for\n    // an empty set of equations as the empty matrix.\n    if (input.NumElements() == 0 || rhs.NumElements() == 0) {\n      done();\n      return;\n    }\n\n    // TODO(rmlarsen): Convert to std::make_unique when available.\n    std::unique_ptr solver(new CudaSolver(context));\n\n    // Make a copy of the input for the factorization step, or, if adjoint_ is\n    // false, try to reuse the input buffer if this op owns it exclusively.\n    Tensor input_copy;\n    const GPUDevice& device = context->eigen_device();\n    if (adjoint_) {\n      // For the adjoint case, it is simpler to always make a transposed copy up\n      // front.\n      OP_REQUIRES_OK_ASYNC(\n          context,\n          solver->allocate_scoped_tensor(DataTypeToEnum::value,\n                                         input.shape(), &input_copy),\n          done);\n      OP_REQUIRES_OK_ASYNC(context,\n                           DoMatrixTranspose(device, input, &input_copy), done);\n    } else {\n      OP_REQUIRES_OK_ASYNC(\n          context,\n          solver->forward_input_or_allocate_scoped_tensor(\n              {0}, DataTypeToEnum::value, input.shape(), &input_copy),\n          done);\n      if (!input.SharesBufferWith(input_copy)) {\n        device.memcpy(input_copy.flat().data(),\n                      input.flat().data(),\n                      input.NumElements() * sizeof(Scalar));\n      }\n    }\n    auto input_copy_reshaped = input_copy.template flat_inner_dims();\n    const int64 batch_size = input_copy_reshaped.dimension(0);\n\n    // Allocate pivots on the device.\n    Tensor pivots;\n    OP_REQUIRES_OK_ASYNC(\n        context,\n        solver->allocate_scoped_tensor(DataTypeToEnum::value,\n                                       TensorShape{batch_size, n}, &pivots),\n        done);\n    auto pivots_mat = pivots.template matrix();\n\n    // 1. Compute the partially pivoted LU factorization(s) of the\n    // matrix/matrices.\n    std::vector dev_info;\n    auto input_copy_ptrs = solver->GetScratchSpace(\n        sizeof(Scalar*) * batch_size, \"input_copt_ptrs\",\n        /* on_host */ true);\n    const int kMaxMatrixSizeToBatchSizeRatio = 128;\n    const bool use_batched_solver =\n        n <= kMaxMatrixSizeToBatchSizeRatio * batch_size;\n    if (use_batched_solver) {\n      // For small matrices or large batch sizes, we use the batched interface\n      // from cuBlas.\n      const Scalar** input_copy_ptrs_base =\n          reinterpret_cast(input_copy_ptrs.mutable_data());\n      for (int batch = 0; batch < batch_size; ++batch) {\n        input_copy_ptrs_base[batch] = &input_copy_reshaped(batch, 0, 0);\n      }\n      dev_info.push_back(\n          solver->GetDeviceLapackInfo(batch_size, \"getrfBatched\"));\n      OP_REQUIRES_OK_ASYNC(\n          context,\n          solver->GetrfBatched(n, input_copy_ptrs_base, n, pivots_mat.data(),\n                               &dev_info.back(), batch_size),\n          done);\n    } else {\n      // For small batch sizes or large matrices, we use the non-batched\n      // interface from cuSolver, which is much faster for large matrices.\n      dev_info.push_back(solver->GetDeviceLapackInfo(batch_size, \"getrf\"));\n      for (int batch = 0; batch < batch_size; ++batch) {\n        OP_REQUIRES_OK_ASYNC(\n            context,\n            solver->Getrf(n, n, &input_copy_reshaped(batch, 0, 0), n,\n                          &pivots_mat(batch, 0), &dev_info.back()(batch)),\n            done);\n      }\n    }\n\n    // 2. Make a transposed copy of the right-hand sides. This is necessary\n    // because cuBLAS assumes column-major storage while TensorFlow TF uses\n    // row-major.\n    TensorShape transposed_rhs_shape(rhs.shape());\n    transposed_rhs_shape.RemoveLastDims(2);\n    transposed_rhs_shape.AddDim(nrhs);\n    transposed_rhs_shape.AddDim(n);\n    Tensor transposed_rhs;\n    OP_REQUIRES_OK_ASYNC(\n        context,\n        solver->allocate_scoped_tensor(DataTypeToEnum::value,\n                                       transposed_rhs_shape, &transposed_rhs),\n        done);\n    if (nrhs > 1) {\n      OP_REQUIRES_OK_ASYNC(\n          context, DoMatrixTranspose(device, rhs, &transposed_rhs), done);\n    } else {\n      device.memcpy(transposed_rhs.flat().data(),\n                    rhs.flat().data(),\n                    rhs.NumElements() * sizeof(Scalar));\n    }\n\n    // 3. Solve op(A) X = B (in column major form).\n    // We use a trick here: If adjoint_ is true, we converted A to column major\n    // form above. If adjoint is false then I leave A in row-major form and use\n    // trans_a = CUBLAS_OP_T to effectively transform it to column-major on the\n    // fly. (This means that we actually use the LU-factorization of A^T in that\n    // case, but that is equally good for solving AX=B). This way we save an\n    // explicit transpose in the more common case of adjoint_ == false.\n    auto input_copy_ptr_array = solver->GetScratchSpace(\n        sizeof(Scalar*) * batch_size, \"input_copy_ptr_array\",\n        /* on_host */ true);\n    auto transposed_rhs_ptr_array = solver->GetScratchSpace(\n        sizeof(Scalar*) * batch_size, \"transposed_rhs_ptr_array\",\n        /* on_host */ true);\n    auto transposed_rhs_reshaped =\n        transposed_rhs.template flat_inner_dims();\n    if (use_batched_solver) {\n      const Scalar** input_copy_ptrs_base =\n          reinterpret_cast(input_copy_ptr_array.mutable_data());\n      const Scalar** transposed_rhs_ptrs_base =\n          reinterpret_cast(\n              transposed_rhs_ptr_array.mutable_data());\n      for (int batch = 0; batch < batch_size; ++batch) {\n        input_copy_ptrs_base[batch] = &input_copy_reshaped(batch, 0, 0);\n        transposed_rhs_ptrs_base[batch] = &transposed_rhs_reshaped(batch, 0, 0);\n      }\n      int host_info = 0;\n      OP_REQUIRES_OK_ASYNC(\n          context,\n          solver->GetrsBatched(adjoint_ ? CUBLAS_OP_C : CUBLAS_OP_T, n, nrhs,\n                               input_copy_ptrs_base, n, pivots_mat.data(),\n                               transposed_rhs_ptrs_base, n, &host_info,\n                               batch_size),\n          done);\n      OP_REQUIRES_ASYNC(\n          context, host_info == 0,\n          errors::InvalidArgument(\"The \", -host_info,\n                                  \"'th argument to cublas*getrsBatched had \"\n                                  \"an illegal value.\"),\n          done);\n    } else {\n      dev_info.push_back(solver->GetDeviceLapackInfo(batch_size, \"getrs\"));\n      for (int batch = 0; batch < batch_size; ++batch) {\n        OP_REQUIRES_OK_ASYNC(\n            context,\n            solver->Getrs(adjoint_ ? CUBLAS_OP_C : CUBLAS_OP_T, n, nrhs,\n                          &input_copy_reshaped(batch, 0, 0), n,\n                          &pivots_mat(batch, 0),\n                          &transposed_rhs_reshaped(batch, 0, 0), n,\n                          &dev_info.back()(batch)),\n            done);\n      }\n    }\n\n    // 4. Transpose X to get the final result in row-major form.\n    if (nrhs > 1) {\n      OP_REQUIRES_OK_ASYNC(\n          context, DoMatrixTranspose(device, transposed_rhs, output), done);\n    } else {\n      device.memcpy(output->flat().data(),\n                    transposed_rhs.flat().data(),\n                    transposed_rhs.NumElements() * sizeof(Scalar));\n    }\n\n    // Callback for checking info after kernels finish. Also capture the\n    // temporary Tensors/ScratchSpace so they don't get deallocated before the\n    // kernels run. TODO(rmlarsen): Use move capture once C++14 becomes\n    // available.\n    auto info_checker = [context, done, dev_info](\n                            const Status& status,\n                            const std::vector& host_infos) {\n      if (!status.ok() && errors::IsInvalidArgument(status) &&\n          !host_infos.empty()) {\n        for (int i = 0; i < host_infos[0].size(); ++i) {\n          // Match the CPU error message for singular matrices. Otherwise\n          // just print the original error message from the status below.\n          OP_REQUIRES_ASYNC(context, host_infos[0].data()[i] <= 0,\n                            errors::InvalidArgument(kErrMsg), done);\n        }\n      }\n      OP_REQUIRES_OK_ASYNC(context, status, done);\n      done();\n    };\n    CudaSolver::CheckLapackInfoAndDeleteSolverAsync(std::move(solver), dev_info,\n                                                    std::move(info_checker));\n  }", "func_hash": 232512673394609281083836207268567643755, "file_name": "matrix_solve_op.cc", "file_hash": 18056043033202767652193305242094140715, "cwe": ["CWE-354"], "cve": "CVE-2021-41206", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions several TensorFlow operations are missing validation for the shapes of the tensor arguments involved in the call. Depending on the API, this can result in undefined behavior and segfault or `CHECK`-fail related crashes but in some scenarios writes and reads from heap populated arrays are also possible. We have discovered these issues internally via tooling while working on improving/testing GPU op determinism. As such, we don't have reproducers and there will be multiple fixes for these issues. These fixes will be included in TensorFlow 2.7.0. We will also cherrypick these commits on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41206"}
{"idx": 241369, "project": "tensorflow", "commit_id": "579261dcd446385831fe4f7457d802a59685121d", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/579261dcd446385831fe4f7457d802a59685121d", "commit_message": "Fix crash in MatrixSolve when inputs have different batch dimensions.\n\nBefore, the process would crash or certain elements would be silently ignored. Now an InvalidArgument is raised.\n\nPiperOrigin-RevId: 384844020\nChange-Id: Iba44417e383bdd0e1abc4012bfca83b2377dd335", "target": 0, "func": "  void ComputeAsync(OpKernelContext* context, DoneCallback done) final {\n    const Tensor& input = context->input(0);\n    const Tensor& rhs = context->input(1);\n    const int ndims = input.dims();\n    const int64 n = input.dim_size(ndims - 1);\n    const int64 nrhs = rhs.dim_size(ndims - 1);\n    // Validate inputs.\n    OP_REQUIRES_ASYNC(\n        context, ndims >= 2,\n        errors::InvalidArgument(\"Input must have rank >= 2, got \", ndims),\n        done);\n    OP_REQUIRES_ASYNC(context, rhs.dims() == ndims,\n                      errors::InvalidArgument(\n                          \"Input and right-hand side must have same rank, got \",\n                          ndims, \" != \", rhs.dims()),\n                      done);\n    OP_REQUIRES_ASYNC(\n        context, input.dim_size(ndims - 2) == n,\n        errors::InvalidArgument(\"Input matrices must be squares, got \",\n                                input.dim_size(ndims - 2), \" != \", n),\n        done);\n    OP_REQUIRES_ASYNC(context, rhs.dim_size(ndims - 2) == n,\n                      errors::InvalidArgument(\n                          \"Input matrix and right-hand side must have the \"\n                          \"same number of rows, got \",\n                          n, \" != \", rhs.dim_size(ndims - 2)),\n                      done);\n    for (int dim = 0; dim < ndims - 2; dim++) {\n      OP_REQUIRES_ASYNC(\n          context, input.dim_size(dim) == rhs.dim_size(dim),\n          errors::InvalidArgument(\n              \"All input tensors must have the same outer dimensions.\"),\n          done);\n    }\n\n    // Allocate output.\n    Tensor* output;\n    OP_REQUIRES_OK_ASYNC(\n        context,\n        context->forward_input_or_allocate_output({1}, 0, rhs.shape(), &output),\n        done);\n\n    // To be consistent with the MatrixInverse op, we define the solution for\n    // an empty set of equations as the empty matrix.\n    if (input.NumElements() == 0 || rhs.NumElements() == 0) {\n      done();\n      return;\n    }\n\n    // TODO(rmlarsen): Convert to std::make_unique when available.\n    std::unique_ptr solver(new CudaSolver(context));\n\n    // Make a copy of the input for the factorization step, or, if adjoint_ is\n    // false, try to reuse the input buffer if this op owns it exclusively.\n    Tensor input_copy;\n    const GPUDevice& device = context->eigen_device();\n    if (adjoint_) {\n      // For the adjoint case, it is simpler to always make a transposed copy up\n      // front.\n      OP_REQUIRES_OK_ASYNC(\n          context,\n          solver->allocate_scoped_tensor(DataTypeToEnum::value,\n                                         input.shape(), &input_copy),\n          done);\n      OP_REQUIRES_OK_ASYNC(context,\n                           DoMatrixTranspose(device, input, &input_copy), done);\n    } else {\n      OP_REQUIRES_OK_ASYNC(\n          context,\n          solver->forward_input_or_allocate_scoped_tensor(\n              {0}, DataTypeToEnum::value, input.shape(), &input_copy),\n          done);\n      if (!input.SharesBufferWith(input_copy)) {\n        device.memcpy(input_copy.flat().data(),\n                      input.flat().data(),\n                      input.NumElements() * sizeof(Scalar));\n      }\n    }\n    auto input_copy_reshaped = input_copy.template flat_inner_dims();\n    const int64 batch_size = input_copy_reshaped.dimension(0);\n\n    // Allocate pivots on the device.\n    Tensor pivots;\n    OP_REQUIRES_OK_ASYNC(\n        context,\n        solver->allocate_scoped_tensor(DataTypeToEnum::value,\n                                       TensorShape{batch_size, n}, &pivots),\n        done);\n    auto pivots_mat = pivots.template matrix();\n\n    // 1. Compute the partially pivoted LU factorization(s) of the\n    // matrix/matrices.\n    std::vector dev_info;\n    auto input_copy_ptrs = solver->GetScratchSpace(\n        sizeof(Scalar*) * batch_size, \"input_copt_ptrs\",\n        /* on_host */ true);\n    const int kMaxMatrixSizeToBatchSizeRatio = 128;\n    const bool use_batched_solver =\n        n <= kMaxMatrixSizeToBatchSizeRatio * batch_size;\n    if (use_batched_solver) {\n      // For small matrices or large batch sizes, we use the batched interface\n      // from cuBlas.\n      const Scalar** input_copy_ptrs_base =\n          reinterpret_cast(input_copy_ptrs.mutable_data());\n      for (int batch = 0; batch < batch_size; ++batch) {\n        input_copy_ptrs_base[batch] = &input_copy_reshaped(batch, 0, 0);\n      }\n      dev_info.push_back(\n          solver->GetDeviceLapackInfo(batch_size, \"getrfBatched\"));\n      OP_REQUIRES_OK_ASYNC(\n          context,\n          solver->GetrfBatched(n, input_copy_ptrs_base, n, pivots_mat.data(),\n                               &dev_info.back(), batch_size),\n          done);\n    } else {\n      // For small batch sizes or large matrices, we use the non-batched\n      // interface from cuSolver, which is much faster for large matrices.\n      dev_info.push_back(solver->GetDeviceLapackInfo(batch_size, \"getrf\"));\n      for (int batch = 0; batch < batch_size; ++batch) {\n        OP_REQUIRES_OK_ASYNC(\n            context,\n            solver->Getrf(n, n, &input_copy_reshaped(batch, 0, 0), n,\n                          &pivots_mat(batch, 0), &dev_info.back()(batch)),\n            done);\n      }\n    }\n\n    // 2. Make a transposed copy of the right-hand sides. This is necessary\n    // because cuBLAS assumes column-major storage while TensorFlow TF uses\n    // row-major.\n    TensorShape transposed_rhs_shape(rhs.shape());\n    transposed_rhs_shape.RemoveLastDims(2);\n    transposed_rhs_shape.AddDim(nrhs);\n    transposed_rhs_shape.AddDim(n);\n    Tensor transposed_rhs;\n    OP_REQUIRES_OK_ASYNC(\n        context,\n        solver->allocate_scoped_tensor(DataTypeToEnum::value,\n                                       transposed_rhs_shape, &transposed_rhs),\n        done);\n    if (nrhs > 1) {\n      OP_REQUIRES_OK_ASYNC(\n          context, DoMatrixTranspose(device, rhs, &transposed_rhs), done);\n    } else {\n      device.memcpy(transposed_rhs.flat().data(),\n                    rhs.flat().data(),\n                    rhs.NumElements() * sizeof(Scalar));\n    }\n\n    // 3. Solve op(A) X = B (in column major form).\n    // We use a trick here: If adjoint_ is true, we converted A to column major\n    // form above. If adjoint is false then I leave A in row-major form and use\n    // trans_a = CUBLAS_OP_T to effectively transform it to column-major on the\n    // fly. (This means that we actually use the LU-factorization of A^T in that\n    // case, but that is equally good for solving AX=B). This way we save an\n    // explicit transpose in the more common case of adjoint_ == false.\n    auto input_copy_ptr_array = solver->GetScratchSpace(\n        sizeof(Scalar*) * batch_size, \"input_copy_ptr_array\",\n        /* on_host */ true);\n    auto transposed_rhs_ptr_array = solver->GetScratchSpace(\n        sizeof(Scalar*) * batch_size, \"transposed_rhs_ptr_array\",\n        /* on_host */ true);\n    auto transposed_rhs_reshaped =\n        transposed_rhs.template flat_inner_dims();\n    if (use_batched_solver) {\n      const Scalar** input_copy_ptrs_base =\n          reinterpret_cast(input_copy_ptr_array.mutable_data());\n      const Scalar** transposed_rhs_ptrs_base =\n          reinterpret_cast(\n              transposed_rhs_ptr_array.mutable_data());\n      for (int batch = 0; batch < batch_size; ++batch) {\n        input_copy_ptrs_base[batch] = &input_copy_reshaped(batch, 0, 0);\n        transposed_rhs_ptrs_base[batch] = &transposed_rhs_reshaped(batch, 0, 0);\n      }\n      int host_info = 0;\n      OP_REQUIRES_OK_ASYNC(\n          context,\n          solver->GetrsBatched(adjoint_ ? CUBLAS_OP_C : CUBLAS_OP_T, n, nrhs,\n                               input_copy_ptrs_base, n, pivots_mat.data(),\n                               transposed_rhs_ptrs_base, n, &host_info,\n                               batch_size),\n          done);\n      OP_REQUIRES_ASYNC(\n          context, host_info == 0,\n          errors::InvalidArgument(\"The \", -host_info,\n                                  \"'th argument to cublas*getrsBatched had \"\n                                  \"an illegal value.\"),\n          done);\n    } else {\n      dev_info.push_back(solver->GetDeviceLapackInfo(batch_size, \"getrs\"));\n      for (int batch = 0; batch < batch_size; ++batch) {\n        OP_REQUIRES_OK_ASYNC(\n            context,\n            solver->Getrs(adjoint_ ? CUBLAS_OP_C : CUBLAS_OP_T, n, nrhs,\n                          &input_copy_reshaped(batch, 0, 0), n,\n                          &pivots_mat(batch, 0),\n                          &transposed_rhs_reshaped(batch, 0, 0), n,\n                          &dev_info.back()(batch)),\n            done);\n      }\n    }\n\n    // 4. Transpose X to get the final result in row-major form.\n    if (nrhs > 1) {\n      OP_REQUIRES_OK_ASYNC(\n          context, DoMatrixTranspose(device, transposed_rhs, output), done);\n    } else {\n      device.memcpy(output->flat().data(),\n                    transposed_rhs.flat().data(),\n                    transposed_rhs.NumElements() * sizeof(Scalar));\n    }\n\n    // Callback for checking info after kernels finish. Also capture the\n    // temporary Tensors/ScratchSpace so they don't get deallocated before the\n    // kernels run. TODO(rmlarsen): Use move capture once C++14 becomes\n    // available.\n    auto info_checker = [context, done, dev_info](\n                            const Status& status,\n                            const std::vector& host_infos) {\n      if (!status.ok() && errors::IsInvalidArgument(status) &&\n          !host_infos.empty()) {\n        for (int i = 0; i < host_infos[0].size(); ++i) {\n          // Match the CPU error message for singular matrices. Otherwise\n          // just print the original error message from the status below.\n          OP_REQUIRES_ASYNC(context, host_infos[0].data()[i] <= 0,\n                            errors::InvalidArgument(kErrMsg), done);\n        }\n      }\n      OP_REQUIRES_OK_ASYNC(context, status, done);\n      done();\n    };\n    CudaSolver::CheckLapackInfoAndDeleteSolverAsync(std::move(solver), dev_info,\n                                                    std::move(info_checker));\n  }", "func_hash": 213027909579375149223707117272594449042, "file_name": "matrix_solve_op.cc", "file_hash": 56729187938743390978402639550963026335, "cwe": ["CWE-354"], "cve": "CVE-2021-41206", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions several TensorFlow operations are missing validation for the shapes of the tensor arguments involved in the call. Depending on the API, this can result in undefined behavior and segfault or `CHECK`-fail related crashes but in some scenarios writes and reads from heap populated arrays are also possible. We have discovered these issues internally via tooling while working on improving/testing GPU op determinism. As such, we don't have reproducers and there will be multiple fixes for these issues. These fixes will be included in TensorFlow 2.7.0. We will also cherrypick these commits on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41206"}
{"idx": 196689, "project": "tensorflow", "commit_id": "cebe3c45d76357d201c65bdbbf0dbe6e8a63bbdb", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/cebe3c45d76357d201c65bdbbf0dbe6e8a63bbdb", "commit_message": "Fix tf.raw_ops.StagePeek vulnerability with invalid `index`.\n\nCheck that input is actually a scalar before treating it as such.\n\nPiperOrigin-RevId: 445524908", "target": 1, "func": "  void Compute(OpKernelContext* ctx) override {\n    Buffer* buf = nullptr;\n    OP_REQUIRES_OK(ctx, GetBuffer(ctx, def(), &buf));\n    core::ScopedUnref scope(buf);\n    Buffer::Tuple tuple;\n\n    std::size_t index = ctx->input(0).scalar()();\n\n    OP_REQUIRES_OK(ctx, buf->Peek(index, &tuple));\n\n    OP_REQUIRES(\n        ctx, tuple.size() == (size_t)ctx->num_outputs(),\n        errors::InvalidArgument(\"Mismatch stage/unstage: \", tuple.size(),\n                                \" vs. \", ctx->num_outputs()));\n\n    for (size_t i = 0; i < tuple.size(); ++i) {\n      ctx->set_output(i, tuple[i]);\n    }\n  }", "func_hash": 321476459442808105718031824942985787186, "file_name": "stage_op.cc", "file_hash": 203338145673187111221975146552959312769, "cwe": ["CWE-703"], "cve": "CVE-2022-29195", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.StagePeek` does not fully validate the input arguments. This results in a `CHECK`-failure which can be used to trigger a denial of service attack. The code assumes `index` is a scalar but there is no validation for this before accessing its value. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29195"}
{"idx": 242619, "project": "tensorflow", "commit_id": "cebe3c45d76357d201c65bdbbf0dbe6e8a63bbdb", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/cebe3c45d76357d201c65bdbbf0dbe6e8a63bbdb", "commit_message": "Fix tf.raw_ops.StagePeek vulnerability with invalid `index`.\n\nCheck that input is actually a scalar before treating it as such.\n\nPiperOrigin-RevId: 445524908", "target": 0, "func": "  void Compute(OpKernelContext* ctx) override {\n    Buffer* buf = nullptr;\n    OP_REQUIRES_OK(ctx, GetBuffer(ctx, def(), &buf));\n    core::ScopedUnref scope(buf);\n    Buffer::Tuple tuple;\n\n    buf->Get(&tuple);\n\n    OP_REQUIRES(\n        ctx, tuple.size() == (size_t)ctx->num_outputs(),\n        errors::InvalidArgument(\"Mismatch stage/unstage: \", tuple.size(),\n                                \" vs. \", ctx->num_outputs()));\n\n    for (size_t i = 0; i < tuple.size(); ++i) {\n      ctx->set_output(i, tuple[i]);\n    }\n  }", "func_hash": 150871818833070085390431100112319012215, "file_name": "stage_op.cc", "file_hash": 292796960162980121952379513053668377918, "cwe": ["CWE-703"], "cve": "CVE-2022-29195", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.StagePeek` does not fully validate the input arguments. This results in a `CHECK`-failure which can be used to trigger a denial of service attack. The code assumes `index` is a scalar but there is no validation for this before accessing its value. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29195"}
{"idx": 196691, "project": "gpac", "commit_id": "71460d72ec07df766dab0a4d52687529f3efcf0a", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/71460d72ec07df766dab0a4d52687529f3efcf0a", "commit_message": "fixed #1876", "target": 1, "func": "static GF_Err isoffin_process(GF_Filter *filter)\n{\n\tISOMReader *read = gf_filter_get_udta(filter);\n\tu32 i, count = gf_list_count(read->channels);\n\tBool is_active = GF_FALSE;\n\tBool in_is_eos = GF_FALSE;\n\tBool check_forced_end = GF_FALSE;\n\tBool has_new_data = GF_FALSE;\n\tu64 min_offset_plus_one = 0;\n\tu32 nb_forced_end=0;\n\tif (read->in_error)\n\t\treturn read->in_error;\n\n\tif (read->pid) {\n\t\tBool fetch_input = GF_TRUE;\n\n\t\t//we failed at loading the init segment during a dash switch, retry\n\t\tif (!read->is_partial_download && !read->mem_load_mode && (read->moov_not_loaded==2) ) {\n\t\t\tisoffin_configure_pid(filter, read->pid, GF_FALSE);\n\t\t\tif (read->moov_not_loaded) return GF_OK;\n\t\t}\n\t\tif (read->mem_load_mode==2) {\n\t\t\tif (!read->force_fetch && read->mem_blob.size > read->mstore_size) {\n\t\t\t\tfetch_input = GF_FALSE;\n\t\t\t}\n\t\t\tread->force_fetch = GF_FALSE;\n\t\t}\n\t\twhile (fetch_input) {\n\t\t\tGF_FilterPacket *pck = gf_filter_pid_get_packet(read->pid);\n\t\t\tif (!pck) {\n\t\t\t\t//we issued a seek, wait for the first packet to be received before fetching channels\n\t\t\t\t//otherwise we could end up reading from the wrong cache\n\t\t\t\tif (read->wait_for_source) {\n\t\t\t\t\t//something went wrong during the seek request\n\t\t\t\t\tif (gf_filter_pid_is_eos(read->pid))\n\t\t\t\t\t\treturn GF_EOS;\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tread->wait_for_source = GF_FALSE;\n\n\t\t\tif (read->mem_load_mode) {\n\t\t\t\tu32 data_size;\n\t\t\t\tconst u8 *pck_data = gf_filter_pck_get_data(pck, &data_size);\n\t\t\t\tisoffin_push_buffer(filter, read, pck_data, data_size);\n\t\t\t}\n\t\t\t//we just had a switch but init seg is not completely done: input packet is only a part of the init, drop it\n\t\t\telse if (read->moov_not_loaded==2) {\n\t\t\t\tgf_filter_pid_drop_packet(read->pid);\n\t\t\t\treturn GF_OK;\n\t\t\t}\n\t\t\tgf_filter_pid_drop_packet(read->pid);\n\t\t\thas_new_data = GF_TRUE;\n\t\t\tif (read->in_error)\n\t\t\t\treturn read->in_error;\n\t\t}\n\t\tif (gf_filter_pid_is_eos(read->pid)) {\n\t\t\tread->input_loaded = GF_TRUE;\n\t\t\tin_is_eos = GF_TRUE;\n\t\t}\n\t\tif (read->input_is_stop) {\n\t\t\tread->input_loaded = GF_TRUE;\n\t\t\tin_is_eos = GF_TRUE;\n\t\t\tread->input_is_stop = GF_FALSE;\n\t\t}\n\t\tif (!read->frag_type && read->input_loaded) {\n\t\t\tin_is_eos = GF_TRUE;\n\t\t}\n        //segment is invalid, wait for eos on input an send eos on all channels\n        if (read->invalid_segment) {\n            if (!in_is_eos) return GF_OK;\n            read->invalid_segment = GF_FALSE;\n\n            for (i=0; ichannels, i);\n                if (!ch->playing) {\n                    continue;\n                }\n                if (!ch->eos_sent) {\n                    ch->eos_sent = GF_TRUE;\n                    gf_filter_pid_set_eos(ch->pid);\n                }\n            }\n            read->eos_signaled = GF_TRUE;\n            return GF_EOS;\n        }\n\t} else if (read->extern_mov) {\n\t\tin_is_eos = GF_TRUE;\n\t\tread->input_loaded = GF_TRUE;\n\t}\n\tif (read->moov_not_loaded==1) {\n\t\tif (read->mem_load_mode)\n\t\t\treturn GF_OK;\n\t\tread->moov_not_loaded = GF_FALSE;\n\t\treturn isoffin_setup(filter, read);\n\t}\n\n\tif (read->refresh_fragmented) {\n\t\tconst GF_PropertyValue *prop;\n\n\t\tif (in_is_eos) {\n\t\t\tread->refresh_fragmented = GF_FALSE;\n\t\t} else {\n\t\t\tprop = gf_filter_pid_get_property(read->pid, GF_PROP_PID_FILE_CACHED);\n\t\t\tif (prop && prop->value.boolean)\n\t\t\t\tread->refresh_fragmented = GF_FALSE;\n\t\t}\n\n\t\tif (has_new_data) {\n\t\t\tu64 bytesMissing=0;\n\t\t\tGF_Err e;\n\t\t\tconst char *new_url = NULL;\n\t\t\tprop = gf_filter_pid_get_property(read->pid, GF_PROP_PID_FILEPATH);\n\t\t\tif (prop) new_url = prop->value.string;\n\n\t\t\te = gf_isom_refresh_fragmented(read->mov, &bytesMissing, new_url);\n\n\t\t\tif (e && (e!= GF_ISOM_INCOMPLETE_FILE)) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_DASH, (\"[IsoMedia] Failed to refresh current segment: %s\\n\", gf_error_to_string(e) ));\n\t\t\t\tread->refresh_fragmented = GF_FALSE;\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, (\"[IsoMedia] Refreshing current segment at UTC \"LLU\" - \"LLU\" bytes still missing - input is EOS %d\\n\", gf_net_get_utc(), bytesMissing, in_is_eos));\n\t\t\t}\n\n\t\t\tif (!read->refresh_fragmented && (e==GF_ISOM_INCOMPLETE_FILE)) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_DASH, (\"[IsoMedia] Incomplete Segment received - \"LLU\" bytes missing but EOF found\\n\", bytesMissing ));\n\t\t\t}\n\n#ifndef GPAC_DISABLE_LOG\n\t\t\tif (gf_log_tool_level_on(GF_LOG_DASH, GF_LOG_DEBUG)) {\n\t\t\t\tfor (i=0; ichannels, i);\n\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, (\"[IsoMedia] refresh track %d fragment - cur sample %d - new sample count %d\\n\", ch->track, ch->sample_num, gf_isom_get_sample_count(ch->owner->mov, ch->track) ));\n\t\t\t\t}\n\t\t\t}\n#endif\n\t\t\tisor_check_producer_ref_time(read);\n\t\t\tif (!read->frag_type)\n\t\t\t\tread->refresh_fragmented = GF_FALSE;\n\t\t}\n\t}\n\n\tfor (i=0; ichannels, i);\n\t\tif (!ch->playing) {\n\t\t\tnb_forced_end++;\n\t\t\tcontinue;\n\t\t}\n\t\t//eos not sent on this channel, we are active\n\t\tif (!ch->eos_sent)\n\t\t\tis_active = GF_TRUE;\n\n\t\twhile (nb_pck) {\n\t\t\tch->sample_data_offset = 0;\n\t\t\tif (!read->full_segment_flush && gf_filter_pid_would_block(ch->pid) )\n\t\t\t\tbreak;\n\n\t\t\tif (ch->item_id) {\n\t\t\t\tisor_reader_get_sample_from_item(ch);\n\t\t\t} else {\n\t\t\t\tisor_reader_get_sample(ch);\n\t\t\t}\n\n\t\t\tif (read->stsd && (ch->last_sample_desc_index != read->stsd) && ch->sample) {\n\t\t\t\tisor_reader_release_sample(ch);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ch->sample) {\n\t\t\t\tu32 sample_dur;\n\t\t\t\tu8 dep_flags;\n\t\t\t\tu8 *subs_buf;\n\t\t\t\tu32 subs_buf_size;\n\t\t\t\tGF_FilterPacket *pck;\n\t\t\t\tif (ch->needs_pid_reconfig) {\n\t\t\t\t\tisor_update_channel_config(ch);\n\t\t\t\t\tch->needs_pid_reconfig = GF_FALSE;\n\t\t\t\t}\n\n\t\t\t\t//we have at least two samples, update GF_PROP_PID_HAS_SYNC if needed\n\t\t\t\tif (ch->check_has_rap && (gf_isom_get_sample_count(ch->owner->mov, ch->track)>1) && (gf_isom_has_sync_points(ch->owner->mov, ch->track)==1)) {\n\t\t\t\t\tch->check_has_rap = GF_FALSE;\n\t\t\t\t\tch->has_rap = GF_TRUE;\n\t\t\t\t\tgf_filter_pid_set_property(ch->pid, GF_PROP_PID_HAS_SYNC, &PROP_BOOL(ch->has_rap) );\n\t\t\t\t}\n\n\t\t\t\t//strip param sets from payload, trigger reconfig if needed\n\t\t\t\tisor_reader_check_config(ch);\n\n\t\t\t\tif (read->nodata) {\n\t\t\t\t\tpck = gf_filter_pck_new_shared(ch->pid, NULL, ch->sample->dataLength, NULL);\n\t\t\t\t\tif (!pck) return GF_OUT_OF_MEM;\n\t\t\t\t} else {\n\t\t\t\t\tpck = gf_filter_pck_new_alloc(ch->pid, ch->sample->dataLength, &data);\n\t\t\t\t\tif (!pck) return GF_OUT_OF_MEM;\n\n\t\t\t\t\tmemcpy(data, ch->sample->data, ch->sample->dataLength);\n\t\t\t\t}\n\t\t\t\tgf_filter_pck_set_dts(pck, ch->dts);\n\t\t\t\tgf_filter_pck_set_cts(pck, ch->cts);\n\t\t\t\tif (ch->sample->IsRAP==-1) {\n\t\t\t\t\tgf_filter_pck_set_sap(pck, GF_FILTER_SAP_1);\n\t\t\t\t\tch->redundant = 1;\n\t\t\t\t} else {\n\t\t\t\t\tgf_filter_pck_set_sap(pck, (GF_FilterSAPType) ch->sample->IsRAP);\n\t\t\t\t}\n\n\t\t\t\tif (ch->sap_3)\n\t\t\t\t\tgf_filter_pck_set_sap(pck, GF_FILTER_SAP_3);\n\t\t\t\telse if (ch->sap_4_type) {\n\t\t\t\t\tgf_filter_pck_set_sap(pck, (ch->sap_4_type==GF_ISOM_SAMPLE_PREROLL) ? GF_FILTER_SAP_4_PROL : GF_FILTER_SAP_4);\n\t\t\t\t\tgf_filter_pck_set_roll_info(pck, ch->roll);\n\t\t\t\t}\n\n\t\t\t\tsample_dur = ch->au_duration;\n\t\t\t\tif (ch->sample->nb_pack)\n\t\t\t\t\tsample_dur *= ch->sample->nb_pack;\n\t\t\t\tgf_filter_pck_set_duration(pck, sample_dur);\n\t\t\t\tgf_filter_pck_set_seek_flag(pck, ch->seek_flag);\n\n\t\t\t\t//for now we only signal xPS mask for non-sap\n\t\t\t\tif (ch->xps_mask && !gf_filter_pck_get_sap(pck) ) {\n\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_XPS_MASK, &PROP_UINT(ch->xps_mask) );\n\t\t\t\t}\n\n\t\t\t\tdep_flags = ch->isLeading;\n\t\t\t\tdep_flags <<= 2;\n\t\t\t\tdep_flags |= ch->dependsOn;\n\t\t\t\tdep_flags <<= 2;\n\t\t\t\tdep_flags |= ch->dependedOn;\n\t\t\t\tdep_flags <<= 2;\n\t\t\t\tdep_flags |= ch->redundant;\n\n\t\t\t\tif (dep_flags)\n\t\t\t\t\tgf_filter_pck_set_dependency_flags(pck, dep_flags);\n\n\t\t\t\tgf_filter_pck_set_crypt_flags(pck, ch->pck_encrypted ? GF_FILTER_PCK_CRYPT : 0);\n\t\t\t\tgf_filter_pck_set_seq_num(pck, ch->sample_num);\n\n\n\t\t\t\tsubs_buf = gf_isom_sample_get_subsamples_buffer(read->mov, ch->track, ch->sample_num, &subs_buf_size);\n\t\t\t\tif (subs_buf) {\n\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_SUBS, &PROP_DATA_NO_COPY(subs_buf, subs_buf_size) );\n\t\t\t\t}\n\n\t\t\t\tif (ch->sai_buffer && ch->pck_encrypted) {\n\t\t\t\t\tassert(ch->sai_buffer_size);\n\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_CENC_SAI, &PROP_DATA(ch->sai_buffer, ch->sai_buffer_size) );\n\t\t\t\t}\n\n\t\t\t\tif (read->sigfrag) {\n\t\t\t\t\tGF_ISOFragmentBoundaryInfo finfo;\n\t\t\t\t\tif (gf_isom_sample_is_fragment_start(read->mov, ch->track, ch->sample_num, &finfo) ) {\n\t\t\t\t\t\tu64 start=0;\n\t\t\t\t\t\tu32 traf_start = finfo.seg_start_plus_one ? 2 : 1;\n\n\t\t\t\t\t\tif (finfo.seg_start_plus_one)\n\t\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_CUE_START, &PROP_BOOL(GF_TRUE));\n\n\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_FRAG_START, &PROP_UINT(traf_start));\n\n\t\t\t\t\t\tstart = finfo.frag_start;\n\t\t\t\t\t\tif (finfo.seg_start_plus_one) start = finfo.seg_start_plus_one-1;\n\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_FRAG_RANGE, &PROP_FRAC64_INT(start, finfo.mdat_end));\n\t\t\t\t\t\tif (finfo.moof_template) {\n\t\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_MOOF_TEMPLATE, &PROP_DATA((u8 *)finfo.moof_template, finfo.moof_template_size));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (finfo.sidx_end) {\n\t\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_SIDX_RANGE, &PROP_FRAC64_INT(finfo.sidx_start , finfo.sidx_end));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (read->seg_name_changed) {\n\t\t\t\t\t\t\tconst GF_PropertyValue *p = gf_filter_pid_get_property(read->pid, GF_PROP_PID_URL);\n\t\t\t\t\t\t\tread->seg_name_changed = GF_FALSE;\n\t\t\t\t\t\t\tif (p && p->value.string) {\n\t\t\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PID_URL, &PROP_STRING(p->value.string));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (ch->sender_ntp) {\n\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_SENDER_NTP, &PROP_LONGUINT(ch->sender_ntp));\n\t\t\t\t\tif (ch->ntp_at_server_ntp) {\n\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_RECEIVER_NTP, &PROP_LONGUINT(ch->ntp_at_server_ntp));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tch->eos_sent = GF_FALSE;\n\n\t\t\t\t//this might not be the true end of stream\n\t\t\t\tif ((ch->streamType==GF_STREAM_AUDIO) && (ch->sample_num == gf_isom_get_sample_count(read->mov, ch->track))) {\n\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_END_RANGE, &PROP_BOOL(GF_TRUE));\n\t\t\t\t}\n\n\t\t\t\tgf_filter_pck_send(pck);\n\t\t\t\tisor_reader_release_sample(ch);\n\n\t\t\t\tch->last_valid_sample_data_offset = ch->sample_data_offset;\n\t\t\t\tnb_pck--;\n\t\t\t} else if (ch->last_state==GF_EOS) {\n\t\t\t\tif (ch->playing == 2) {\n\t\t\t\t\tif (in_is_eos) {\n\t\t\t\t\t\tch->playing = GF_FALSE;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnb_forced_end++;\n\t\t\t\t\t\tcheck_forced_end = GF_TRUE;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (in_is_eos && !ch->eos_sent) {\n\t\t\t\t\tvoid *tfrf;\n\t\t\t\t\tconst void *gf_isom_get_tfrf(GF_ISOFile *movie, u32 trackNumber);\n\n\t\t\t\t\tch->eos_sent = GF_TRUE;\n\t\t\t\t\tread->eos_signaled = GF_TRUE;\n\n\t\t\t\t\ttfrf = (void *) gf_isom_get_tfrf(read->mov, ch->track);\n\t\t\t\t\tif (tfrf) {\n\t\t\t\t\t\tgf_filter_pid_set_info_str(ch->pid, \"smooth_tfrf\", &PROP_POINTER(tfrf) );\n\t\t\t\t\t\tch->last_has_tfrf = GF_TRUE;\n\t\t\t\t\t} else if (ch->last_has_tfrf) {\n\t\t\t\t\t\tgf_filter_pid_set_info_str(ch->pid, \"smooth_tfrf\", NULL);\n\t\t\t\t\t\tch->last_has_tfrf = GF_FALSE;\n\t\t\t\t\t}\n\n\t\t\t\t\tgf_filter_pid_set_eos(ch->pid);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\tread->force_fetch = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!min_offset_plus_one || (min_offset_plus_one - 1 > ch->last_valid_sample_data_offset))\n\t\t\tmin_offset_plus_one = 1 + ch->last_valid_sample_data_offset;\n\t}\n\tif (read->mem_load_mode && min_offset_plus_one) {\n\t\tisoffin_purge_mem(read, min_offset_plus_one-1);\n\t}\n\n\t//we reached end of playback due to play range request, we must send eos - however for safety reason with DASH, we first need to cancel the input\n\tif (read->pid && check_forced_end && (nb_forced_end==count)) {\n\t\t//abort input\n\t\tGF_FilterEvent evt;\n\t\tGF_FEVT_INIT(evt, GF_FEVT_STOP, read->pid);\n\t\tgf_filter_pid_send_event(read->pid, &evt);\n\t}\n\n\n\tif (!is_active) {\n\t\treturn GF_EOS;\n\t}\n\t//if (in_is_eos)\n//\tgf_filter_ask_rt_reschedule(filter, 1);\n\treturn GF_OK;\n\n}", "func_hash": 245491994913846374509516795584789756192, "file_name": "isoffin_read.c", "file_hash": 80320074166992838039801529564251755054, "cwe": ["CWE-703"], "cve": "CVE-2021-40592", "cve_desc": "GPAC version before commit 71460d72ec07df766dab0a4d52687529f3efcf0a (version v1.0.1 onwards) contains loop with unreachable exit condition ('infinite loop') vulnerability in ISOBMFF reader filter, isoffin_read.c. Function isoffin_process() can result in DoS by infinite loop. To exploit, the victim must open a specially crafted mp4 file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40592"}
{"idx": 242637, "project": "gpac", "commit_id": "71460d72ec07df766dab0a4d52687529f3efcf0a", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/71460d72ec07df766dab0a4d52687529f3efcf0a", "commit_message": "fixed #1876", "target": 0, "func": "static GF_Err isoffin_process(GF_Filter *filter)\n{\n\tISOMReader *read = gf_filter_get_udta(filter);\n\tu32 i, count = gf_list_count(read->channels);\n\tBool is_active = GF_FALSE;\n\tBool in_is_eos = GF_FALSE;\n\tBool check_forced_end = GF_FALSE;\n\tBool has_new_data = GF_FALSE;\n\tu64 min_offset_plus_one = 0;\n\tu32 nb_forced_end=0;\n\tif (read->in_error)\n\t\treturn read->in_error;\n\n\tif (read->pid) {\n\t\tBool fetch_input = GF_TRUE;\n\n\t\t//we failed at loading the init segment during a dash switch, retry\n\t\tif (!read->is_partial_download && !read->mem_load_mode && (read->moov_not_loaded==2) ) {\n\t\t\tisoffin_configure_pid(filter, read->pid, GF_FALSE);\n\t\t\tif (read->moov_not_loaded) return GF_OK;\n\t\t}\n\t\tif (read->mem_load_mode==2) {\n\t\t\tif (!read->force_fetch && read->mem_blob.size > read->mstore_size) {\n\t\t\t\tfetch_input = GF_FALSE;\n\t\t\t}\n\t\t\tread->force_fetch = GF_FALSE;\n\t\t}\n\t\twhile (fetch_input) {\n\t\t\tGF_FilterPacket *pck = gf_filter_pid_get_packet(read->pid);\n\t\t\tif (!pck) {\n\t\t\t\t//we issued a seek, wait for the first packet to be received before fetching channels\n\t\t\t\t//otherwise we could end up reading from the wrong cache\n\t\t\t\tif (read->wait_for_source) {\n\t\t\t\t\t//something went wrong during the seek request\n\t\t\t\t\tif (gf_filter_pid_is_eos(read->pid))\n\t\t\t\t\t\treturn GF_EOS;\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tread->wait_for_source = GF_FALSE;\n\n\t\t\tif (read->mem_load_mode) {\n\t\t\t\tu32 data_size;\n\t\t\t\tconst u8 *pck_data = gf_filter_pck_get_data(pck, &data_size);\n\t\t\t\tisoffin_push_buffer(filter, read, pck_data, data_size);\n\t\t\t}\n\t\t\t//we just had a switch but init seg is not completely done: input packet is only a part of the init, drop it\n\t\t\telse if (read->moov_not_loaded==2) {\n\t\t\t\tgf_filter_pid_drop_packet(read->pid);\n\t\t\t\treturn GF_OK;\n\t\t\t}\n\t\t\tgf_filter_pid_drop_packet(read->pid);\n\t\t\thas_new_data = GF_TRUE;\n\t\t\tif (read->in_error)\n\t\t\t\treturn read->in_error;\n\t\t}\n\t\tif (gf_filter_pid_is_eos(read->pid)) {\n\t\t\tread->input_loaded = GF_TRUE;\n\t\t\tin_is_eos = GF_TRUE;\n\t\t}\n\t\tif (read->input_is_stop) {\n\t\t\tread->input_loaded = GF_TRUE;\n\t\t\tin_is_eos = GF_TRUE;\n\t\t\tread->input_is_stop = GF_FALSE;\n\t\t}\n\t\tif (!read->frag_type && read->input_loaded) {\n\t\t\tin_is_eos = GF_TRUE;\n\t\t}\n        //segment is invalid, wait for eos on input an send eos on all channels\n        if (read->invalid_segment) {\n            if (!in_is_eos) return GF_OK;\n            read->invalid_segment = GF_FALSE;\n\n            for (i=0; ichannels, i);\n                if (!ch->playing) {\n                    continue;\n                }\n                if (!ch->eos_sent) {\n                    ch->eos_sent = GF_TRUE;\n                    gf_filter_pid_set_eos(ch->pid);\n                }\n            }\n            read->eos_signaled = GF_TRUE;\n            return GF_EOS;\n        }\n\t} else if (read->extern_mov) {\n\t\tin_is_eos = GF_TRUE;\n\t\tread->input_loaded = GF_TRUE;\n\t}\n\tif (read->moov_not_loaded==1) {\n\t\tif (read->mem_load_mode)\n\t\t\treturn GF_OK;\n\t\tread->moov_not_loaded = GF_FALSE;\n\t\treturn isoffin_setup(filter, read);\n\t}\n\n\tif (read->refresh_fragmented) {\n\t\tconst GF_PropertyValue *prop;\n\n\t\tif (in_is_eos) {\n\t\t\tread->refresh_fragmented = GF_FALSE;\n\t\t} else {\n\t\t\tprop = gf_filter_pid_get_property(read->pid, GF_PROP_PID_FILE_CACHED);\n\t\t\tif (prop && prop->value.boolean)\n\t\t\t\tread->refresh_fragmented = GF_FALSE;\n\t\t}\n\n\t\tif (has_new_data) {\n\t\t\tu64 bytesMissing=0;\n\t\t\tGF_Err e;\n\t\t\tconst char *new_url = NULL;\n\t\t\tprop = gf_filter_pid_get_property(read->pid, GF_PROP_PID_FILEPATH);\n\t\t\tif (prop) new_url = prop->value.string;\n\n\t\t\te = gf_isom_refresh_fragmented(read->mov, &bytesMissing, new_url);\n\n\t\t\tif (e && (e!= GF_ISOM_INCOMPLETE_FILE)) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_DASH, (\"[IsoMedia] Failed to refresh current segment: %s\\n\", gf_error_to_string(e) ));\n\t\t\t\tread->refresh_fragmented = GF_FALSE;\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, (\"[IsoMedia] Refreshing current segment at UTC \"LLU\" - \"LLU\" bytes still missing - input is EOS %d\\n\", gf_net_get_utc(), bytesMissing, in_is_eos));\n\t\t\t}\n\n\t\t\tif (!read->refresh_fragmented && (e==GF_ISOM_INCOMPLETE_FILE)) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_DASH, (\"[IsoMedia] Incomplete Segment received - \"LLU\" bytes missing but EOF found\\n\", bytesMissing ));\n\t\t\t}\n\n#ifndef GPAC_DISABLE_LOG\n\t\t\tif (gf_log_tool_level_on(GF_LOG_DASH, GF_LOG_DEBUG)) {\n\t\t\t\tfor (i=0; ichannels, i);\n\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, (\"[IsoMedia] refresh track %d fragment - cur sample %d - new sample count %d\\n\", ch->track, ch->sample_num, gf_isom_get_sample_count(ch->owner->mov, ch->track) ));\n\t\t\t\t}\n\t\t\t}\n#endif\n\t\t\tisor_check_producer_ref_time(read);\n\t\t\tif (!read->frag_type)\n\t\t\t\tread->refresh_fragmented = GF_FALSE;\n\t\t}\n\t}\n\n\tfor (i=0; ichannels, i);\n\t\tif (!ch->playing) {\n\t\t\tnb_forced_end++;\n\t\t\tcontinue;\n\t\t}\n\t\t//eos not sent on this channel, we are active\n\t\tif (!ch->eos_sent)\n\t\t\tis_active = GF_TRUE;\n\n\t\twhile (nb_pck) {\n\t\t\tch->sample_data_offset = 0;\n\t\t\tif (!read->full_segment_flush && gf_filter_pid_would_block(ch->pid) )\n\t\t\t\tbreak;\n\n\t\t\tif (ch->item_id) {\n\t\t\t\tisor_reader_get_sample_from_item(ch);\n\t\t\t} else {\n\t\t\t\tisor_reader_get_sample(ch);\n\t\t\t}\n\n\t\t\tif (read->stsd && (ch->last_sample_desc_index != read->stsd) && ch->sample) {\n\t\t\t\tisor_reader_release_sample(ch);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ch->sample) {\n\t\t\t\tu32 sample_dur;\n\t\t\t\tu8 dep_flags;\n\t\t\t\tu8 *subs_buf;\n\t\t\t\tu32 subs_buf_size;\n\t\t\t\tGF_FilterPacket *pck;\n\t\t\t\tif (ch->needs_pid_reconfig) {\n\t\t\t\t\tisor_update_channel_config(ch);\n\t\t\t\t\tch->needs_pid_reconfig = GF_FALSE;\n\t\t\t\t}\n\n\t\t\t\t//we have at least two samples, update GF_PROP_PID_HAS_SYNC if needed\n\t\t\t\tif (ch->check_has_rap && (gf_isom_get_sample_count(ch->owner->mov, ch->track)>1) && (gf_isom_has_sync_points(ch->owner->mov, ch->track)==1)) {\n\t\t\t\t\tch->check_has_rap = GF_FALSE;\n\t\t\t\t\tch->has_rap = GF_TRUE;\n\t\t\t\t\tgf_filter_pid_set_property(ch->pid, GF_PROP_PID_HAS_SYNC, &PROP_BOOL(ch->has_rap) );\n\t\t\t\t}\n\n\t\t\t\t//strip param sets from payload, trigger reconfig if needed\n\t\t\t\tisor_reader_check_config(ch);\n\n\t\t\t\tif (read->nodata) {\n\t\t\t\t\tpck = gf_filter_pck_new_shared(ch->pid, NULL, ch->sample->dataLength, NULL);\n\t\t\t\t\tif (!pck) return GF_OUT_OF_MEM;\n\t\t\t\t} else {\n\t\t\t\t\tpck = gf_filter_pck_new_alloc(ch->pid, ch->sample->dataLength, &data);\n\t\t\t\t\tif (!pck) return GF_OUT_OF_MEM;\n\n\t\t\t\t\tmemcpy(data, ch->sample->data, ch->sample->dataLength);\n\t\t\t\t}\n\t\t\t\tgf_filter_pck_set_dts(pck, ch->dts);\n\t\t\t\tgf_filter_pck_set_cts(pck, ch->cts);\n\t\t\t\tif (ch->sample->IsRAP==-1) {\n\t\t\t\t\tgf_filter_pck_set_sap(pck, GF_FILTER_SAP_1);\n\t\t\t\t\tch->redundant = 1;\n\t\t\t\t} else {\n\t\t\t\t\tgf_filter_pck_set_sap(pck, (GF_FilterSAPType) ch->sample->IsRAP);\n\t\t\t\t}\n\n\t\t\t\tif (ch->sap_3)\n\t\t\t\t\tgf_filter_pck_set_sap(pck, GF_FILTER_SAP_3);\n\t\t\t\telse if (ch->sap_4_type) {\n\t\t\t\t\tgf_filter_pck_set_sap(pck, (ch->sap_4_type==GF_ISOM_SAMPLE_PREROLL) ? GF_FILTER_SAP_4_PROL : GF_FILTER_SAP_4);\n\t\t\t\t\tgf_filter_pck_set_roll_info(pck, ch->roll);\n\t\t\t\t}\n\n\t\t\t\tsample_dur = ch->au_duration;\n\t\t\t\tif (ch->sample->nb_pack)\n\t\t\t\t\tsample_dur *= ch->sample->nb_pack;\n\t\t\t\tgf_filter_pck_set_duration(pck, sample_dur);\n\t\t\t\tgf_filter_pck_set_seek_flag(pck, ch->seek_flag);\n\n\t\t\t\t//for now we only signal xPS mask for non-sap\n\t\t\t\tif (ch->xps_mask && !gf_filter_pck_get_sap(pck) ) {\n\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_XPS_MASK, &PROP_UINT(ch->xps_mask) );\n\t\t\t\t}\n\n\t\t\t\tdep_flags = ch->isLeading;\n\t\t\t\tdep_flags <<= 2;\n\t\t\t\tdep_flags |= ch->dependsOn;\n\t\t\t\tdep_flags <<= 2;\n\t\t\t\tdep_flags |= ch->dependedOn;\n\t\t\t\tdep_flags <<= 2;\n\t\t\t\tdep_flags |= ch->redundant;\n\n\t\t\t\tif (dep_flags)\n\t\t\t\t\tgf_filter_pck_set_dependency_flags(pck, dep_flags);\n\n\t\t\t\tgf_filter_pck_set_crypt_flags(pck, ch->pck_encrypted ? GF_FILTER_PCK_CRYPT : 0);\n\t\t\t\tgf_filter_pck_set_seq_num(pck, ch->sample_num);\n\n\n\t\t\t\tsubs_buf = gf_isom_sample_get_subsamples_buffer(read->mov, ch->track, ch->sample_num, &subs_buf_size);\n\t\t\t\tif (subs_buf) {\n\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_SUBS, &PROP_DATA_NO_COPY(subs_buf, subs_buf_size) );\n\t\t\t\t}\n\n\t\t\t\tif (ch->sai_buffer && ch->pck_encrypted) {\n\t\t\t\t\tassert(ch->sai_buffer_size);\n\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_CENC_SAI, &PROP_DATA(ch->sai_buffer, ch->sai_buffer_size) );\n\t\t\t\t}\n\n\t\t\t\tif (read->sigfrag) {\n\t\t\t\t\tGF_ISOFragmentBoundaryInfo finfo;\n\t\t\t\t\tif (gf_isom_sample_is_fragment_start(read->mov, ch->track, ch->sample_num, &finfo) ) {\n\t\t\t\t\t\tu64 start=0;\n\t\t\t\t\t\tu32 traf_start = finfo.seg_start_plus_one ? 2 : 1;\n\n\t\t\t\t\t\tif (finfo.seg_start_plus_one)\n\t\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_CUE_START, &PROP_BOOL(GF_TRUE));\n\n\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_FRAG_START, &PROP_UINT(traf_start));\n\n\t\t\t\t\t\tstart = finfo.frag_start;\n\t\t\t\t\t\tif (finfo.seg_start_plus_one) start = finfo.seg_start_plus_one-1;\n\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_FRAG_RANGE, &PROP_FRAC64_INT(start, finfo.mdat_end));\n\t\t\t\t\t\tif (finfo.moof_template) {\n\t\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_MOOF_TEMPLATE, &PROP_DATA((u8 *)finfo.moof_template, finfo.moof_template_size));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (finfo.sidx_end) {\n\t\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_SIDX_RANGE, &PROP_FRAC64_INT(finfo.sidx_start , finfo.sidx_end));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (read->seg_name_changed) {\n\t\t\t\t\t\t\tconst GF_PropertyValue *p = gf_filter_pid_get_property(read->pid, GF_PROP_PID_URL);\n\t\t\t\t\t\t\tread->seg_name_changed = GF_FALSE;\n\t\t\t\t\t\t\tif (p && p->value.string) {\n\t\t\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PID_URL, &PROP_STRING(p->value.string));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (ch->sender_ntp) {\n\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_SENDER_NTP, &PROP_LONGUINT(ch->sender_ntp));\n\t\t\t\t\tif (ch->ntp_at_server_ntp) {\n\t\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_RECEIVER_NTP, &PROP_LONGUINT(ch->ntp_at_server_ntp));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tch->eos_sent = GF_FALSE;\n\n\t\t\t\t//this might not be the true end of stream\n\t\t\t\tif ((ch->streamType==GF_STREAM_AUDIO) && (ch->sample_num == gf_isom_get_sample_count(read->mov, ch->track))) {\n\t\t\t\t\tgf_filter_pck_set_property(pck, GF_PROP_PCK_END_RANGE, &PROP_BOOL(GF_TRUE));\n\t\t\t\t}\n\n\t\t\t\tgf_filter_pck_send(pck);\n\t\t\t\tisor_reader_release_sample(ch);\n\n\t\t\t\tch->last_valid_sample_data_offset = ch->sample_data_offset;\n\t\t\t\tnb_pck--;\n\t\t\t} else if (ch->last_state==GF_EOS) {\n\t\t\t\tif (ch->playing == 2) {\n\t\t\t\t\tif (in_is_eos) {\n\t\t\t\t\t\tch->playing = GF_FALSE;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnb_forced_end++;\n\t\t\t\t\t\tcheck_forced_end = GF_TRUE;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (in_is_eos && !ch->eos_sent) {\n\t\t\t\t\tvoid *tfrf;\n\t\t\t\t\tconst void *gf_isom_get_tfrf(GF_ISOFile *movie, u32 trackNumber);\n\n\t\t\t\t\tch->eos_sent = GF_TRUE;\n\t\t\t\t\tread->eos_signaled = GF_TRUE;\n\n\t\t\t\t\ttfrf = (void *) gf_isom_get_tfrf(read->mov, ch->track);\n\t\t\t\t\tif (tfrf) {\n\t\t\t\t\t\tgf_filter_pid_set_info_str(ch->pid, \"smooth_tfrf\", &PROP_POINTER(tfrf) );\n\t\t\t\t\t\tch->last_has_tfrf = GF_TRUE;\n\t\t\t\t\t} else if (ch->last_has_tfrf) {\n\t\t\t\t\t\tgf_filter_pid_set_info_str(ch->pid, \"smooth_tfrf\", NULL);\n\t\t\t\t\t\tch->last_has_tfrf = GF_FALSE;\n\t\t\t\t\t}\n\n\t\t\t\t\tgf_filter_pid_set_eos(ch->pid);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} else if (ch->last_state==GF_ISOM_INVALID_FILE) {\n\t\t\t\tif (!ch->eos_sent) {\n\t\t\t\t\tch->eos_sent = GF_TRUE;\n\t\t\t\t\tread->eos_signaled = GF_TRUE;\n\t\t\t\t\tgf_filter_pid_set_eos(ch->pid);\n\t\t\t\t}\n\t\t\t\treturn ch->last_state;\n\t\t\t} else {\n\t\t\t\tread->force_fetch = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!min_offset_plus_one || (min_offset_plus_one - 1 > ch->last_valid_sample_data_offset))\n\t\t\tmin_offset_plus_one = 1 + ch->last_valid_sample_data_offset;\n\t}\n\tif (read->mem_load_mode && min_offset_plus_one) {\n\t\tisoffin_purge_mem(read, min_offset_plus_one-1);\n\t}\n\n\t//we reached end of playback due to play range request, we must send eos - however for safety reason with DASH, we first need to cancel the input\n\tif (read->pid && check_forced_end && (nb_forced_end==count)) {\n\t\t//abort input\n\t\tGF_FilterEvent evt;\n\t\tGF_FEVT_INIT(evt, GF_FEVT_STOP, read->pid);\n\t\tgf_filter_pid_send_event(read->pid, &evt);\n\t}\n\n\n\tif (!is_active) {\n\t\treturn GF_EOS;\n\t}\n\t//if (in_is_eos)\n//\tgf_filter_ask_rt_reschedule(filter, 1);\n\treturn GF_OK;\n\n}", "func_hash": 305058451325362998718292493453495076439, "file_name": "isoffin_read.c", "file_hash": 45568496591393007238506246573526523584, "cwe": ["CWE-703"], "cve": "CVE-2021-40592", "cve_desc": "GPAC version before commit 71460d72ec07df766dab0a4d52687529f3efcf0a (version v1.0.1 onwards) contains loop with unreachable exit condition ('infinite loop') vulnerability in ISOBMFF reader filter, isoffin_read.c. Function isoffin_process() can result in DoS by infinite loop. To exploit, the victim must open a specially crafted mp4 file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40592"}
{"idx": 196698, "project": "tensorflow", "commit_id": "67bfd9feeecfb3c61d80f0e46d89c170fbee682b", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/67bfd9feeecfb3c61d80f0e46d89c170fbee682b", "commit_message": "Make SparseFillEmptyRows validate that the length of `values` must be equal to the number of index tuples.\n\nPiperOrigin-RevId: 399969549\nChange-Id: I3c2f2ca1c1d2cc88bb5951c6958b38c16e9436c8", "target": 1, "func": "void SparseFillEmptyRowsOpImpl(OpKernelContext* context,\n                               AsyncOpKernel::DoneCallback done = nullptr) {\n  // Note that setting this empty lambda as the default parameter value directly\n  // can cause strange compiler/linker errors, so we do it like this instead.\n  if (!done) {\n    done = [] {};\n  }\n\n  const int kIndicesInput = 0;\n  const int kValuesInput = 1;\n  const int kDenseShapeInput = 2;\n  const int kDefaultValueInput = 3;\n\n  const Tensor& indices_t = context->input(kIndicesInput);\n  const Tensor& values_t = context->input(kValuesInput);\n  const Tensor& dense_shape_t = context->input(kDenseShapeInput);\n  const Tensor& default_value_t = context->input(kDefaultValueInput);\n\n  OP_REQUIRES_ASYNC(\n      context, TensorShapeUtils::IsVector(dense_shape_t.shape()),\n      errors::InvalidArgument(\"dense_shape must be a vector, saw: \",\n                              dense_shape_t.shape().DebugString()),\n      done);\n  OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsMatrix(indices_t.shape()),\n                    errors::InvalidArgument(\"indices must be a matrix, saw: \",\n                                            indices_t.shape().DebugString()),\n                    done);\n  OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsVector(values_t.shape()),\n                    errors::InvalidArgument(\"values must be a vector, saw: \",\n                                            values_t.shape().DebugString()),\n                    done);\n  OP_REQUIRES_ASYNC(\n      context, TensorShapeUtils::IsScalar(default_value_t.shape()),\n      errors::InvalidArgument(\"default_value must be a scalar, saw: \",\n                              default_value_t.shape().DebugString()),\n      done);\n  // TODO(ebrevdo): add shape checks between values, indices,\n  // Also add check that dense rank > 0.\n  OP_REQUIRES_ASYNC(context, dense_shape_t.NumElements() != 0,\n                    errors::InvalidArgument(\"Dense shape cannot be empty.\"),\n                    done);\n\n  using FunctorType = functor::SparseFillEmptyRows;\n  OP_REQUIRES_OK_ASYNC(context,\n                       FunctorType()(context, default_value_t, indices_t,\n                                     values_t, dense_shape_t, done),\n                       done);\n}", "func_hash": 163337242627579814226114932816582213259, "file_name": "sparse_fill_empty_rows_op.cc", "file_hash": 115550743256362209093747086328381163455, "cwe": ["CWE-125"], "cve": "CVE-2021-41224", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions the implementation of `SparseFillEmptyRows` can be made to trigger a heap OOB access. This occurs whenever the size of `indices` does not match the size of `values`. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41224"}
{"idx": 242899, "project": "tensorflow", "commit_id": "67bfd9feeecfb3c61d80f0e46d89c170fbee682b", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/67bfd9feeecfb3c61d80f0e46d89c170fbee682b", "commit_message": "Make SparseFillEmptyRows validate that the length of `values` must be equal to the number of index tuples.\n\nPiperOrigin-RevId: 399969549\nChange-Id: I3c2f2ca1c1d2cc88bb5951c6958b38c16e9436c8", "target": 0, "func": "void SparseFillEmptyRowsOpImpl(OpKernelContext* context,\n                               AsyncOpKernel::DoneCallback done = nullptr) {\n  // Note that setting this empty lambda as the default parameter value directly\n  // can cause strange compiler/linker errors, so we do it like this instead.\n  if (!done) {\n    done = [] {};\n  }\n\n  const int kIndicesInput = 0;\n  const int kValuesInput = 1;\n  const int kDenseShapeInput = 2;\n  const int kDefaultValueInput = 3;\n\n  const Tensor& indices_t = context->input(kIndicesInput);\n  const Tensor& values_t = context->input(kValuesInput);\n  const Tensor& dense_shape_t = context->input(kDenseShapeInput);\n  const Tensor& default_value_t = context->input(kDefaultValueInput);\n\n  OP_REQUIRES_ASYNC(\n      context, TensorShapeUtils::IsVector(dense_shape_t.shape()),\n      errors::InvalidArgument(\"dense_shape must be a vector, saw: \",\n                              dense_shape_t.shape().DebugString()),\n      done);\n  OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsMatrix(indices_t.shape()),\n                    errors::InvalidArgument(\"indices must be a matrix, saw: \",\n                                            indices_t.shape().DebugString()),\n                    done);\n  OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsVector(values_t.shape()),\n                    errors::InvalidArgument(\"values must be a vector, saw: \",\n                                            values_t.shape().DebugString()),\n                    done);\n  OP_REQUIRES_ASYNC(\n      context, indices_t.dim_size(0) == values_t.dim_size(0),\n      errors::InvalidArgument(\"The length of `values` (\", values_t.dim_size(0),\n                              \") must match the first dimension of `indices` (\",\n                              indices_t.dim_size(0), \").\"),\n      done);\n  OP_REQUIRES_ASYNC(\n      context, TensorShapeUtils::IsScalar(default_value_t.shape()),\n      errors::InvalidArgument(\"default_value must be a scalar, saw: \",\n                              default_value_t.shape().DebugString()),\n      done);\n  // TODO(ebrevdo): add shape checks between values, indices,\n  // Also add check that dense rank > 0.\n  OP_REQUIRES_ASYNC(context, dense_shape_t.NumElements() != 0,\n                    errors::InvalidArgument(\"Dense shape cannot be empty.\"),\n                    done);\n\n  using FunctorType = functor::SparseFillEmptyRows;\n  OP_REQUIRES_OK_ASYNC(context,\n                       FunctorType()(context, default_value_t, indices_t,\n                                     values_t, dense_shape_t, done),\n                       done);\n}", "func_hash": 284557281436675521731008929242198087362, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2021-41224", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions the implementation of `SparseFillEmptyRows` can be made to trigger a heap OOB access. This occurs whenever the size of `indices` does not match the size of `values`. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41224"}
{"idx": 196705, "project": "tensorflow", "commit_id": "11ced8467eccad9c7cb94867708be8fa5c66c730", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/11ced8467eccad9c7cb94867708be8fa5c66c730", "commit_message": "Fix UB in SparseTensorDenseAdd\n\nAdded more input validation to avoid nullptr dereferencing and array index\nout of bounds issues.\n\nPiperOrigin-RevId: 446192704", "target": 1, "func": "Status ValidateInputs(const Tensor *a_indices, const Tensor *a_values,\n                      const Tensor *a_shape, const Tensor *b) {\n  if (!TensorShapeUtils::IsMatrix(a_indices->shape())) {\n    return errors::InvalidArgument(\n        \"Input a_indices should be a matrix but received shape: \",\n        a_indices->shape().DebugString());\n  }\n  if (!TensorShapeUtils::IsVector(a_values->shape()) ||\n      !TensorShapeUtils::IsVector(a_shape->shape())) {\n    return errors::InvalidArgument(\n        \"Inputs a_values and a_shape should be vectors \"\n        \"but received shapes: \",\n        a_values->shape().DebugString(), \" and \",\n        a_shape->shape().DebugString());\n  }\n  if (a_shape->NumElements() != b->dims()) {\n    return errors::InvalidArgument(\n        \"Two operands have different ranks; received: \", a_shape->NumElements(),\n        \" and \", b->dims());\n  }\n  const auto a_shape_flat = a_shape->flat();\n  for (int i = 0; i < b->dims(); ++i) {\n    if (a_shape_flat(i) != b->dim_size(i)) {\n      return errors::InvalidArgument(\n          \"Dimension \", i,\n          \" does not equal (no broadcasting is supported): sparse side \",\n          a_shape_flat(i), \" vs dense side \", b->dim_size(i));\n    }\n  }\n  return Status::OK();\n}", "func_hash": 308425823880781073775676879611190785715, "file_name": "sparse_tensor_dense_add_op.cc", "file_hash": 91198918327439956509177796541242214319, "cwe": ["CWE-20"], "cve": "CVE-2022-29206", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.SparseTensorDenseAdd` does not fully validate the input arguments. In this case, a reference gets bound to a `nullptr` during kernel execution. This is undefined behavior. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29206"}
{"idx": 242926, "project": "tensorflow", "commit_id": "11ced8467eccad9c7cb94867708be8fa5c66c730", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/11ced8467eccad9c7cb94867708be8fa5c66c730", "commit_message": "Fix UB in SparseTensorDenseAdd\n\nAdded more input validation to avoid nullptr dereferencing and array index\nout of bounds issues.\n\nPiperOrigin-RevId: 446192704", "target": 0, "func": "Status ValidateInputs(const Tensor *a_indices, const Tensor *a_values,\n                      const Tensor *a_shape, const Tensor *b) {\n  if (!TensorShapeUtils::IsMatrix(a_indices->shape())) {\n    return errors::InvalidArgument(\n        \"Input a_indices should be a matrix but received shape: \",\n        a_indices->shape().DebugString());\n  }\n  if (!TensorShapeUtils::IsVector(a_values->shape()) ||\n      !TensorShapeUtils::IsVector(a_shape->shape())) {\n    return errors::InvalidArgument(\n        \"Inputs a_values and a_shape should be vectors \"\n        \"but received shapes: \",\n        a_values->shape().DebugString(), \" and \",\n        a_shape->shape().DebugString());\n  }\n  int64_t nnz = a_indices->dim_size(0);\n  int64_t ndims = a_indices->dim_size(1);\n  if (a_values->dim_size(0) != nnz) {\n    return errors::InvalidArgument(\"Dimensions \", nnz, \" and \",\n                                   a_values->dim_size(0),\n                                   \" are not compatible\");\n  }\n  if (a_shape->dim_size(0) != ndims) {\n    return errors::InvalidArgument(\"Dimensions \", ndims, \" and \",\n                                   a_shape->dim_size(0), \" are not compatible\");\n  }\n  if (a_shape->NumElements() != b->dims()) {\n    return errors::InvalidArgument(\n        \"Two operands have different ranks; received: \", a_shape->NumElements(),\n        \" and \", b->dims());\n  }\n  const auto a_shape_flat = a_shape->flat();\n  for (int i = 0; i < b->dims(); ++i) {\n    if (a_shape_flat(i) != b->dim_size(i)) {\n      return errors::InvalidArgument(\n          \"Dimension \", i,\n          \" does not equal (no broadcasting is supported): sparse side \",\n          a_shape_flat(i), \" vs dense side \", b->dim_size(i));\n    }\n  }\n\n  // Check for invalid indices.\n  const auto a_indices_mat = a_indices->flat_inner_dims();\n\n  for (int64_t zidx = 0; zidx < nnz; ++zidx) {\n    for (int64_t didx = 0; didx < ndims; ++didx) {\n      const Index idx = a_indices_mat(zidx, didx);\n      if (idx < 0 || idx >= a_shape_flat(didx)) {\n        return errors::InvalidArgument(\n            \"Sparse tensor has an invalid index on dimension \", didx,\n            \": \"\n            \"a_indices(\",\n            zidx, \",\", didx, \") = \", idx,\n            \", dense tensor shape: \", a_shape_flat);\n      }\n    }\n  }\n\n  return Status::OK();\n}", "func_hash": 310798775905628265586866839597720584207, "file_name": "sparse_tensor_dense_add_op.cc", "file_hash": 106434963445193170812694157920438487376, "cwe": ["CWE-20"], "cve": "CVE-2022-29206", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.SparseTensorDenseAdd` does not fully validate the input arguments. In this case, a reference gets bound to a `nullptr` during kernel execution. This is undefined behavior. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29206"}
{"idx": 196790, "project": "tensorflow", "commit_id": "a4e138660270e7599793fa438cd7b2fc2ce215a6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a4e138660270e7599793fa438cd7b2fc2ce215a6", "commit_message": "Add remaining validation to `sdca_internal.cc`\n\nPiperOrigin-RevId: 387738010\nChange-Id: I28eedcfd87a53aaf34deb075acea1f8c95470808", "target": 1, "func": "Status Examples::Initialize(OpKernelContext* const context,\n                            const ModelWeights& weights,\n                            const int num_sparse_features,\n                            const int num_sparse_features_with_values,\n                            const int num_dense_features) {\n  num_features_ = num_sparse_features + num_dense_features;\n\n  OpInputList sparse_example_indices_inputs;\n  TF_RETURN_IF_ERROR(context->input_list(\"sparse_example_indices\",\n                                         &sparse_example_indices_inputs));\n  if (sparse_example_indices_inputs.size() != num_sparse_features)\n    return errors::InvalidArgument(\n        \"Expected \", num_sparse_features,\n        \" tensors in sparse_example_indices but got \",\n        sparse_example_indices_inputs.size());\n  OpInputList sparse_feature_indices_inputs;\n  TF_RETURN_IF_ERROR(context->input_list(\"sparse_feature_indices\",\n                                         &sparse_feature_indices_inputs));\n  if (sparse_feature_indices_inputs.size() != num_sparse_features)\n    return errors::InvalidArgument(\n        \"Expected \", num_sparse_features,\n        \" tensors in sparse_feature_indices but got \",\n        sparse_feature_indices_inputs.size());\n  OpInputList sparse_feature_values_inputs;\n  if (num_sparse_features_with_values > 0) {\n    TF_RETURN_IF_ERROR(context->input_list(\"sparse_feature_values\",\n                                           &sparse_feature_values_inputs));\n    if (sparse_feature_values_inputs.size() != num_sparse_features_with_values)\n      return errors::InvalidArgument(\n          \"Expected \", num_sparse_features_with_values,\n          \" tensors in sparse_feature_values but got \",\n          sparse_feature_values_inputs.size());\n  }\n\n  const Tensor* example_weights_t;\n  TF_RETURN_IF_ERROR(context->input(\"example_weights\", &example_weights_t));\n  auto example_weights = example_weights_t->flat();\n\n  if (example_weights.size() >= std::numeric_limits::max()) {\n    return errors::InvalidArgument(strings::Printf(\n        \"Too many examples in a mini-batch: %zu > %d\", example_weights.size(),\n        std::numeric_limits::max()));\n  }\n\n  // The static_cast here is safe since num_examples can be at max an int.\n  const int num_examples = static_cast(example_weights.size());\n  const Tensor* example_labels_t;\n  TF_RETURN_IF_ERROR(context->input(\"example_labels\", &example_labels_t));\n  auto example_labels = example_labels_t->flat();\n\n  OpInputList dense_features_inputs;\n  TF_RETURN_IF_ERROR(\n      context->input_list(\"dense_features\", &dense_features_inputs));\n\n  examples_.clear();\n  examples_.resize(num_examples);\n  probabilities_.resize(num_examples);\n  sampled_index_.resize(num_examples);\n  sampled_count_.resize(num_examples);\n  for (int example_id = 0; example_id < num_examples; ++example_id) {\n    Example* const example = &examples_[example_id];\n    example->sparse_features_.resize(num_sparse_features);\n    example->dense_vectors_.resize(num_dense_features);\n    example->example_weight_ = example_weights(example_id);\n    example->example_label_ = example_labels(example_id);\n  }\n  const DeviceBase::CpuWorkerThreads& worker_threads =\n      *context->device()->tensorflow_cpu_worker_threads();\n  TF_RETURN_IF_ERROR(CreateSparseFeatureRepresentation(\n      worker_threads, num_examples, num_sparse_features, weights,\n      sparse_example_indices_inputs, sparse_feature_indices_inputs,\n      sparse_feature_values_inputs, &examples_));\n  TF_RETURN_IF_ERROR(CreateDenseFeatureRepresentation(\n      worker_threads, num_examples, num_dense_features, weights,\n      dense_features_inputs, &examples_));\n  TF_RETURN_IF_ERROR(ComputeSquaredNormPerExample(\n      worker_threads, num_examples, num_sparse_features, num_dense_features,\n      &examples_));\n  return Status::OK();\n}", "func_hash": 183156860369052380668778554351089179754, "file_name": "sdca_internal.cc", "file_hash": 189786435377355636606855329054946360663, "cwe": ["CWE-703"], "cve": "CVE-2021-37672", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can read from outside of bounds of heap allocated data by sending specially crafted illegal arguments to `tf.raw_ops.SdcaOptimizerV2`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/sdca_internal.cc#L320-L353) does not check that the length of `example_labels` is the same as the number of examples. We have patched the issue in GitHub commit a4e138660270e7599793fa438cd7b2fc2ce215a6. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37672"}
{"idx": 245140, "project": "tensorflow", "commit_id": "a4e138660270e7599793fa438cd7b2fc2ce215a6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a4e138660270e7599793fa438cd7b2fc2ce215a6", "commit_message": "Add remaining validation to `sdca_internal.cc`\n\nPiperOrigin-RevId: 387738010\nChange-Id: I28eedcfd87a53aaf34deb075acea1f8c95470808", "target": 0, "func": "Status Examples::Initialize(OpKernelContext* const context,\n                            const ModelWeights& weights,\n                            const int num_sparse_features,\n                            const int num_sparse_features_with_values,\n                            const int num_dense_features) {\n  num_features_ = num_sparse_features + num_dense_features;\n\n  OpInputList sparse_example_indices_inputs;\n  TF_RETURN_IF_ERROR(context->input_list(\"sparse_example_indices\",\n                                         &sparse_example_indices_inputs));\n  if (sparse_example_indices_inputs.size() != num_sparse_features)\n    return errors::InvalidArgument(\n        \"Expected \", num_sparse_features,\n        \" tensors in sparse_example_indices but got \",\n        sparse_example_indices_inputs.size());\n  OpInputList sparse_feature_indices_inputs;\n  TF_RETURN_IF_ERROR(context->input_list(\"sparse_feature_indices\",\n                                         &sparse_feature_indices_inputs));\n  if (sparse_feature_indices_inputs.size() != num_sparse_features)\n    return errors::InvalidArgument(\n        \"Expected \", num_sparse_features,\n        \" tensors in sparse_feature_indices but got \",\n        sparse_feature_indices_inputs.size());\n  OpInputList sparse_feature_values_inputs;\n  if (num_sparse_features_with_values > 0) {\n    TF_RETURN_IF_ERROR(context->input_list(\"sparse_feature_values\",\n                                           &sparse_feature_values_inputs));\n    if (sparse_feature_values_inputs.size() != num_sparse_features_with_values)\n      return errors::InvalidArgument(\n          \"Expected \", num_sparse_features_with_values,\n          \" tensors in sparse_feature_values but got \",\n          sparse_feature_values_inputs.size());\n  }\n\n  const Tensor* example_weights_t;\n  TF_RETURN_IF_ERROR(context->input(\"example_weights\", &example_weights_t));\n  auto example_weights = example_weights_t->flat();\n\n  if (example_weights.size() >= std::numeric_limits::max()) {\n    return errors::InvalidArgument(strings::Printf(\n        \"Too many examples in a mini-batch: %zu > %d\", example_weights.size(),\n        std::numeric_limits::max()));\n  }\n\n  // The static_cast here is safe since num_examples can be at max an int.\n  const int num_examples = static_cast(example_weights.size());\n  const Tensor* example_labels_t;\n  TF_RETURN_IF_ERROR(context->input(\"example_labels\", &example_labels_t));\n  auto example_labels = example_labels_t->flat();\n  if (example_labels.size() != num_examples) {\n    return errors::InvalidArgument(\"Expected \", num_examples,\n                                   \" example labels but got \",\n                                   example_labels.size());\n  }\n\n  OpInputList dense_features_inputs;\n  TF_RETURN_IF_ERROR(\n      context->input_list(\"dense_features\", &dense_features_inputs));\n\n  examples_.clear();\n  examples_.resize(num_examples);\n  probabilities_.resize(num_examples);\n  sampled_index_.resize(num_examples);\n  sampled_count_.resize(num_examples);\n  for (int example_id = 0; example_id < num_examples; ++example_id) {\n    Example* const example = &examples_[example_id];\n    example->sparse_features_.resize(num_sparse_features);\n    example->dense_vectors_.resize(num_dense_features);\n    example->example_weight_ = example_weights(example_id);\n    example->example_label_ = example_labels(example_id);\n  }\n  const DeviceBase::CpuWorkerThreads& worker_threads =\n      *context->device()->tensorflow_cpu_worker_threads();\n  TF_RETURN_IF_ERROR(CreateSparseFeatureRepresentation(\n      worker_threads, num_examples, num_sparse_features, weights,\n      sparse_example_indices_inputs, sparse_feature_indices_inputs,\n      sparse_feature_values_inputs, &examples_));\n  TF_RETURN_IF_ERROR(CreateDenseFeatureRepresentation(\n      worker_threads, num_examples, num_dense_features, weights,\n      dense_features_inputs, &examples_));\n  TF_RETURN_IF_ERROR(ComputeSquaredNormPerExample(\n      worker_threads, num_examples, num_sparse_features, num_dense_features,\n      &examples_));\n  return Status::OK();\n}", "func_hash": 260741602322702772753001144224568198903, "file_name": "sdca_internal.cc", "file_hash": 181960497028529937456505885431082793104, "cwe": ["CWE-703"], "cve": "CVE-2021-37672", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can read from outside of bounds of heap allocated data by sending specially crafted illegal arguments to `tf.raw_ops.SdcaOptimizerV2`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/sdca_internal.cc#L320-L353) does not check that the length of `example_labels` is the same as the number of examples. We have patched the issue in GitHub commit a4e138660270e7599793fa438cd7b2fc2ce215a6. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37672"}
{"idx": 196801, "project": "gpac", "commit_id": "f5a038e6893019ee471b6a57490cf7a495673816", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/f5a038e6893019ee471b6a57490cf7a495673816", "commit_message": "fixed #1885", "target": 1, "func": "GF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth)\n{\n\tu32 i, sceneT, odT, descIndex, size, size64;\n\tGF_InitialObjectDescriptor *iod;\n\tGF_SLConfig slc;\n\tGF_ISOSample *samp;\n\tBool remove_ocr;\n\tu8 *buffer;\n\tchar buf64[5000], sdpLine[5100];\n\n\n\tgf_isom_sdp_clean(file);\n\n\tif (bandwidth) {\n\t\tsprintf(buf64, \"b=AS:%d\", bandwidth);\n\t\tgf_isom_sdp_add_line(file, buf64);\n\t}\n    //xtended attribute for copyright\n    if (gf_sys_is_test_mode()) {\n        sprintf(buf64, \"a=x-copyright: %s\", \"MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)\");\n    } else {\n        sprintf(buf64, \"a=x-copyright: MP4/3GP File hinted with GPAC %s - %s\", gf_gpac_version(), gf_gpac_copyright() );\n    }\n\tgf_isom_sdp_add_line(file, buf64);\n\n\tif (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK;\n\n\todT = sceneT = 0;\n\tfor (i=0; iESDescriptors)) {\n\t\t\tesd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0);\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t\tgf_list_rem(iod->ESDescriptors, 0);\n\t\t}\n\n\n\t\t/*get OD esd, and embbed stream data if possible*/\n\t\tif (odT) {\n\t\t\tesd = gf_isom_get_esd(file, odT, 1);\n\t\t\tif (gf_isom_get_sample_count(file, odT)==1) {\n\t\t\t\tsamp = gf_isom_get_sample(file, odT, 1, &descIndex);\n\t\t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) {\n\t\t\t\t\tInitSL_NULL(&slc);\n\t\t\t\t\tslc.predefined = 0;\n\t\t\t\t\tslc.hasRandomAccessUnitsOnlyFlag = 1;\n\t\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT);\n\t\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t\t//set the SL for future extraction\n\t\t\t\t\tgf_isom_set_extraction_slc(file, odT, 1, &slc);\n\n\t\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\t\tbuf64[size64] = 0;\n\t\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-od-au;base64,%s\", buf64);\n\n\t\t\t\t\tif (esd->decoderConfig) {\n\t\t\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\t\t}\n\t\t\t\t\tsize64 = (u32) strlen(sdpLine)+1;\n\t\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * size64);\n\t\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t\t} else {\n\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_RTP, (\"[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\t\tis_ok = 0;\n\t\t\t\t}\n\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t}\n\t\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\t\t//OK, add this to our IOD\n\t\t\tgf_list_add(iod->ESDescriptors, esd);\n\t\t}\n\n\t\tesd = gf_isom_get_esd(file, sceneT, 1);\n\t\tif (gf_isom_get_sample_count(file, sceneT)==1) {\n\t\t\tsamp = gf_isom_get_sample(file, sceneT, 1, &descIndex);\n\t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) {\n\n\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT);\n\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t//set the SL for future extraction\n\t\t\t\tgf_isom_set_extraction_slc(file, sceneT, 1, &slc);\n\t\t\t\t//encode in Base64 the sample\n\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\tbuf64[size64] = 0;\n\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-bifs-au;base64,%s\", buf64);\n\n\t\t\t\tif (esd->decoderConfig) {\n\t\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\t}\n\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1));\n\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\tis_ok = 0;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\tgf_list_add(iod->ESDescriptors, esd);\n\n\t\tif (is_ok) {\n\t\t\tu32 has_a, has_v, has_i_a, has_i_v;\n\t\t\thas_a = has_v = has_i_a = has_i_v = 0;\n\t\t\tfor (i=0; idecoderConfig) {\n\t\t\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++;\n\t\t\t\t\t\telse has_v++;\n\t\t\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n\t\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++;\n\t\t\t\t\t\telse has_a++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)esd);\n\t\t\t}\n\t\t\t/*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/\n\t\t\tif (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) {\n\t\t\t\tsprintf(sdpLine, \"a=isma-compliance:1,1.0,1\");\n\t\t\t\tgf_isom_sdp_add_line(file, sdpLine);\n\t\t\t}\n\t\t}\n\t}\n\n\t//encode the IOD\n\tbuffer = NULL;\n\tsize = 0;\n\tgf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size);\n\tgf_odf_desc_del((GF_Descriptor *)iod);\n\n\t//encode in Base64 the iod\n\tsize64 = gf_base64_encode(buffer, size, buf64, 2000);\n\tbuf64[size64] = 0;\n\tgf_free(buffer);\n\n\tsprintf(sdpLine, \"a=mpeg4-iod:\\\"data:application/mpeg4-iod;base64,%s\\\"\", buf64);\n\tgf_isom_sdp_add_line(file, sdpLine);\n\n\treturn GF_OK;\n}", "func_hash": 123828913884454942556959015680908121097, "file_name": "isom_hinter.c", "file_hash": 94306079889139284150664165649647698827, "cwe": ["CWE-703"], "cve": "CVE-2021-40567", "cve_desc": "Segmentation fault vulnerability exists in Gpac through 1.0.1 via the gf_odf_size_descriptor function in desc_private.c when using mp4box, which causes a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40567"}
{"idx": 245434, "project": "gpac", "commit_id": "f5a038e6893019ee471b6a57490cf7a495673816", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/f5a038e6893019ee471b6a57490cf7a495673816", "commit_message": "fixed #1885", "target": 0, "func": "GF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth)\n{\n\tu32 i, sceneT, odT, descIndex, size, size64;\n\tGF_InitialObjectDescriptor *iod;\n\tGF_SLConfig slc;\n\tGF_ISOSample *samp;\n\tBool remove_ocr;\n\tu8 *buffer;\n\tchar buf64[5000], sdpLine[5100];\n\n\n\tgf_isom_sdp_clean(file);\n\n\tif (bandwidth) {\n\t\tsprintf(buf64, \"b=AS:%d\", bandwidth);\n\t\tgf_isom_sdp_add_line(file, buf64);\n\t}\n    //xtended attribute for copyright\n    if (gf_sys_is_test_mode()) {\n        sprintf(buf64, \"a=x-copyright: %s\", \"MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)\");\n    } else {\n        sprintf(buf64, \"a=x-copyright: MP4/3GP File hinted with GPAC %s - %s\", gf_gpac_version(), gf_gpac_copyright() );\n    }\n\tgf_isom_sdp_add_line(file, buf64);\n\n\tif (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK;\n\n\todT = sceneT = 0;\n\tfor (i=0; iESDescriptors)) {\n\t\t\tesd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0);\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t\tgf_list_rem(iod->ESDescriptors, 0);\n\t\t}\n\n\n\t\t/*get OD esd, and embbed stream data if possible*/\n\t\tif (odT) {\n\t\t\tesd = gf_isom_get_esd(file, odT, 1);\n\t\t\tif (gf_isom_get_sample_count(file, odT)==1) {\n\t\t\t\tsamp = gf_isom_get_sample(file, odT, 1, &descIndex);\n\t\t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) {\n\t\t\t\t\tInitSL_NULL(&slc);\n\t\t\t\t\tslc.predefined = 0;\n\t\t\t\t\tslc.hasRandomAccessUnitsOnlyFlag = 1;\n\t\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT);\n\t\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t\t//set the SL for future extraction\n\t\t\t\t\tgf_isom_set_extraction_slc(file, odT, 1, &slc);\n\n\t\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\t\tbuf64[size64] = 0;\n\t\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-od-au;base64,%s\", buf64);\n\n\t\t\t\t\tif (esd->decoderConfig) {\n\t\t\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\t\t}\n\t\t\t\t\tsize64 = (u32) strlen(sdpLine)+1;\n\t\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * size64);\n\t\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t\t} else {\n\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_RTP, (\"[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\t\tis_ok = 0;\n\t\t\t\t}\n\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t}\n\t\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\t\t//OK, add this to our IOD\n\t\t\tgf_list_add(iod->ESDescriptors, esd);\n\t\t}\n\n\t\tesd = gf_isom_get_esd(file, sceneT, 1);\n\t\tif (gf_isom_get_sample_count(file, sceneT)==1) {\n\t\t\tsamp = gf_isom_get_sample(file, sceneT, 1, &descIndex);\n\t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) {\n\t\t\t\tInitSL_NULL(&slc);\n\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT);\n\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t//set the SL for future extraction\n\t\t\t\tgf_isom_set_extraction_slc(file, sceneT, 1, &slc);\n\t\t\t\t//encode in Base64 the sample\n\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\tbuf64[size64] = 0;\n\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-bifs-au;base64,%s\", buf64);\n\n\t\t\t\tif (esd->decoderConfig) {\n\t\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\t}\n\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1));\n\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\tis_ok = 0;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\tgf_list_add(iod->ESDescriptors, esd);\n\n\t\tif (is_ok) {\n\t\t\tu32 has_a, has_v, has_i_a, has_i_v;\n\t\t\thas_a = has_v = has_i_a = has_i_v = 0;\n\t\t\tfor (i=0; idecoderConfig) {\n\t\t\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++;\n\t\t\t\t\t\telse has_v++;\n\t\t\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n\t\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++;\n\t\t\t\t\t\telse has_a++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)esd);\n\t\t\t}\n\t\t\t/*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/\n\t\t\tif (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) {\n\t\t\t\tsprintf(sdpLine, \"a=isma-compliance:1,1.0,1\");\n\t\t\t\tgf_isom_sdp_add_line(file, sdpLine);\n\t\t\t}\n\t\t}\n\t}\n\n\t//encode the IOD\n\tbuffer = NULL;\n\tsize = 0;\n\tgf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size);\n\tgf_odf_desc_del((GF_Descriptor *)iod);\n\n\t//encode in Base64 the iod\n\tsize64 = gf_base64_encode(buffer, size, buf64, 2000);\n\tbuf64[size64] = 0;\n\tgf_free(buffer);\n\n\tsprintf(sdpLine, \"a=mpeg4-iod:\\\"data:application/mpeg4-iod;base64,%s\\\"\", buf64);\n\tgf_isom_sdp_add_line(file, sdpLine);\n\n\treturn GF_OK;\n}", "func_hash": 303417005627420629887148853980716072397, "file_name": "isom_hinter.c", "file_hash": 42590680344413091509080711519758588742, "cwe": ["CWE-703"], "cve": "CVE-2021-40567", "cve_desc": "Segmentation fault vulnerability exists in Gpac through 1.0.1 via the gf_odf_size_descriptor function in desc_private.c when using mp4box, which causes a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40567"}
{"idx": 196829, "project": "tensorflow", "commit_id": "9a133d73ae4b4664d22bd1aa6d654fec13c52ee1", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/9a133d73ae4b4664d22bd1aa6d654fec13c52ee1", "commit_message": "Prevent segfault in `GetSessionHandle{,V2}`.\n\nIn eager mode, session state is null.\n\nPiperOrigin-RevId: 332548597\nChange-Id: If094812c2e094044220b9ba28f7d7601be042f38", "target": 1, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor& val = ctx->input(0);\n    int64 id = ctx->session_state()->GetNewId();\n    TensorStore::TensorAndKey tk{val, id, requested_device()};\n    OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(name(), tk));\n\n    Tensor* handle = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));\n    if (ctx->expected_output_dtype(0) == DT_RESOURCE) {\n      ResourceHandle resource_handle = MakeResourceHandle(\n          ctx, SessionState::kTensorHandleResourceTypeName,\n          tk.GetHandle(name()));\n      resource_handle.set_maybe_type_name(\n          SessionState::kTensorHandleResourceTypeName);\n      handle->scalar()() = resource_handle;\n    } else {\n      // Legacy behavior in V1.\n      handle->flat().setConstant(tk.GetHandle(name()));\n    }\n  }", "func_hash": 265136132776865637405047291994320353020, "file_name": "session_ops.cc", "file_hash": 301236181949638816884177571060128580318, "cwe": ["CWE-476"], "cve": "CVE-2020-15204", "cve_desc": "In eager mode, TensorFlow before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1 does not set the session state. Hence, calling `tf.raw_ops.GetSessionHandle` or `tf.raw_ops.GetSessionHandleV2` results in a null pointer dereference In linked snippet, in eager mode, `ctx->session_state()` returns `nullptr`. Since code immediately dereferences this, we get a segmentation fault. The issue is patched in commit 9a133d73ae4b4664d22bd1aa6d654fec13c52ee1, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15204"}
{"idx": 245921, "project": "tensorflow", "commit_id": "9a133d73ae4b4664d22bd1aa6d654fec13c52ee1", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/9a133d73ae4b4664d22bd1aa6d654fec13c52ee1", "commit_message": "Prevent segfault in `GetSessionHandle{,V2}`.\n\nIn eager mode, session state is null.\n\nPiperOrigin-RevId: 332548597\nChange-Id: If094812c2e094044220b9ba28f7d7601be042f38", "target": 0, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor& val = ctx->input(0);\n    auto session_state = ctx->session_state();\n    OP_REQUIRES(ctx, session_state != nullptr,\n                errors::FailedPrecondition(\n                    \"GetSessionHandle called on null session state\"));\n    int64 id = session_state->GetNewId();\n    TensorStore::TensorAndKey tk{val, id, requested_device()};\n    OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(name(), tk));\n\n    Tensor* handle = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));\n    if (ctx->expected_output_dtype(0) == DT_RESOURCE) {\n      ResourceHandle resource_handle = MakeResourceHandle(\n          ctx, SessionState::kTensorHandleResourceTypeName,\n          tk.GetHandle(name()));\n      resource_handle.set_maybe_type_name(\n          SessionState::kTensorHandleResourceTypeName);\n      handle->scalar()() = resource_handle;\n    } else {\n      // Legacy behavior in V1.\n      handle->flat().setConstant(tk.GetHandle(name()));\n    }\n  }", "func_hash": 297244264653800469833284157710994110214, "file_name": "session_ops.cc", "file_hash": 303341858564051211151362713951438565129, "cwe": ["CWE-476"], "cve": "CVE-2020-15204", "cve_desc": "In eager mode, TensorFlow before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1 does not set the session state. Hence, calling `tf.raw_ops.GetSessionHandle` or `tf.raw_ops.GetSessionHandleV2` results in a null pointer dereference In linked snippet, in eager mode, `ctx->session_state()` returns `nullptr`. Since code immediately dereferences this, we get a segmentation fault. The issue is patched in commit 9a133d73ae4b4664d22bd1aa6d654fec13c52ee1, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15204"}
{"idx": 196834, "project": "tensorflow", "commit_id": "701cfaca222a82afbeeb17496bd718baa65a67d2", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/701cfaca222a82afbeeb17496bd718baa65a67d2", "commit_message": "Fix heap out of bounds error in tf.raw_ops.SparseCountSparseOutput shape inference when it is called with invalid inputs, and add a test for it.\n\nPiperOrigin-RevId: 405766415\nChange-Id: I77d244ef35f351ef7b6f821efd959cac2c66db24", "target": 1, "func": "Status SparseCountSparseOutputShapeFn(InferenceContext *c) {\n  auto rank = c->Dim(c->input(0), 1);\n  auto nvals = c->UnknownDim();\n  c->set_output(0, c->Matrix(nvals, rank));  // out.indices\n  c->set_output(1, c->Vector(nvals));        // out.values\n  c->set_output(2, c->Vector(rank));         // out.dense_shape\n  return Status::OK();\n}", "func_hash": 288638774639466658606082764141579193752, "file_name": "count_ops.cc", "file_hash": 285251304555239344227100279342018211632, "cwe": ["CWE-125"], "cve": "CVE-2021-41210", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions the shape inference functions for `SparseCountSparseOutput` can trigger a read outside of bounds of heap allocated array. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41210"}
{"idx": 246207, "project": "tensorflow", "commit_id": "701cfaca222a82afbeeb17496bd718baa65a67d2", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/701cfaca222a82afbeeb17496bd718baa65a67d2", "commit_message": "Fix heap out of bounds error in tf.raw_ops.SparseCountSparseOutput shape inference when it is called with invalid inputs, and add a test for it.\n\nPiperOrigin-RevId: 405766415\nChange-Id: I77d244ef35f351ef7b6f821efd959cac2c66db24", "target": 0, "func": "Status SparseCountSparseOutputShapeFn(InferenceContext *c) {\n  ShapeHandle unused;\n  TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &unused));\n  auto rank = c->Dim(c->input(0), 1);\n  auto nvals = c->UnknownDim();\n  c->set_output(0, c->Matrix(nvals, rank));  // out.indices\n  c->set_output(1, c->Vector(nvals));        // out.values\n  c->set_output(2, c->Vector(rank));         // out.dense_shape\n  return Status::OK();\n}", "func_hash": 271491902662668268509988539707707762247, "file_name": "count_ops.cc", "file_hash": 129709593460413124359725410007396484757, "cwe": ["CWE-125"], "cve": "CVE-2021-41210", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions the shape inference functions for `SparseCountSparseOutput` can trigger a read outside of bounds of heap allocated array. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41210"}
{"idx": 196841, "project": "furnace", "commit_id": "0eb02422d5161767e9983bdaa5c429762d3477ce", "project_url": "https://github.com/tildearrow/furnace", "commit_url": "https://github.com/tildearrow/furnace/commit/0eb02422d5161767e9983bdaa5c429762d3477ce", "commit_message": "fix possible pattern crash\n\nissue #325", "target": 1, "func": "inline void FurnaceGUI::patternRow(int i, bool isPlaying, float lineHeight, int chans, int ord, const DivPattern** patCache) {\n  static char id[32];\n  bool selectedRow=(i>=sel1.y && i<=sel2.y);\n  ImGui::TableNextRow(0,lineHeight);\n  ImGui::TableNextColumn();\n  float cursorPosY=ImGui::GetCursorPos().y-ImGui::GetScrollY();\n  // check if the row is visible\n  if (cursorPosY<-lineHeight || cursorPosY>ImGui::GetWindowSize().y) {\n    return;\n  }\n  // check if we are in range\n  if (ord<0 || ord>=e->song.ordersLen) {\n    return;\n  }\n  if (i<0 || i>=e->song.patLen) {\n    return;\n  }\n  bool isPushing=false;\n  ImVec4 activeColor=uiColors[GUI_COLOR_PATTERN_ACTIVE];\n  ImVec4 inactiveColor=uiColors[GUI_COLOR_PATTERN_INACTIVE];\n  ImVec4 rowIndexColor=uiColors[GUI_COLOR_PATTERN_ROW_INDEX];\n  if (e->song.hilightB>0 && !(i%e->song.hilightB)) {\n    activeColor=uiColors[GUI_COLOR_PATTERN_ACTIVE_HI2];\n    inactiveColor=uiColors[GUI_COLOR_PATTERN_INACTIVE_HI2];\n    rowIndexColor=uiColors[GUI_COLOR_PATTERN_ROW_INDEX_HI2];\n  } else if (e->song.hilightA>0 && !(i%e->song.hilightA)) {\n    activeColor=uiColors[GUI_COLOR_PATTERN_ACTIVE_HI1];\n    inactiveColor=uiColors[GUI_COLOR_PATTERN_INACTIVE_HI1];\n    rowIndexColor=uiColors[GUI_COLOR_PATTERN_ROW_INDEX_HI1];\n  }\n  // check overflow highlight\n  if (settings.overflowHighlight) {\n    if (edit && cursor.y==i) {\n      ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_EDITING]));\n    } else if (isPlaying && oldRow==i) {\n      ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_PLAY_HEAD]));\n    } else if (e->song.hilightB>0 && !(i%e->song.hilightB)) {\n      ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_2]));\n    } else if (e->song.hilightA>0 && !(i%e->song.hilightA)) {\n      ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_1]));\n    }\n  } else {\n    isPushing=true;\n    if (edit && cursor.y==i) {\n      ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_EDITING]));\n    } else if (isPlaying && oldRow==i) {\n      ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_PLAY_HEAD]));\n    } else if (e->song.hilightB>0 && !(i%e->song.hilightB)) {\n      ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_2]));\n    } else if (e->song.hilightA>0 && !(i%e->song.hilightA)) {\n      ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_1]));\n    } else {\n      isPushing=false;\n    }\n  }\n  // row number\n  if (settings.patRowsBase==1) {\n    ImGui::TextColored(rowIndexColor,\" %.2X \",i);\n  } else {\n    ImGui::TextColored(rowIndexColor,\"%3d \",i);\n  }\n  // for each column\n  for (int j=0; jsong.chanShow[j]) {\n      patChanX[j]=ImGui::GetCursorPosX();\n      continue;\n    }\n    int chanVolMax=e->getMaxVolumeChan(j);\n    if (chanVolMax<1) chanVolMax=1;\n    const DivPattern* pat=patCache[j];\n    ImGui::TableNextColumn();\n    patChanX[j]=ImGui::GetCursorPosX();\n\n    // selection highlight flags\n    int sel1XSum=sel1.xCoarse*32+sel1.xFine;\n    int sel2XSum=sel2.xCoarse*32+sel2.xFine;\n    int j32=j*32;\n    bool selectedNote=selectedRow && (j32>=sel1XSum && j32<=sel2XSum);\n    bool selectedIns=selectedRow && (j32+1>=sel1XSum && j32+1<=sel2XSum);\n    bool selectedVol=selectedRow && (j32+2>=sel1XSum && j32+2<=sel2XSum);\n    bool cursorNote=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==0);\n    bool cursorIns=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==1);\n    bool cursorVol=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==2);\n\n    // note\n    sprintf(id,\"%s##PN_%d_%d\",noteName(pat->data[i][0],pat->data[i][1]),i,j);\n    if (pat->data[i][0]==0 && pat->data[i][1]==0) {\n      ImGui::PushStyleColor(ImGuiCol_Text,inactiveColor);\n    } else {\n      ImGui::PushStyleColor(ImGuiCol_Text,activeColor);\n    }\n    if (cursorNote) {\n      ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]);\n      ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]);\n      ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]);\n      ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,threeChars);\n      demandX=ImGui::GetCursorPosX();\n      ImGui::PopStyleColor(3);\n    } else {\n      if (selectedNote) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]);\n      ImGui::Selectable(id,isPushing || selectedNote,ImGuiSelectableFlags_NoPadWithHalfSpacing,threeChars);\n      if (selectedNote) ImGui::PopStyleColor();\n    }\n    if (ImGui::IsItemClicked()) {\n      startSelection(j,0,i);\n    }\n    if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) {\n      updateSelection(j,0,i);\n    }\n    ImGui::PopStyleColor();\n\n    // the following is only visible when the channel is not collapsed\n    if (!e->song.chanCollapse[j]) {\n      // instrument\n      if (pat->data[i][2]==-1) {\n        ImGui::PushStyleColor(ImGuiCol_Text,inactiveColor);\n        sprintf(id,\"..##PI_%d_%d\",i,j);\n      } else {\n        if (pat->data[i][2]<0 || pat->data[i][2]>=e->song.insLen) {\n          ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_INS_ERROR]);\n        } else {\n          DivInstrumentType t=e->song.ins[pat->data[i][2]]->type;\n          if (t!=DIV_INS_AMIGA && t!=e->getPreferInsType(j)) {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_INS_WARN]);\n          } else {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_INS]);\n          }\n        }\n        sprintf(id,\"%.2X##PI_%d_%d\",pat->data[i][2],i,j);\n      }\n      ImGui::SameLine(0.0f,0.0f);\n      if (cursorIns) {\n        ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]);\n        ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]);\n        ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]);\n        ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n        demandX=ImGui::GetCursorPosX();\n        ImGui::PopStyleColor(3);\n      } else {\n        if (selectedIns) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]);\n        ImGui::Selectable(id,isPushing || selectedIns,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n        if (selectedIns) ImGui::PopStyleColor();\n      }\n      if (ImGui::IsItemClicked()) {\n        startSelection(j,1,i);\n      }\n      if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) {\n        updateSelection(j,1,i);\n      }\n      ImGui::PopStyleColor();\n\n      // volume\n      if (pat->data[i][3]==-1) {\n        sprintf(id,\"..##PV_%d_%d\",i,j);\n        ImGui::PushStyleColor(ImGuiCol_Text,inactiveColor);\n      } else {\n        int volColor=(pat->data[i][3]*127)/chanVolMax;\n        if (volColor>127) volColor=127;\n        if (volColor<0) volColor=0;\n        sprintf(id,\"%.2X##PV_%d_%d\",pat->data[i][3],i,j);\n        ImGui::PushStyleColor(ImGuiCol_Text,volColors[volColor]);\n      }\n      ImGui::SameLine(0.0f,0.0f);\n      if (cursorVol) {\n        ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]);\n        ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]);\n        ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]);\n        ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n        demandX=ImGui::GetCursorPosX();\n        ImGui::PopStyleColor(3);\n      } else {\n        if (selectedVol) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]);\n        ImGui::Selectable(id,isPushing || selectedVol,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n        if (selectedVol) ImGui::PopStyleColor();\n      }\n      if (ImGui::IsItemClicked()) {\n        startSelection(j,2,i);\n      }\n      if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) {\n        updateSelection(j,2,i);\n      }\n      ImGui::PopStyleColor();\n\n      // effects\n      for (int k=0; ksong.pat[j].effectRows; k++) {\n        int index=4+(k<<1);\n        bool selectedEffect=selectedRow && (j32+index-1>=sel1XSum && j32+index-1<=sel2XSum);\n        bool selectedEffectVal=selectedRow && (j32+index>=sel1XSum && j32+index<=sel2XSum);\n        bool cursorEffect=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==index-1);\n        bool cursorEffectVal=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==index);\n        \n        // effect\n        if (pat->data[i][index]==-1) {\n          sprintf(id,\"..##PE%d_%d_%d\",k,i,j);\n          ImGui::PushStyleColor(ImGuiCol_Text,inactiveColor);\n        } else {\n          sprintf(id,\"%.2X##PE%d_%d_%d\",pat->data[i][index],k,i,j);\n          if (pat->data[i][index]<0x10) {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[fxColors[pat->data[i][index]]]);\n          } else if (pat->data[i][index]<0x20) {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_SYS_PRIMARY]);\n          } else if (pat->data[i][index]<0x30) {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_SYS_SECONDARY]);\n          } else if (pat->data[i][index]<0x48) {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_SYS_PRIMARY]);\n          } else if (pat->data[i][index]<0x90) {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_INVALID]);\n          } else if (pat->data[i][index]<0xa0) {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_MISC]);\n          } else if (pat->data[i][index]<0xc0) {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_INVALID]);\n          } else if (pat->data[i][index]<0xd0) {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_SPEED]);\n          } else if (pat->data[i][index]<0xe0) {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_INVALID]);\n          } else {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[extFxColors[pat->data[i][index]-0xe0]]);\n          }\n        }\n        ImGui::SameLine(0.0f,0.0f);\n        if (cursorEffect) {\n          ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]);  \n          ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]);\n          ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]);\n          ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n          demandX=ImGui::GetCursorPosX();\n          ImGui::PopStyleColor(3);\n        } else {\n          if (selectedEffect) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]);\n          ImGui::Selectable(id,isPushing || selectedEffect,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n          if (selectedEffect) ImGui::PopStyleColor();\n        }\n        if (ImGui::IsItemClicked()) {\n          startSelection(j,index-1,i);\n        }\n        if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) {\n          updateSelection(j,index-1,i);\n        }\n\n        // effect value\n        if (pat->data[i][index+1]==-1) {\n          sprintf(id,\"..##PF%d_%d_%d\",k,i,j);\n        } else {\n          sprintf(id,\"%.2X##PF%d_%d_%d\",pat->data[i][index+1],k,i,j);\n        }\n        ImGui::SameLine(0.0f,0.0f);\n        if (cursorEffectVal) {\n          ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]);  \n          ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]);\n          ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]);\n          ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n          demandX=ImGui::GetCursorPosX();\n          ImGui::PopStyleColor(3);\n        } else {\n          if (selectedEffectVal) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]);\n          ImGui::Selectable(id,isPushing || selectedEffectVal,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n          if (selectedEffectVal) ImGui::PopStyleColor();\n        }\n        if (ImGui::IsItemClicked()) {\n          startSelection(j,index,i);\n        }\n        if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) {\n          updateSelection(j,index,i);\n        }\n        ImGui::PopStyleColor();\n      }\n    }\n  }\n  if (isPushing) {\n    ImGui::PopStyleColor();\n  }\n  ImGui::TableNextColumn();\n  patChanX[chans]=ImGui::GetCursorPosX();\n}", "func_hash": 17036366544095628794236625993100848883, "file_name": "pattern.cpp", "file_hash": 65197606135408680585944772278654686188, "cwe": ["CWE-703"], "cve": "CVE-2022-1289", "cve_desc": "A denial of service vulnerability was found in tildearrow Furnace. It has been classified as problematic. This is due to an incomplete fix of CVE-2022-1211. It is possible to initiate the attack remotely but it requires user interaction. The issue got fixed with the patch 0eb02422d5161767e9983bdaa5c429762d3477ce.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1289"}
{"idx": 246237, "project": "furnace", "commit_id": "0eb02422d5161767e9983bdaa5c429762d3477ce", "project_url": "https://github.com/tildearrow/furnace", "commit_url": "https://github.com/tildearrow/furnace/commit/0eb02422d5161767e9983bdaa5c429762d3477ce", "commit_message": "fix possible pattern crash\n\nissue #325", "target": 0, "func": "inline void FurnaceGUI::patternRow(int i, bool isPlaying, float lineHeight, int chans, int ord, const DivPattern** patCache) {\n  static char id[32];\n  bool selectedRow=(i>=sel1.y && i<=sel2.y);\n  ImGui::TableNextRow(0,lineHeight);\n  ImGui::TableNextColumn();\n  float cursorPosY=ImGui::GetCursorPos().y-ImGui::GetScrollY();\n  // check if the row is visible\n  if (cursorPosY<-lineHeight || cursorPosY>ImGui::GetWindowSize().y) {\n    return;\n  }\n  // check if we are in range\n  if (ord<0 || ord>=e->song.ordersLen) {\n    return;\n  }\n  if (i<0 || i>=e->song.patLen) {\n    return;\n  }\n  bool isPushing=false;\n  ImVec4 activeColor=uiColors[GUI_COLOR_PATTERN_ACTIVE];\n  ImVec4 inactiveColor=uiColors[GUI_COLOR_PATTERN_INACTIVE];\n  ImVec4 rowIndexColor=uiColors[GUI_COLOR_PATTERN_ROW_INDEX];\n  if (e->song.hilightB>0 && !(i%e->song.hilightB)) {\n    activeColor=uiColors[GUI_COLOR_PATTERN_ACTIVE_HI2];\n    inactiveColor=uiColors[GUI_COLOR_PATTERN_INACTIVE_HI2];\n    rowIndexColor=uiColors[GUI_COLOR_PATTERN_ROW_INDEX_HI2];\n  } else if (e->song.hilightA>0 && !(i%e->song.hilightA)) {\n    activeColor=uiColors[GUI_COLOR_PATTERN_ACTIVE_HI1];\n    inactiveColor=uiColors[GUI_COLOR_PATTERN_INACTIVE_HI1];\n    rowIndexColor=uiColors[GUI_COLOR_PATTERN_ROW_INDEX_HI1];\n  }\n  // check overflow highlight\n  if (settings.overflowHighlight) {\n    if (edit && cursor.y==i) {\n      ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_EDITING]));\n    } else if (isPlaying && oldRow==i) {\n      ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_PLAY_HEAD]));\n    } else if (e->song.hilightB>0 && !(i%e->song.hilightB)) {\n      ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_2]));\n    } else if (e->song.hilightA>0 && !(i%e->song.hilightA)) {\n      ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_1]));\n    }\n  } else {\n    isPushing=true;\n    if (edit && cursor.y==i) {\n      ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_EDITING]));\n    } else if (isPlaying && oldRow==i) {\n      ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_PLAY_HEAD]));\n    } else if (e->song.hilightB>0 && !(i%e->song.hilightB)) {\n      ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_2]));\n    } else if (e->song.hilightA>0 && !(i%e->song.hilightA)) {\n      ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_1]));\n    } else {\n      isPushing=false;\n    }\n  }\n  // row number\n  if (settings.patRowsBase==1) {\n    ImGui::TextColored(rowIndexColor,\" %.2X \",i);\n  } else {\n    ImGui::TextColored(rowIndexColor,\"%3d \",i);\n  }\n  // for each column\n  for (int j=0; jsong.chanShow[j]) {\n      patChanX[j]=ImGui::GetCursorPosX();\n      continue;\n    }\n    int chanVolMax=e->getMaxVolumeChan(j);\n    if (chanVolMax<1) chanVolMax=1;\n    const DivPattern* pat=patCache[j];\n    ImGui::TableNextColumn();\n    patChanX[j]=ImGui::GetCursorPosX();\n\n    // selection highlight flags\n    int sel1XSum=sel1.xCoarse*32+sel1.xFine;\n    int sel2XSum=sel2.xCoarse*32+sel2.xFine;\n    int j32=j*32;\n    bool selectedNote=selectedRow && (j32>=sel1XSum && j32<=sel2XSum);\n    bool selectedIns=selectedRow && (j32+1>=sel1XSum && j32+1<=sel2XSum);\n    bool selectedVol=selectedRow && (j32+2>=sel1XSum && j32+2<=sel2XSum);\n    bool cursorNote=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==0);\n    bool cursorIns=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==1);\n    bool cursorVol=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==2);\n\n    // note\n    sprintf(id,\"%s##PN_%d_%d\",noteName(pat->data[i][0],pat->data[i][1]),i,j);\n    if (pat->data[i][0]==0 && pat->data[i][1]==0) {\n      ImGui::PushStyleColor(ImGuiCol_Text,inactiveColor);\n    } else {\n      ImGui::PushStyleColor(ImGuiCol_Text,activeColor);\n    }\n    if (cursorNote) {\n      ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]);\n      ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]);\n      ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]);\n      ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,threeChars);\n      demandX=ImGui::GetCursorPosX();\n      ImGui::PopStyleColor(3);\n    } else {\n      if (selectedNote) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]);\n      ImGui::Selectable(id,isPushing || selectedNote,ImGuiSelectableFlags_NoPadWithHalfSpacing,threeChars);\n      if (selectedNote) ImGui::PopStyleColor();\n    }\n    if (ImGui::IsItemClicked()) {\n      startSelection(j,0,i);\n    }\n    if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) {\n      updateSelection(j,0,i);\n    }\n    ImGui::PopStyleColor();\n\n    // the following is only visible when the channel is not collapsed\n    if (!e->song.chanCollapse[j]) {\n      // instrument\n      if (pat->data[i][2]==-1) {\n        ImGui::PushStyleColor(ImGuiCol_Text,inactiveColor);\n        sprintf(id,\"..##PI_%d_%d\",i,j);\n      } else {\n        if (pat->data[i][2]<0 || pat->data[i][2]>=e->song.insLen) {\n          ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_INS_ERROR]);\n        } else {\n          DivInstrumentType t=e->song.ins[pat->data[i][2]]->type;\n          if (t!=DIV_INS_AMIGA && t!=e->getPreferInsType(j)) {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_INS_WARN]);\n          } else {\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_INS]);\n          }\n        }\n        sprintf(id,\"%.2X##PI_%d_%d\",pat->data[i][2],i,j);\n      }\n      ImGui::SameLine(0.0f,0.0f);\n      if (cursorIns) {\n        ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]);\n        ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]);\n        ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]);\n        ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n        demandX=ImGui::GetCursorPosX();\n        ImGui::PopStyleColor(3);\n      } else {\n        if (selectedIns) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]);\n        ImGui::Selectable(id,isPushing || selectedIns,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n        if (selectedIns) ImGui::PopStyleColor();\n      }\n      if (ImGui::IsItemClicked()) {\n        startSelection(j,1,i);\n      }\n      if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) {\n        updateSelection(j,1,i);\n      }\n      ImGui::PopStyleColor();\n\n      // volume\n      if (pat->data[i][3]==-1) {\n        sprintf(id,\"..##PV_%d_%d\",i,j);\n        ImGui::PushStyleColor(ImGuiCol_Text,inactiveColor);\n      } else {\n        int volColor=(pat->data[i][3]*127)/chanVolMax;\n        if (volColor>127) volColor=127;\n        if (volColor<0) volColor=0;\n        sprintf(id,\"%.2X##PV_%d_%d\",pat->data[i][3],i,j);\n        ImGui::PushStyleColor(ImGuiCol_Text,volColors[volColor]);\n      }\n      ImGui::SameLine(0.0f,0.0f);\n      if (cursorVol) {\n        ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]);\n        ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]);\n        ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]);\n        ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n        demandX=ImGui::GetCursorPosX();\n        ImGui::PopStyleColor(3);\n      } else {\n        if (selectedVol) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]);\n        ImGui::Selectable(id,isPushing || selectedVol,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n        if (selectedVol) ImGui::PopStyleColor();\n      }\n      if (ImGui::IsItemClicked()) {\n        startSelection(j,2,i);\n      }\n      if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) {\n        updateSelection(j,2,i);\n      }\n      ImGui::PopStyleColor();\n\n      // effects\n      for (int k=0; ksong.pat[j].effectRows; k++) {\n        int index=4+(k<<1);\n        bool selectedEffect=selectedRow && (j32+index-1>=sel1XSum && j32+index-1<=sel2XSum);\n        bool selectedEffectVal=selectedRow && (j32+index>=sel1XSum && j32+index<=sel2XSum);\n        bool cursorEffect=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==index-1);\n        bool cursorEffectVal=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==index);\n        \n        // effect\n        if (pat->data[i][index]==-1) {\n          sprintf(id,\"..##PE%d_%d_%d\",k,i,j);\n          ImGui::PushStyleColor(ImGuiCol_Text,inactiveColor);\n        } else {\n          if (pat->data[i][index]>0xff) {\n            sprintf(id,\"??##PE%d_%d_%d\",k,i,j);\n            ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_INVALID]);\n          } else {\n            const unsigned char data=pat->data[i][index];\n            sprintf(id,\"%.2X##PE%d_%d_%d\",data,k,i,j);\n            if (data<0x10) {\n              ImGui::PushStyleColor(ImGuiCol_Text,uiColors[fxColors[data]]);\n            } else if (data<0x20) {\n              ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_SYS_PRIMARY]);\n            } else if (data<0x30) {\n              ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_SYS_SECONDARY]);\n            } else if (data<0x48) {\n              ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_SYS_PRIMARY]);\n            } else if (data<0x90) {\n              ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_INVALID]);\n            } else if (data<0xa0) {\n              ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_MISC]);\n            } else if (data<0xc0) {\n              ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_INVALID]);\n            } else if (data<0xd0) {\n              ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_SPEED]);\n            } else if (data<0xe0) {\n              ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_INVALID]);\n            } else {\n              ImGui::PushStyleColor(ImGuiCol_Text,uiColors[extFxColors[data-0xe0]]);\n            }\n          }\n        }\n        ImGui::SameLine(0.0f,0.0f);\n        if (cursorEffect) {\n          ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]);  \n          ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]);\n          ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]);\n          ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n          demandX=ImGui::GetCursorPosX();\n          ImGui::PopStyleColor(3);\n        } else {\n          if (selectedEffect) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]);\n          ImGui::Selectable(id,isPushing || selectedEffect,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n          if (selectedEffect) ImGui::PopStyleColor();\n        }\n        if (ImGui::IsItemClicked()) {\n          startSelection(j,index-1,i);\n        }\n        if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) {\n          updateSelection(j,index-1,i);\n        }\n\n        // effect value\n        if (pat->data[i][index+1]==-1) {\n          sprintf(id,\"..##PF%d_%d_%d\",k,i,j);\n        } else {\n          sprintf(id,\"%.2X##PF%d_%d_%d\",pat->data[i][index+1],k,i,j);\n        }\n        ImGui::SameLine(0.0f,0.0f);\n        if (cursorEffectVal) {\n          ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]);  \n          ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]);\n          ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]);\n          ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n          demandX=ImGui::GetCursorPosX();\n          ImGui::PopStyleColor(3);\n        } else {\n          if (selectedEffectVal) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]);\n          ImGui::Selectable(id,isPushing || selectedEffectVal,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars);\n          if (selectedEffectVal) ImGui::PopStyleColor();\n        }\n        if (ImGui::IsItemClicked()) {\n          startSelection(j,index,i);\n        }\n        if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) {\n          updateSelection(j,index,i);\n        }\n        ImGui::PopStyleColor();\n      }\n    }\n  }\n  if (isPushing) {\n    ImGui::PopStyleColor();\n  }\n  ImGui::TableNextColumn();\n  patChanX[chans]=ImGui::GetCursorPosX();\n}", "func_hash": 128714146198604784815522114188273080778, "file_name": "pattern.cpp", "file_hash": 168724633676180669300352035041454609320, "cwe": ["CWE-703"], "cve": "CVE-2022-1289", "cve_desc": "A denial of service vulnerability was found in tildearrow Furnace. It has been classified as problematic. This is due to an incomplete fix of CVE-2022-1211. It is possible to initiate the attack remotely but it requires user interaction. The issue got fixed with the patch 0eb02422d5161767e9983bdaa5c429762d3477ce.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1289"}
{"idx": 196846, "project": "tensorflow", "commit_id": "1e206baedf8bef0334cca3eb92bab134ef525a28", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/1e206baedf8bef0334cca3eb92bab134ef525a28", "commit_message": "Prevent a division by 0 in division ops.\n\nPiperOrigin-RevId: 385223169\nChange-Id: Ia4228960b5d2aa44480385f74bdd70d21a3613c3", "target": 1, "func": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n  auto* params = reinterpret_cast(node->builtin_data);\n  OpData* data = reinterpret_cast(node->user_data);\n\n  const TfLiteTensor* input1;\n  TF_LITE_ENSURE_OK(context,\n                    GetInputSafe(context, node, kInputTensor1, &input1));\n  const TfLiteTensor* input2;\n  TF_LITE_ENSURE_OK(context,\n                    GetInputSafe(context, node, kInputTensor2, &input2));\n  TfLiteTensor* output;\n  TF_LITE_ENSURE_OK(context,\n                    GetOutputSafe(context, node, kOutputTensor, &output));\n\n  if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32) {\n    EvalDiv(context, node, params, data, input1, input2, output);\n  } else if (output->type == kTfLiteUInt8) {\n    TF_LITE_ENSURE_OK(\n        context, EvalQuantized(context, node, params, data, input1,\n                                            input2, output));\n  } else {\n    context->ReportError(\n        context,\n        \"Div only supports FLOAT32, INT32 and quantized UINT8 now, got %d.\",\n        output->type);\n    return kTfLiteError;\n  }\n\n  return kTfLiteOk;\n}", "func_hash": 74793210691338682931219587955813295204, "file_name": "div.cc", "file_hash": 136615346340517059112870142252291864399, "cwe": ["CWE-369"], "cve": "CVE-2021-37683", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of division in TFLite is [vulnerable to a division by 0 error](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/lite/kernels/div.cc). There is no check that the divisor tensor does not contain zero elements. We have patched the issue in GitHub commit 1e206baedf8bef0334cca3eb92bab134ef525a28. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37683"}
{"idx": 246495, "project": "tensorflow", "commit_id": "1e206baedf8bef0334cca3eb92bab134ef525a28", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/1e206baedf8bef0334cca3eb92bab134ef525a28", "commit_message": "Prevent a division by 0 in division ops.\n\nPiperOrigin-RevId: 385223169\nChange-Id: Ia4228960b5d2aa44480385f74bdd70d21a3613c3", "target": 0, "func": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n  auto* params = reinterpret_cast(node->builtin_data);\n  OpData* data = reinterpret_cast(node->user_data);\n\n  const TfLiteTensor* input1;\n  TF_LITE_ENSURE_OK(context,\n                    GetInputSafe(context, node, kInputTensor1, &input1));\n  const TfLiteTensor* input2;\n  TF_LITE_ENSURE_OK(context,\n                    GetInputSafe(context, node, kInputTensor2, &input2));\n  TfLiteTensor* output;\n  TF_LITE_ENSURE_OK(context,\n                    GetOutputSafe(context, node, kOutputTensor, &output));\n\n  // TODO(b/193904910): This can written with C++ templates\n#define TF_LITE_CHECK_DIV_NON_ZERO(data_type)                       \\\n  const auto* input2_data = GetTensorData(input2);       \\\n  const size_t input2_elements = input2->bytes / sizeof(data_type); \\\n  for (size_t i = 0; i < input2_elements; i++) {                    \\\n    TF_LITE_ENSURE(context, input2_data[i] != 0);                   \\\n  }\n\n  if (output->type == kTfLiteFloat32) {\n    // Div by zero seems ok in this case, just like in TF case infinities are\n    // returned. So we don't do a check at this point.\n    EvalDiv(context, node, params, data, input1, input2, output);\n  } else if (output->type == kTfLiteInt32) {\n    TF_LITE_CHECK_DIV_NON_ZERO(int32_t);\n    EvalDiv(context, node, params, data, input1, input2, output);\n  } else if (output->type == kTfLiteUInt8) {\n    TF_LITE_CHECK_DIV_NON_ZERO(uint8_t);\n    TF_LITE_ENSURE_OK(\n        context, EvalQuantized(context, node, params, data, input1,\n                                            input2, output));\n  } else {\n    context->ReportError(\n        context,\n        \"Div only supports FLOAT32, INT32 and quantized UINT8 now, got %d.\",\n        output->type);\n    return kTfLiteError;\n  }\n#undef TF_LITE_CHECK_DIV_NON_ZERO\n\n  return kTfLiteOk;\n}", "func_hash": 11976239460896947994282427616906942562, "file_name": "div.cc", "file_hash": 298114320359155685162419383998362245720, "cwe": ["CWE-369"], "cve": "CVE-2021-37683", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of division in TFLite is [vulnerable to a division by 0 error](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/lite/kernels/div.cc). There is no check that the divisor tensor does not contain zero elements. We have patched the issue in GitHub commit 1e206baedf8bef0334cca3eb92bab134ef525a28. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37683"}
{"idx": 196860, "project": "gpac", "commit_id": "a51f951b878c2b73c1d8e2f1518c7cdc5fb82c3f", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/a51f951b878c2b73c1d8e2f1518c7cdc5fb82c3f", "commit_message": "fixed #1782 (fuzz)", "target": 1, "func": "GF_Err afra_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tunsigned int i;\n\tGF_AdobeFragRandomAccessBox *ptr = (GF_AdobeFragRandomAccessBox *)s;\n\n\tISOM_DECREASE_SIZE(ptr, 9)\n\tptr->long_ids = gf_bs_read_int(bs, 1);\n\tptr->long_offsets = gf_bs_read_int(bs, 1);\n\tptr->global_entries = gf_bs_read_int(bs, 1);\n\tptr->reserved = gf_bs_read_int(bs, 5);\n\tptr->time_scale = gf_bs_read_u32(bs);\n\n\tptr->entry_count = gf_bs_read_u32(bs);\n\tif (ptr->size / ( (ptr->long_offsets ? 16 : 12) ) < ptr->entry_count)\n\t\treturn GF_ISOM_INVALID_FILE;\n\n\tfor (i=0; ientry_count; i++) {\n\t\tGF_AfraEntry *ae = gf_malloc(sizeof(GF_AfraEntry));\n\t\tif (!ae) return GF_OUT_OF_MEM;\n\n\t\tISOM_DECREASE_SIZE(ptr, 8)\n\t\tae->time = gf_bs_read_u64(bs);\n\t\tif (ptr->long_offsets) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 8)\n\t\t\tae->offset = gf_bs_read_u64(bs);\n\t\t} else {\n\t\t\tISOM_DECREASE_SIZE(ptr, 4)\n\t\t\tae->offset = gf_bs_read_u32(bs);\n\t\t}\n\n\t\tgf_list_insert(ptr->local_access_entries, ae, i);\n\t}\n\n\tif (ptr->global_entries) {\n\t\tISOM_DECREASE_SIZE(ptr, 4)\n\t\tptr->global_entry_count = gf_bs_read_u32(bs);\n\t\tfor (i=0; iglobal_entry_count; i++) {\n\t\t\tGF_GlobalAfraEntry *ae = gf_malloc(sizeof(GF_GlobalAfraEntry));\n\t\t\tif (!ae) return GF_OUT_OF_MEM;\n\t\t\tISOM_DECREASE_SIZE(ptr, 8)\n\t\t\tae->time = gf_bs_read_u64(bs);\n\t\t\tif (ptr->long_ids) {\n\t\t\t\tISOM_DECREASE_SIZE(ptr, 8)\n\t\t\t\tae->segment = gf_bs_read_u32(bs);\n\t\t\t\tae->fragment = gf_bs_read_u32(bs);\n\t\t\t} else {\n\t\t\t\tISOM_DECREASE_SIZE(ptr, 4)\n\t\t\t\tae->segment = gf_bs_read_u16(bs);\n\t\t\t\tae->fragment = gf_bs_read_u16(bs);\n\t\t\t}\n\t\t\tif (ptr->long_offsets) {\n\t\t\t\tISOM_DECREASE_SIZE(ptr, 16)\n\t\t\t\tae->afra_offset = gf_bs_read_u64(bs);\n\t\t\t\tae->offset_from_afra = gf_bs_read_u64(bs);\n\t\t\t} else {\n\t\t\t\tISOM_DECREASE_SIZE(ptr, 8)\n\t\t\t\tae->afra_offset = gf_bs_read_u32(bs);\n\t\t\t\tae->offset_from_afra = gf_bs_read_u32(bs);\n\t\t\t}\n\n\t\t\tgf_list_insert(ptr->global_access_entries, ae, i);\n\t\t}\n\t}\n\n\treturn GF_OK;\n}", "func_hash": 312927211426500504617752335989791880756, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2021-33361", "cve_desc": "Memory leak in the afra_box_read function in MP4Box in GPAC 1.0.1 allows attackers to read memory via a crafted file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-33361"}
{"idx": 246693, "project": "gpac", "commit_id": "a51f951b878c2b73c1d8e2f1518c7cdc5fb82c3f", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/a51f951b878c2b73c1d8e2f1518c7cdc5fb82c3f", "commit_message": "fixed #1782 (fuzz)", "target": 0, "func": "GF_Err afra_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tunsigned int i;\n\tGF_AdobeFragRandomAccessBox *ptr = (GF_AdobeFragRandomAccessBox *)s;\n\n\tISOM_DECREASE_SIZE(ptr, 9)\n\tptr->long_ids = gf_bs_read_int(bs, 1);\n\tptr->long_offsets = gf_bs_read_int(bs, 1);\n\tptr->global_entries = gf_bs_read_int(bs, 1);\n\tptr->reserved = gf_bs_read_int(bs, 5);\n\tptr->time_scale = gf_bs_read_u32(bs);\n\n\tptr->entry_count = gf_bs_read_u32(bs);\n\tif (ptr->size / ( (ptr->long_offsets ? 16 : 12) ) < ptr->entry_count)\n\t\treturn GF_ISOM_INVALID_FILE;\n\n\tfor (i=0; ientry_count; i++) {\n\t\tGF_AfraEntry *ae = gf_malloc(sizeof(GF_AfraEntry));\n\t\tif (!ae) return GF_OUT_OF_MEM;\n\t\tgf_list_insert(ptr->local_access_entries, ae, i);\n\n\t\tISOM_DECREASE_SIZE(ptr, 8)\n\t\tae->time = gf_bs_read_u64(bs);\n\t\tif (ptr->long_offsets) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 8)\n\t\t\tae->offset = gf_bs_read_u64(bs);\n\t\t} else {\n\t\t\tISOM_DECREASE_SIZE(ptr, 4)\n\t\t\tae->offset = gf_bs_read_u32(bs);\n\t\t}\n\t}\n\n\tif (ptr->global_entries) {\n\t\tISOM_DECREASE_SIZE(ptr, 4)\n\t\tptr->global_entry_count = gf_bs_read_u32(bs);\n\t\tfor (i=0; iglobal_entry_count; i++) {\n\t\t\tGF_GlobalAfraEntry *ae = gf_malloc(sizeof(GF_GlobalAfraEntry));\n\t\t\tif (!ae) return GF_OUT_OF_MEM;\n\t\t\tgf_list_insert(ptr->global_access_entries, ae, i);\n\n\t\t\tISOM_DECREASE_SIZE(ptr, 8)\n\t\t\tae->time = gf_bs_read_u64(bs);\n\t\t\tif (ptr->long_ids) {\n\t\t\t\tISOM_DECREASE_SIZE(ptr, 8)\n\t\t\t\tae->segment = gf_bs_read_u32(bs);\n\t\t\t\tae->fragment = gf_bs_read_u32(bs);\n\t\t\t} else {\n\t\t\t\tISOM_DECREASE_SIZE(ptr, 4)\n\t\t\t\tae->segment = gf_bs_read_u16(bs);\n\t\t\t\tae->fragment = gf_bs_read_u16(bs);\n\t\t\t}\n\t\t\tif (ptr->long_offsets) {\n\t\t\t\tISOM_DECREASE_SIZE(ptr, 16)\n\t\t\t\tae->afra_offset = gf_bs_read_u64(bs);\n\t\t\t\tae->offset_from_afra = gf_bs_read_u64(bs);\n\t\t\t} else {\n\t\t\t\tISOM_DECREASE_SIZE(ptr, 8)\n\t\t\t\tae->afra_offset = gf_bs_read_u32(bs);\n\t\t\t\tae->offset_from_afra = gf_bs_read_u32(bs);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn GF_OK;\n}", "func_hash": 301022642870722199968022360468016167215, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2021-33361", "cve_desc": "Memory leak in the afra_box_read function in MP4Box in GPAC 1.0.1 allows attackers to read memory via a crafted file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-33361"}
{"idx": 196885, "project": "tensorflow", "commit_id": "9e62869465573cb2d9b5053f1fa02a81fce21d69", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/9e62869465573cb2d9b5053f1fa02a81fce21d69", "commit_message": "Add more validation to `RequantizationRangePerChannel`.\n\nPiperOrigin-RevId: 387693946\nChange-Id: Ife8dcbdb021bec4787eef6a4361dd08f17c14bd6", "target": 1, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor& input = ctx->input(kInputTensorIndex);\n    const Tensor& input_min = ctx->input(kInputMinIndex);\n    const Tensor& input_max = ctx->input(kInputMaxIndex);\n\n    const size_t depth = input_max.NumElements();\n    OP_REQUIRES(\n        ctx, input_min.dim_size(0) == depth,\n        errors::InvalidArgument(\"input_min has incorrect size, expected \",\n                                depth, \" was \", input_min.dim_size(0)));\n    OP_REQUIRES(\n        ctx, input_max.dim_size(0) == depth,\n        errors::InvalidArgument(\"input_max has incorrect size, expected \",\n                                depth, \" was \", input_max.dim_size(0)));\n\n    const float* input_min_data = input_min.flat().data();\n    const float* input_max_data = input_max.flat().data();\n    std::vector ranges(depth);\n    bool is_non_negative = true;\n    Eigen::array shuffling({1, 0});\n    auto input_matrix = input.flat_inner_dims();\n\n    // TODO: verify performance of not transposing and finding the min max\n    // directly from input_matrix vs the one presented below of transposing and\n    // using the transposed matrix as the transposing operation in itself might\n    // be more costly.\n    // Note that this operation is a calibration step for quantization and will\n    // cease to exist in the final inference graph(will exist as a const node).\n    auto transposed_input = input_matrix.shuffle(shuffling);\n\n    // Find the ranges of each channel in parallel.\n    float out_min_max = std::numeric_limits::min();\n\n#ifdef ENABLE_ONEDNN_OPENMP\n#ifdef _MSC_VER\n#pragma omp parallel for\n#else\n#pragma omp parallel for reduction(max : out_min_max)\n#endif\n#endif  // ENABLE_ONEDNN_OPENMP\n    // TODO: Add eigen parallel_for\n    for (int64_t i = 0; i < depth; ++i) {\n      Eigen::Tensor min =\n          transposed_input.chip<0>(i).minimum();\n      Eigen::Tensor max =\n          transposed_input.chip<0>(i).maximum();\n      const int32_t min_per_channel = min();\n      const int32_t max_per_channel = max();\n      const int32_t abs_max =\n          std::max(std::abs(min_per_channel), std::abs(max_per_channel));\n      float scale =\n          std::max(std::abs(input_min_data[i]), std::abs(input_max_data[i]));\n      ranges[i] =\n          scale * static_cast(abs_max) / static_cast(1L << 31);\n      if (min_per_channel < 0) is_non_negative = false;\n\n      // Thread-local out_min_max.\n      out_min_max = std::max(out_min_max, ranges[i]);\n    }\n\n    // All local out_min_max gets max-reduced into one global out_min_max at\n    // the end of the loop by specifying reduction(max:out_min_max) along with\n    // omp parallel for.\n\n    // Fixing max to clip_value_max_ (example 6.0 to support relu6)\n    if (out_min_max > clip_value_max_) out_min_max = clip_value_max_;\n\n    Tensor* output_min = nullptr;\n    Tensor* output_max = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputMinIndex, {}, &output_min));\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputMaxIndex, {}, &output_max));\n    output_min->flat()(0) = is_non_negative ? 0.0f : -out_min_max;\n    output_max->flat()(0) = out_min_max;\n  }", "func_hash": 260350269729869693096839937488434150493, "file_name": "mkl_requantization_range_per_channel_op.cc", "file_hash": 184757242449876370761844438653930390458, "cwe": ["CWE-703"], "cve": "CVE-2021-37665", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions due to incomplete validation in MKL implementation of requantization, an attacker can trigger undefined behavior via binding a reference to a null pointer or can access data outside the bounds of heap allocated arrays. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/mkl/mkl_requantization_range_per_channel_op.cc) does not validate the dimensions of the `input` tensor. A similar issue occurs in `MklRequantizePerChannelOp`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/mkl/mkl_requantize_per_channel_op.cc) does not perform full validation for all the input arguments. We have patched the issue in GitHub commit 9e62869465573cb2d9b5053f1fa02a81fce21d69 and in the Github commit 203214568f5bc237603dbab6e1fd389f1572f5c9. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37665"}
{"idx": 247290, "project": "tensorflow", "commit_id": "9e62869465573cb2d9b5053f1fa02a81fce21d69", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/9e62869465573cb2d9b5053f1fa02a81fce21d69", "commit_message": "Add more validation to `RequantizationRangePerChannel`.\n\nPiperOrigin-RevId: 387693946\nChange-Id: Ife8dcbdb021bec4787eef6a4361dd08f17c14bd6", "target": 0, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor& input = ctx->input(kInputTensorIndex);\n    const Tensor& input_min = ctx->input(kInputMinIndex);\n    const Tensor& input_max = ctx->input(kInputMaxIndex);\n\n    const size_t depth = input_max.NumElements();\n    OP_REQUIRES(\n        ctx, input_min.dim_size(0) == depth,\n        errors::InvalidArgument(\"input_min has incorrect size, expected \",\n                                depth, \" was \", input_min.dim_size(0)));\n    OP_REQUIRES(\n        ctx, input_max.dim_size(0) == depth,\n        errors::InvalidArgument(\"input_max has incorrect size, expected \",\n                                depth, \" was \", input_max.dim_size(0)));\n    OP_REQUIRES(\n        ctx, input_min.NumElements() == depth,\n        errors::InvalidArgument(\"input_min must have the same number of \"\n                                \"elements as input_max, got \",\n                                input_min.NumElements(), \" and \", depth));\n    OP_REQUIRES(ctx, input.NumElements() > 0,\n                errors::InvalidArgument(\"input must not be empty\"));\n    OP_REQUIRES(ctx, input.dims() == 4,\n                errors::InvalidArgument(\"input must be in NHWC format\"));\n    OP_REQUIRES(\n        ctx, input.dim_size(3) == depth,\n        errors::InvalidArgument(\n            \"input must have same number of channels as length of input_min: \",\n            input.dim_size(3), \" vs \", depth));\n\n    const float* input_min_data = input_min.flat().data();\n    const float* input_max_data = input_max.flat().data();\n    std::vector ranges(depth);\n    bool is_non_negative = true;\n    Eigen::array shuffling({1, 0});\n    auto input_matrix = input.flat_inner_dims();\n\n    // TODO: verify performance of not transposing and finding the min max\n    // directly from input_matrix vs the one presented below of transposing and\n    // using the transposed matrix as the transposing operation in itself might\n    // be more costly.\n    // Note that this operation is a calibration step for quantization and will\n    // cease to exist in the final inference graph(will exist as a const node).\n    auto transposed_input = input_matrix.shuffle(shuffling);\n\n    // Find the ranges of each channel in parallel.\n    float out_min_max = std::numeric_limits::min();\n\n#ifdef ENABLE_ONEDNN_OPENMP\n#ifdef _MSC_VER\n#pragma omp parallel for\n#else\n#pragma omp parallel for reduction(max : out_min_max)\n#endif\n#endif  // ENABLE_ONEDNN_OPENMP\n    // TODO: Add eigen parallel_for\n    for (int64_t i = 0; i < depth; ++i) {\n      Eigen::Tensor min =\n          transposed_input.chip<0>(i).minimum();\n      Eigen::Tensor max =\n          transposed_input.chip<0>(i).maximum();\n      const int32_t min_per_channel = min();\n      const int32_t max_per_channel = max();\n      const int32_t abs_max =\n          std::max(std::abs(min_per_channel), std::abs(max_per_channel));\n      float scale =\n          std::max(std::abs(input_min_data[i]), std::abs(input_max_data[i]));\n      ranges[i] =\n          scale * static_cast(abs_max) / static_cast(1L << 31);\n      if (min_per_channel < 0) is_non_negative = false;\n\n      // Thread-local out_min_max.\n      out_min_max = std::max(out_min_max, ranges[i]);\n    }\n\n    // All local out_min_max gets max-reduced into one global out_min_max at\n    // the end of the loop by specifying reduction(max:out_min_max) along with\n    // omp parallel for.\n\n    // Fixing max to clip_value_max_ (example 6.0 to support relu6)\n    if (out_min_max > clip_value_max_) out_min_max = clip_value_max_;\n\n    Tensor* output_min = nullptr;\n    Tensor* output_max = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputMinIndex, {}, &output_min));\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputMaxIndex, {}, &output_max));\n    output_min->flat()(0) = is_non_negative ? 0.0f : -out_min_max;\n    output_max->flat()(0) = out_min_max;\n  }", "func_hash": 65335252627103993681002050942452280098, "file_name": "mkl_requantization_range_per_channel_op.cc", "file_hash": 130833376136830385582561054482718538709, "cwe": ["CWE-703"], "cve": "CVE-2021-37665", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions due to incomplete validation in MKL implementation of requantization, an attacker can trigger undefined behavior via binding a reference to a null pointer or can access data outside the bounds of heap allocated arrays. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/mkl/mkl_requantization_range_per_channel_op.cc) does not validate the dimensions of the `input` tensor. A similar issue occurs in `MklRequantizePerChannelOp`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/mkl/mkl_requantize_per_channel_op.cc) does not perform full validation for all the input arguments. We have patched the issue in GitHub commit 9e62869465573cb2d9b5053f1fa02a81fce21d69 and in the Github commit 203214568f5bc237603dbab6e1fd389f1572f5c9. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37665"}
{"idx": 196889, "project": "rpm", "commit_id": "bd36c5dc9fb6d90c46fbfed8c2d67516fc571ec8", "project_url": "https://github.com/rpm-software-management/rpm", "commit_url": "https://github.com/rpm-software-management/rpm/commit/bd36c5dc9fb6d90c46fbfed8c2d67516fc571ec8", "commit_message": "Validate and require subkey binding signatures on PGP public keys\n\nAll subkeys must be followed by a binding signature by the primary key\nas per the OpenPGP RFC, enforce the presence and validity in the parser.\n\nThe implementation is as kludgey as they come to work around our\nsimple-minded parser structure without touching API, to maximise\nbackportability. Store all the raw packets internally as we decode them\nto be able to access previous elements at will, needed to validate ordering\nand access the actual data. Add testcases for manipulated keys whose\nimport previously would succeed.\n\nDepends on the two previous commits:\n7b399fcb8f52566e6f3b4327197a85facd08db91 and\n236b802a4aa48711823a191d1b7f753c82a89ec5\n\nFixes CVE-2021-3521.", "target": 1, "func": "int pgpPrtParams(const uint8_t * pkts, size_t pktlen, unsigned int pkttype,\n\t\t pgpDigParams * ret)\n{\n    const uint8_t *p = pkts;\n    const uint8_t *pend = pkts + pktlen;\n    pgpDigParams digp = NULL;\n    struct pgpPkt pkt;\n    int rc = -1; /* assume failure */\n\n    while (p < pend) {\n\tif (decodePkt(p, (pend - p), &pkt))\n\t    break;\n\n\tif (digp == NULL) {\n\t    if (pkttype && pkt.tag != pkttype) {\n\t\tbreak;\n\t    } else {\n\t\tdigp = pgpDigParamsNew(pkt.tag);\n\t    }\n\t}\n\n\tif (pgpPrtPkt(&pkt, digp))\n\t    break;\n\n\tp += (pkt.body - pkt.head) + pkt.blen;\n\tif (pkttype == PGPTAG_SIGNATURE)\n\t    break;\n    }\n\n    rc = (digp && (p == pend)) ? 0 : -1;\n\n    if (ret && rc == 0) {\n\t*ret = digp;\n    } else {\n\tpgpDigParamsFree(digp);\n    }\n    return rc;\n}", "func_hash": 241902861702092358566393446057169117418, "file_name": "rpmpgp.c", "file_hash": 261680371397829724328332349939648686474, "cwe": ["CWE-284"], "cve": "CVE-2021-3521", "cve_desc": "There is a flaw in RPM's signature functionality. OpenPGP subkeys are associated with a primary key via a \"binding signature.\" RPM does not check the binding signature of subkeys prior to importing them. If an attacker is able to add or socially engineer another party to add a malicious subkey to a legitimate public key, RPM could wrongly trust a malicious signature. The greatest impact of this flaw is to data integrity. To exploit this flaw, an attacker must either compromise an RPM repository or convince an administrator to install an untrusted RPM or public key. It is strongly recommended to only use RPMs and public keys from trusted sources.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3521"}
{"idx": 247337, "project": "rpm", "commit_id": "bd36c5dc9fb6d90c46fbfed8c2d67516fc571ec8", "project_url": "https://github.com/rpm-software-management/rpm", "commit_url": "https://github.com/rpm-software-management/rpm/commit/bd36c5dc9fb6d90c46fbfed8c2d67516fc571ec8", "commit_message": "Validate and require subkey binding signatures on PGP public keys\n\nAll subkeys must be followed by a binding signature by the primary key\nas per the OpenPGP RFC, enforce the presence and validity in the parser.\n\nThe implementation is as kludgey as they come to work around our\nsimple-minded parser structure without touching API, to maximise\nbackportability. Store all the raw packets internally as we decode them\nto be able to access previous elements at will, needed to validate ordering\nand access the actual data. Add testcases for manipulated keys whose\nimport previously would succeed.\n\nDepends on the two previous commits:\n7b399fcb8f52566e6f3b4327197a85facd08db91 and\n236b802a4aa48711823a191d1b7f753c82a89ec5\n\nFixes CVE-2021-3521.", "target": 0, "func": "int pgpPrtParams(const uint8_t * pkts, size_t pktlen, unsigned int pkttype,\n\t\t pgpDigParams * ret)\n{\n    const uint8_t *p = pkts;\n    const uint8_t *pend = pkts + pktlen;\n    pgpDigParams digp = NULL;\n    pgpDigParams selfsig = NULL;\n    int i = 0;\n    int alloced = 16; /* plenty for normal cases */\n    struct pgpPkt *all = xmalloc(alloced * sizeof(*all));\n    int rc = -1; /* assume failure */\n    int expect = 0;\n    int prevtag = 0;\n\n    while (p < pend) {\n\tstruct pgpPkt *pkt = &all[i];\n\tif (decodePkt(p, (pend - p), pkt))\n\t    break;\n\n\tif (digp == NULL) {\n\t    if (pkttype && pkt->tag != pkttype) {\n\t\tbreak;\n\t    } else {\n\t\tdigp = pgpDigParamsNew(pkt->tag);\n\t    }\n\t}\n\n\tif (expect) {\n\t    if (pkt->tag != expect)\n\t\tbreak;\n\t    selfsig = pgpDigParamsNew(pkt->tag);\n\t}\n\n\tif (pgpPrtPkt(pkt, selfsig ? selfsig : digp))\n\t    break;\n\n\tif (selfsig) {\n\t    /* subkeys must be followed by binding signature */\n\t    if (prevtag == PGPTAG_PUBLIC_SUBKEY) {\n\t\tif (selfsig->sigtype != PGPSIGTYPE_SUBKEY_BINDING)\n\t\t    break;\n\t    }\n\n\t    int xx = pgpVerifySelf(digp, selfsig, all, i);\n\n\t    selfsig = pgpDigParamsFree(selfsig);\n\t    if (xx)\n\t\tbreak;\n\t    expect = 0;\n\t}\n\n\tif (pkt->tag == PGPTAG_PUBLIC_SUBKEY)\n\t    expect = PGPTAG_SIGNATURE;\n\tprevtag = pkt->tag;\n\n\ti++;\n\tp += (pkt->body - pkt->head) + pkt->blen;\n\tif (pkttype == PGPTAG_SIGNATURE)\n\t    break;\n\n\tif (alloced <= i) {\n\t    alloced *= 2;\n\t    all = xrealloc(all, alloced * sizeof(*all));\n\t}\n    }\n\n    rc = (digp && (p == pend) && expect == 0) ? 0 : -1;\n\n    free(all);\n    if (ret && rc == 0) {\n\t*ret = digp;\n    } else {\n\tpgpDigParamsFree(digp);\n    }\n    return rc;\n}", "func_hash": 60576529030332020496700497247000582633, "file_name": "rpmpgp.c", "file_hash": 239865202965429172751618330846379616622, "cwe": ["CWE-284"], "cve": "CVE-2021-3521", "cve_desc": "There is a flaw in RPM's signature functionality. OpenPGP subkeys are associated with a primary key via a \"binding signature.\" RPM does not check the binding signature of subkeys prior to importing them. If an attacker is able to add or socially engineer another party to add a malicious subkey to a legitimate public key, RPM could wrongly trust a malicious signature. The greatest impact of this flaw is to data integrity. To exploit this flaw, an attacker must either compromise an RPM repository or convince an administrator to install an untrusted RPM or public key. It is strongly recommended to only use RPMs and public keys from trusted sources.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3521"}
{"idx": 196893, "project": "envoy", "commit_id": "e9f936d85dc1edc34fabd0a1725ec180f2316353", "project_url": "https://github.com/istio/envoy", "commit_url": "https://github.com/envoyproxy/envoy/commit/e9f936d85dc1edc34fabd0a1725ec180f2316353", "commit_message": "CVE-2022-21654\n\ntls allows re-use when some cert validation settings have changed\n\nSigned-off-by: Yan Avlasov ", "target": 1, "func": "void DefaultCertValidator::updateDigestForSessionId(bssl::ScopedEVP_MD_CTX& md,\n                                                    uint8_t hash_buffer[EVP_MAX_MD_SIZE],\n                                                    unsigned hash_length) {\n  int rc;\n\n  // Hash all the settings that affect whether the server will allow/accept\n  // the client connection. This ensures that the client is always validated against\n  // the correct settings, even if session resumption across different listeners\n  // is enabled.\n  if (ca_cert_ != nullptr) {\n    rc = X509_digest(ca_cert_.get(), EVP_sha256(), hash_buffer, &hash_length);\n    RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n    RELEASE_ASSERT(hash_length == SHA256_DIGEST_LENGTH,\n                   fmt::format(\"invalid SHA256 hash length {}\", hash_length));\n\n    rc = EVP_DigestUpdate(md.get(), hash_buffer, hash_length);\n    RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n  }\n\n  for (const auto& hash : verify_certificate_hash_list_) {\n    rc = EVP_DigestUpdate(md.get(), hash.data(),\n                          hash.size() *\n                              sizeof(std::remove_reference::type::value_type));\n    RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n  }\n\n  for (const auto& hash : verify_certificate_spki_list_) {\n    rc = EVP_DigestUpdate(md.get(), hash.data(),\n                          hash.size() *\n                              sizeof(std::remove_reference::type::value_type));\n    RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n  }\n}", "func_hash": 140411723524972581248505271605198365196, "file_name": "default_validator.cc", "file_hash": 12469299547216327731154844869138538271, "cwe": ["CWE-362"], "cve": "CVE-2022-21654", "cve_desc": "Envoy is an open source edge and service proxy, designed for cloud-native applications. Envoy's tls allows re-use when some cert validation settings have changed from their default configuration. The only workaround for this issue is to ensure that default tls settings are used. Users are advised to upgrade.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21654"}
{"idx": 247550, "project": "envoy", "commit_id": "e9f936d85dc1edc34fabd0a1725ec180f2316353", "project_url": "https://github.com/istio/envoy", "commit_url": "https://github.com/envoyproxy/envoy/commit/e9f936d85dc1edc34fabd0a1725ec180f2316353", "commit_message": "CVE-2022-21654\n\ntls allows re-use when some cert validation settings have changed\n\nSigned-off-by: Yan Avlasov ", "target": 0, "func": "void DefaultCertValidator::updateDigestForSessionId(bssl::ScopedEVP_MD_CTX& md,\n                                                    uint8_t hash_buffer[EVP_MAX_MD_SIZE],\n                                                    unsigned hash_length) {\n  int rc;\n\n  // Hash all the settings that affect whether the server will allow/accept\n  // the client connection. This ensures that the client is always validated against\n  // the correct settings, even if session resumption across different listeners\n  // is enabled.\n  if (ca_cert_ != nullptr) {\n    rc = X509_digest(ca_cert_.get(), EVP_sha256(), hash_buffer, &hash_length);\n    RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n    RELEASE_ASSERT(hash_length == SHA256_DIGEST_LENGTH,\n                   fmt::format(\"invalid SHA256 hash length {}\", hash_length));\n\n    rc = EVP_DigestUpdate(md.get(), hash_buffer, hash_length);\n    RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n  }\n\n  for (const auto& hash : verify_certificate_hash_list_) {\n    rc = EVP_DigestUpdate(md.get(), hash.data(),\n                          hash.size() *\n                              sizeof(std::remove_reference::type::value_type));\n    RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n  }\n\n  for (const auto& hash : verify_certificate_spki_list_) {\n    rc = EVP_DigestUpdate(md.get(), hash.data(),\n                          hash.size() *\n                              sizeof(std::remove_reference::type::value_type));\n    RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n  }\n\n  rc = EVP_DigestUpdate(md.get(), &verify_trusted_ca_, sizeof(verify_trusted_ca_));\n  RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n\n  if (config_ != nullptr) {\n    for (const auto& matcher : config_->subjectAltNameMatchers()) {\n      size_t hash = MessageUtil::hash(matcher);\n      rc = EVP_DigestUpdate(md.get(), &hash, sizeof(hash));\n      RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n    }\n\n    const std::string& crl = config_->certificateRevocationList();\n    if (!crl.empty()) {\n      rc = EVP_DigestUpdate(md.get(), crl.data(), crl.length());\n      RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n    }\n\n    bool allow_expired = config_->allowExpiredCertificate();\n    rc = EVP_DigestUpdate(md.get(), &allow_expired, sizeof(allow_expired));\n    RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n\n    auto trust_chain_verification = config_->trustChainVerification();\n    rc = EVP_DigestUpdate(md.get(), &trust_chain_verification, sizeof(trust_chain_verification));\n    RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n\n    auto only_leaf_crl = config_->onlyVerifyLeafCertificateCrl();\n    rc = EVP_DigestUpdate(md.get(), &only_leaf_crl, sizeof(only_leaf_crl));\n    RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n  }\n}", "func_hash": 325686322374262257116614301181972043862, "file_name": "default_validator.cc", "file_hash": 261316308158712382898480668520478060002, "cwe": ["CWE-362"], "cve": "CVE-2022-21654", "cve_desc": "Envoy is an open source edge and service proxy, designed for cloud-native applications. Envoy's tls allows re-use when some cert validation settings have changed from their default configuration. The only workaround for this issue is to ensure that default tls settings are used. Users are advised to upgrade.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21654"}
{"idx": 196894, "project": "cryptopp", "commit_id": "9425e16437439e68c7d96abef922167d68fafaff", "project_url": "https://github.com/weidai11/cryptopp", "commit_url": "https://github.com/weidai11/cryptopp/commit/9425e16437439e68c7d96abef922167d68fafaff", "commit_message": "Fix for CVE-2015-2141. Thanks to Evgeny Sidorov for reporting. Squaring to satisfy Jacobi requirements suggested by JPM.", "target": 1, "func": "Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const\n{\n\tDoQuickSanityCheck();\n\tModularArithmetic modn(m_n);\n\tInteger r, rInv;\n\tdo {\t// do this in a loop for people using small numbers for testing\n\t\tr.Randomize(rng, Integer::One(), m_n - Integer::One());\n\t\trInv = modn.MultiplicativeInverse(r);\n\t} while (rInv.IsZero());\n\tInteger re = modn.Square(r);\n\tre = modn.Multiply(re, x);\t\t\t// blind\n\n\tInteger cp=re%m_p, cq=re%m_q;\n\tif (Jacobi(cp, m_p) * Jacobi(cq, m_q) != 1)\n\t{\n\t\tcp = cp.IsOdd() ? (cp+m_p) >> 1 : cp >> 1;\n\t\tcq = cq.IsOdd() ? (cq+m_q) >> 1 : cq >> 1;\n\t}\n\n\t#pragma omp parallel\n\t\t#pragma omp sections\n\t\t{\n\t\t\t#pragma omp section\n\t\t\t\tcp = ModularSquareRoot(cp, m_p);\n\t\t\t#pragma omp section\n\t\t\t\tcq = ModularSquareRoot(cq, m_q);\n\t\t}\n\n\tInteger y = CRT(cq, m_q, cp, m_p, m_u);\n\ty = modn.Multiply(y, rInv);\t\t\t\t// unblind\n\ty = STDMIN(y, m_n-y);\n\tif (ApplyFunction(y) != x)\t\t\t\t// check\n\t\tthrow Exception(Exception::OTHER_ERROR, \"InvertibleRWFunction: computational error during private key operation\");\n\treturn y;\n}", "func_hash": 290420030541756407514179370586675759104, "file_name": "rw.cpp", "file_hash": 28365074804944330860384058197646130181, "cwe": ["CWE-399"], "cve": "CVE-2015-2141", "cve_desc": "The InvertibleRWFunction::CalculateInverse function in rw.cpp in libcrypt++ 5.6.2 does not properly blind private key operations for the Rabin-Williams digital signature algorithm, which allows remote attackers to obtain private keys via a timing attack.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-2141"}
{"idx": 247755, "project": "cryptopp", "commit_id": "9425e16437439e68c7d96abef922167d68fafaff", "project_url": "https://github.com/weidai11/cryptopp", "commit_url": "https://github.com/weidai11/cryptopp/commit/9425e16437439e68c7d96abef922167d68fafaff", "commit_message": "Fix for CVE-2015-2141. Thanks to Evgeny Sidorov for reporting. Squaring to satisfy Jacobi requirements suggested by JPM.", "target": 0, "func": "Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const\n{\n\tDoQuickSanityCheck();\n\tModularArithmetic modn(m_n);\n\tInteger r, rInv;\n\n\t// do this in a loop for people using small numbers for testing\n\tdo {\n\t\tr.Randomize(rng, Integer::One(), m_n - Integer::One());\n\t\t// Fix for CVE-2015-2141. Thanks to Evgeny Sidorov for reporting.\n\t\t// Squaring to satisfy Jacobi requirements suggested by JPM.\n\t\tr = modn.Square(r);\n\t\trInv = modn.MultiplicativeInverse(r);\n\t} while (rInv.IsZero());\n\n\tInteger re = modn.Square(r);\n\tre = modn.Multiply(re, x);\t\t\t// blind\n\n\tInteger cp=re%m_p, cq=re%m_q;\n\tif (Jacobi(cp, m_p) * Jacobi(cq, m_q) != 1)\n\t{\n\t\tcp = cp.IsOdd() ? (cp+m_p) >> 1 : cp >> 1;\n\t\tcq = cq.IsOdd() ? (cq+m_q) >> 1 : cq >> 1;\n\t}\n\n\t#pragma omp parallel\n\t\t#pragma omp sections\n\t\t{\n\t\t\t#pragma omp section\n\t\t\t\tcp = ModularSquareRoot(cp, m_p);\n\t\t\t#pragma omp section\n\t\t\t\tcq = ModularSquareRoot(cq, m_q);\n\t\t}\n\n\tInteger y = CRT(cq, m_q, cp, m_p, m_u);\n\ty = modn.Multiply(y, rInv);\t\t\t\t// unblind\n\ty = STDMIN(y, m_n-y);\n\tif (ApplyFunction(y) != x)\t\t\t\t// check\n\t\tthrow Exception(Exception::OTHER_ERROR, \"InvertibleRWFunction: computational error during private key operation\");\n\treturn y;\n}", "func_hash": 219645734588480704184819433477808470944, "file_name": "rw.cpp", "file_hash": 218677143327030170385078111268666623845, "cwe": ["CWE-399"], "cve": "CVE-2015-2141", "cve_desc": "The InvertibleRWFunction::CalculateInverse function in rw.cpp in libcrypt++ 5.6.2 does not properly blind private key operations for the Rabin-Williams digital signature algorithm, which allows remote attackers to obtain private keys via a timing attack.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-2141"}
{"idx": 196993, "project": "libjxl", "commit_id": "7dfa400ded53919d986c5d3d23446a09e0cf481b", "project_url": "https://github.com/libjxl/libjxl", "commit_url": "https://github.com/libjxl/libjxl/commit/7dfa400ded53919d986c5d3d23446a09e0cf481b", "commit_message": "Fix handling of APNG with 0 delay_den (#313)", "target": 1, "func": "Status DecodeImageAPNG(Span bytes, ThreadPool* pool,\n                       CodecInOut* io) {\n  Reader r;\n  unsigned int id, i, j, w, h, w0, h0, x0, y0;\n  unsigned int delay_num, delay_den, dop, bop, rowbytes, imagesize;\n  unsigned char sig[8];\n  png_structp png_ptr;\n  png_infop info_ptr;\n  CHUNK chunk;\n  CHUNK chunkIHDR;\n  std::vector chunksInfo;\n  bool isAnimated = false;\n  bool skipFirst = false;\n  bool hasInfo = false;\n  bool all_dispose_bg = true;\n  APNGFrame frameRaw = {};\n\n  r = {bytes.data(), bytes.data() + bytes.size()};\n  // Not an aPNG => not an error\n  unsigned char png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};\n  if (r.Read(sig, 8) || memcmp(sig, png_signature, 8) != 0) {\n    return false;\n  }\n  id = read_chunk(&r, &chunkIHDR);\n\n  io->frames.clear();\n  io->dec_pixels = 0;\n  io->metadata.m.SetUintSamples(8);\n  io->metadata.m.SetAlphaBits(8);\n  io->metadata.m.color_encoding =\n      ColorEncoding::SRGB();  // todo: get data from png metadata\n  (void)io->dec_hints.Foreach(\n      [](const std::string& key, const std::string& /*value*/) {\n        JXL_WARNING(\"APNG decoder ignoring %s hint\", key.c_str());\n        return true;\n      });\n\n  bool errorstate = true;\n  if (id == kId_IHDR && chunkIHDR.size == 25) {\n    w0 = w = png_get_uint_32(chunkIHDR.p + 8);\n    h0 = h = png_get_uint_32(chunkIHDR.p + 12);\n\n    if (w > cMaxPNGSize || h > cMaxPNGSize) {\n      return false;\n    }\n\n    x0 = 0;\n    y0 = 0;\n    delay_num = 1;\n    delay_den = 10;\n    dop = 0;\n    bop = 0;\n    rowbytes = w * 4;\n    imagesize = h * rowbytes;\n\n    frameRaw.p = new unsigned char[imagesize];\n    frameRaw.rows = new png_bytep[h * sizeof(png_bytep)];\n    for (j = 0; j < h; j++) frameRaw.rows[j] = frameRaw.p + j * rowbytes;\n\n    if (!processing_start(png_ptr, info_ptr, (void*)&frameRaw, hasInfo,\n                          chunkIHDR, chunksInfo)) {\n      bool last_base_was_none = true;\n      while (!r.Eof()) {\n        id = read_chunk(&r, &chunk);\n        if (!id) break;\n        JXL_ASSERT(chunk.p != nullptr);\n\n        if (id == kId_acTL && !hasInfo && !isAnimated) {\n          isAnimated = true;\n          skipFirst = true;\n          io->metadata.m.have_animation = true;\n          io->metadata.m.animation.tps_numerator = 1000;\n        } else if (id == kId_IEND ||\n                   (id == kId_fcTL && (!hasInfo || isAnimated))) {\n          if (hasInfo) {\n            if (!processing_finish(png_ptr, info_ptr)) {\n              ImageBundle bundle(&io->metadata.m);\n              bundle.duration = delay_num * 1000 / delay_den;\n              bundle.origin.x0 = x0;\n              bundle.origin.y0 = y0;\n              // TODO(veluca): this could in principle be implemented.\n              if (last_base_was_none && !all_dispose_bg &&\n                  (x0 != 0 || y0 != 0 || w0 != w || h0 != h || bop != 0)) {\n                return JXL_FAILURE(\n                    \"APNG with dispose-to-0 is not supported for non-full or \"\n                    \"blended frames\");\n              }\n              switch (dop) {\n                case 0:\n                  bundle.use_for_next_frame = true;\n                  last_base_was_none = false;\n                  all_dispose_bg = false;\n                  break;\n                case 2:\n                  bundle.use_for_next_frame = false;\n                  all_dispose_bg = false;\n                  break;\n                default:\n                  bundle.use_for_next_frame = false;\n                  last_base_was_none = true;\n              }\n              bundle.blend = bop != 0;\n              io->dec_pixels += w0 * h0;\n\n              Image3F sub_frame(w0, h0);\n              ImageF sub_frame_alpha(w0, h0);\n              for (size_t y = 0; y < h0; ++y) {\n                float* const JXL_RESTRICT row_r = sub_frame.PlaneRow(0, y);\n                float* const JXL_RESTRICT row_g = sub_frame.PlaneRow(1, y);\n                float* const JXL_RESTRICT row_b = sub_frame.PlaneRow(2, y);\n                float* const JXL_RESTRICT row_alpha = sub_frame_alpha.Row(y);\n                uint8_t* const f = frameRaw.rows[y];\n                for (size_t x = 0; x < w0; ++x) {\n                  if (f[4 * x + 3] == 0) {\n                    row_alpha[x] = 0;\n                    row_r[x] = 0;\n                    row_g[x] = 0;\n                    row_b[x] = 0;\n                    continue;\n                  }\n                  row_r[x] = f[4 * x + 0] * (1.f / 255);\n                  row_g[x] = f[4 * x + 1] * (1.f / 255);\n                  row_b[x] = f[4 * x + 2] * (1.f / 255);\n                  row_alpha[x] = f[4 * x + 3] * (1.f / 255);\n                }\n              }\n              bundle.SetFromImage(std::move(sub_frame), ColorEncoding::SRGB());\n              bundle.SetAlpha(std::move(sub_frame_alpha),\n                              /*alpha_is_premultiplied=*/false);\n              io->frames.push_back(std::move(bundle));\n            } else {\n              delete[] chunk.p;\n              break;\n            }\n          }\n\n          if (id == kId_IEND) {\n            errorstate = false;\n            break;\n          }\n          // At this point the old frame is done. Let's start a new one.\n          w0 = png_get_uint_32(chunk.p + 12);\n          h0 = png_get_uint_32(chunk.p + 16);\n          x0 = png_get_uint_32(chunk.p + 20);\n          y0 = png_get_uint_32(chunk.p + 24);\n          delay_num = png_get_uint_16(chunk.p + 28);\n          delay_den = png_get_uint_16(chunk.p + 30);\n          dop = chunk.p[32];\n          bop = chunk.p[33];\n\n          if (w0 > cMaxPNGSize || h0 > cMaxPNGSize || x0 > cMaxPNGSize ||\n              y0 > cMaxPNGSize || x0 + w0 > w || y0 + h0 > h || dop > 2 ||\n              bop > 1) {\n            delete[] chunk.p;\n            break;\n          }\n\n          if (hasInfo) {\n            memcpy(chunkIHDR.p + 8, chunk.p + 12, 8);\n            if (processing_start(png_ptr, info_ptr, (void*)&frameRaw, hasInfo,\n                                 chunkIHDR, chunksInfo)) {\n              delete[] chunk.p;\n              break;\n            }\n          } else\n            skipFirst = false;\n\n          if (io->frames.size() == (skipFirst ? 1 : 0)) {\n            bop = 0;\n            if (dop == 2) dop = 1;\n          }\n        } else if (id == kId_IDAT) {\n          hasInfo = true;\n          if (processing_data(png_ptr, info_ptr, chunk.p, chunk.size)) {\n            delete[] chunk.p;\n            break;\n          }\n        } else if (id == kId_fdAT && isAnimated) {\n          png_save_uint_32(chunk.p + 4, chunk.size - 16);\n          memcpy(chunk.p + 8, \"IDAT\", 4);\n          if (processing_data(png_ptr, info_ptr, chunk.p + 4, chunk.size - 4)) {\n            delete[] chunk.p;\n            break;\n          }\n        } else if (!isAbc(chunk.p[4]) || !isAbc(chunk.p[5]) ||\n                   !isAbc(chunk.p[6]) || !isAbc(chunk.p[7])) {\n          delete[] chunk.p;\n          break;\n        } else if (!hasInfo) {\n          if (processing_data(png_ptr, info_ptr, chunk.p, chunk.size)) {\n            delete[] chunk.p;\n            break;\n          }\n          chunksInfo.push_back(chunk);\n          continue;\n        }\n        delete[] chunk.p;\n      }\n    }\n    delete[] frameRaw.rows;\n    delete[] frameRaw.p;\n  }\n\n  for (i = 0; i < chunksInfo.size(); i++) delete[] chunksInfo[i].p;\n\n  chunksInfo.clear();\n  delete[] chunkIHDR.p;\n\n  if (errorstate) return false;\n  SetIntensityTarget(io);\n  return true;\n}", "func_hash": 313851366023244520296960010326993371914, "file_name": "codec_apng.cc", "file_hash": 303923165706235443177070807550807665571, "cwe": ["CWE-369"], "cve": "CVE-2021-36692", "cve_desc": "libjxl v0.3.7 is affected by a Divide By Zero in issue in lib/extras/codec_apng.cc jxl::DecodeImageAPNG(). When encoding a malicous APNG file using cjxl, an attacker can trigger a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-36692"}
{"idx": 249510, "project": "libjxl", "commit_id": "7dfa400ded53919d986c5d3d23446a09e0cf481b", "project_url": "https://github.com/libjxl/libjxl", "commit_url": "https://github.com/libjxl/libjxl/commit/7dfa400ded53919d986c5d3d23446a09e0cf481b", "commit_message": "Fix handling of APNG with 0 delay_den (#313)", "target": 0, "func": "Status DecodeImageAPNG(Span bytes, ThreadPool* pool,\n                       CodecInOut* io) {\n  Reader r;\n  unsigned int id, i, j, w, h, w0, h0, x0, y0;\n  unsigned int delay_num, delay_den, dop, bop, rowbytes, imagesize;\n  unsigned char sig[8];\n  png_structp png_ptr;\n  png_infop info_ptr;\n  CHUNK chunk;\n  CHUNK chunkIHDR;\n  std::vector chunksInfo;\n  bool isAnimated = false;\n  bool skipFirst = false;\n  bool hasInfo = false;\n  bool all_dispose_bg = true;\n  APNGFrame frameRaw = {};\n\n  r = {bytes.data(), bytes.data() + bytes.size()};\n  // Not an aPNG => not an error\n  unsigned char png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};\n  if (r.Read(sig, 8) || memcmp(sig, png_signature, 8) != 0) {\n    return false;\n  }\n  id = read_chunk(&r, &chunkIHDR);\n\n  io->frames.clear();\n  io->dec_pixels = 0;\n  io->metadata.m.SetUintSamples(8);\n  io->metadata.m.SetAlphaBits(8);\n  io->metadata.m.color_encoding =\n      ColorEncoding::SRGB();  // todo: get data from png metadata\n  (void)io->dec_hints.Foreach(\n      [](const std::string& key, const std::string& /*value*/) {\n        JXL_WARNING(\"APNG decoder ignoring %s hint\", key.c_str());\n        return true;\n      });\n\n  bool errorstate = true;\n  if (id == kId_IHDR && chunkIHDR.size == 25) {\n    w0 = w = png_get_uint_32(chunkIHDR.p + 8);\n    h0 = h = png_get_uint_32(chunkIHDR.p + 12);\n\n    if (w > cMaxPNGSize || h > cMaxPNGSize) {\n      return false;\n    }\n\n    x0 = 0;\n    y0 = 0;\n    delay_num = 1;\n    delay_den = 10;\n    dop = 0;\n    bop = 0;\n    rowbytes = w * 4;\n    imagesize = h * rowbytes;\n\n    frameRaw.p = new unsigned char[imagesize];\n    frameRaw.rows = new png_bytep[h * sizeof(png_bytep)];\n    for (j = 0; j < h; j++) frameRaw.rows[j] = frameRaw.p + j * rowbytes;\n\n    if (!processing_start(png_ptr, info_ptr, (void*)&frameRaw, hasInfo,\n                          chunkIHDR, chunksInfo)) {\n      bool last_base_was_none = true;\n      while (!r.Eof()) {\n        id = read_chunk(&r, &chunk);\n        if (!id) break;\n        JXL_ASSERT(chunk.p != nullptr);\n\n        if (id == kId_acTL && !hasInfo && !isAnimated) {\n          isAnimated = true;\n          skipFirst = true;\n          io->metadata.m.have_animation = true;\n          io->metadata.m.animation.tps_numerator = 1000;\n        } else if (id == kId_IEND ||\n                   (id == kId_fcTL && (!hasInfo || isAnimated))) {\n          if (hasInfo) {\n            if (!processing_finish(png_ptr, info_ptr)) {\n              ImageBundle bundle(&io->metadata.m);\n              bundle.duration = delay_num * 1000 / delay_den;\n              bundle.origin.x0 = x0;\n              bundle.origin.y0 = y0;\n              // TODO(veluca): this could in principle be implemented.\n              if (last_base_was_none && !all_dispose_bg &&\n                  (x0 != 0 || y0 != 0 || w0 != w || h0 != h || bop != 0)) {\n                return JXL_FAILURE(\n                    \"APNG with dispose-to-0 is not supported for non-full or \"\n                    \"blended frames\");\n              }\n              switch (dop) {\n                case 0:\n                  bundle.use_for_next_frame = true;\n                  last_base_was_none = false;\n                  all_dispose_bg = false;\n                  break;\n                case 2:\n                  bundle.use_for_next_frame = false;\n                  all_dispose_bg = false;\n                  break;\n                default:\n                  bundle.use_for_next_frame = false;\n                  last_base_was_none = true;\n              }\n              bundle.blend = bop != 0;\n              io->dec_pixels += w0 * h0;\n\n              Image3F sub_frame(w0, h0);\n              ImageF sub_frame_alpha(w0, h0);\n              for (size_t y = 0; y < h0; ++y) {\n                float* const JXL_RESTRICT row_r = sub_frame.PlaneRow(0, y);\n                float* const JXL_RESTRICT row_g = sub_frame.PlaneRow(1, y);\n                float* const JXL_RESTRICT row_b = sub_frame.PlaneRow(2, y);\n                float* const JXL_RESTRICT row_alpha = sub_frame_alpha.Row(y);\n                uint8_t* const f = frameRaw.rows[y];\n                for (size_t x = 0; x < w0; ++x) {\n                  if (f[4 * x + 3] == 0) {\n                    row_alpha[x] = 0;\n                    row_r[x] = 0;\n                    row_g[x] = 0;\n                    row_b[x] = 0;\n                    continue;\n                  }\n                  row_r[x] = f[4 * x + 0] * (1.f / 255);\n                  row_g[x] = f[4 * x + 1] * (1.f / 255);\n                  row_b[x] = f[4 * x + 2] * (1.f / 255);\n                  row_alpha[x] = f[4 * x + 3] * (1.f / 255);\n                }\n              }\n              bundle.SetFromImage(std::move(sub_frame), ColorEncoding::SRGB());\n              bundle.SetAlpha(std::move(sub_frame_alpha),\n                              /*alpha_is_premultiplied=*/false);\n              io->frames.push_back(std::move(bundle));\n            } else {\n              delete[] chunk.p;\n              break;\n            }\n          }\n\n          if (id == kId_IEND) {\n            errorstate = false;\n            break;\n          }\n          // At this point the old frame is done. Let's start a new one.\n          w0 = png_get_uint_32(chunk.p + 12);\n          h0 = png_get_uint_32(chunk.p + 16);\n          x0 = png_get_uint_32(chunk.p + 20);\n          y0 = png_get_uint_32(chunk.p + 24);\n          delay_num = png_get_uint_16(chunk.p + 28);\n          delay_den = png_get_uint_16(chunk.p + 30);\n          dop = chunk.p[32];\n          bop = chunk.p[33];\n\n          if (!delay_den) delay_den = 100;\n\n          if (w0 > cMaxPNGSize || h0 > cMaxPNGSize || x0 > cMaxPNGSize ||\n              y0 > cMaxPNGSize || x0 + w0 > w || y0 + h0 > h || dop > 2 ||\n              bop > 1) {\n            delete[] chunk.p;\n            break;\n          }\n\n          if (hasInfo) {\n            memcpy(chunkIHDR.p + 8, chunk.p + 12, 8);\n            if (processing_start(png_ptr, info_ptr, (void*)&frameRaw, hasInfo,\n                                 chunkIHDR, chunksInfo)) {\n              delete[] chunk.p;\n              break;\n            }\n          } else\n            skipFirst = false;\n\n          if (io->frames.size() == (skipFirst ? 1 : 0)) {\n            bop = 0;\n            if (dop == 2) dop = 1;\n          }\n        } else if (id == kId_IDAT) {\n          hasInfo = true;\n          if (processing_data(png_ptr, info_ptr, chunk.p, chunk.size)) {\n            delete[] chunk.p;\n            break;\n          }\n        } else if (id == kId_fdAT && isAnimated) {\n          png_save_uint_32(chunk.p + 4, chunk.size - 16);\n          memcpy(chunk.p + 8, \"IDAT\", 4);\n          if (processing_data(png_ptr, info_ptr, chunk.p + 4, chunk.size - 4)) {\n            delete[] chunk.p;\n            break;\n          }\n        } else if (!isAbc(chunk.p[4]) || !isAbc(chunk.p[5]) ||\n                   !isAbc(chunk.p[6]) || !isAbc(chunk.p[7])) {\n          delete[] chunk.p;\n          break;\n        } else if (!hasInfo) {\n          if (processing_data(png_ptr, info_ptr, chunk.p, chunk.size)) {\n            delete[] chunk.p;\n            break;\n          }\n          chunksInfo.push_back(chunk);\n          continue;\n        }\n        delete[] chunk.p;\n      }\n    }\n    delete[] frameRaw.rows;\n    delete[] frameRaw.p;\n  }\n\n  for (i = 0; i < chunksInfo.size(); i++) delete[] chunksInfo[i].p;\n\n  chunksInfo.clear();\n  delete[] chunkIHDR.p;\n\n  if (errorstate) return false;\n  SetIntensityTarget(io);\n  return true;\n}", "func_hash": 120159629770079906091018300159930359241, "file_name": "codec_apng.cc", "file_hash": 71568842210478250977539605329835891073, "cwe": ["CWE-369"], "cve": "CVE-2021-36692", "cve_desc": "libjxl v0.3.7 is affected by a Divide By Zero in issue in lib/extras/codec_apng.cc jxl::DecodeImageAPNG(). When encoding a malicous APNG file using cjxl, an attacker can trigger a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-36692"}
{"idx": 197015, "project": "gpac", "commit_id": "dae9900580a8888969481cd72035408091edb11b", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/dae9900580a8888969481cd72035408091edb11b", "commit_message": "fixed #1659", "target": 1, "func": "GF_Err SetupWriters(MovieWriter *mw, GF_List *writers, u8 interleaving)\n{\n\tu32 i, trackCount;\n\tTrackWriter *writer;\n\tGF_TrackBox *trak;\n\tGF_ISOFile *movie = mw->movie;\n\n\tmw->total_samples = mw->nb_done = 0;\n\tif (!movie->moov) return GF_OK;\n\n\ttrackCount = gf_list_count(movie->moov->trackList);\n\tfor (i = 0; i < trackCount; i++) {\n\t\ttrak = gf_isom_get_track(movie->moov, i+1);\n\n\t\tGF_SAFEALLOC(writer, TrackWriter);\n\t\tif (!writer) goto exit;\n\t\twriter->sampleNumber = 1;\n\t\twriter->mdia = trak->Media;\n\t\twriter->stbl = trak->Media->information->sampleTable;\n\t\twriter->timeScale = trak->Media->mediaHeader->timeScale;\n\t\twriter->all_dref_mode = Media_SelfContainedType(writer->mdia);\n\n\t\tif (trak->sample_encryption)\n\t\t\twriter->prevent_dispatch = GF_TRUE;\n\n\t\twriter->isDone = 0;\n\t\twriter->DTSprev = 0;\n\t\twriter->chunkDur = 0;\n\t\twriter->chunkSize = 0;\n\t\twriter->constant_size = writer->constant_dur = 0;\n\t\tif (writer->stbl->SampleSize->sampleSize)\n\t\t\twriter->constant_size = writer->stbl->SampleSize->sampleSize;\n\t\tif (writer->stbl->TimeToSample->nb_entries==1) {\n\t\t\twriter->constant_dur = writer->stbl->TimeToSample->entries[0].sampleDelta;\n\t\t\tif (writer->constant_dur>1) writer->constant_dur = 0;\n\t\t}\n\t\tif (!writer->constant_dur || !writer->constant_size || (writer->constant_size>=10))\n\t\t\twriter->constant_size = writer->constant_dur = 0;\n\n\t\twriter->stsc = (GF_SampleToChunkBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_STSC);\n\t\tif (!writer->stsc) return GF_OUT_OF_MEM;\n\t\tif (writer->stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\t\twriter->stco = gf_isom_box_new(GF_ISOM_BOX_TYPE_STCO);\n\t\t} else {\n\t\t\twriter->stco = gf_isom_box_new(GF_ISOM_BOX_TYPE_CO64);\n\t\t}\n\t\tif (!writer->stco) return GF_OUT_OF_MEM;\n\t\t/*stops from chunk escape*/\n\t\tif (interleaving) writer->stbl->MaxSamplePerChunk = 0;\n\t\t/*for progress, assume only one descIndex*/\n\t\tif (Media_IsSelfContained(writer->mdia, 1))\n\t\t\tmw->total_samples += writer->stbl->SampleSize->sampleCount;\n\t\t/*optimization for interleaving: put audio last (this can be overridden by priorities)*/\n\t\tif (movie->storageMode != GF_ISOM_STORE_INTERLEAVED) {\n\t\t\tgf_list_add(writers, writer);\n\t\t} else {\n\t\t\tif (writer->mdia->information->InfoHeader && writer->mdia->information->InfoHeader->type == GF_ISOM_BOX_TYPE_SMHD) {\n\t\t\t\tgf_list_add(writers, writer);\n\t\t\t} else {\n\t\t\t\tgf_list_insert(writers, writer, 0);\n\t\t\t}\n\t\t}\n\t\tif (movie->sample_groups_in_traf && trak->Media->information->sampleTable) {\n\t\t\tgf_isom_box_array_del_parent(&trak->Media->information->sampleTable->child_boxes, trak->Media->information->sampleTable->sampleGroupsDescription);\n\t\t\ttrak->Media->information->sampleTable->sampleGroupsDescription = NULL;\n\t\t}\n\t}\n\treturn GF_OK;\n\nexit:\n\tCleanWriters(writers);\n\treturn GF_OUT_OF_MEM;\n}", "func_hash": 186223260006462489135452631752417424978, "file_name": "isom_store.c", "file_hash": 163429096111764821481093789064862178187, "cwe": ["CWE-476"], "cve": "CVE-2020-35981", "cve_desc": "An issue was discovered in GPAC version 0.8.0 and 1.0.1. There is an invalid pointer dereference in the function SetupWriters() in isomedia/isom_store.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35981"}
{"idx": 249989, "project": "gpac", "commit_id": "dae9900580a8888969481cd72035408091edb11b", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/dae9900580a8888969481cd72035408091edb11b", "commit_message": "fixed #1659", "target": 0, "func": "GF_Err SetupWriters(MovieWriter *mw, GF_List *writers, u8 interleaving)\n{\n\tu32 i, trackCount;\n\tTrackWriter *writer;\n\tGF_TrackBox *trak;\n\tGF_ISOFile *movie = mw->movie;\n\n\tmw->total_samples = mw->nb_done = 0;\n\tif (!movie->moov) return GF_OK;\n\n\ttrackCount = gf_list_count(movie->moov->trackList);\n\tfor (i = 0; i < trackCount; i++) {\n\t\tGF_SampleTableBox *stbl;\n\t\ttrak = gf_isom_get_track(movie->moov, i+1);\n\n\t\tstbl = (trak->Media && trak->Media->information) ? trak->Media->information->sampleTable : NULL;\n\t\tif (!stbl || !stbl->SampleSize || !stbl->ChunkOffset || !stbl->SampleToChunk) {\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\t\tGF_SAFEALLOC(writer, TrackWriter);\n\t\tif (!writer) goto exit;\n\t\twriter->sampleNumber = 1;\n\t\twriter->mdia = trak->Media;\n\t\twriter->stbl = trak->Media->information->sampleTable;\n\t\twriter->timeScale = trak->Media->mediaHeader->timeScale;\n\t\twriter->all_dref_mode = Media_SelfContainedType(writer->mdia);\n\n\t\tif (trak->sample_encryption)\n\t\t\twriter->prevent_dispatch = GF_TRUE;\n\n\t\twriter->isDone = 0;\n\t\twriter->DTSprev = 0;\n\t\twriter->chunkDur = 0;\n\t\twriter->chunkSize = 0;\n\t\twriter->constant_size = writer->constant_dur = 0;\n\t\tif (writer->stbl->SampleSize->sampleSize)\n\t\t\twriter->constant_size = writer->stbl->SampleSize->sampleSize;\n\t\tif (writer->stbl->TimeToSample->nb_entries==1) {\n\t\t\twriter->constant_dur = writer->stbl->TimeToSample->entries[0].sampleDelta;\n\t\t\tif (writer->constant_dur>1) writer->constant_dur = 0;\n\t\t}\n\t\tif (!writer->constant_dur || !writer->constant_size || (writer->constant_size>=10))\n\t\t\twriter->constant_size = writer->constant_dur = 0;\n\n\t\twriter->stsc = (GF_SampleToChunkBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_STSC);\n\t\tif (!writer->stsc) return GF_OUT_OF_MEM;\n\t\tif (writer->stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\t\twriter->stco = gf_isom_box_new(GF_ISOM_BOX_TYPE_STCO);\n\t\t} else {\n\t\t\twriter->stco = gf_isom_box_new(GF_ISOM_BOX_TYPE_CO64);\n\t\t}\n\t\tif (!writer->stco) return GF_OUT_OF_MEM;\n\t\t/*stops from chunk escape*/\n\t\tif (interleaving) writer->stbl->MaxSamplePerChunk = 0;\n\t\t/*for progress, assume only one descIndex*/\n\t\tif (Media_IsSelfContained(writer->mdia, 1))\n\t\t\tmw->total_samples += writer->stbl->SampleSize->sampleCount;\n\t\t/*optimization for interleaving: put audio last (this can be overridden by priorities)*/\n\t\tif (movie->storageMode != GF_ISOM_STORE_INTERLEAVED) {\n\t\t\tgf_list_add(writers, writer);\n\t\t} else {\n\t\t\tif (writer->mdia->information->InfoHeader && writer->mdia->information->InfoHeader->type == GF_ISOM_BOX_TYPE_SMHD) {\n\t\t\t\tgf_list_add(writers, writer);\n\t\t\t} else {\n\t\t\t\tgf_list_insert(writers, writer, 0);\n\t\t\t}\n\t\t}\n\t\tif (movie->sample_groups_in_traf && trak->Media->information->sampleTable) {\n\t\t\tgf_isom_box_array_del_parent(&trak->Media->information->sampleTable->child_boxes, trak->Media->information->sampleTable->sampleGroupsDescription);\n\t\t\ttrak->Media->information->sampleTable->sampleGroupsDescription = NULL;\n\t\t}\n\t}\n\treturn GF_OK;\n\nexit:\n\tCleanWriters(writers);\n\treturn GF_OUT_OF_MEM;\n}", "func_hash": 296089217308000127694937850240852623280, "file_name": "isom_store.c", "file_hash": 338457397792726647767624897587669032469, "cwe": ["CWE-476"], "cve": "CVE-2020-35981", "cve_desc": "An issue was discovered in GPAC version 0.8.0 and 1.0.1. There is an invalid pointer dereference in the function SetupWriters() in isomedia/isom_store.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35981"}
{"idx": 197057, "project": "drogon", "commit_id": "3c785326c63a34aa1799a639ae185bc9453cb447", "project_url": "https://github.com/drogonframework/drogon", "commit_url": "https://github.com/drogonframework/drogon/commit/3c785326c63a34aa1799a639ae185bc9453cb447", "commit_message": "Prevent malformed upload path causing arbitrary write (#1174)", "target": 1, "func": "int HttpFileImpl::save(const std::string &path) const\n{\n    assert(!path.empty());\n    if (fileName_.empty())\n        return -1;\n    filesystem::path fsPath(utils::toNativePath(path));\n    if (!fsPath.is_absolute() &&\n        (!fsPath.has_parent_path() ||\n         (fsPath.begin()->string() != \".\" && fsPath.begin()->string() != \"..\")))\n    {\n        filesystem::path fsUploadPath(utils::toNativePath(\n            HttpAppFrameworkImpl::instance().getUploadPath()));\n        fsPath = fsUploadPath / fsPath;\n    }\n    filesystem::path fsFileName(utils::toNativePath(fileName_));\n    if (!filesystem::exists(fsPath))\n    {\n        LOG_TRACE << \"create path:\" << fsPath;\n        drogon::error_code err;\n        filesystem::create_directories(fsPath, err);\n        if (err)\n        {\n            LOG_SYSERR;\n            return -1;\n        }\n    }\n    return saveTo(fsPath / fsFileName);\n}", "func_hash": 314463188138781431986696466899338798829, "file_name": "None", "file_hash": null, "cwe": ["CWE-552"], "cve": "CVE-2022-25297", "cve_desc": "This affects the package drogonframework/drogon before 1.7.5. The unsafe handling of file names during upload using HttpFile::save() method may enable attackers to write files to arbitrary locations outside the designated target folder.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-25297"}
{"idx": 250692, "project": "drogon", "commit_id": "3c785326c63a34aa1799a639ae185bc9453cb447", "project_url": "https://github.com/drogonframework/drogon", "commit_url": "https://github.com/drogonframework/drogon/commit/3c785326c63a34aa1799a639ae185bc9453cb447", "commit_message": "Prevent malformed upload path causing arbitrary write (#1174)", "target": 0, "func": "int HttpFileImpl::saveAs(const std::string &fileName) const\n{\n    assert(!fileName.empty());\n    filesystem::path fsFileName(utils::toNativePath(fileName));\n    if (!fsFileName.is_absolute() && (!fsFileName.has_parent_path() ||\n                                      (fsFileName.begin()->string() != \".\" &&\n                                       fsFileName.begin()->string() != \"..\")))\n    {\n        filesystem::path fsUploadPath(utils::toNativePath(\n            HttpAppFrameworkImpl::instance().getUploadPath()));\n        fsFileName = fsUploadPath / fsFileName;\n    }\n    if (fsFileName.has_parent_path() &&\n        !filesystem::exists(fsFileName.parent_path()))\n    {\n        LOG_TRACE << \"create path:\" << fsFileName.parent_path();\n        drogon::error_code err;\n        filesystem::create_directories(fsFileName.parent_path(), err);\n        if (err)\n        {\n            LOG_SYSERR;\n            return -1;\n        }\n    }\n    return saveTo(fsFileName);\n}", "func_hash": 130624185763099199387957900171257914087, "file_name": "None", "file_hash": null, "cwe": ["CWE-552"], "cve": "CVE-2022-25297", "cve_desc": "This affects the package drogonframework/drogon before 1.7.5. The unsafe handling of file names during upload using HttpFile::save() method may enable attackers to write files to arbitrary locations outside the designated target folder.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-25297"}
{"idx": 197095, "project": "tensorflow", "commit_id": "15691e456c7dc9bd6be203b09765b063bf4a380c", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/15691e456c7dc9bd6be203b09765b063bf4a380c", "commit_message": "Prevent dereferencing of null pointers in TFLite's `add.cc`.\n\nPiperOrigin-RevId: 387244946\nChange-Id: I56094233327fbd8439b92e1dbb1262176e00eeb9", "target": 1, "func": "inline void BinaryBroadcastFiveFold(const ArithmeticParams& unswitched_params,\n                                    const RuntimeShape& unswitched_input1_shape,\n                                    const T* unswitched_input1_data,\n                                    const RuntimeShape& unswitched_input2_shape,\n                                    const T* unswitched_input2_data,\n                                    const RuntimeShape& output_shape,\n                                    T* output_data, ElementwiseF elementwise_f,\n                                    ScalarBroadcastF scalar_broadcast_f) {\n  ArithmeticParams switched_params = unswitched_params;\n  switched_params.input1_offset = unswitched_params.input2_offset;\n  switched_params.input1_multiplier = unswitched_params.input2_multiplier;\n  switched_params.input1_shift = unswitched_params.input2_shift;\n  switched_params.input2_offset = unswitched_params.input1_offset;\n  switched_params.input2_multiplier = unswitched_params.input1_multiplier;\n  switched_params.input2_shift = unswitched_params.input1_shift;\n\n  const bool use_unswitched =\n      unswitched_params.broadcast_category ==\n      tflite::BroadcastableOpCategory::kFirstInputBroadcastsFast;\n\n  const ArithmeticParams& params =\n      use_unswitched ? unswitched_params : switched_params;\n  const T* input1_data =\n      use_unswitched ? unswitched_input1_data : unswitched_input2_data;\n  const T* input2_data =\n      use_unswitched ? unswitched_input2_data : unswitched_input1_data;\n\n  // Fivefold nested loops. The second input resets its position for each\n  // iteration of the second loop. The first input resets its position at the\n  // beginning of the fourth loop. The innermost loop is an elementwise add of\n  // sections of the arrays.\n  T* output_data_ptr = output_data;\n  const T* input1_data_ptr = input1_data;\n  const T* input2_data_reset = input2_data;\n  // In the fivefold pattern, y0, y2 and y4 are not broadcast, and so shared\n  // between input shapes. y3 for input 1 is always broadcast, and so the\n  // dimension there is 1, whereas optionally y1 might be broadcast for\n  // input 2. Put another way, input1.shape.FlatSize = y0 * y1 * y2 * y4,\n  // input2.shape.FlatSize = y0 * y2 * y3 * y4.\n  int y0 = params.broadcast_shape[0];\n  int y1 = params.broadcast_shape[1];\n  int y2 = params.broadcast_shape[2];\n  int y3 = params.broadcast_shape[3];\n  int y4 = params.broadcast_shape[4];\n  if (y4 > 1) {\n    // General fivefold pattern, with y4 > 1 so there is a non-broadcast inner\n    // dimension.\n    for (int i0 = 0; i0 < y0; ++i0) {\n      const T* input2_data_ptr = nullptr;\n      for (int i1 = 0; i1 < y1; ++i1) {\n        input2_data_ptr = input2_data_reset;\n        for (int i2 = 0; i2 < y2; ++i2) {\n          for (int i3 = 0; i3 < y3; ++i3) {\n            elementwise_f(y4, params, input1_data_ptr, input2_data_ptr,\n                          output_data_ptr);\n            input2_data_ptr += y4;\n            output_data_ptr += y4;\n          }\n          // We have broadcast y4 of input1 data y3 times, and now move on.\n          input1_data_ptr += y4;\n        }\n      }\n      // We have broadcast y2*y3*y4 of input2 data y1 times, and now move on.\n      input2_data_reset = input2_data_ptr;\n    }\n  } else {\n    // Special case of y4 == 1, in which the innermost loop is a single\n    // element and can be combined with the next (y3) as an inner broadcast.\n    //\n    // Note that this handles the case of pure scalar broadcast when\n    // y0 == y1 == y2 == 1. With low overhead it handles cases such as scalar\n    // broadcast with batch (as y2 > 1).\n    //\n    // NOTE The process is the same as the above general case except\n    // simplified for y4 == 1 and the loop over y3 is contained within the\n    // AddScalarBroadcast function.\n    for (int i0 = 0; i0 < y0; ++i0) {\n      const T* input2_data_ptr = nullptr;\n      for (int i1 = 0; i1 < y1; ++i1) {\n        input2_data_ptr = input2_data_reset;\n        for (int i2 = 0; i2 < y2; ++i2) {\n          scalar_broadcast_f(y3, params, *input1_data_ptr, input2_data_ptr,\n                             output_data_ptr);\n          input2_data_ptr += y3;\n          output_data_ptr += y3;\n          input1_data_ptr += 1;\n        }\n      }\n      input2_data_reset = input2_data_ptr;\n    }\n  }\n}", "func_hash": 189506316609912057332068378278926028013, "file_name": "optimized_ops.h", "file_hash": 272937509923686290195986142976705267114, "cwe": ["CWE-369"], "cve": "CVE-2021-37688", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can craft a TFLite model that would trigger a null pointer dereference, which would result in a crash and denial of service. The [implementation](https://github.com/tensorflow/tensorflow/blob/149562d49faa709ea80df1d99fc41d005b81082a/tensorflow/lite/kernels/internal/optimized/optimized_ops.h#L268-L285) unconditionally dereferences a pointer. We have patched the issue in GitHub commit 15691e456c7dc9bd6be203b09765b063bf4a380c. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37688"}
{"idx": 251946, "project": "tensorflow", "commit_id": "15691e456c7dc9bd6be203b09765b063bf4a380c", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/15691e456c7dc9bd6be203b09765b063bf4a380c", "commit_message": "Prevent dereferencing of null pointers in TFLite's `add.cc`.\n\nPiperOrigin-RevId: 387244946\nChange-Id: I56094233327fbd8439b92e1dbb1262176e00eeb9", "target": 0, "func": "inline void BinaryBroadcastFiveFold(const ArithmeticParams& unswitched_params,\n                                    const RuntimeShape& unswitched_input1_shape,\n                                    const T* unswitched_input1_data,\n                                    const RuntimeShape& unswitched_input2_shape,\n                                    const T* unswitched_input2_data,\n                                    const RuntimeShape& output_shape,\n                                    T* output_data, ElementwiseF elementwise_f,\n                                    ScalarBroadcastF scalar_broadcast_f) {\n  ArithmeticParams switched_params = unswitched_params;\n  switched_params.input1_offset = unswitched_params.input2_offset;\n  switched_params.input1_multiplier = unswitched_params.input2_multiplier;\n  switched_params.input1_shift = unswitched_params.input2_shift;\n  switched_params.input2_offset = unswitched_params.input1_offset;\n  switched_params.input2_multiplier = unswitched_params.input1_multiplier;\n  switched_params.input2_shift = unswitched_params.input1_shift;\n\n  const bool use_unswitched =\n      unswitched_params.broadcast_category ==\n      tflite::BroadcastableOpCategory::kFirstInputBroadcastsFast;\n\n  const ArithmeticParams& params =\n      use_unswitched ? unswitched_params : switched_params;\n  const T* input1_data =\n      use_unswitched ? unswitched_input1_data : unswitched_input2_data;\n  const T* input2_data =\n      use_unswitched ? unswitched_input2_data : unswitched_input1_data;\n\n  // Fivefold nested loops. The second input resets its position for each\n  // iteration of the second loop. The first input resets its position at the\n  // beginning of the fourth loop. The innermost loop is an elementwise add of\n  // sections of the arrays.\n  T* output_data_ptr = output_data;\n  const T* input1_data_ptr = input1_data;\n  const T* input2_data_reset = input2_data;\n  // In the fivefold pattern, y0, y2 and y4 are not broadcast, and so shared\n  // between input shapes. y3 for input 1 is always broadcast, and so the\n  // dimension there is 1, whereas optionally y1 might be broadcast for\n  // input 2. Put another way, input1.shape.FlatSize = y0 * y1 * y2 * y4,\n  // input2.shape.FlatSize = y0 * y2 * y3 * y4.\n  int y0 = params.broadcast_shape[0];\n  int y1 = params.broadcast_shape[1];\n  int y2 = params.broadcast_shape[2];\n  int y3 = params.broadcast_shape[3];\n  int y4 = params.broadcast_shape[4];\n  if (y4 > 1) {\n    // General fivefold pattern, with y4 > 1 so there is a non-broadcast inner\n    // dimension.\n    for (int i0 = 0; i0 < y0; ++i0) {\n      const T* input2_data_ptr = nullptr;\n      for (int i1 = 0; i1 < y1; ++i1) {\n        input2_data_ptr = input2_data_reset;\n        for (int i2 = 0; i2 < y2; ++i2) {\n          for (int i3 = 0; i3 < y3; ++i3) {\n            elementwise_f(y4, params, input1_data_ptr, input2_data_ptr,\n                          output_data_ptr);\n            input2_data_ptr += y4;\n            output_data_ptr += y4;\n          }\n          // We have broadcast y4 of input1 data y3 times, and now move on.\n          input1_data_ptr += y4;\n        }\n      }\n      // We have broadcast y2*y3*y4 of input2 data y1 times, and now move on.\n      input2_data_reset = input2_data_ptr;\n    }\n  } else if (input1_data_ptr != nullptr) {\n    // Special case of y4 == 1, in which the innermost loop is a single\n    // element and can be combined with the next (y3) as an inner broadcast.\n    //\n    // Note that this handles the case of pure scalar broadcast when\n    // y0 == y1 == y2 == 1. With low overhead it handles cases such as scalar\n    // broadcast with batch (as y2 > 1).\n    //\n    // NOTE The process is the same as the above general case except\n    // simplified for y4 == 1 and the loop over y3 is contained within the\n    // AddScalarBroadcast function.\n    for (int i0 = 0; i0 < y0; ++i0) {\n      const T* input2_data_ptr = nullptr;\n      for (int i1 = 0; i1 < y1; ++i1) {\n        input2_data_ptr = input2_data_reset;\n        for (int i2 = 0; i2 < y2; ++i2) {\n          scalar_broadcast_f(y3, params, *input1_data_ptr, input2_data_ptr,\n                             output_data_ptr);\n          input2_data_ptr += y3;\n          output_data_ptr += y3;\n          input1_data_ptr += 1;\n        }\n      }\n      input2_data_reset = input2_data_ptr;\n    }\n  }\n}", "func_hash": 63045231057409915908146244179275974599, "file_name": "optimized_ops.h", "file_hash": 177051404573399480037200295059071309532, "cwe": ["CWE-369"], "cve": "CVE-2021-37688", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can craft a TFLite model that would trigger a null pointer dereference, which would result in a crash and denial of service. The [implementation](https://github.com/tensorflow/tensorflow/blob/149562d49faa709ea80df1d99fc41d005b81082a/tensorflow/lite/kernels/internal/optimized/optimized_ops.h#L268-L285) unconditionally dereferences a pointer. We have patched the issue in GitHub commit 15691e456c7dc9bd6be203b09765b063bf4a380c. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37688"}
{"idx": 197111, "project": "tinyexr", "commit_id": "a685e3332f61cd4e59324bf3f669d36973d64270", "project_url": "https://github.com/syoyo/tinyexr", "commit_url": "https://github.com/syoyo/tinyexr/commit/a685e3332f61cd4e59324bf3f669d36973d64270", "commit_message": "Make line_no with too large value(2**20) invalid. Fixes #124", "target": 1, "func": "static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header,\n                       const std::vector &offsets,\n                       const unsigned char *head, const size_t size,\n                       std::string *err) {\n  int num_channels = exr_header->num_channels;\n\n  int num_scanline_blocks = 1;\n  if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {\n    num_scanline_blocks = 16;\n  } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {\n    num_scanline_blocks = 32;\n  } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {\n    num_scanline_blocks = 16;\n  }\n\n  int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1;\n  int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1;\n\n  if ((data_width < 0) || (data_height < 0)) {\n    if (err) {\n      std::stringstream ss;\n      ss << \"Invalid data width or data height: \" << data_width << \", \"\n         << data_height << std::endl;\n      (*err) += ss.str();\n    }\n    return TINYEXR_ERROR_INVALID_DATA;\n  }\n\n  // Do not allow too large data_width and data_height. header invalid?\n  {\n    const int threshold = 1024 * 8192;  // heuristics\n    if ((data_width > threshold) || (data_height > threshold)) {\n      if (err) {\n        std::stringstream ss;\n        ss << \"data_with or data_height too large. data_width: \" << data_width\n           << \", \"\n           << \"data_height = \" << data_height << std::endl;\n        (*err) += ss.str();\n      }\n      return TINYEXR_ERROR_INVALID_DATA;\n    }\n  }\n\n  size_t num_blocks = offsets.size();\n\n  std::vector channel_offset_list;\n  int pixel_data_size = 0;\n  size_t channel_offset = 0;\n  if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size,\n                                     &channel_offset, num_channels,\n                                     exr_header->channels)) {\n    if (err) {\n      (*err) += \"Failed to compute channel layout.\\n\";\n    }\n    return TINYEXR_ERROR_INVALID_DATA;\n  }\n\n  bool invalid_data = false;  // TODO(LTE): Use atomic lock for MT safety.\n\n  if (exr_header->tiled) {\n    // value check\n    if (exr_header->tile_size_x < 0) {\n      if (err) {\n        std::stringstream ss;\n        ss << \"Invalid tile size x : \" << exr_header->tile_size_x << \"\\n\";\n        (*err) += ss.str();\n      }\n      return TINYEXR_ERROR_INVALID_HEADER;\n    }\n\n    if (exr_header->tile_size_y < 0) {\n      if (err) {\n        std::stringstream ss;\n        ss << \"Invalid tile size y : \" << exr_header->tile_size_y << \"\\n\";\n        (*err) += ss.str();\n      }\n      return TINYEXR_ERROR_INVALID_HEADER;\n    }\n\n    size_t num_tiles = offsets.size();  // = # of blocks\n\n    exr_image->tiles = static_cast(\n        calloc(sizeof(EXRTile), static_cast(num_tiles)));\n\n    for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) {\n      // Allocate memory for each tile.\n      exr_image->tiles[tile_idx].images = tinyexr::AllocateImage(\n          num_channels, exr_header->channels, exr_header->requested_pixel_types,\n          exr_header->tile_size_x, exr_header->tile_size_y);\n\n      // 16 byte: tile coordinates\n      // 4 byte : data size\n      // ~      : data(uncompressed or compressed)\n      if (offsets[tile_idx] + sizeof(int) * 5 > size) {\n        if (err) {\n          (*err) += \"Insufficient data size.\\n\";\n        }\n        return TINYEXR_ERROR_INVALID_DATA;\n      }\n\n      size_t data_size = size_t(size - (offsets[tile_idx] + sizeof(int) * 5));\n      const unsigned char *data_ptr =\n          reinterpret_cast(head + offsets[tile_idx]);\n\n      int tile_coordinates[4];\n      memcpy(tile_coordinates, data_ptr, sizeof(int) * 4);\n      tinyexr::swap4(reinterpret_cast(&tile_coordinates[0]));\n      tinyexr::swap4(reinterpret_cast(&tile_coordinates[1]));\n      tinyexr::swap4(reinterpret_cast(&tile_coordinates[2]));\n      tinyexr::swap4(reinterpret_cast(&tile_coordinates[3]));\n\n      // @todo{ LoD }\n      if (tile_coordinates[2] != 0) {\n        return TINYEXR_ERROR_UNSUPPORTED_FEATURE;\n      }\n      if (tile_coordinates[3] != 0) {\n        return TINYEXR_ERROR_UNSUPPORTED_FEATURE;\n      }\n\n      int data_len;\n      memcpy(&data_len, data_ptr + 16,\n             sizeof(int));  // 16 = sizeof(tile_coordinates)\n      tinyexr::swap4(reinterpret_cast(&data_len));\n\n      if (data_len < 4 || size_t(data_len) > data_size) {\n        if (err) {\n          (*err) += \"Insufficient data length.\\n\";\n        }\n        return TINYEXR_ERROR_INVALID_DATA;\n      }\n\n      // Move to data addr: 20 = 16 + 4;\n      data_ptr += 20;\n\n      tinyexr::DecodeTiledPixelData(\n          exr_image->tiles[tile_idx].images,\n          &(exr_image->tiles[tile_idx].width),\n          &(exr_image->tiles[tile_idx].height),\n          exr_header->requested_pixel_types, data_ptr,\n          static_cast(data_len), exr_header->compression_type,\n          exr_header->line_order, data_width, data_height, tile_coordinates[0],\n          tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y,\n          static_cast(pixel_data_size),\n          static_cast(exr_header->num_custom_attributes),\n          exr_header->custom_attributes,\n          static_cast(exr_header->num_channels), exr_header->channels,\n          channel_offset_list);\n\n      exr_image->tiles[tile_idx].offset_x = tile_coordinates[0];\n      exr_image->tiles[tile_idx].offset_y = tile_coordinates[1];\n      exr_image->tiles[tile_idx].level_x = tile_coordinates[2];\n      exr_image->tiles[tile_idx].level_y = tile_coordinates[3];\n\n      exr_image->num_tiles = static_cast(num_tiles);\n    }\n  } else {  // scanline format\n\n    // Don't allow too large image(256GB * pixel_data_size or more). Workaround\n    // for #104.\n    size_t total_data_len =\n        size_t(data_width) * size_t(data_height) * size_t(num_channels);\n    const bool total_data_len_overflown = sizeof(void*) == 8 ? (total_data_len >= 0x4000000000) : false;\n    if ((total_data_len == 0) || total_data_len_overflown ) {\n      if (err) {\n        std::stringstream ss;\n        ss << \"Image data size is zero or too large: width = \" << data_width\n           << \", height = \" << data_height << \", channels = \" << num_channels\n           << std::endl;\n        (*err) += ss.str();\n      }\n      return TINYEXR_ERROR_INVALID_DATA;\n    }\n\n    exr_image->images = tinyexr::AllocateImage(\n        num_channels, exr_header->channels, exr_header->requested_pixel_types,\n        data_width, data_height);\n\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n    for (int y = 0; y < static_cast(num_blocks); y++) {\n      size_t y_idx = static_cast(y);\n\n      if (offsets[y_idx] + sizeof(int) * 2 > size) {\n        invalid_data = true;\n      } else {\n        // 4 byte: scan line\n        // 4 byte: data size\n        // ~     : pixel data(uncompressed or compressed)\n        size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2));\n        const unsigned char *data_ptr =\n            reinterpret_cast(head + offsets[y_idx]);\n\n        int line_no;\n        memcpy(&line_no, data_ptr, sizeof(int));\n        int data_len;\n        memcpy(&data_len, data_ptr + 4, sizeof(int));\n        tinyexr::swap4(reinterpret_cast(&line_no));\n        tinyexr::swap4(reinterpret_cast(&data_len));\n\n        if (size_t(data_len) > data_size) {\n          invalid_data = true;\n        } else if (data_len == 0) {\n          // TODO(syoyo): May be ok to raise the threshold for example `data_len\n          // < 4`\n          invalid_data = true;\n        } else {\n          // line_no may be negative.\n          int end_line_no = (std::min)(line_no + num_scanline_blocks,\n                                       (exr_header->data_window[3] + 1));\n\n          int num_lines = end_line_no - line_no;\n\n          if (num_lines <= 0) {\n            invalid_data = true;\n          } else {\n            // Move to data addr: 8 = 4 + 4;\n            data_ptr += 8;\n\n            // Adjust line_no with data_window.bmin.y\n\n            // overflow check\n            tinyexr_int64 lno = static_cast(line_no) - static_cast(exr_header->data_window[1]);\n            if (lno > std::numeric_limits::max()) {\n              line_no = -1; // invalid\n            } else if (lno < -std::numeric_limits::max()) {\n              line_no = -1; // invalid\n            } else {\n              line_no -= exr_header->data_window[1];\n            }\n\n            if (line_no < 0) {\n              invalid_data = true;\n            } else {\n              if (!tinyexr::DecodePixelData(\n                      exr_image->images, exr_header->requested_pixel_types,\n                      data_ptr, static_cast(data_len),\n                      exr_header->compression_type, exr_header->line_order,\n                      data_width, data_height, data_width, y, line_no,\n                      num_lines, static_cast(pixel_data_size),\n                      static_cast(exr_header->num_custom_attributes),\n                      exr_header->custom_attributes,\n                      static_cast(exr_header->num_channels),\n                      exr_header->channels, channel_offset_list)) {\n                invalid_data = true;\n              }\n            }\n          }\n        }\n      }\n    }  // omp parallel\n  }\n\n  if (invalid_data) {\n    if (err) {\n      std::stringstream ss;\n      (*err) += \"Invalid data found when decoding pixels.\\n\";\n    }\n    return TINYEXR_ERROR_INVALID_DATA;\n  }\n\n  // Overwrite `pixel_type` with `requested_pixel_type`.\n  {\n    for (int c = 0; c < exr_header->num_channels; c++) {\n      exr_header->pixel_types[c] = exr_header->requested_pixel_types[c];\n    }\n  }\n\n  {\n    exr_image->num_channels = num_channels;\n\n    exr_image->width = data_width;\n    exr_image->height = data_height;\n  }\n\n  return TINYEXR_SUCCESS;\n}", "func_hash": 204576660378471471312302041175468111939, "file_name": "tinyexr.h", "file_hash": 28581937103314011160798682220091501322, "cwe": ["CWE-20"], "cve": "CVE-2020-19490", "cve_desc": "tinyexr 0.9.5 has a integer overflow over-write in tinyexr::DecodePixelData in tinyexr.h, related to OpenEXR code.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-19490"}
{"idx": 252437, "project": "tinyexr", "commit_id": "a685e3332f61cd4e59324bf3f669d36973d64270", "project_url": "https://github.com/syoyo/tinyexr", "commit_url": "https://github.com/syoyo/tinyexr/commit/a685e3332f61cd4e59324bf3f669d36973d64270", "commit_message": "Make line_no with too large value(2**20) invalid. Fixes #124", "target": 0, "func": "static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header,\n                       const std::vector &offsets,\n                       const unsigned char *head, const size_t size,\n                       std::string *err) {\n  int num_channels = exr_header->num_channels;\n\n  int num_scanline_blocks = 1;\n  if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {\n    num_scanline_blocks = 16;\n  } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {\n    num_scanline_blocks = 32;\n  } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {\n    num_scanline_blocks = 16;\n  }\n\n  int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1;\n  int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1;\n\n  if ((data_width < 0) || (data_height < 0)) {\n    if (err) {\n      std::stringstream ss;\n      ss << \"Invalid data width or data height: \" << data_width << \", \"\n         << data_height << std::endl;\n      (*err) += ss.str();\n    }\n    return TINYEXR_ERROR_INVALID_DATA;\n  }\n\n  // Do not allow too large data_width and data_height. header invalid?\n  {\n    const int threshold = 1024 * 8192;  // heuristics\n    if ((data_width > threshold) || (data_height > threshold)) {\n      if (err) {\n        std::stringstream ss;\n        ss << \"data_with or data_height too large. data_width: \" << data_width\n           << \", \"\n           << \"data_height = \" << data_height << std::endl;\n        (*err) += ss.str();\n      }\n      return TINYEXR_ERROR_INVALID_DATA;\n    }\n  }\n\n  size_t num_blocks = offsets.size();\n\n  std::vector channel_offset_list;\n  int pixel_data_size = 0;\n  size_t channel_offset = 0;\n  if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size,\n                                     &channel_offset, num_channels,\n                                     exr_header->channels)) {\n    if (err) {\n      (*err) += \"Failed to compute channel layout.\\n\";\n    }\n    return TINYEXR_ERROR_INVALID_DATA;\n  }\n\n  bool invalid_data = false;  // TODO(LTE): Use atomic lock for MT safety.\n\n  if (exr_header->tiled) {\n    // value check\n    if (exr_header->tile_size_x < 0) {\n      if (err) {\n        std::stringstream ss;\n        ss << \"Invalid tile size x : \" << exr_header->tile_size_x << \"\\n\";\n        (*err) += ss.str();\n      }\n      return TINYEXR_ERROR_INVALID_HEADER;\n    }\n\n    if (exr_header->tile_size_y < 0) {\n      if (err) {\n        std::stringstream ss;\n        ss << \"Invalid tile size y : \" << exr_header->tile_size_y << \"\\n\";\n        (*err) += ss.str();\n      }\n      return TINYEXR_ERROR_INVALID_HEADER;\n    }\n\n    size_t num_tiles = offsets.size();  // = # of blocks\n\n    exr_image->tiles = static_cast(\n        calloc(sizeof(EXRTile), static_cast(num_tiles)));\n\n    for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) {\n      // Allocate memory for each tile.\n      exr_image->tiles[tile_idx].images = tinyexr::AllocateImage(\n          num_channels, exr_header->channels, exr_header->requested_pixel_types,\n          exr_header->tile_size_x, exr_header->tile_size_y);\n\n      // 16 byte: tile coordinates\n      // 4 byte : data size\n      // ~      : data(uncompressed or compressed)\n      if (offsets[tile_idx] + sizeof(int) * 5 > size) {\n        if (err) {\n          (*err) += \"Insufficient data size.\\n\";\n        }\n        return TINYEXR_ERROR_INVALID_DATA;\n      }\n\n      size_t data_size = size_t(size - (offsets[tile_idx] + sizeof(int) * 5));\n      const unsigned char *data_ptr =\n          reinterpret_cast(head + offsets[tile_idx]);\n\n      int tile_coordinates[4];\n      memcpy(tile_coordinates, data_ptr, sizeof(int) * 4);\n      tinyexr::swap4(reinterpret_cast(&tile_coordinates[0]));\n      tinyexr::swap4(reinterpret_cast(&tile_coordinates[1]));\n      tinyexr::swap4(reinterpret_cast(&tile_coordinates[2]));\n      tinyexr::swap4(reinterpret_cast(&tile_coordinates[3]));\n\n      // @todo{ LoD }\n      if (tile_coordinates[2] != 0) {\n        return TINYEXR_ERROR_UNSUPPORTED_FEATURE;\n      }\n      if (tile_coordinates[3] != 0) {\n        return TINYEXR_ERROR_UNSUPPORTED_FEATURE;\n      }\n\n      int data_len;\n      memcpy(&data_len, data_ptr + 16,\n             sizeof(int));  // 16 = sizeof(tile_coordinates)\n      tinyexr::swap4(reinterpret_cast(&data_len));\n\n      if (data_len < 4 || size_t(data_len) > data_size) {\n        if (err) {\n          (*err) += \"Insufficient data length.\\n\";\n        }\n        return TINYEXR_ERROR_INVALID_DATA;\n      }\n\n      // Move to data addr: 20 = 16 + 4;\n      data_ptr += 20;\n\n      tinyexr::DecodeTiledPixelData(\n          exr_image->tiles[tile_idx].images,\n          &(exr_image->tiles[tile_idx].width),\n          &(exr_image->tiles[tile_idx].height),\n          exr_header->requested_pixel_types, data_ptr,\n          static_cast(data_len), exr_header->compression_type,\n          exr_header->line_order, data_width, data_height, tile_coordinates[0],\n          tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y,\n          static_cast(pixel_data_size),\n          static_cast(exr_header->num_custom_attributes),\n          exr_header->custom_attributes,\n          static_cast(exr_header->num_channels), exr_header->channels,\n          channel_offset_list);\n\n      exr_image->tiles[tile_idx].offset_x = tile_coordinates[0];\n      exr_image->tiles[tile_idx].offset_y = tile_coordinates[1];\n      exr_image->tiles[tile_idx].level_x = tile_coordinates[2];\n      exr_image->tiles[tile_idx].level_y = tile_coordinates[3];\n\n      exr_image->num_tiles = static_cast(num_tiles);\n    }\n  } else {  // scanline format\n\n    // Don't allow too large image(256GB * pixel_data_size or more). Workaround\n    // for #104.\n    size_t total_data_len =\n        size_t(data_width) * size_t(data_height) * size_t(num_channels);\n    const bool total_data_len_overflown = sizeof(void*) == 8 ? (total_data_len >= 0x4000000000) : false;\n    if ((total_data_len == 0) || total_data_len_overflown ) {\n      if (err) {\n        std::stringstream ss;\n        ss << \"Image data size is zero or too large: width = \" << data_width\n           << \", height = \" << data_height << \", channels = \" << num_channels\n           << std::endl;\n        (*err) += ss.str();\n      }\n      return TINYEXR_ERROR_INVALID_DATA;\n    }\n\n    exr_image->images = tinyexr::AllocateImage(\n        num_channels, exr_header->channels, exr_header->requested_pixel_types,\n        data_width, data_height);\n\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n    for (int y = 0; y < static_cast(num_blocks); y++) {\n      size_t y_idx = static_cast(y);\n\n      if (offsets[y_idx] + sizeof(int) * 2 > size) {\n        invalid_data = true;\n      } else {\n        // 4 byte: scan line\n        // 4 byte: data size\n        // ~     : pixel data(uncompressed or compressed)\n        size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2));\n        const unsigned char *data_ptr =\n            reinterpret_cast(head + offsets[y_idx]);\n\n        int line_no;\n        memcpy(&line_no, data_ptr, sizeof(int));\n        int data_len;\n        memcpy(&data_len, data_ptr + 4, sizeof(int));\n        tinyexr::swap4(reinterpret_cast(&line_no));\n        tinyexr::swap4(reinterpret_cast(&data_len));\n\n        if (size_t(data_len) > data_size) {\n          invalid_data = true;\n\n        } else if ((line_no > (2 << 20)) || (line_no < -(2 << 20))) {\n          // Too large value. Assume this is invalid\n          // 2**20 = 1048576 = heuristic value.\n          invalid_data = true;\n        } else if (data_len == 0) {\n          // TODO(syoyo): May be ok to raise the threshold for example `data_len\n          // < 4`\n          invalid_data = true;\n        } else {\n          // line_no may be negative.\n          int end_line_no = (std::min)(line_no + num_scanline_blocks,\n                                       (exr_header->data_window[3] + 1));\n\n          int num_lines = end_line_no - line_no;\n\n          if (num_lines <= 0) {\n            invalid_data = true;\n          } else {\n            // Move to data addr: 8 = 4 + 4;\n            data_ptr += 8;\n\n            // Adjust line_no with data_window.bmin.y\n\n            // overflow check\n            tinyexr_int64 lno = static_cast(line_no) - static_cast(exr_header->data_window[1]);\n            if (lno > std::numeric_limits::max()) {\n              line_no = -1; // invalid\n            } else if (lno < -std::numeric_limits::max()) {\n              line_no = -1; // invalid\n            } else {\n              line_no -= exr_header->data_window[1];\n            }\n\n            if (line_no < 0) {\n              invalid_data = true;\n            } else {\n              if (!tinyexr::DecodePixelData(\n                      exr_image->images, exr_header->requested_pixel_types,\n                      data_ptr, static_cast(data_len),\n                      exr_header->compression_type, exr_header->line_order,\n                      data_width, data_height, data_width, y, line_no,\n                      num_lines, static_cast(pixel_data_size),\n                      static_cast(exr_header->num_custom_attributes),\n                      exr_header->custom_attributes,\n                      static_cast(exr_header->num_channels),\n                      exr_header->channels, channel_offset_list)) {\n                invalid_data = true;\n              }\n            }\n          }\n        }\n      }\n    }  // omp parallel\n  }\n\n  if (invalid_data) {\n    if (err) {\n      std::stringstream ss;\n      (*err) += \"Invalid data found when decoding pixels.\\n\";\n    }\n    return TINYEXR_ERROR_INVALID_DATA;\n  }\n\n  // Overwrite `pixel_type` with `requested_pixel_type`.\n  {\n    for (int c = 0; c < exr_header->num_channels; c++) {\n      exr_header->pixel_types[c] = exr_header->requested_pixel_types[c];\n    }\n  }\n\n  {\n    exr_image->num_channels = num_channels;\n\n    exr_image->width = data_width;\n    exr_image->height = data_height;\n  }\n\n  return TINYEXR_SUCCESS;\n}", "func_hash": 151063885227112731774220545683650954280, "file_name": "tinyexr.h", "file_hash": 117099710183052888477970990927407043374, "cwe": ["CWE-20"], "cve": "CVE-2020-19490", "cve_desc": "tinyexr 0.9.5 has a integer overflow over-write in tinyexr::DecodePixelData in tinyexr.h, related to OpenEXR code.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-19490"}
{"idx": 197128, "project": "mruby", "commit_id": "f72315575f78a9a773adbce0ee7d3ec33434cb76", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/f72315575f78a9a773adbce0ee7d3ec33434cb76", "commit_message": "codegen.c: fix a argument generation bug in array assignment.", "target": 1, "func": "gen_assignment(codegen_scope *s, node *tree, node *rhs, int sp, int val)\n{\n  int idx;\n  int type = nint(tree->car);\n\n  switch (type) {\n  case NODE_GVAR:\n  case NODE_ARG:\n  case NODE_LVAR:\n  case NODE_IVAR:\n  case NODE_CVAR:\n  case NODE_CONST:\n  case NODE_NIL:\n  case NODE_MASGN:\n    if (rhs) {\n      codegen(s, rhs, VAL);\n      pop();\n      sp = cursp();\n    }\n    break;\n\n  case NODE_COLON2:\n  case NODE_CALL:\n  case NODE_SCALL:\n    /* keep evaluation order */\n    break;\n\n  case NODE_NVAR:\n    codegen_error(s, \"Can't assign to numbered parameter\");\n    break;\n\n  default:\n    codegen_error(s, \"unknown lhs\");\n    break;\n  }\n\n  tree = tree->cdr;\n  switch (type) {\n  case NODE_GVAR:\n    gen_setxv(s, OP_SETGV, sp, nsym(tree), val);\n    break;\n  case NODE_ARG:\n  case NODE_LVAR:\n    idx = lv_idx(s, nsym(tree));\n    if (idx > 0) {\n      if (idx != sp) {\n        gen_move(s, idx, sp, val);\n      }\n      break;\n    }\n    else {                      /* upvar */\n      gen_setupvar(s, sp, nsym(tree));\n    }\n    break;\n  case NODE_IVAR:\n    gen_setxv(s, OP_SETIV, sp, nsym(tree), val);\n    break;\n  case NODE_CVAR:\n    gen_setxv(s, OP_SETCV, sp, nsym(tree), val);\n    break;\n  case NODE_CONST:\n    gen_setxv(s, OP_SETCONST, sp, nsym(tree), val);\n    break;\n  case NODE_COLON2:\n    if (sp) {\n      gen_move(s, cursp(), sp, 0);\n    }\n    sp = cursp();\n    push();\n    codegen(s, tree->car, VAL);\n    if (rhs) {\n      codegen(s, rhs, VAL); pop();\n      gen_move(s, sp, cursp(), 0);\n    }\n    pop_n(2);\n    idx = new_sym(s, nsym(tree->cdr));\n    genop_2(s, OP_SETMCNST, sp, idx);\n    break;\n\n  case NODE_CALL:\n  case NODE_SCALL:\n    {\n      int noself = 0, safe = (type == NODE_SCALL), skip = 0, top, call, n = 0;\n      mrb_sym mid = nsym(tree->cdr->car);\n\n      top = cursp();\n      if (val || sp == cursp()) {\n        push();                   /* room for retval */\n      }\n      call = cursp();\n      if (!tree->car) {\n        noself = 1;\n        push();\n      }\n      else {\n        codegen(s, tree->car, VAL); /* receiver */\n      }\n      if (safe) {\n        int recv = cursp()-1;\n        gen_move(s, cursp(), recv, 1);\n        skip = genjmp2_0(s, OP_JMPNIL, cursp(), val);\n      }\n      tree = tree->cdr->cdr->car;\n      if (tree) {\n        if (tree->car) {            /* positional arguments */\n          n = gen_values(s, tree->car, VAL, (tree->cdr->car)?13:14);\n          if (n < 0) {              /* variable length */\n            n = 15;\n            push();\n          }\n        }\n        if (tree->cdr->car) {       /* keyword arguments */\n          if (n == 14) {\n            pop_n(n);\n            genop_2(s, OP_ARRAY, cursp(), n);\n            push();\n            n = 15;\n          }\n          gen_hash(s, tree->cdr->car->cdr, VAL, 0);\n          if (n < 14) {\n            n++;\n          }\n          else {\n            pop_n(2);\n            genop_2(s, OP_ARYPUSH, cursp(), 1);\n          }\n          push();\n        }\n      }\n      if (rhs) {\n        codegen(s, rhs, VAL);\n        pop();\n      }\n      else {\n        gen_move(s, cursp(), sp, 0);\n      }\n      if (val) {\n        gen_move(s, top, cursp(), 1);\n      }\n      if (n < 14) {\n        n++;\n      }\n      else {\n        pop();\n        genop_2(s, OP_ARYPUSH, cursp(), 1);\n      }\n      s->sp = call;\n      if (mid == MRB_OPSYM_2(s->mrb, aref) && n == 2) {\n        genop_1(s, OP_SETIDX, cursp());\n      }\n      else {\n        genop_3(s, noself ? OP_SSEND : OP_SEND, cursp(), new_sym(s, attrsym(s, mid)), n);\n      }\n      if (safe) {\n        dispatch(s, skip);\n      }\n      s->sp = top;\n    }\n    break;\n\n  case NODE_MASGN:\n    gen_vmassignment(s, tree->car, sp, val);\n    break;\n\n  /* splat without assignment */\n  case NODE_NIL:\n    break;\n\n  default:\n    codegen_error(s, \"unknown lhs\");\n    break;\n  }\n  if (val) push();\n}", "func_hash": 236078569306136776334536654321578023921, "file_name": "codegen.c", "file_hash": 69656694646846748382204460208931803734, "cwe": ["CWE-125"], "cve": "CVE-2022-0717", "cve_desc": "Out-of-bounds Read in GitHub repository mruby/mruby prior to 3.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0717"}
{"idx": 253515, "project": "mruby", "commit_id": "f72315575f78a9a773adbce0ee7d3ec33434cb76", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/f72315575f78a9a773adbce0ee7d3ec33434cb76", "commit_message": "codegen.c: fix a argument generation bug in array assignment.", "target": 0, "func": "gen_assignment(codegen_scope *s, node *tree, node *rhs, int sp, int val)\n{\n  int idx;\n  int type = nint(tree->car);\n\n  switch (type) {\n  case NODE_GVAR:\n  case NODE_ARG:\n  case NODE_LVAR:\n  case NODE_IVAR:\n  case NODE_CVAR:\n  case NODE_CONST:\n  case NODE_NIL:\n  case NODE_MASGN:\n    if (rhs) {\n      codegen(s, rhs, VAL);\n      pop();\n      sp = cursp();\n    }\n    break;\n\n  case NODE_COLON2:\n  case NODE_CALL:\n  case NODE_SCALL:\n    /* keep evaluation order */\n    break;\n\n  case NODE_NVAR:\n    codegen_error(s, \"Can't assign to numbered parameter\");\n    break;\n\n  default:\n    codegen_error(s, \"unknown lhs\");\n    break;\n  }\n\n  tree = tree->cdr;\n  switch (type) {\n  case NODE_GVAR:\n    gen_setxv(s, OP_SETGV, sp, nsym(tree), val);\n    break;\n  case NODE_ARG:\n  case NODE_LVAR:\n    idx = lv_idx(s, nsym(tree));\n    if (idx > 0) {\n      if (idx != sp) {\n        gen_move(s, idx, sp, val);\n      }\n      break;\n    }\n    else {                      /* upvar */\n      gen_setupvar(s, sp, nsym(tree));\n    }\n    break;\n  case NODE_IVAR:\n    gen_setxv(s, OP_SETIV, sp, nsym(tree), val);\n    break;\n  case NODE_CVAR:\n    gen_setxv(s, OP_SETCV, sp, nsym(tree), val);\n    break;\n  case NODE_CONST:\n    gen_setxv(s, OP_SETCONST, sp, nsym(tree), val);\n    break;\n  case NODE_COLON2:\n    if (sp) {\n      gen_move(s, cursp(), sp, 0);\n    }\n    sp = cursp();\n    push();\n    codegen(s, tree->car, VAL);\n    if (rhs) {\n      codegen(s, rhs, VAL); pop();\n      gen_move(s, sp, cursp(), 0);\n    }\n    pop_n(2);\n    idx = new_sym(s, nsym(tree->cdr));\n    genop_2(s, OP_SETMCNST, sp, idx);\n    break;\n\n  case NODE_CALL:\n  case NODE_SCALL:\n    {\n      int noself = 0, safe = (type == NODE_SCALL), skip = 0, top, call, n = 0;\n      mrb_sym mid = nsym(tree->cdr->car);\n\n      top = cursp();\n      if (val || sp == cursp()) {\n        push();                   /* room for retval */\n      }\n      call = cursp();\n      if (!tree->car) {\n        noself = 1;\n        push();\n      }\n      else {\n        codegen(s, tree->car, VAL); /* receiver */\n      }\n      if (safe) {\n        int recv = cursp()-1;\n        gen_move(s, cursp(), recv, 1);\n        skip = genjmp2_0(s, OP_JMPNIL, cursp(), val);\n      }\n      tree = tree->cdr->cdr->car;\n      if (tree) {\n        if (tree->car) {            /* positional arguments */\n          n = gen_values(s, tree->car, VAL, (tree->cdr->car)?13:14);\n          if (n < 0) {              /* variable length */\n            n = 15;\n            push();\n          }\n        }\n        if (tree->cdr->car) {       /* keyword arguments */\n          if (n == 14) {\n            pop_n(n);\n            genop_2(s, OP_ARRAY, cursp(), n);\n            push();\n            n = 15;\n          }\n          gen_hash(s, tree->cdr->car->cdr, VAL, 0);\n          if (n < 14) {\n            n++;\n          }\n          else {\n            pop_n(2);\n            genop_2(s, OP_ARYPUSH, cursp(), 1);\n          }\n          push();\n        }\n      }\n      if (rhs) {\n        codegen(s, rhs, VAL);\n        pop();\n      }\n      else {\n        gen_move(s, cursp(), sp, 0);\n      }\n      if (val) {\n        gen_move(s, top, cursp(), 1);\n      }\n      if (n < 15) {\n        n++;\n        if (n == 15) {\n          pop_n(14);\n          genop_2(s, OP_ARRAY, cursp(), 15);\n        }\n      }\n      else {\n        pop();\n        genop_2(s, OP_ARYPUSH, cursp(), 1);\n      }\n      s->sp = call;\n      if (mid == MRB_OPSYM_2(s->mrb, aref) && n == 2) {\n        genop_1(s, OP_SETIDX, cursp());\n      }\n      else {\n        genop_3(s, noself ? OP_SSEND : OP_SEND, cursp(), new_sym(s, attrsym(s, mid)), n);\n      }\n      if (safe) {\n        dispatch(s, skip);\n      }\n      s->sp = top;\n    }\n    break;\n\n  case NODE_MASGN:\n    gen_vmassignment(s, tree->car, sp, val);\n    break;\n\n  /* splat without assignment */\n  case NODE_NIL:\n    break;\n\n  default:\n    codegen_error(s, \"unknown lhs\");\n    break;\n  }\n  if (val) push();\n}", "func_hash": 24141483316666647152319474982009169945, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2022-0717", "cve_desc": "Out-of-bounds Read in GitHub repository mruby/mruby prior to 3.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0717"}
{"idx": 197135, "project": "linux", "commit_id": "505d9dcb0f7ddf9d075e729523a33d38642ae680", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/505d9dcb0f7ddf9d075e729523a33d38642ae680", "commit_message": "crypto: ccp - fix resource leaks in ccp_run_aes_gcm_cmd()\n\nThere are three bugs in this code:\n\n1) If we ccp_init_data() fails for &src then we need to free aad.\n   Use goto e_aad instead of goto e_ctx.\n2) The label to free the &final_wa was named incorrectly as \"e_tag\" but\n   it should have been \"e_final_wa\".  One error path leaked &final_wa.\n3) The &tag was leaked on one error path.  In that case, I added a free\n   before the goto because the resource was local to that block.\n\nFixes: 36cf515b9bbe (\"crypto: ccp - Enable support for AES GCM on v5 CCPs\")\nReported-by: \"minihanshen(\u6c88\u660e\u822a)\" \nSigned-off-by: Dan Carpenter \nReviewed-by: John Allen \nTested-by: John Allen \nSigned-off-by: Herbert Xu ", "target": 1, "func": "ccp_run_aes_gcm_cmd(struct ccp_cmd_queue *cmd_q, struct ccp_cmd *cmd)\n{\n\tstruct ccp_aes_engine *aes = &cmd->u.aes;\n\tstruct ccp_dm_workarea key, ctx, final_wa, tag;\n\tstruct ccp_data src, dst;\n\tstruct ccp_data aad;\n\tstruct ccp_op op;\n\tunsigned int dm_offset;\n\tunsigned int authsize;\n\tunsigned int jobid;\n\tunsigned int ilen;\n\tbool in_place = true; /* Default value */\n\t__be64 *final;\n\tint ret;\n\n\tstruct scatterlist *p_inp, sg_inp[2];\n\tstruct scatterlist *p_tag, sg_tag[2];\n\tstruct scatterlist *p_outp, sg_outp[2];\n\tstruct scatterlist *p_aad;\n\n\tif (!aes->iv)\n\t\treturn -EINVAL;\n\n\tif (!((aes->key_len == AES_KEYSIZE_128) ||\n\t\t(aes->key_len == AES_KEYSIZE_192) ||\n\t\t(aes->key_len == AES_KEYSIZE_256)))\n\t\treturn -EINVAL;\n\n\tif (!aes->key) /* Gotta have a key SGL */\n\t\treturn -EINVAL;\n\n\t/* Zero defaults to 16 bytes, the maximum size */\n\tauthsize = aes->authsize ? aes->authsize : AES_BLOCK_SIZE;\n\tswitch (authsize) {\n\tcase 16:\n\tcase 15:\n\tcase 14:\n\tcase 13:\n\tcase 12:\n\tcase 8:\n\tcase 4:\n\t\tbreak;\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\n\t/* First, decompose the source buffer into AAD & PT,\n\t * and the destination buffer into AAD, CT & tag, or\n\t * the input into CT & tag.\n\t * It is expected that the input and output SGs will\n\t * be valid, even if the AAD and input lengths are 0.\n\t */\n\tp_aad = aes->src;\n\tp_inp = scatterwalk_ffwd(sg_inp, aes->src, aes->aad_len);\n\tp_outp = scatterwalk_ffwd(sg_outp, aes->dst, aes->aad_len);\n\tif (aes->action == CCP_AES_ACTION_ENCRYPT) {\n\t\tilen = aes->src_len;\n\t\tp_tag = scatterwalk_ffwd(sg_tag, p_outp, ilen);\n\t} else {\n\t\t/* Input length for decryption includes tag */\n\t\tilen = aes->src_len - authsize;\n\t\tp_tag = scatterwalk_ffwd(sg_tag, p_inp, ilen);\n\t}\n\n\tjobid = CCP_NEW_JOBID(cmd_q->ccp);\n\n\tmemset(&op, 0, sizeof(op));\n\top.cmd_q = cmd_q;\n\top.jobid = jobid;\n\top.sb_key = cmd_q->sb_key; /* Pre-allocated */\n\top.sb_ctx = cmd_q->sb_ctx; /* Pre-allocated */\n\top.init = 1;\n\top.u.aes.type = aes->type;\n\n\t/* Copy the key to the LSB */\n\tret = ccp_init_dm_workarea(&key, cmd_q,\n\t\t\t\t   CCP_AES_CTX_SB_COUNT * CCP_SB_BYTES,\n\t\t\t\t   DMA_TO_DEVICE);\n\tif (ret)\n\t\treturn ret;\n\n\tdm_offset = CCP_SB_BYTES - aes->key_len;\n\tret = ccp_set_dm_area(&key, dm_offset, aes->key, 0, aes->key_len);\n\tif (ret)\n\t\tgoto e_key;\n\tret = ccp_copy_to_sb(cmd_q, &key, op.jobid, op.sb_key,\n\t\t\t     CCP_PASSTHRU_BYTESWAP_256BIT);\n\tif (ret) {\n\t\tcmd->engine_error = cmd_q->cmd_error;\n\t\tgoto e_key;\n\t}\n\n\t/* Copy the context (IV) to the LSB.\n\t * There is an assumption here that the IV is 96 bits in length, plus\n\t * a nonce of 32 bits. If no IV is present, use a zeroed buffer.\n\t */\n\tret = ccp_init_dm_workarea(&ctx, cmd_q,\n\t\t\t\t   CCP_AES_CTX_SB_COUNT * CCP_SB_BYTES,\n\t\t\t\t   DMA_BIDIRECTIONAL);\n\tif (ret)\n\t\tgoto e_key;\n\n\tdm_offset = CCP_AES_CTX_SB_COUNT * CCP_SB_BYTES - aes->iv_len;\n\tret = ccp_set_dm_area(&ctx, dm_offset, aes->iv, 0, aes->iv_len);\n\tif (ret)\n\t\tgoto e_ctx;\n\n\tret = ccp_copy_to_sb(cmd_q, &ctx, op.jobid, op.sb_ctx,\n\t\t\t     CCP_PASSTHRU_BYTESWAP_256BIT);\n\tif (ret) {\n\t\tcmd->engine_error = cmd_q->cmd_error;\n\t\tgoto e_ctx;\n\t}\n\n\top.init = 1;\n\tif (aes->aad_len > 0) {\n\t\t/* Step 1: Run a GHASH over the Additional Authenticated Data */\n\t\tret = ccp_init_data(&aad, cmd_q, p_aad, aes->aad_len,\n\t\t\t\t    AES_BLOCK_SIZE,\n\t\t\t\t    DMA_TO_DEVICE);\n\t\tif (ret)\n\t\t\tgoto e_ctx;\n\n\t\top.u.aes.mode = CCP_AES_MODE_GHASH;\n\t\top.u.aes.action = CCP_AES_GHASHAAD;\n\n\t\twhile (aad.sg_wa.bytes_left) {\n\t\t\tccp_prepare_data(&aad, NULL, &op, AES_BLOCK_SIZE, true);\n\n\t\t\tret = cmd_q->ccp->vdata->perform->aes(&op);\n\t\t\tif (ret) {\n\t\t\t\tcmd->engine_error = cmd_q->cmd_error;\n\t\t\t\tgoto e_aad;\n\t\t\t}\n\n\t\t\tccp_process_data(&aad, NULL, &op);\n\t\t\top.init = 0;\n\t\t}\n\t}\n\n\top.u.aes.mode = CCP_AES_MODE_GCTR;\n\top.u.aes.action = aes->action;\n\n\tif (ilen > 0) {\n\t\t/* Step 2: Run a GCTR over the plaintext */\n\t\tin_place = (sg_virt(p_inp) == sg_virt(p_outp)) ? true : false;\n\n\t\tret = ccp_init_data(&src, cmd_q, p_inp, ilen,\n\t\t\t\t    AES_BLOCK_SIZE,\n\t\t\t\t    in_place ? DMA_BIDIRECTIONAL\n\t\t\t\t\t     : DMA_TO_DEVICE);\n\t\tif (ret)\n\t\t\tgoto e_ctx;\n\n\t\tif (in_place) {\n\t\t\tdst = src;\n\t\t} else {\n\t\t\tret = ccp_init_data(&dst, cmd_q, p_outp, ilen,\n\t\t\t\t\t    AES_BLOCK_SIZE, DMA_FROM_DEVICE);\n\t\t\tif (ret)\n\t\t\t\tgoto e_src;\n\t\t}\n\n\t\top.soc = 0;\n\t\top.eom = 0;\n\t\top.init = 1;\n\t\twhile (src.sg_wa.bytes_left) {\n\t\t\tccp_prepare_data(&src, &dst, &op, AES_BLOCK_SIZE, true);\n\t\t\tif (!src.sg_wa.bytes_left) {\n\t\t\t\tunsigned int nbytes = ilen % AES_BLOCK_SIZE;\n\n\t\t\t\tif (nbytes) {\n\t\t\t\t\top.eom = 1;\n\t\t\t\t\top.u.aes.size = (nbytes * 8) - 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tret = cmd_q->ccp->vdata->perform->aes(&op);\n\t\t\tif (ret) {\n\t\t\t\tcmd->engine_error = cmd_q->cmd_error;\n\t\t\t\tgoto e_dst;\n\t\t\t}\n\n\t\t\tccp_process_data(&src, &dst, &op);\n\t\t\top.init = 0;\n\t\t}\n\t}\n\n\t/* Step 3: Update the IV portion of the context with the original IV */\n\tret = ccp_copy_from_sb(cmd_q, &ctx, op.jobid, op.sb_ctx,\n\t\t\t       CCP_PASSTHRU_BYTESWAP_256BIT);\n\tif (ret) {\n\t\tcmd->engine_error = cmd_q->cmd_error;\n\t\tgoto e_dst;\n\t}\n\n\tret = ccp_set_dm_area(&ctx, dm_offset, aes->iv, 0, aes->iv_len);\n\tif (ret)\n\t\tgoto e_dst;\n\n\tret = ccp_copy_to_sb(cmd_q, &ctx, op.jobid, op.sb_ctx,\n\t\t\t     CCP_PASSTHRU_BYTESWAP_256BIT);\n\tif (ret) {\n\t\tcmd->engine_error = cmd_q->cmd_error;\n\t\tgoto e_dst;\n\t}\n\n\t/* Step 4: Concatenate the lengths of the AAD and source, and\n\t * hash that 16 byte buffer.\n\t */\n\tret = ccp_init_dm_workarea(&final_wa, cmd_q, AES_BLOCK_SIZE,\n\t\t\t\t   DMA_BIDIRECTIONAL);\n\tif (ret)\n\t\tgoto e_dst;\n\tfinal = (__be64 *)final_wa.address;\n\tfinal[0] = cpu_to_be64(aes->aad_len * 8);\n\tfinal[1] = cpu_to_be64(ilen * 8);\n\n\tmemset(&op, 0, sizeof(op));\n\top.cmd_q = cmd_q;\n\top.jobid = jobid;\n\top.sb_key = cmd_q->sb_key; /* Pre-allocated */\n\top.sb_ctx = cmd_q->sb_ctx; /* Pre-allocated */\n\top.init = 1;\n\top.u.aes.type = aes->type;\n\top.u.aes.mode = CCP_AES_MODE_GHASH;\n\top.u.aes.action = CCP_AES_GHASHFINAL;\n\top.src.type = CCP_MEMTYPE_SYSTEM;\n\top.src.u.dma.address = final_wa.dma.address;\n\top.src.u.dma.length = AES_BLOCK_SIZE;\n\top.dst.type = CCP_MEMTYPE_SYSTEM;\n\top.dst.u.dma.address = final_wa.dma.address;\n\top.dst.u.dma.length = AES_BLOCK_SIZE;\n\top.eom = 1;\n\top.u.aes.size = 0;\n\tret = cmd_q->ccp->vdata->perform->aes(&op);\n\tif (ret)\n\t\tgoto e_dst;\n\n\tif (aes->action == CCP_AES_ACTION_ENCRYPT) {\n\t\t/* Put the ciphered tag after the ciphertext. */\n\t\tccp_get_dm_area(&final_wa, 0, p_tag, 0, authsize);\n\t} else {\n\t\t/* Does this ciphered tag match the input? */\n\t\tret = ccp_init_dm_workarea(&tag, cmd_q, authsize,\n\t\t\t\t\t   DMA_BIDIRECTIONAL);\n\t\tif (ret)\n\t\t\tgoto e_tag;\n\t\tret = ccp_set_dm_area(&tag, 0, p_tag, 0, authsize);\n\t\tif (ret)\n\t\t\tgoto e_tag;\n\n\t\tret = crypto_memneq(tag.address, final_wa.address,\n\t\t\t\t    authsize) ? -EBADMSG : 0;\n\t\tccp_dm_free(&tag);\n\t}\n\ne_tag:\n\tccp_dm_free(&final_wa);\n\ne_dst:\n\tif (ilen > 0 && !in_place)\n\t\tccp_free_data(&dst, cmd_q);\n\ne_src:\n\tif (ilen > 0)\n\t\tccp_free_data(&src, cmd_q);\n\ne_aad:\n\tif (aes->aad_len)\n\t\tccp_free_data(&aad, cmd_q);\n\ne_ctx:\n\tccp_dm_free(&ctx);\n\ne_key:\n\tccp_dm_free(&key);\n\n\treturn ret;\n}", "func_hash": 164338035268758054525512134234222500237, "file_name": "ccp-ops.c", "file_hash": 220238669007539960746784666211129167889, "cwe": ["CWE-703"], "cve": "CVE-2021-3744", "cve_desc": "A memory leak flaw was found in the Linux kernel in the ccp_run_aes_gcm_cmd() function in drivers/crypto/ccp/ccp-ops.c, which allows attackers to cause a denial of service (memory consumption). This vulnerability is similar with the older CVE-2019-18808.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3744"}
{"idx": 253699, "project": "linux", "commit_id": "505d9dcb0f7ddf9d075e729523a33d38642ae680", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/505d9dcb0f7ddf9d075e729523a33d38642ae680", "commit_message": "crypto: ccp - fix resource leaks in ccp_run_aes_gcm_cmd()\n\nThere are three bugs in this code:\n\n1) If we ccp_init_data() fails for &src then we need to free aad.\n   Use goto e_aad instead of goto e_ctx.\n2) The label to free the &final_wa was named incorrectly as \"e_tag\" but\n   it should have been \"e_final_wa\".  One error path leaked &final_wa.\n3) The &tag was leaked on one error path.  In that case, I added a free\n   before the goto because the resource was local to that block.\n\nFixes: 36cf515b9bbe (\"crypto: ccp - Enable support for AES GCM on v5 CCPs\")\nReported-by: \"minihanshen(\u6c88\u660e\u822a)\" \nSigned-off-by: Dan Carpenter \nReviewed-by: John Allen \nTested-by: John Allen \nSigned-off-by: Herbert Xu ", "target": 0, "func": "ccp_run_aes_gcm_cmd(struct ccp_cmd_queue *cmd_q, struct ccp_cmd *cmd)\n{\n\tstruct ccp_aes_engine *aes = &cmd->u.aes;\n\tstruct ccp_dm_workarea key, ctx, final_wa, tag;\n\tstruct ccp_data src, dst;\n\tstruct ccp_data aad;\n\tstruct ccp_op op;\n\tunsigned int dm_offset;\n\tunsigned int authsize;\n\tunsigned int jobid;\n\tunsigned int ilen;\n\tbool in_place = true; /* Default value */\n\t__be64 *final;\n\tint ret;\n\n\tstruct scatterlist *p_inp, sg_inp[2];\n\tstruct scatterlist *p_tag, sg_tag[2];\n\tstruct scatterlist *p_outp, sg_outp[2];\n\tstruct scatterlist *p_aad;\n\n\tif (!aes->iv)\n\t\treturn -EINVAL;\n\n\tif (!((aes->key_len == AES_KEYSIZE_128) ||\n\t\t(aes->key_len == AES_KEYSIZE_192) ||\n\t\t(aes->key_len == AES_KEYSIZE_256)))\n\t\treturn -EINVAL;\n\n\tif (!aes->key) /* Gotta have a key SGL */\n\t\treturn -EINVAL;\n\n\t/* Zero defaults to 16 bytes, the maximum size */\n\tauthsize = aes->authsize ? aes->authsize : AES_BLOCK_SIZE;\n\tswitch (authsize) {\n\tcase 16:\n\tcase 15:\n\tcase 14:\n\tcase 13:\n\tcase 12:\n\tcase 8:\n\tcase 4:\n\t\tbreak;\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\n\t/* First, decompose the source buffer into AAD & PT,\n\t * and the destination buffer into AAD, CT & tag, or\n\t * the input into CT & tag.\n\t * It is expected that the input and output SGs will\n\t * be valid, even if the AAD and input lengths are 0.\n\t */\n\tp_aad = aes->src;\n\tp_inp = scatterwalk_ffwd(sg_inp, aes->src, aes->aad_len);\n\tp_outp = scatterwalk_ffwd(sg_outp, aes->dst, aes->aad_len);\n\tif (aes->action == CCP_AES_ACTION_ENCRYPT) {\n\t\tilen = aes->src_len;\n\t\tp_tag = scatterwalk_ffwd(sg_tag, p_outp, ilen);\n\t} else {\n\t\t/* Input length for decryption includes tag */\n\t\tilen = aes->src_len - authsize;\n\t\tp_tag = scatterwalk_ffwd(sg_tag, p_inp, ilen);\n\t}\n\n\tjobid = CCP_NEW_JOBID(cmd_q->ccp);\n\n\tmemset(&op, 0, sizeof(op));\n\top.cmd_q = cmd_q;\n\top.jobid = jobid;\n\top.sb_key = cmd_q->sb_key; /* Pre-allocated */\n\top.sb_ctx = cmd_q->sb_ctx; /* Pre-allocated */\n\top.init = 1;\n\top.u.aes.type = aes->type;\n\n\t/* Copy the key to the LSB */\n\tret = ccp_init_dm_workarea(&key, cmd_q,\n\t\t\t\t   CCP_AES_CTX_SB_COUNT * CCP_SB_BYTES,\n\t\t\t\t   DMA_TO_DEVICE);\n\tif (ret)\n\t\treturn ret;\n\n\tdm_offset = CCP_SB_BYTES - aes->key_len;\n\tret = ccp_set_dm_area(&key, dm_offset, aes->key, 0, aes->key_len);\n\tif (ret)\n\t\tgoto e_key;\n\tret = ccp_copy_to_sb(cmd_q, &key, op.jobid, op.sb_key,\n\t\t\t     CCP_PASSTHRU_BYTESWAP_256BIT);\n\tif (ret) {\n\t\tcmd->engine_error = cmd_q->cmd_error;\n\t\tgoto e_key;\n\t}\n\n\t/* Copy the context (IV) to the LSB.\n\t * There is an assumption here that the IV is 96 bits in length, plus\n\t * a nonce of 32 bits. If no IV is present, use a zeroed buffer.\n\t */\n\tret = ccp_init_dm_workarea(&ctx, cmd_q,\n\t\t\t\t   CCP_AES_CTX_SB_COUNT * CCP_SB_BYTES,\n\t\t\t\t   DMA_BIDIRECTIONAL);\n\tif (ret)\n\t\tgoto e_key;\n\n\tdm_offset = CCP_AES_CTX_SB_COUNT * CCP_SB_BYTES - aes->iv_len;\n\tret = ccp_set_dm_area(&ctx, dm_offset, aes->iv, 0, aes->iv_len);\n\tif (ret)\n\t\tgoto e_ctx;\n\n\tret = ccp_copy_to_sb(cmd_q, &ctx, op.jobid, op.sb_ctx,\n\t\t\t     CCP_PASSTHRU_BYTESWAP_256BIT);\n\tif (ret) {\n\t\tcmd->engine_error = cmd_q->cmd_error;\n\t\tgoto e_ctx;\n\t}\n\n\top.init = 1;\n\tif (aes->aad_len > 0) {\n\t\t/* Step 1: Run a GHASH over the Additional Authenticated Data */\n\t\tret = ccp_init_data(&aad, cmd_q, p_aad, aes->aad_len,\n\t\t\t\t    AES_BLOCK_SIZE,\n\t\t\t\t    DMA_TO_DEVICE);\n\t\tif (ret)\n\t\t\tgoto e_ctx;\n\n\t\top.u.aes.mode = CCP_AES_MODE_GHASH;\n\t\top.u.aes.action = CCP_AES_GHASHAAD;\n\n\t\twhile (aad.sg_wa.bytes_left) {\n\t\t\tccp_prepare_data(&aad, NULL, &op, AES_BLOCK_SIZE, true);\n\n\t\t\tret = cmd_q->ccp->vdata->perform->aes(&op);\n\t\t\tif (ret) {\n\t\t\t\tcmd->engine_error = cmd_q->cmd_error;\n\t\t\t\tgoto e_aad;\n\t\t\t}\n\n\t\t\tccp_process_data(&aad, NULL, &op);\n\t\t\top.init = 0;\n\t\t}\n\t}\n\n\top.u.aes.mode = CCP_AES_MODE_GCTR;\n\top.u.aes.action = aes->action;\n\n\tif (ilen > 0) {\n\t\t/* Step 2: Run a GCTR over the plaintext */\n\t\tin_place = (sg_virt(p_inp) == sg_virt(p_outp)) ? true : false;\n\n\t\tret = ccp_init_data(&src, cmd_q, p_inp, ilen,\n\t\t\t\t    AES_BLOCK_SIZE,\n\t\t\t\t    in_place ? DMA_BIDIRECTIONAL\n\t\t\t\t\t     : DMA_TO_DEVICE);\n\t\tif (ret)\n\t\t\tgoto e_aad;\n\n\t\tif (in_place) {\n\t\t\tdst = src;\n\t\t} else {\n\t\t\tret = ccp_init_data(&dst, cmd_q, p_outp, ilen,\n\t\t\t\t\t    AES_BLOCK_SIZE, DMA_FROM_DEVICE);\n\t\t\tif (ret)\n\t\t\t\tgoto e_src;\n\t\t}\n\n\t\top.soc = 0;\n\t\top.eom = 0;\n\t\top.init = 1;\n\t\twhile (src.sg_wa.bytes_left) {\n\t\t\tccp_prepare_data(&src, &dst, &op, AES_BLOCK_SIZE, true);\n\t\t\tif (!src.sg_wa.bytes_left) {\n\t\t\t\tunsigned int nbytes = ilen % AES_BLOCK_SIZE;\n\n\t\t\t\tif (nbytes) {\n\t\t\t\t\top.eom = 1;\n\t\t\t\t\top.u.aes.size = (nbytes * 8) - 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tret = cmd_q->ccp->vdata->perform->aes(&op);\n\t\t\tif (ret) {\n\t\t\t\tcmd->engine_error = cmd_q->cmd_error;\n\t\t\t\tgoto e_dst;\n\t\t\t}\n\n\t\t\tccp_process_data(&src, &dst, &op);\n\t\t\top.init = 0;\n\t\t}\n\t}\n\n\t/* Step 3: Update the IV portion of the context with the original IV */\n\tret = ccp_copy_from_sb(cmd_q, &ctx, op.jobid, op.sb_ctx,\n\t\t\t       CCP_PASSTHRU_BYTESWAP_256BIT);\n\tif (ret) {\n\t\tcmd->engine_error = cmd_q->cmd_error;\n\t\tgoto e_dst;\n\t}\n\n\tret = ccp_set_dm_area(&ctx, dm_offset, aes->iv, 0, aes->iv_len);\n\tif (ret)\n\t\tgoto e_dst;\n\n\tret = ccp_copy_to_sb(cmd_q, &ctx, op.jobid, op.sb_ctx,\n\t\t\t     CCP_PASSTHRU_BYTESWAP_256BIT);\n\tif (ret) {\n\t\tcmd->engine_error = cmd_q->cmd_error;\n\t\tgoto e_dst;\n\t}\n\n\t/* Step 4: Concatenate the lengths of the AAD and source, and\n\t * hash that 16 byte buffer.\n\t */\n\tret = ccp_init_dm_workarea(&final_wa, cmd_q, AES_BLOCK_SIZE,\n\t\t\t\t   DMA_BIDIRECTIONAL);\n\tif (ret)\n\t\tgoto e_dst;\n\tfinal = (__be64 *)final_wa.address;\n\tfinal[0] = cpu_to_be64(aes->aad_len * 8);\n\tfinal[1] = cpu_to_be64(ilen * 8);\n\n\tmemset(&op, 0, sizeof(op));\n\top.cmd_q = cmd_q;\n\top.jobid = jobid;\n\top.sb_key = cmd_q->sb_key; /* Pre-allocated */\n\top.sb_ctx = cmd_q->sb_ctx; /* Pre-allocated */\n\top.init = 1;\n\top.u.aes.type = aes->type;\n\top.u.aes.mode = CCP_AES_MODE_GHASH;\n\top.u.aes.action = CCP_AES_GHASHFINAL;\n\top.src.type = CCP_MEMTYPE_SYSTEM;\n\top.src.u.dma.address = final_wa.dma.address;\n\top.src.u.dma.length = AES_BLOCK_SIZE;\n\top.dst.type = CCP_MEMTYPE_SYSTEM;\n\top.dst.u.dma.address = final_wa.dma.address;\n\top.dst.u.dma.length = AES_BLOCK_SIZE;\n\top.eom = 1;\n\top.u.aes.size = 0;\n\tret = cmd_q->ccp->vdata->perform->aes(&op);\n\tif (ret)\n\t\tgoto e_final_wa;\n\n\tif (aes->action == CCP_AES_ACTION_ENCRYPT) {\n\t\t/* Put the ciphered tag after the ciphertext. */\n\t\tccp_get_dm_area(&final_wa, 0, p_tag, 0, authsize);\n\t} else {\n\t\t/* Does this ciphered tag match the input? */\n\t\tret = ccp_init_dm_workarea(&tag, cmd_q, authsize,\n\t\t\t\t\t   DMA_BIDIRECTIONAL);\n\t\tif (ret)\n\t\t\tgoto e_final_wa;\n\t\tret = ccp_set_dm_area(&tag, 0, p_tag, 0, authsize);\n\t\tif (ret) {\n\t\t\tccp_dm_free(&tag);\n\t\t\tgoto e_final_wa;\n\t\t}\n\n\t\tret = crypto_memneq(tag.address, final_wa.address,\n\t\t\t\t    authsize) ? -EBADMSG : 0;\n\t\tccp_dm_free(&tag);\n\t}\n\ne_final_wa:\n\tccp_dm_free(&final_wa);\n\ne_dst:\n\tif (ilen > 0 && !in_place)\n\t\tccp_free_data(&dst, cmd_q);\n\ne_src:\n\tif (ilen > 0)\n\t\tccp_free_data(&src, cmd_q);\n\ne_aad:\n\tif (aes->aad_len)\n\t\tccp_free_data(&aad, cmd_q);\n\ne_ctx:\n\tccp_dm_free(&ctx);\n\ne_key:\n\tccp_dm_free(&key);\n\n\treturn ret;\n}", "func_hash": 192342382845429506037482636536985801583, "file_name": "ccp-ops.c", "file_hash": 212296156007927081336268591305304160676, "cwe": ["CWE-703"], "cve": "CVE-2021-3744", "cve_desc": "A memory leak flaw was found in the Linux kernel in the ccp_run_aes_gcm_cmd() function in drivers/crypto/ccp/ccp-ops.c, which allows attackers to cause a denial of service (memory consumption). This vulnerability is similar with the older CVE-2019-18808.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3744"}
{"idx": 197142, "project": "tensorflow", "commit_id": "6da6620efad397c85493b8f8667b821403516708", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/6da6620efad397c85493b8f8667b821403516708", "commit_message": "Secure tf.raw_ops.QuantizeV2\n\nValidate size and shape of min_range and max_range\nEnsure axis is within input dims limits\n\nPiperOrigin-RevId: 387232799\nChange-Id: I36975281f7b5758e9e31a8dcc73fe610ef456318", "target": 1, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor& input = ctx->input(0);\n    const Tensor& input_min_range = ctx->input(1);\n    const Tensor& input_max_range = ctx->input(2);\n\n    int num_slices = 1;\n    if (axis_ > -1) {\n      num_slices = input.dim_size(axis_);\n    }\n\n    const TensorShape& minmax_shape = ctx->input(1).shape();\n    Tensor* output = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n\n    Tensor* output_min_tensor = nullptr;\n    Tensor* output_max_tensor = nullptr;\n\n    if (num_slices == 1) {\n      OP_REQUIRES_OK(ctx, ctx->allocate_output(1, {}, &output_min_tensor));\n      OP_REQUIRES_OK(ctx, ctx->allocate_output(2, {}, &output_max_tensor));\n      const float min_range = input_min_range.template flat()(0);\n      const float max_range = input_max_range.template flat()(0);\n      QuantizeTensor(ctx, input, min_range, max_range, output,\n                     output_min_tensor, output_max_tensor);\n      return;\n    }\n\n    OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST,\n                errors::Unimplemented(\"MIN_FIRST mode is not implemented for \"\n                                      \"Quantize with axis != -1.\"));\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(1, minmax_shape, &output_min_tensor));\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(2, minmax_shape, &output_max_tensor));\n\n    auto input_tensor =\n        input.template flat_inner_outer_dims(axis_ - 1);\n    int64_t pre_dim = 1, post_dim = 1;\n    for (int i = 0; i < axis_; ++i) {\n      pre_dim *= output->dim_size(i);\n    }\n    for (int i = axis_ + 1; i < output->dims(); ++i) {\n      post_dim *= output->dim_size(i);\n    }\n    auto output_tensor = output->template bit_casted_shaped(\n        {pre_dim, num_slices, post_dim});\n    auto min_ranges = input_min_range.template vec();\n    auto max_ranges = input_max_range.template vec();\n    for (int i = 0; i < num_slices; ++i) {\n      QuantizeSlice(ctx->eigen_device(), ctx,\n                    input_tensor.template chip<1>(i), min_ranges(i),\n                    max_ranges(i), output_tensor.template chip<1>(i),\n                    &output_min_tensor->flat()(i),\n                    &output_max_tensor->flat()(i));\n    }\n  }", "func_hash": 175054869100587978050053791864843631748, "file_name": "quantize_op.cc", "file_hash": 45910676002815731564213734124644481802, "cwe": ["CWE-476"], "cve": "CVE-2021-37663", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions due to incomplete validation in `tf.raw_ops.QuantizeV2`, an attacker can trigger undefined behavior via binding a reference to a null pointer or can access data outside the bounds of heap allocated arrays. The [implementation](https://github.com/tensorflow/tensorflow/blob/84d053187cb80d975ef2b9684d4b61981bca0c41/tensorflow/core/kernels/quantize_op.cc#L59) has some validation but does not check that `min_range` and `max_range` both have the same non-zero number of elements. If `axis` is provided (i.e., not `-1`), then validation should check that it is a value in range for the rank of `input` tensor and then the lengths of `min_range` and `max_range` inputs match the `axis` dimension of the `input` tensor. We have patched the issue in GitHub commit 6da6620efad397c85493b8f8667b821403516708. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37663"}
{"idx": 253970, "project": "tensorflow", "commit_id": "6da6620efad397c85493b8f8667b821403516708", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/6da6620efad397c85493b8f8667b821403516708", "commit_message": "Secure tf.raw_ops.QuantizeV2\n\nValidate size and shape of min_range and max_range\nEnsure axis is within input dims limits\n\nPiperOrigin-RevId: 387232799\nChange-Id: I36975281f7b5758e9e31a8dcc73fe610ef456318", "target": 0, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor& input = ctx->input(0);\n    const Tensor& input_min_range = ctx->input(1);\n    const Tensor& input_max_range = ctx->input(2);\n\n    int num_slices = 1;\n    if (axis_ > -1) {\n      OP_REQUIRES(\n          ctx, input.dims() > axis_,\n          errors::InvalidArgument(\n              \"Axis is on a zero-based index, so its value must always be less \"\n              \"than number of input's dims, but given axis value was \",\n              axis_, \" and input's dims was \", input.dims()));\n      num_slices = input.dim_size(axis_);\n      OP_REQUIRES(ctx, input_min_range.dims() == 1,\n                  errors::InvalidArgument(\n                      \"If axis is specified, min_range must be a 1-D tensor \"\n                      \"whose size matches the axis dimension of the input and \"\n                      \"output tensors, but min_range dims are \",\n                      input_min_range.dims()));\n      OP_REQUIRES(ctx, input_min_range.dim_size(0) == num_slices,\n                  errors::InvalidArgument(\n                      \"If axis is specified, min_range must be a 1-D tensor \"\n                      \"whose size matches the axis dimension of the input and \"\n                      \"output tensors, but min_range is a 1-D tensor of size \",\n                      input_min_range.dim_size(0),\n                      \" and input's axis dimension is of size \", num_slices));\n      OP_REQUIRES(ctx, input_max_range.dims() == 1,\n                  errors::InvalidArgument(\n                      \"If axis is specified, max_range must be a 1-D tensor \"\n                      \"whose size matches the axis dimension of the input and \"\n                      \"output tensors, but max_range dims are \",\n                      input_max_range.dims()));\n      OP_REQUIRES(ctx, input_max_range.dim_size(0) == num_slices,\n                  errors::InvalidArgument(\n                      \"If axis is specified, max_range must be a 1-D tensor \"\n                      \"whose size matches the axis dimension of the input and \"\n                      \"output tensors, but max_range is a 1-D tensor of size \",\n                      input_max_range.dim_size(0),\n                      \" and input's axis dimension is of size \", num_slices));\n    } else {\n      OP_REQUIRES(ctx, input_min_range.NumElements() == 1,\n                  errors::InvalidArgument(\n                      \"If axis is not specified, min_range must contain a \"\n                      \"single float element, but it contains \",\n                      input_min_range.NumElements(), \" elements\"));\n      OP_REQUIRES(ctx, input_max_range.NumElements() == 1,\n                  errors::InvalidArgument(\n                      \"If axis is not specified, max_range must contain a \"\n                      \"single float element, but it contains \",\n                      input_max_range.NumElements(), \" elements\"));\n    }\n\n    const TensorShape& minmax_shape = ctx->input(1).shape();\n    Tensor* output = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n\n    Tensor* output_min_tensor = nullptr;\n    Tensor* output_max_tensor = nullptr;\n\n    if (num_slices == 1) {\n      OP_REQUIRES_OK(ctx, ctx->allocate_output(1, {}, &output_min_tensor));\n      OP_REQUIRES_OK(ctx, ctx->allocate_output(2, {}, &output_max_tensor));\n      const float min_range = input_min_range.template flat()(0);\n      const float max_range = input_max_range.template flat()(0);\n      QuantizeTensor(ctx, input, min_range, max_range, output,\n                     output_min_tensor, output_max_tensor);\n      return;\n    }\n\n    OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST,\n                errors::Unimplemented(\"MIN_FIRST mode is not implemented for \"\n                                      \"Quantize with axis != -1.\"));\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(1, minmax_shape, &output_min_tensor));\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(2, minmax_shape, &output_max_tensor));\n\n    auto input_tensor =\n        input.template flat_inner_outer_dims(axis_ - 1);\n    int64_t pre_dim = 1, post_dim = 1;\n    for (int i = 0; i < axis_; ++i) {\n      pre_dim *= output->dim_size(i);\n    }\n    for (int i = axis_ + 1; i < output->dims(); ++i) {\n      post_dim *= output->dim_size(i);\n    }\n    auto output_tensor = output->template bit_casted_shaped(\n        {pre_dim, num_slices, post_dim});\n    auto min_ranges = input_min_range.template vec();\n    auto max_ranges = input_max_range.template vec();\n    for (int i = 0; i < num_slices; ++i) {\n      QuantizeSlice(ctx->eigen_device(), ctx,\n                    input_tensor.template chip<1>(i), min_ranges(i),\n                    max_ranges(i), output_tensor.template chip<1>(i),\n                    &output_min_tensor->flat()(i),\n                    &output_max_tensor->flat()(i));\n    }\n  }", "func_hash": 245467204964919391793075021199596127255, "file_name": "quantize_op.cc", "file_hash": 256130062942264695553473842652666995281, "cwe": ["CWE-476"], "cve": "CVE-2021-37663", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions due to incomplete validation in `tf.raw_ops.QuantizeV2`, an attacker can trigger undefined behavior via binding a reference to a null pointer or can access data outside the bounds of heap allocated arrays. The [implementation](https://github.com/tensorflow/tensorflow/blob/84d053187cb80d975ef2b9684d4b61981bca0c41/tensorflow/core/kernels/quantize_op.cc#L59) has some validation but does not check that `min_range` and `max_range` both have the same non-zero number of elements. If `axis` is provided (i.e., not `-1`), then validation should check that it is a value in range for the rank of `input` tensor and then the lengths of `min_range` and `max_range` inputs match the `axis` dimension of the `input` tensor. We have patched the issue in GitHub commit 6da6620efad397c85493b8f8667b821403516708. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37663"}
{"idx": 197185, "project": "FFmpeg", "commit_id": "9ffa49496d1aae4cbbb387aac28a9e061a6ab0a6", "project_url": "https://github.com/FFmpeg/FFmpeg", "commit_url": "https://github.com/FFmpeg/FFmpeg/commit/9ffa49496d1aae4cbbb387aac28a9e061a6ab0a6", "commit_message": "avformat/adtsenc: return value check for init_get_bits in adts_decode_extradata\n\nAs the second argument for init_get_bits (buf) can be crafted, a return value check for this function call is necessary.\n'buf' is  part of  'AVPacket pkt'.\nreplace init_get_bits with init_get_bits8.\n\nSigned-off-by: Michael Niedermayer ", "target": 1, "func": "static int adts_decode_extradata(AVFormatContext *s, ADTSContext *adts, const uint8_t *buf, int size)\n{\n    GetBitContext gb;\n    PutBitContext pb;\n    MPEG4AudioConfig m4ac;\n    int off;\n\n    init_get_bits(&gb, buf, size * 8);\n    off = avpriv_mpeg4audio_get_config2(&m4ac, buf, size, 1, s);\n    if (off < 0)\n        return off;\n    skip_bits_long(&gb, off);\n    adts->objecttype        = m4ac.object_type - 1;\n    adts->sample_rate_index = m4ac.sampling_index;\n    adts->channel_conf      = m4ac.chan_config;\n\n    if (adts->objecttype > 3U) {\n        av_log(s, AV_LOG_ERROR, \"MPEG-4 AOT %d is not allowed in ADTS\\n\", adts->objecttype+1);\n        return AVERROR_INVALIDDATA;\n    }\n    if (adts->sample_rate_index == 15) {\n        av_log(s, AV_LOG_ERROR, \"Escape sample rate index illegal in ADTS\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n    if (get_bits(&gb, 1)) {\n        av_log(s, AV_LOG_ERROR, \"960/120 MDCT window is not allowed in ADTS\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n    if (get_bits(&gb, 1)) {\n        av_log(s, AV_LOG_ERROR, \"Scalable configurations are not allowed in ADTS\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n    if (get_bits(&gb, 1)) {\n        av_log(s, AV_LOG_ERROR, \"Extension flag is not allowed in ADTS\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n    if (!adts->channel_conf) {\n        init_put_bits(&pb, adts->pce_data, MAX_PCE_SIZE);\n\n        put_bits(&pb, 3, 5); //ID_PCE\n        adts->pce_size = (ff_copy_pce_data(&pb, &gb) + 3) / 8;\n        flush_put_bits(&pb);\n    }\n\n    adts->write_adts = 1;\n\n    return 0;\n}", "func_hash": 158925528540777233957652669648532881464, "file_name": "None", "file_hash": null, "cwe": ["CWE-252"], "cve": "CVE-2021-38171", "cve_desc": "adts_decode_extradata in libavformat/adtsenc.c in FFmpeg 4.4 does not check the init_get_bits return value, which is a necessary step because the second argument to init_get_bits can be crafted.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-38171"}
{"idx": 255032, "project": "FFmpeg", "commit_id": "9ffa49496d1aae4cbbb387aac28a9e061a6ab0a6", "project_url": "https://github.com/FFmpeg/FFmpeg", "commit_url": "https://github.com/FFmpeg/FFmpeg/commit/9ffa49496d1aae4cbbb387aac28a9e061a6ab0a6", "commit_message": "avformat/adtsenc: return value check for init_get_bits in adts_decode_extradata\n\nAs the second argument for init_get_bits (buf) can be crafted, a return value check for this function call is necessary.\n'buf' is  part of  'AVPacket pkt'.\nreplace init_get_bits with init_get_bits8.\n\nSigned-off-by: Michael Niedermayer ", "target": 0, "func": "static int adts_decode_extradata(AVFormatContext *s, ADTSContext *adts, const uint8_t *buf, int size)\n{\n    GetBitContext gb;\n    PutBitContext pb;\n    MPEG4AudioConfig m4ac;\n    int off, ret;\n\n    ret = init_get_bits8(&gb, buf, size);\n    if (ret < 0)\n        return ret;\n    off = avpriv_mpeg4audio_get_config2(&m4ac, buf, size, 1, s);\n    if (off < 0)\n        return off;\n    skip_bits_long(&gb, off);\n    adts->objecttype        = m4ac.object_type - 1;\n    adts->sample_rate_index = m4ac.sampling_index;\n    adts->channel_conf      = m4ac.chan_config;\n\n    if (adts->objecttype > 3U) {\n        av_log(s, AV_LOG_ERROR, \"MPEG-4 AOT %d is not allowed in ADTS\\n\", adts->objecttype+1);\n        return AVERROR_INVALIDDATA;\n    }\n    if (adts->sample_rate_index == 15) {\n        av_log(s, AV_LOG_ERROR, \"Escape sample rate index illegal in ADTS\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n    if (get_bits(&gb, 1)) {\n        av_log(s, AV_LOG_ERROR, \"960/120 MDCT window is not allowed in ADTS\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n    if (get_bits(&gb, 1)) {\n        av_log(s, AV_LOG_ERROR, \"Scalable configurations are not allowed in ADTS\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n    if (get_bits(&gb, 1)) {\n        av_log(s, AV_LOG_ERROR, \"Extension flag is not allowed in ADTS\\n\");\n        return AVERROR_INVALIDDATA;\n    }\n    if (!adts->channel_conf) {\n        init_put_bits(&pb, adts->pce_data, MAX_PCE_SIZE);\n\n        put_bits(&pb, 3, 5); //ID_PCE\n        adts->pce_size = (ff_copy_pce_data(&pb, &gb) + 3) / 8;\n        flush_put_bits(&pb);\n    }\n\n    adts->write_adts = 1;\n\n    return 0;\n}", "func_hash": 40516325143740418299117254278054276605, "file_name": "None", "file_hash": null, "cwe": ["CWE-252"], "cve": "CVE-2021-38171", "cve_desc": "adts_decode_extradata in libavformat/adtsenc.c in FFmpeg 4.4 does not check the init_get_bits return value, which is a necessary step because the second argument to init_get_bits can be crafted.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-38171"}
{"idx": 197223, "project": "njs", "commit_id": "ab1702c7af9959366a5ddc4a75b4357d4e9ebdc1", "project_url": "https://github.com/nginx/njs", "commit_url": "https://github.com/nginx/njs/commit/ab1702c7af9959366a5ddc4a75b4357d4e9ebdc1", "commit_message": "Fixed typo while calculating module path length.\n\nThe issue was introduced in 77c398f26d7e (not released yet).", "target": 1, "func": "njs_module_path(njs_vm_t *vm, const njs_str_t *dir, njs_module_info_t *info)\n{\n    char        *p;\n    size_t      length;\n    njs_bool_t  trail;\n    char        src[NJS_MAX_PATH + 1];\n\n    trail = 0;\n    length = info->name.length;\n\n    if (dir != NULL) {\n        length = dir->length;\n\n        if (length == 0) {\n            return NJS_DECLINED;\n        }\n\n        trail = (dir->start[dir->length - 1] != '/');\n\n        if (trail) {\n            length++;\n        }\n    }\n\n    if (njs_slow_path(length > NJS_MAX_PATH)) {\n        return NJS_ERROR;\n    }\n\n    p = &src[0];\n\n    if (dir != NULL) {\n        p = (char *) njs_cpymem(p, dir->start, dir->length);\n\n        if (trail) {\n            *p++ = '/';\n        }\n    }\n\n    p = (char *) njs_cpymem(p, info->name.start, info->name.length);\n    *p = '\\0';\n\n    p = realpath(&src[0], &info->path[0]);\n    if (p == NULL) {\n        return NJS_DECLINED;\n    }\n\n    info->fd = open(&info->path[0], O_RDONLY);\n    if (info->fd < 0) {\n        return NJS_DECLINED;\n    }\n\n\n    info->file.start = (u_char *) &info->path[0];\n    info->file.length = njs_strlen(info->file.start);\n\n    return NJS_OK;\n}", "func_hash": 236847431367932249474325490160608146650, "file_name": "njs_module.c", "file_hash": 230069477074111336405443824718201036517, "cwe": ["CWE-787"], "cve": "CVE-2022-29379", "cve_desc": "Nginx NJS v0.7.3 was discovered to contain a stack overflow in the function njs_default_module_loader at /src/njs/src/njs_module.c. NOTE: multiple third parties dispute this report, e.g., the behavior is only found in unreleased development code that was not part of the 0.7.2, 0.7.3, or 0.7.4 release", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29379"}
{"idx": 255574, "project": "njs", "commit_id": "ab1702c7af9959366a5ddc4a75b4357d4e9ebdc1", "project_url": "https://github.com/nginx/njs", "commit_url": "https://github.com/nginx/njs/commit/ab1702c7af9959366a5ddc4a75b4357d4e9ebdc1", "commit_message": "Fixed typo while calculating module path length.\n\nThe issue was introduced in 77c398f26d7e (not released yet).", "target": 0, "func": "njs_module_path(njs_vm_t *vm, const njs_str_t *dir, njs_module_info_t *info)\n{\n    char        *p;\n    size_t      length;\n    njs_bool_t  trail;\n    char        src[NJS_MAX_PATH + 1];\n\n    trail = 0;\n    length = info->name.length;\n\n    if (dir != NULL) {\n        length += dir->length;\n\n        if (length == 0) {\n            return NJS_DECLINED;\n        }\n\n        trail = (dir->start[dir->length - 1] != '/');\n\n        if (trail) {\n            length++;\n        }\n    }\n\n    if (njs_slow_path(length > NJS_MAX_PATH)) {\n        return NJS_ERROR;\n    }\n\n    p = &src[0];\n\n    if (dir != NULL) {\n        p = (char *) njs_cpymem(p, dir->start, dir->length);\n\n        if (trail) {\n            *p++ = '/';\n        }\n    }\n\n    p = (char *) njs_cpymem(p, info->name.start, info->name.length);\n    *p = '\\0';\n\n    p = realpath(&src[0], &info->path[0]);\n    if (p == NULL) {\n        return NJS_DECLINED;\n    }\n\n    info->fd = open(&info->path[0], O_RDONLY);\n    if (info->fd < 0) {\n        return NJS_DECLINED;\n    }\n\n\n    info->file.start = (u_char *) &info->path[0];\n    info->file.length = njs_strlen(info->file.start);\n\n    return NJS_OK;\n}", "func_hash": 78973632734119439539784178182699583703, "file_name": "njs_module.c", "file_hash": 205736021540779021398705962921872486789, "cwe": ["CWE-787"], "cve": "CVE-2022-29379", "cve_desc": "Nginx NJS v0.7.3 was discovered to contain a stack overflow in the function njs_default_module_loader at /src/njs/src/njs_module.c. NOTE: multiple third parties dispute this report, e.g., the behavior is only found in unreleased development code that was not part of the 0.7.2, 0.7.3, or 0.7.4 release", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29379"}
{"idx": 197239, "project": "tensorflow", "commit_id": "203214568f5bc237603dbab6e1fd389f1572f5c9", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/203214568f5bc237603dbab6e1fd389f1572f5c9", "commit_message": "Reorganize and add more validation to MKL requantization\n\nPiperOrigin-RevId: 387901341\nChange-Id: I2515b9034c64e113db0bcec8337d30643ab0a0f1", "target": 1, "func": "  void Compute(OpKernelContext* ctx) override {\n    try {\n      const Tensor& input = ctx->input(kInputTensorIndex);\n      const Tensor& input_min_vec = ctx->input(kInputMinVecIndex);\n      float* input_min_vec_data = (float*)const_cast(\n          static_cast(input_min_vec.flat().data()));\n      const Tensor& input_max_vec = ctx->input(kInputMaxVecIndex);\n      float* input_max_vec_data = (float*)const_cast(\n          static_cast(input_max_vec.flat().data()));\n\n      const Tensor& input_requested_min = ctx->input(this->kRequestMinIndex);\n      const float input_requested_min_float =\n          input_requested_min.flat()(0);\n      const Tensor& input_requested_max = ctx->input(this->kRequestMaxIndex);\n      const float input_requested_max_float =\n          input_requested_max.flat()(0);\n\n      size_t depth = input_min_vec.NumElements();\n      OP_REQUIRES(\n          ctx, input.dims() == 4,\n          errors::InvalidArgument(\"Current RequantizePerChannel operator\"\n                                  \"supports 4D tensors only.\"));\n      OP_REQUIRES(\n          ctx, input_min_vec.dim_size(0) == depth,\n          errors::InvalidArgument(\"input_min has incorrect size, expected \",\n                                  depth, \" was \", input_min_vec.dim_size(0)));\n      OP_REQUIRES(\n          ctx, input_max_vec.dim_size(0) == depth,\n          errors::InvalidArgument(\"input_max has incorrect size, expected \",\n                                  depth, \" was \", input_max_vec.dim_size(0)));\n\n      if (out_type_ == DT_QINT8) DCHECK(input_requested_min_float < 0.0f);\n\n      const float factor = (out_type_ == DT_QINT8) ? 127.0f : 255.0f;\n      const float requested_min_max =\n          std::max(std::abs(input_requested_min_float),\n                   std::abs(input_requested_max_float));\n      Tensor* output = nullptr;\n      OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputTensorIndex,\n                                               input.shape(), &output));\n\n      std::vector scales(depth);\n      for (int i = 0; i < depth; ++i) {\n        float min_max_from_vec = std::max(std::abs(input_min_vec_data[i]),\n                                          std::abs(input_max_vec_data[i]));\n        scales[i] = factor * (min_max_from_vec / requested_min_max /\n                              static_cast(1L << 31));\n      }\n\n      mkldnn::primitive_attr reorder_attr;\n      reorder_attr.set_output_scales(2, scales);\n\n      memory::dims dims_mkl_order =\n          TFShapeToMklDnnDimsInNCHW(input.shape(), FORMAT_NHWC);\n      memory::desc input_md = memory::desc(dims_mkl_order, MklDnnType(),\n                                           memory::format_tag::nhwc);\n      memory::desc output_md =\n          (out_type_ == DT_QINT8)\n              ? memory::desc(dims_mkl_order, MklDnnType(),\n                             memory::format_tag::nhwc)\n              : memory::desc(dims_mkl_order, MklDnnType(),\n                             memory::format_tag::nhwc);\n\n      void* input_buf =\n          static_cast(const_cast(input.flat().data()));\n      void* output_buf;\n      if (out_type_ == DT_QINT8) {\n        output_buf = static_cast(\n            const_cast(output->flat().data()));\n      } else {\n        output_buf = static_cast(\n            const_cast(output->flat().data()));\n      }\n\n      std::unique_ptr input_mem_prim(\n          new memory(input_md, cpu_engine_, input_buf));\n      std::unique_ptr output_mem_prim(\n          new memory(output_md, cpu_engine_, output_buf));\n\n      mkldnn::reorder::primitive_desc reorder_pd =\n          ReorderPd(cpu_engine_, input_mem_prim->get_desc(), cpu_engine_,\n                    output_mem_prim->get_desc(), reorder_attr);\n      std::shared_ptr reorder_stream;\n      MklDnnThreadPool eigen_tp(ctx);\n      reorder_stream.reset(CreateStream(&eigen_tp, cpu_engine_));\n      std::unordered_map reorder_args = {\n          {MKLDNN_ARG_FROM, *input_mem_prim},\n          {MKLDNN_ARG_TO, *output_mem_prim}};\n      std::unique_ptr reorder_prim(\n          new mkldnn::reorder(reorder_pd));\n      reorder_prim->execute(*reorder_stream, reorder_args);\n\n      Tensor* output_min = nullptr;\n      Tensor* output_max = nullptr;\n      OP_REQUIRES_OK(ctx,\n                     ctx->allocate_output(kOutputMinIndex, {}, &output_min));\n      OP_REQUIRES_OK(ctx,\n                     ctx->allocate_output(kOutputMaxIndex, {}, &output_max));\n\n      output_min->flat()(0) = input_requested_min_float;\n      output_max->flat()(0) = input_requested_max_float;\n    } catch (mkldnn::error& e) {\n      string error_msg = \"Status: \" + std::to_string(e.status) +\n                         \", message: \" + std::string(e.message) + \", in file \" +\n                         std::string(__FILE__) + \":\" + std::to_string(__LINE__);\n      OP_REQUIRES_OK(\n          ctx, errors::Aborted(\"Operation received an exception:\", error_msg));\n    }\n  }", "func_hash": 324241400481110766657474950076141174434, "file_name": "mkl_requantize_per_channel_op.cc", "file_hash": 251676487738280920031977890166955496760, "cwe": ["CWE-20"], "cve": "CVE-2021-37665", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions due to incomplete validation in MKL implementation of requantization, an attacker can trigger undefined behavior via binding a reference to a null pointer or can access data outside the bounds of heap allocated arrays. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/mkl/mkl_requantization_range_per_channel_op.cc) does not validate the dimensions of the `input` tensor. A similar issue occurs in `MklRequantizePerChannelOp`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/mkl/mkl_requantize_per_channel_op.cc) does not perform full validation for all the input arguments. We have patched the issue in GitHub commit 9e62869465573cb2d9b5053f1fa02a81fce21d69 and in the Github commit 203214568f5bc237603dbab6e1fd389f1572f5c9. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37665"}
{"idx": 255787, "project": "tensorflow", "commit_id": "203214568f5bc237603dbab6e1fd389f1572f5c9", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/203214568f5bc237603dbab6e1fd389f1572f5c9", "commit_message": "Reorganize and add more validation to MKL requantization\n\nPiperOrigin-RevId: 387901341\nChange-Id: I2515b9034c64e113db0bcec8337d30643ab0a0f1", "target": 0, "func": "  void Compute(OpKernelContext* ctx) override {\n    try {\n      const Tensor& input = ctx->input(kInputTensorIndex);\n      OP_REQUIRES(\n          ctx, input.dims() == 4,\n          errors::InvalidArgument(\"Current RequantizePerChannel operator\"\n                                  \"supports 4D tensors only.\"));\n\n      const Tensor& input_min_vec = ctx->input(kInputMinVecIndex);\n      size_t depth = input_min_vec.NumElements();\n      float* input_min_vec_data = (float*)const_cast(\n          static_cast(input_min_vec.flat().data()));\n\n      const Tensor& input_max_vec = ctx->input(kInputMaxVecIndex);\n      OP_REQUIRES(\n          ctx, input_max_vec.NumElements() == depth,\n          errors::InvalidArgument(\"input_max has incorrect size, expected \",\n                                  depth, \" was \", input_max_vec.NumElements()));\n      float* input_max_vec_data = (float*)const_cast(\n          static_cast(input_max_vec.flat().data()));\n\n      const Tensor& input_requested_min = ctx->input(this->kRequestMinIndex);\n      OP_REQUIRES(\n          ctx, input_requested_min.NumElements() == 1,\n          errors::InvalidArgument(\"requested_output_min must be a scalar\"));\n      const float input_requested_min_float =\n          input_requested_min.flat()(0);\n\n      const Tensor& input_requested_max = ctx->input(this->kRequestMaxIndex);\n      OP_REQUIRES(\n          ctx, input_requested_min.NumElements() == 1,\n          errors::InvalidArgument(\"requested_output_max must be a scalar\"));\n      const float input_requested_max_float =\n          input_requested_max.flat()(0);\n\n      if (out_type_ == DT_QINT8) {\n        OP_REQUIRES(ctx, input_requested_min_float < 0.0f,\n                    errors::InvalidArgument(\n                        \"If out_type is QINT8, requested_output_max must be \"\n                        \"non negative, got \",\n                        input_requested_min_float));\n      }\n\n      const float factor = (out_type_ == DT_QINT8) ? 127.0f : 255.0f;\n      const float requested_min_max =\n          std::max(std::abs(input_requested_min_float),\n                   std::abs(input_requested_max_float));\n      Tensor* output = nullptr;\n      OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputTensorIndex,\n                                               input.shape(), &output));\n\n      std::vector scales(depth);\n      for (int i = 0; i < depth; ++i) {\n        float min_max_from_vec = std::max(std::abs(input_min_vec_data[i]),\n                                          std::abs(input_max_vec_data[i]));\n        scales[i] = factor * (min_max_from_vec / requested_min_max /\n                              static_cast(1L << 31));\n      }\n\n      mkldnn::primitive_attr reorder_attr;\n      reorder_attr.set_output_scales(2, scales);\n\n      memory::dims dims_mkl_order =\n          TFShapeToMklDnnDimsInNCHW(input.shape(), FORMAT_NHWC);\n      memory::desc input_md = memory::desc(dims_mkl_order, MklDnnType(),\n                                           memory::format_tag::nhwc);\n      memory::desc output_md =\n          (out_type_ == DT_QINT8)\n              ? memory::desc(dims_mkl_order, MklDnnType(),\n                             memory::format_tag::nhwc)\n              : memory::desc(dims_mkl_order, MklDnnType(),\n                             memory::format_tag::nhwc);\n\n      void* input_buf =\n          static_cast(const_cast(input.flat().data()));\n      void* output_buf;\n      if (out_type_ == DT_QINT8) {\n        output_buf = static_cast(\n            const_cast(output->flat().data()));\n      } else {\n        output_buf = static_cast(\n            const_cast(output->flat().data()));\n      }\n\n      std::unique_ptr input_mem_prim(\n          new memory(input_md, cpu_engine_, input_buf));\n      std::unique_ptr output_mem_prim(\n          new memory(output_md, cpu_engine_, output_buf));\n\n      mkldnn::reorder::primitive_desc reorder_pd =\n          ReorderPd(cpu_engine_, input_mem_prim->get_desc(), cpu_engine_,\n                    output_mem_prim->get_desc(), reorder_attr);\n      std::shared_ptr reorder_stream;\n      MklDnnThreadPool eigen_tp(ctx);\n      reorder_stream.reset(CreateStream(&eigen_tp, cpu_engine_));\n      std::unordered_map reorder_args = {\n          {MKLDNN_ARG_FROM, *input_mem_prim},\n          {MKLDNN_ARG_TO, *output_mem_prim}};\n      std::unique_ptr reorder_prim(\n          new mkldnn::reorder(reorder_pd));\n      reorder_prim->execute(*reorder_stream, reorder_args);\n\n      Tensor* output_min = nullptr;\n      Tensor* output_max = nullptr;\n      OP_REQUIRES_OK(ctx,\n                     ctx->allocate_output(kOutputMinIndex, {}, &output_min));\n      OP_REQUIRES_OK(ctx,\n                     ctx->allocate_output(kOutputMaxIndex, {}, &output_max));\n\n      output_min->flat()(0) = input_requested_min_float;\n      output_max->flat()(0) = input_requested_max_float;\n    } catch (mkldnn::error& e) {\n      string error_msg = \"Status: \" + std::to_string(e.status) +\n                         \", message: \" + std::string(e.message) + \", in file \" +\n                         std::string(__FILE__) + \":\" + std::to_string(__LINE__);\n      OP_REQUIRES_OK(\n          ctx, errors::Aborted(\"Operation received an exception:\", error_msg));\n    }\n  }", "func_hash": 201878661619754288848170161353082339443, "file_name": "mkl_requantize_per_channel_op.cc", "file_hash": 305646743359625407590451757209165637710, "cwe": ["CWE-20"], "cve": "CVE-2021-37665", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions due to incomplete validation in MKL implementation of requantization, an attacker can trigger undefined behavior via binding a reference to a null pointer or can access data outside the bounds of heap allocated arrays. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/mkl/mkl_requantization_range_per_channel_op.cc) does not validate the dimensions of the `input` tensor. A similar issue occurs in `MklRequantizePerChannelOp`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/mkl/mkl_requantize_per_channel_op.cc) does not perform full validation for all the input arguments. We have patched the issue in GitHub commit 9e62869465573cb2d9b5053f1fa02a81fce21d69 and in the Github commit 203214568f5bc237603dbab6e1fd389f1572f5c9. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37665"}
{"idx": 197242, "project": "tensorflow", "commit_id": "537bc7c723439b9194a358f64d871dd326c18887", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/537bc7c723439b9194a358f64d871dd326c18887", "commit_message": "Fix a null pointer exception caused by branching on uninitialized data.\n\nThis is due to not checking that the params for the quantization exists. If there is no quantization, we should not access the `.params` field.\n\nPiperOrigin-RevId: 385163909\nChange-Id: I2beb8d50649b6542db224c163033fbcbaa49314f", "target": 1, "func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n  const auto* params = reinterpret_cast(node->builtin_data);\n  OpData* op_data = reinterpret_cast(node->user_data);\n  int scratch_tensor_index = op_data->scratch_tensor_index;\n\n  // Check we have all the inputs and outputs we need.\n  TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);\n  TF_LITE_ENSURE_EQ(context, node->inputs->size, 5);\n\n  const TfLiteTensor* input;\n  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n  const TfLiteTensor* weights_feature;\n  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kWeightsFeatureTensor,\n                                          &weights_feature));\n  const TfLiteTensor* weights_time;\n  TF_LITE_ENSURE_OK(\n      context, GetInputSafe(context, node, kWeightsTimeTensor, &weights_time));\n\n  TF_LITE_ENSURE(context,\n                 input->type == kTfLiteFloat32 || input->type == kTfLiteInt8);\n\n  // Check all the parameters of tensor match within themselves and match the\n  // input configuration.\n  const int rank = params->rank;\n  const int batch_size = input->dims->data[0];\n  const int num_filters = weights_feature->dims->data[0];\n  TF_LITE_ENSURE(context, rank != 0);\n  TF_LITE_ENSURE_EQ(context, num_filters % rank, 0);\n  const int num_units = num_filters / rank;\n  const int memory_size = weights_time->dims->data[1];\n  TF_LITE_ENSURE_EQ(context, input->dims->data[1],\n                    weights_feature->dims->data[1]);\n  TF_LITE_ENSURE_EQ(context, weights_time->dims->data[0], num_filters);\n\n  const TfLiteTensor* bias = GetOptionalInputTensor(context, node, kBiasTensor);\n  if (bias) {\n    TF_LITE_ENSURE_EQ(context, bias->dims->data[0], num_units);\n  }\n\n  const TfLiteTensor* state;\n  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kStateTensor, &state));\n  TfLiteTensor* output;\n  TF_LITE_ENSURE_OK(context,\n                    GetOutputSafe(context, node, kOutputTensor, &output));\n\n  // Check the shape of input state tensors.\n  TF_LITE_ENSURE_EQ(context, NumDimensions(state), 2);\n  TF_LITE_ENSURE_EQ(context, SizeOfDimension(state, 0), batch_size);\n  TF_LITE_ENSURE_EQ(context, SizeOfDimension(state, 1),\n                    memory_size * num_filters);\n\n  // Resize output.\n  TfLiteIntArray* output_size_array = TfLiteIntArrayCreate(2);\n  output_size_array->data[0] = batch_size;\n  output_size_array->data[1] = num_units;\n  TF_LITE_ENSURE_OK(context,\n                    context->ResizeTensor(context, output, output_size_array));\n\n  // The weights are of consistent type, so it suffices to check one.\n  const bool is_hybrid_op = IsHybridOp(input, weights_feature);\n  const bool is_full_integer = input->type == kTfLiteInt8;\n\n  // Resize scratch.\n  TfLiteIntArrayFree(node->temporaries);\n  if (is_hybrid_op) {\n    node->temporaries = TfLiteIntArrayCreate(6);\n  } else if (is_full_integer) {\n    node->temporaries = TfLiteIntArrayCreate(2);\n  } else {\n    node->temporaries = TfLiteIntArrayCreate(1);\n  }\n  node->temporaries->data[0] = scratch_tensor_index;\n\n  TfLiteIntArray* scratch_size_array = TfLiteIntArrayCreate(2);\n  scratch_size_array->data[0] = batch_size;\n  scratch_size_array->data[1] = num_filters;\n\n  TfLiteTensor* scratch_tensor;\n  TF_LITE_ENSURE_OK(\n      context, GetTemporarySafe(context, node, /*index=*/0, &scratch_tensor));\n\n  // The scratch buffer is of type int32 for full integer svdf and it's of type\n  // float32 for hybrid and float case.\n  if (is_full_integer) {\n    scratch_tensor->type = kTfLiteInt32;\n  } else {\n    scratch_tensor->type = kTfLiteFloat32;\n  }\n  scratch_tensor->allocation_type = kTfLiteArenaRw;\n  TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scratch_tensor,\n                                                   scratch_size_array));\n\n  if (is_hybrid_op) {\n    op_data->compute_row_sums = true;\n    // Tell interpreter to allocate temporary tensors to store quantized values\n    // of input tensors.\n    node->temporaries->data[1] = scratch_tensor_index + 1;\n    TfLiteTensor* input_quantized;\n    TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, /*index=*/1,\n                                                &input_quantized));\n    input_quantized->type = weights_feature->type;\n    input_quantized->allocation_type = kTfLiteArenaRw;\n    if (!TfLiteIntArrayEqual(input_quantized->dims, input->dims)) {\n      TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);\n      TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,\n                                                       input_quantized_size));\n    }\n\n    // Tell interpreter to allocate temporary tensors to store scaling factors.\n    node->temporaries->data[2] = scratch_tensor_index + 2;\n    TfLiteTensor* scaling_factors;\n    TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, /*index=*/2,\n                                                &scaling_factors));\n    scaling_factors->type = kTfLiteFloat32;\n    scaling_factors->allocation_type = kTfLiteArenaRw;\n    int scaling_dims[1] = {batch_size};\n    if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {\n      TfLiteIntArray* scaling_factors_size = TfLiteIntArrayCreate(1);\n      scaling_factors_size->data[0] = batch_size;\n      TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scaling_factors,\n                                                       scaling_factors_size));\n    }\n\n    // Used to store dequantized weights_time matrix for hybrid computation of\n    // matmul(state, weights_time), which occurs in floating point.\n    node->temporaries->data[3] = scratch_tensor_index + 3;\n    TfLiteTensor* float_weights_time;\n    TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, /*index=*/3,\n                                                &float_weights_time));\n    float_weights_time->type = kTfLiteFloat32;\n    // Persistent so that we can compute the dequantized weights only once.\n    float_weights_time->allocation_type = kTfLiteArenaRwPersistent;\n    if (!TfLiteIntArrayEqual(float_weights_time->dims, weights_time->dims)) {\n      TfLiteIntArray* float_weights_time_size =\n          TfLiteIntArrayCopy(weights_time->dims);\n      TF_LITE_ENSURE_OK(context,\n                        context->ResizeTensor(context, float_weights_time,\n                                              float_weights_time_size));\n    }\n\n    node->temporaries->data[4] = scratch_tensor_index + 4;\n    TfLiteTensor* zero_points;\n    TF_LITE_ENSURE_OK(\n        context, GetTemporarySafe(context, node, /*index=*/4, &zero_points));\n    zero_points->type = kTfLiteFloat32;\n    zero_points->allocation_type = kTfLiteArenaRw;\n    int zero_points_dims[1] = {batch_size};\n    if (!TfLiteIntArrayEqualsArray(zero_points->dims, 1, zero_points_dims)) {\n      TfLiteIntArray* zero_points_size = TfLiteIntArrayCreate(1);\n      zero_points_size->data[0] = zero_points_dims[0];\n      TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, zero_points,\n                                                       zero_points_size));\n    }\n\n    node->temporaries->data[5] = scratch_tensor_index + 5;\n    TfLiteTensor* row_sums;\n    TF_LITE_ENSURE_OK(context,\n                      GetTemporarySafe(context, node, /*index=*/5, &row_sums));\n    row_sums->type = kTfLiteFloat32;\n    row_sums->allocation_type = kTfLiteArenaRwPersistent;\n    int row_sums_dims[1] = {num_filters};\n    if (!TfLiteIntArrayEqualsArray(row_sums->dims, 1, row_sums_dims)) {\n      TfLiteIntArray* row_sums_size = TfLiteIntArrayCreate(1);\n      row_sums_size->data[0] = row_sums_dims[0];\n      TF_LITE_ENSURE_OK(\n          context, context->ResizeTensor(context, row_sums, row_sums_size));\n    }\n  }\n  if (is_full_integer) {\n    // Allocated one extra tensor.\n    TfLiteIntArray* output_temp_size_array = TfLiteIntArrayCreate(2);\n    output_temp_size_array->data[0] = num_units;\n    output_temp_size_array->data[1] = batch_size;\n    node->temporaries->data[1] = scratch_tensor_index + 1;\n    TfLiteTensor* output_temp;\n    TF_LITE_ENSURE_OK(\n        context, GetTemporarySafe(context, node, /*index=*/1, &output_temp));\n    output_temp->type = kTfLiteInt32;\n    output_temp->allocation_type = kTfLiteArenaRw;\n    TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, output_temp,\n                                                     output_temp_size_array));\n\n    // Calculate effective scales.\n    auto* input_params =\n        reinterpret_cast(input->quantization.params);\n    auto* weights_feature_params = reinterpret_cast(\n        weights_feature->quantization.params);\n    auto* state_params =\n        reinterpret_cast(state->quantization.params);\n    auto* weight_time_params = reinterpret_cast(\n        weights_time->quantization.params);\n    auto* output_params = reinterpret_cast(\n        output->quantization.params);\n    const double effective_scale_1 = input_params->scale->data[0] *\n                                     weights_feature_params->scale->data[0] /\n                                     state_params->scale->data[0];\n    const double effective_scale_2 = state_params->scale->data[0] *\n                                     weight_time_params->scale->data[0] /\n                                     output_params->scale->data[0];\n    QuantizeMultiplier(effective_scale_1, &op_data->effective_scale_1_a,\n                       &op_data->effective_scale_1_b);\n    QuantizeMultiplier(effective_scale_2, &op_data->effective_scale_2_a,\n                       &op_data->effective_scale_2_b);\n  }\n  return kTfLiteOk;\n}", "func_hash": 233995710646174347190469029723118566827, "file_name": "svdf.cc", "file_hash": 151141611170941646620182312728274364600, "cwe": ["CWE-908"], "cve": "CVE-2021-37682", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions all TFLite operations that use quantization can be made to use unitialized values. [For example](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/lite/kernels/depthwise_conv.cc#L198-L200). The issue stems from the fact that `quantization.params` is only valid if `quantization.type` is different that `kTfLiteNoQuantization`. However, these checks are missing in large parts of the code. We have patched the issue in GitHub commits 537bc7c723439b9194a358f64d871dd326c18887, 4a91f2069f7145aab6ba2d8cfe41be8a110c18a5 and 8933b8a21280696ab119b63263babdb54c298538. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37682"}
{"idx": 255807, "project": "tensorflow", "commit_id": "537bc7c723439b9194a358f64d871dd326c18887", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/537bc7c723439b9194a358f64d871dd326c18887", "commit_message": "Fix a null pointer exception caused by branching on uninitialized data.\n\nThis is due to not checking that the params for the quantization exists. If there is no quantization, we should not access the `.params` field.\n\nPiperOrigin-RevId: 385163909\nChange-Id: I2beb8d50649b6542db224c163033fbcbaa49314f", "target": 0, "func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n  const auto* params = reinterpret_cast(node->builtin_data);\n  OpData* op_data = reinterpret_cast(node->user_data);\n  int scratch_tensor_index = op_data->scratch_tensor_index;\n\n  // Check we have all the inputs and outputs we need.\n  TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);\n  TF_LITE_ENSURE_EQ(context, node->inputs->size, 5);\n\n  const TfLiteTensor* input;\n  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n  const TfLiteTensor* weights_feature;\n  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kWeightsFeatureTensor,\n                                          &weights_feature));\n  const TfLiteTensor* weights_time;\n  TF_LITE_ENSURE_OK(\n      context, GetInputSafe(context, node, kWeightsTimeTensor, &weights_time));\n\n  TF_LITE_ENSURE(context,\n                 input->type == kTfLiteFloat32 || input->type == kTfLiteInt8);\n\n  // Check all the parameters of tensor match within themselves and match the\n  // input configuration.\n  const int rank = params->rank;\n  const int batch_size = input->dims->data[0];\n  const int num_filters = weights_feature->dims->data[0];\n  TF_LITE_ENSURE(context, rank != 0);\n  TF_LITE_ENSURE_EQ(context, num_filters % rank, 0);\n  const int num_units = num_filters / rank;\n  const int memory_size = weights_time->dims->data[1];\n  TF_LITE_ENSURE_EQ(context, input->dims->data[1],\n                    weights_feature->dims->data[1]);\n  TF_LITE_ENSURE_EQ(context, weights_time->dims->data[0], num_filters);\n\n  const TfLiteTensor* bias = GetOptionalInputTensor(context, node, kBiasTensor);\n  if (bias) {\n    TF_LITE_ENSURE_EQ(context, bias->dims->data[0], num_units);\n  }\n\n  const TfLiteTensor* state;\n  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kStateTensor, &state));\n  TfLiteTensor* output;\n  TF_LITE_ENSURE_OK(context,\n                    GetOutputSafe(context, node, kOutputTensor, &output));\n\n  // Check the shape of input state tensors.\n  TF_LITE_ENSURE_EQ(context, NumDimensions(state), 2);\n  TF_LITE_ENSURE_EQ(context, SizeOfDimension(state, 0), batch_size);\n  TF_LITE_ENSURE_EQ(context, SizeOfDimension(state, 1),\n                    memory_size * num_filters);\n\n  // Resize output.\n  TfLiteIntArray* output_size_array = TfLiteIntArrayCreate(2);\n  output_size_array->data[0] = batch_size;\n  output_size_array->data[1] = num_units;\n  TF_LITE_ENSURE_OK(context,\n                    context->ResizeTensor(context, output, output_size_array));\n\n  // The weights are of consistent type, so it suffices to check one.\n  const bool is_hybrid_op = IsHybridOp(input, weights_feature);\n  const bool is_full_integer = input->type == kTfLiteInt8;\n\n  // Resize scratch.\n  TfLiteIntArrayFree(node->temporaries);\n  if (is_hybrid_op) {\n    node->temporaries = TfLiteIntArrayCreate(6);\n  } else if (is_full_integer) {\n    node->temporaries = TfLiteIntArrayCreate(2);\n  } else {\n    node->temporaries = TfLiteIntArrayCreate(1);\n  }\n  node->temporaries->data[0] = scratch_tensor_index;\n\n  TfLiteIntArray* scratch_size_array = TfLiteIntArrayCreate(2);\n  scratch_size_array->data[0] = batch_size;\n  scratch_size_array->data[1] = num_filters;\n\n  TfLiteTensor* scratch_tensor;\n  TF_LITE_ENSURE_OK(\n      context, GetTemporarySafe(context, node, /*index=*/0, &scratch_tensor));\n\n  // The scratch buffer is of type int32 for full integer svdf and it's of type\n  // float32 for hybrid and float case.\n  if (is_full_integer) {\n    scratch_tensor->type = kTfLiteInt32;\n  } else {\n    scratch_tensor->type = kTfLiteFloat32;\n  }\n  scratch_tensor->allocation_type = kTfLiteArenaRw;\n  TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scratch_tensor,\n                                                   scratch_size_array));\n\n  if (is_hybrid_op) {\n    op_data->compute_row_sums = true;\n    // Tell interpreter to allocate temporary tensors to store quantized values\n    // of input tensors.\n    node->temporaries->data[1] = scratch_tensor_index + 1;\n    TfLiteTensor* input_quantized;\n    TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, /*index=*/1,\n                                                &input_quantized));\n    input_quantized->type = weights_feature->type;\n    input_quantized->allocation_type = kTfLiteArenaRw;\n    if (!TfLiteIntArrayEqual(input_quantized->dims, input->dims)) {\n      TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);\n      TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,\n                                                       input_quantized_size));\n    }\n\n    // Tell interpreter to allocate temporary tensors to store scaling factors.\n    node->temporaries->data[2] = scratch_tensor_index + 2;\n    TfLiteTensor* scaling_factors;\n    TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, /*index=*/2,\n                                                &scaling_factors));\n    scaling_factors->type = kTfLiteFloat32;\n    scaling_factors->allocation_type = kTfLiteArenaRw;\n    int scaling_dims[1] = {batch_size};\n    if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {\n      TfLiteIntArray* scaling_factors_size = TfLiteIntArrayCreate(1);\n      scaling_factors_size->data[0] = batch_size;\n      TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scaling_factors,\n                                                       scaling_factors_size));\n    }\n\n    // Used to store dequantized weights_time matrix for hybrid computation of\n    // matmul(state, weights_time), which occurs in floating point.\n    node->temporaries->data[3] = scratch_tensor_index + 3;\n    TfLiteTensor* float_weights_time;\n    TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, /*index=*/3,\n                                                &float_weights_time));\n    float_weights_time->type = kTfLiteFloat32;\n    // Persistent so that we can compute the dequantized weights only once.\n    float_weights_time->allocation_type = kTfLiteArenaRwPersistent;\n    if (!TfLiteIntArrayEqual(float_weights_time->dims, weights_time->dims)) {\n      TfLiteIntArray* float_weights_time_size =\n          TfLiteIntArrayCopy(weights_time->dims);\n      TF_LITE_ENSURE_OK(context,\n                        context->ResizeTensor(context, float_weights_time,\n                                              float_weights_time_size));\n    }\n\n    node->temporaries->data[4] = scratch_tensor_index + 4;\n    TfLiteTensor* zero_points;\n    TF_LITE_ENSURE_OK(\n        context, GetTemporarySafe(context, node, /*index=*/4, &zero_points));\n    zero_points->type = kTfLiteFloat32;\n    zero_points->allocation_type = kTfLiteArenaRw;\n    int zero_points_dims[1] = {batch_size};\n    if (!TfLiteIntArrayEqualsArray(zero_points->dims, 1, zero_points_dims)) {\n      TfLiteIntArray* zero_points_size = TfLiteIntArrayCreate(1);\n      zero_points_size->data[0] = zero_points_dims[0];\n      TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, zero_points,\n                                                       zero_points_size));\n    }\n\n    node->temporaries->data[5] = scratch_tensor_index + 5;\n    TfLiteTensor* row_sums;\n    TF_LITE_ENSURE_OK(context,\n                      GetTemporarySafe(context, node, /*index=*/5, &row_sums));\n    row_sums->type = kTfLiteFloat32;\n    row_sums->allocation_type = kTfLiteArenaRwPersistent;\n    int row_sums_dims[1] = {num_filters};\n    if (!TfLiteIntArrayEqualsArray(row_sums->dims, 1, row_sums_dims)) {\n      TfLiteIntArray* row_sums_size = TfLiteIntArrayCreate(1);\n      row_sums_size->data[0] = row_sums_dims[0];\n      TF_LITE_ENSURE_OK(\n          context, context->ResizeTensor(context, row_sums, row_sums_size));\n    }\n  }\n  if (is_full_integer) {\n    // Allocated one extra tensor.\n    TfLiteIntArray* output_temp_size_array = TfLiteIntArrayCreate(2);\n    output_temp_size_array->data[0] = num_units;\n    output_temp_size_array->data[1] = batch_size;\n    node->temporaries->data[1] = scratch_tensor_index + 1;\n    TfLiteTensor* output_temp;\n    TF_LITE_ENSURE_OK(\n        context, GetTemporarySafe(context, node, /*index=*/1, &output_temp));\n    output_temp->type = kTfLiteInt32;\n    output_temp->allocation_type = kTfLiteArenaRw;\n    TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, output_temp,\n                                                     output_temp_size_array));\n\n    // Calculate effective scales.\n    TF_LITE_ENSURE(context, input->quantization.type != kTfLiteNoQuantization);\n    auto* input_params =\n        reinterpret_cast(input->quantization.params);\n    TF_LITE_ENSURE(context,\n                   weights_feature->quantization.type != kTfLiteNoQuantization);\n    auto* weights_feature_params = reinterpret_cast(\n        weights_feature->quantization.params);\n    TF_LITE_ENSURE(context, state->quantization.type != kTfLiteNoQuantization);\n    auto* state_params =\n        reinterpret_cast(state->quantization.params);\n    TF_LITE_ENSURE(context,\n                   weights_time->quantization.type != kTfLiteNoQuantization);\n    auto* weight_time_params = reinterpret_cast(\n        weights_time->quantization.params);\n    TF_LITE_ENSURE(context, output->quantization.type != kTfLiteNoQuantization);\n    auto* output_params = reinterpret_cast(\n        output->quantization.params);\n    const double effective_scale_1 = input_params->scale->data[0] *\n                                     weights_feature_params->scale->data[0] /\n                                     state_params->scale->data[0];\n    const double effective_scale_2 = state_params->scale->data[0] *\n                                     weight_time_params->scale->data[0] /\n                                     output_params->scale->data[0];\n    QuantizeMultiplier(effective_scale_1, &op_data->effective_scale_1_a,\n                       &op_data->effective_scale_1_b);\n    QuantizeMultiplier(effective_scale_2, &op_data->effective_scale_2_a,\n                       &op_data->effective_scale_2_b);\n  }\n  return kTfLiteOk;\n}", "func_hash": 188910489616727486494118083484300735225, "file_name": "None", "file_hash": null, "cwe": ["CWE-908"], "cve": "CVE-2021-37682", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions all TFLite operations that use quantization can be made to use unitialized values. [For example](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/lite/kernels/depthwise_conv.cc#L198-L200). The issue stems from the fact that `quantization.params` is only valid if `quantization.type` is different that `kTfLiteNoQuantization`. However, these checks are missing in large parts of the code. We have patched the issue in GitHub commits 537bc7c723439b9194a358f64d871dd326c18887, 4a91f2069f7145aab6ba2d8cfe41be8a110c18a5 and 8933b8a21280696ab119b63263babdb54c298538. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37682"}
{"idx": 197247, "project": "tensorflow", "commit_id": "ee119d4a498979525046fba1c3dd3f13a039fbb1", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/ee119d4a498979525046fba1c3dd3f13a039fbb1", "commit_message": "Fix segmentation fault in shape inference logic.\n\nWhen running shape functions, some functions (such as `MutableHashTableShape`)\nproduce extra output information in the form of a `ShapeAndType` struct.  The\nshapes embedded in this struct are owned by an inference context that is\ncleaned up almost immediately; if the upstream code attempts to access this\nshape information, it can trigger a segfault.\n\n`ShapeRefiner` is mitigating this for normal output shapes by cloning them\n(and thus putting the newly created shape under ownership of an inference\ncontext that will not die), but we were not doing the same for shapes and\ntypes.  This commit fixes that by doing similar logic on output shapes and\ntypes.\n\nPiperOrigin-RevId: 384761124\nChange-Id: I07c0c42d29dfbb55bfa13ec1f09ef825fb0a1a1d", "target": 1, "func": "Status ShapeRefiner::InferShapesForFunctionSubNode(\n    const Node* node, InferenceContext* outer_context) {\n  TF_RETURN_IF_ERROR(AddNodeInternal(node, outer_context));\n  InferenceContext* node_context = CHECK_NOTNULL(GetContext(node));\n\n  if (StringPiece(node->type_string()) == kArgOp) {\n    // Handle special node: function input.\n    // Shapes for these nodes are provided in the outer inference\n    // context.\n\n    int index;\n    TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(node->def()), \"index\", &index));\n\n    if (index < 0 || outer_context->num_inputs() <= index) {\n      return errors::Internal(\n          \"Function instantiation included invalid input index: \", index,\n          \" not in [0, \", outer_context->num_inputs(), \").\");\n    }\n\n    // TODO(b/134547156): TEMPORARY WORKAROUND. If input shape handle is not set\n    // in outer context, set _Arg node output shape to unknown.\n    if (outer_context->input(index).SameHandle(ShapeHandle())) {\n      VLOG(1) << \"Function instantiation has undefined input shape at \"\n              << \"index: \" << index << \" in the outer inference context.\";\n      node_context->set_output(0, node_context->UnknownShape());\n    } else {\n      node_context->set_output(0, outer_context->input(index));\n    }\n\n    auto* resource = outer_context->input_handle_shapes_and_types(index);\n    if (resource) {\n      node_context->set_output_handle_shapes_and_types(0, *resource);\n    }\n  } else if (StringPiece(node->type_string()) == kRetvalOp) {\n    // Handle special node: function output.\n    // Shapes inferred for these nodes go into the outer inference\n    // context.\n\n    int index;\n    TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(node->def()), \"index\", &index));\n\n    if (index < 0 || outer_context->num_outputs() <= index) {\n      return errors::Internal(\n          \"Function instantiation included invalid output index: \", index,\n          \" not in [0, \", outer_context->num_outputs(), \").\");\n    }\n\n    // outer_context outlives node_context, therefore we need to create\n    // a new shape handle owned by outer_context instead.\n    ShapeHandle handle;\n    TensorShapeProto proto;\n    node_context->ShapeHandleToProto(node_context->input(0), &proto);\n    TF_RETURN_IF_ERROR(outer_context->MakeShapeFromShapeProto(proto, &handle));\n    outer_context->set_output(index, handle);\n\n    auto* resource = node_context->input_handle_shapes_and_types(0);\n    if (resource) {\n      outer_context->set_output_handle_shapes_and_types(index, *resource);\n    }\n  }\n\n  return Status::OK();\n}", "func_hash": 296174489268649475183296977682065052967, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-37690", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions when running shape functions, some functions (such as `MutableHashTableShape`) produce extra output information in the form of a `ShapeAndType` struct. The shapes embedded in this struct are owned by an inference context that is cleaned up almost immediately; if the upstream code attempts to access this shape information, it can trigger a segfault. `ShapeRefiner` is mitigating this for normal output shapes by cloning them (and thus putting the newly created shape under ownership of an inference context that will not die), but we were not doing the same for shapes and types. This commit fixes that by doing similar logic on output shapes and types. We have patched the issue in GitHub commit ee119d4a498979525046fba1c3dd3f13a039fbb1. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37690"}
{"idx": 255932, "project": "tensorflow", "commit_id": "ee119d4a498979525046fba1c3dd3f13a039fbb1", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/ee119d4a498979525046fba1c3dd3f13a039fbb1", "commit_message": "Fix segmentation fault in shape inference logic.\n\nWhen running shape functions, some functions (such as `MutableHashTableShape`)\nproduce extra output information in the form of a `ShapeAndType` struct.  The\nshapes embedded in this struct are owned by an inference context that is\ncleaned up almost immediately; if the upstream code attempts to access this\nshape information, it can trigger a segfault.\n\n`ShapeRefiner` is mitigating this for normal output shapes by cloning them\n(and thus putting the newly created shape under ownership of an inference\ncontext that will not die), but we were not doing the same for shapes and\ntypes.  This commit fixes that by doing similar logic on output shapes and\ntypes.\n\nPiperOrigin-RevId: 384761124\nChange-Id: I07c0c42d29dfbb55bfa13ec1f09ef825fb0a1a1d", "target": 0, "func": "Status ShapeRefiner::InferShapesForFunctionSubNode(\n    const Node* node, InferenceContext* outer_context) {\n  TF_RETURN_IF_ERROR(AddNodeInternal(node, outer_context));\n  InferenceContext* node_context = CHECK_NOTNULL(GetContext(node));\n\n  if (StringPiece(node->type_string()) == kArgOp) {\n    // Handle special node: function input.\n    // Shapes for these nodes are provided in the outer inference\n    // context.\n\n    int index;\n    TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(node->def()), \"index\", &index));\n\n    if (index < 0 || outer_context->num_inputs() <= index) {\n      return errors::Internal(\n          \"Function instantiation included invalid input index: \", index,\n          \" not in [0, \", outer_context->num_inputs(), \").\");\n    }\n\n    // TODO(b/134547156): TEMPORARY WORKAROUND. If input shape handle is not set\n    // in outer context, set _Arg node output shape to unknown.\n    if (outer_context->input(index).SameHandle(ShapeHandle())) {\n      VLOG(1) << \"Function instantiation has undefined input shape at \"\n              << \"index: \" << index << \" in the outer inference context.\";\n      node_context->set_output(0, node_context->UnknownShape());\n    } else {\n      node_context->set_output(0, outer_context->input(index));\n    }\n\n    auto* resource = outer_context->input_handle_shapes_and_types(index);\n    if (resource) {\n      node_context->set_output_handle_shapes_and_types(0, *resource);\n    }\n  } else if (StringPiece(node->type_string()) == kRetvalOp) {\n    // Handle special node: function output.\n    // Shapes inferred for these nodes go into the outer inference\n    // context.\n\n    int index;\n    TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(node->def()), \"index\", &index));\n\n    if (index < 0 || outer_context->num_outputs() <= index) {\n      return errors::Internal(\n          \"Function instantiation included invalid output index: \", index,\n          \" not in [0, \", outer_context->num_outputs(), \").\");\n    }\n\n    // outer_context outlives node_context, therefore we need to create\n    // a new shape handle owned by outer_context instead.\n    ShapeHandle handle;\n    TensorShapeProto proto;\n    node_context->ShapeHandleToProto(node_context->input(0), &proto);\n    TF_RETURN_IF_ERROR(outer_context->MakeShapeFromShapeProto(proto, &handle));\n    outer_context->set_output(index, handle);\n\n    const std::vector* resource =\n        node_context->input_handle_shapes_and_types(0);\n    if (resource) {\n      // `ShapesAndType`s contain `ShapeHandle`s.  These `ShapeHandle`s point\n      // to `Shape`s that are owned by a different inference context too.  We\n      // need to copy them to the outer context to prevent them from being\n      // destroyed before they are used.\n      std::vector copied_shapes_and_types;\n      for (auto& shape_and_type : *resource) {\n        ShapeHandle handle;\n        TensorShapeProto proto;\n        node_context->ShapeHandleToProto(shape_and_type.shape, &proto);\n        TF_RETURN_IF_ERROR(\n            outer_context->MakeShapeFromShapeProto(proto, &handle));\n        copied_shapes_and_types.push_back(\n            ShapeAndType(handle, shape_and_type.dtype, shape_and_type.type));\n      }\n\n      outer_context->set_output_handle_shapes_and_types(\n          index, copied_shapes_and_types);\n    }\n  }\n\n  return Status::OK();\n}", "func_hash": 25506560335878301067355400382857145905, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2021-37690", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions when running shape functions, some functions (such as `MutableHashTableShape`) produce extra output information in the form of a `ShapeAndType` struct. The shapes embedded in this struct are owned by an inference context that is cleaned up almost immediately; if the upstream code attempts to access this shape information, it can trigger a segfault. `ShapeRefiner` is mitigating this for normal output shapes by cloning them (and thus putting the newly created shape under ownership of an inference context that will not die), but we were not doing the same for shapes and types. This commit fixes that by doing similar logic on output shapes and types. We have patched the issue in GitHub commit ee119d4a498979525046fba1c3dd3f13a039fbb1. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37690"}
{"idx": 197262, "project": "tensorflow", "commit_id": "e6cf28c72ba2eb949ca950d834dd6d66bb01cfae", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e6cf28c72ba2eb949ca950d834dd6d66bb01cfae", "commit_message": "Validate that matrix dimension sizes in SparseMatMul are positive.\n\nPiperOrigin-RevId: 401149683\nChange-Id: Ib33eafc561a39c8741ece80b2edce6d4aae9a57d", "target": 1, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor& a = ctx->input(0);\n    const Tensor& b = ctx->input(1);\n    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a.shape()),\n                errors::InvalidArgument(\"a is not a matrix\"));\n    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(b.shape()),\n                errors::InvalidArgument(\"b is not a matrix\"));\n\n    const int m = transpose_a_ ? a.dim_size(1) : a.dim_size(0);\n    const int k = transpose_a_ ? a.dim_size(0) : a.dim_size(1);\n    const int n = transpose_b_ ? b.dim_size(0) : b.dim_size(1);\n    const int k2 = transpose_b_ ? b.dim_size(1) : b.dim_size(0);\n\n    OP_REQUIRES(ctx, k == k2,\n                errors::InvalidArgument(\n                    \"Matrix size incompatible: a: \", a.shape().DebugString(),\n                    \", b: \", b.shape().DebugString()));\n    Tensor* output = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({m, n}), &output));\n\n    if (k == 0) {\n      // If the inner dimension k in the matrix multiplication is zero, we fill\n      // the output with zeros.\n      functor::SetZeroFunctor f;\n      f(ctx->eigen_device(), output->flat());\n      return;\n    }\n\n    auto out = output->matrix();\n\n    std::unique_ptr a_float;\n    std::unique_ptr b_float;\n    if (!a_is_sparse_ && !b_is_sparse_) {\n      auto left = &a;\n      auto right = &b;\n      // TODO(agarwal): multi-thread the conversions from bfloat16 to float.\n      if (std::is_same::value) {\n        a_float.reset(new Tensor(DT_FLOAT, a.shape()));\n        BFloat16ToFloat(a.flat().data(),\n                        a_float->flat().data(), a.NumElements());\n        left = a_float.get();\n      }\n      if (std::is_same::value) {\n        b_float.reset(new Tensor(DT_FLOAT, b.shape()));\n        BFloat16ToFloat(b.flat().data(),\n                        b_float->flat().data(), b.NumElements());\n        right = b_float.get();\n      }\n      Eigen::array, 1> dim_pair;\n      dim_pair[0].first = transpose_a_ ? 0 : 1;\n      dim_pair[0].second = transpose_b_ ? 1 : 0;\n\n      out.device(ctx->template eigen_device()) =\n          left->matrix().contract(right->matrix(), dim_pair);\n      return;\n    }\n\n    auto left = &a;\n    auto right = &b;\n    bool transpose_output = false;\n    bool transpose_a = transpose_a_;\n    bool transpose_b = transpose_b_;\n    if (!a_is_sparse_) {\n      // Swap the order of multiplications using the identity:\n      // A * B = (B' *  A')'.\n      std::swap(left, right);\n      std::swap(transpose_a, transpose_b);\n      transpose_a = !transpose_a;\n      transpose_b = !transpose_b;\n      transpose_output = !transpose_output;\n    }\n\n    std::unique_ptr right_tr;\n    if (transpose_b) {\n      // TODO(agarwal): avoid transposing the matrix here and directly handle\n      // transpose in CreateDenseSlices.\n      OP_REQUIRES(ctx, right->dim_size(0) != 0,\n                  errors::InvalidArgument(\"b has an entry 0 in it's shape.\"));\n      OP_REQUIRES(ctx, right->dim_size(1) != 0,\n                  errors::InvalidArgument(\"b has an entry 0 in it's shape.\"));\n      right_tr.reset(\n          new Tensor(right->dtype(),\n                     TensorShape({right->dim_size(1), right->dim_size(0)})));\n\n      const auto perm = dsizes_10();\n      if (transpose_output) {\n        right_tr->matrix().device(ctx->template eigen_device()) =\n            right->matrix().shuffle(perm);\n      } else {\n        right_tr->matrix().device(ctx->template eigen_device()) =\n            right->matrix().shuffle(perm);\n      }\n      right = right_tr.get();\n    }\n\n    if (transpose_output) {\n      DoMatMul::Compute(&this->cache_tr_, left->matrix(),\n                                right->matrix(), transpose_a,\n                                ctx->device()->tensorflow_cpu_worker_threads(),\n                                transpose_output, &out);\n    } else {\n      DoMatMul::Compute(&this->cache_nt_, left->matrix(),\n                                right->matrix(), transpose_a,\n                                ctx->device()->tensorflow_cpu_worker_threads(),\n                                transpose_output, &out);\n    }\n  }", "func_hash": 281398484697111962957982643274603954439, "file_name": "sparse_matmul_op.cc", "file_hash": 108103579052154515117474451671828260520, "cwe": ["CWE-125"], "cve": "CVE-2021-41219", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions the code for sparse matrix multiplication is vulnerable to undefined behavior via binding a reference to `nullptr`. This occurs whenever the dimensions of `a` or `b` are 0 or less. In the case on one of these is 0, an empty output tensor should be allocated (to conserve the invariant that output tensors are always allocated when the operation is successful) but nothing should be written to it (that is, we should return early from the kernel implementation). Otherwise, attempts to write to this empty tensor would result in heap OOB access. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41219"}
{"idx": 256138, "project": "tensorflow", "commit_id": "e6cf28c72ba2eb949ca950d834dd6d66bb01cfae", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/e6cf28c72ba2eb949ca950d834dd6d66bb01cfae", "commit_message": "Validate that matrix dimension sizes in SparseMatMul are positive.\n\nPiperOrigin-RevId: 401149683\nChange-Id: Ib33eafc561a39c8741ece80b2edce6d4aae9a57d", "target": 0, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor& a = ctx->input(0);\n    const Tensor& b = ctx->input(1);\n    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a.shape()),\n                errors::InvalidArgument(\"a is not a matrix\"));\n    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(b.shape()),\n                errors::InvalidArgument(\"b is not a matrix\"));\n\n    const int m = transpose_a_ ? a.dim_size(1) : a.dim_size(0);\n    const int k = transpose_a_ ? a.dim_size(0) : a.dim_size(1);\n    const int n = transpose_b_ ? b.dim_size(0) : b.dim_size(1);\n    const int k2 = transpose_b_ ? b.dim_size(1) : b.dim_size(0);\n\n    OP_REQUIRES(ctx, k == k2,\n                errors::InvalidArgument(\n                    \"Matrix size incompatible: a: \", a.shape().DebugString(),\n                    \", b: \", b.shape().DebugString()));\n    OP_REQUIRES(ctx, m >= 0 && n >= 0 && k >= 0,\n                errors::InvalidArgument(\n                    \"Matrix dimensions cannot be negative: a: \",\n                    a.shape().DebugString(), \", b: \", b.shape().DebugString()));\n    Tensor* output = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({m, n}), &output));\n\n    // Return early if at least one of the output dimension size is 0.\n    if (m == 0 || n == 0) {\n      return;\n    }\n\n    if (k == 0) {\n      // If the inner dimension k in the matrix multiplication is zero, we fill\n      // the output with zeros.\n      functor::SetZeroFunctor f;\n      f(ctx->eigen_device(), output->flat());\n      return;\n    }\n\n    auto out = output->matrix();\n\n    std::unique_ptr a_float;\n    std::unique_ptr b_float;\n    if (!a_is_sparse_ && !b_is_sparse_) {\n      auto left = &a;\n      auto right = &b;\n      // TODO(agarwal): multi-thread the conversions from bfloat16 to float.\n      if (std::is_same::value) {\n        a_float.reset(new Tensor(DT_FLOAT, a.shape()));\n        BFloat16ToFloat(a.flat().data(),\n                        a_float->flat().data(), a.NumElements());\n        left = a_float.get();\n      }\n      if (std::is_same::value) {\n        b_float.reset(new Tensor(DT_FLOAT, b.shape()));\n        BFloat16ToFloat(b.flat().data(),\n                        b_float->flat().data(), b.NumElements());\n        right = b_float.get();\n      }\n      Eigen::array, 1> dim_pair;\n      dim_pair[0].first = transpose_a_ ? 0 : 1;\n      dim_pair[0].second = transpose_b_ ? 1 : 0;\n\n      out.device(ctx->template eigen_device()) =\n          left->matrix().contract(right->matrix(), dim_pair);\n      return;\n    }\n\n    auto left = &a;\n    auto right = &b;\n    bool transpose_output = false;\n    bool transpose_a = transpose_a_;\n    bool transpose_b = transpose_b_;\n    if (!a_is_sparse_) {\n      // Swap the order of multiplications using the identity:\n      // A * B = (B' *  A')'.\n      std::swap(left, right);\n      std::swap(transpose_a, transpose_b);\n      transpose_a = !transpose_a;\n      transpose_b = !transpose_b;\n      transpose_output = !transpose_output;\n    }\n\n    std::unique_ptr right_tr;\n    if (transpose_b) {\n      // TODO(agarwal): avoid transposing the matrix here and directly handle\n      // transpose in CreateDenseSlices.\n      OP_REQUIRES(ctx, right->dim_size(0) != 0,\n                  errors::InvalidArgument(\"b has an entry 0 in it's shape.\"));\n      OP_REQUIRES(ctx, right->dim_size(1) != 0,\n                  errors::InvalidArgument(\"b has an entry 0 in it's shape.\"));\n      right_tr.reset(\n          new Tensor(right->dtype(),\n                     TensorShape({right->dim_size(1), right->dim_size(0)})));\n\n      const auto perm = dsizes_10();\n      if (transpose_output) {\n        right_tr->matrix().device(ctx->template eigen_device()) =\n            right->matrix().shuffle(perm);\n      } else {\n        right_tr->matrix().device(ctx->template eigen_device()) =\n            right->matrix().shuffle(perm);\n      }\n      right = right_tr.get();\n    }\n\n    if (transpose_output) {\n      DoMatMul::Compute(&this->cache_tr_, left->matrix(),\n                                right->matrix(), transpose_a,\n                                ctx->device()->tensorflow_cpu_worker_threads(),\n                                transpose_output, &out);\n    } else {\n      DoMatMul::Compute(&this->cache_nt_, left->matrix(),\n                                right->matrix(), transpose_a,\n                                ctx->device()->tensorflow_cpu_worker_threads(),\n                                transpose_output, &out);\n    }\n  }", "func_hash": 324184408352079066865576775824843839346, "file_name": "sparse_matmul_op.cc", "file_hash": 60640554660394807532445387638343536122, "cwe": ["CWE-125"], "cve": "CVE-2021-41219", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions the code for sparse matrix multiplication is vulnerable to undefined behavior via binding a reference to `nullptr`. This occurs whenever the dimensions of `a` or `b` are 0 or less. In the case on one of these is 0, an empty output tensor should be allocated (to conserve the invariant that output tensors are always allocated when the operation is successful) but nothing should be written to it (that is, we should return early from the kernel implementation). Otherwise, attempts to write to this empty tensor would result in heap OOB access. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41219"}
{"idx": 197305, "project": "pjproject", "commit_id": "11559e49e65bdf00922ad5ae28913ec6a198d508", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/11559e49e65bdf00922ad5ae28913ec6a198d508", "commit_message": "Merge pull request from GHSA-vhxv-phmx-g52q\n\n* Prevent OOB read/write when parsing RTCP FB RPSI\n\n* Add log information\n\n* Modification based on comments.", "target": 1, "func": "PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_rpsi(\n\t\t\t\t\tconst void *buf,\n\t\t\t\t\tpj_size_t length,\n\t\t\t\t\tpjmedia_rtcp_fb_rpsi *rpsi)\n{\n    pjmedia_rtcp_common *hdr = (pjmedia_rtcp_common*) buf;\n    pj_uint8_t *p;\n    pj_uint8_t padlen;\n    pj_size_t rpsi_len;\n\n    PJ_ASSERT_RETURN(buf && rpsi, PJ_EINVAL);\n    PJ_ASSERT_RETURN(length >= sizeof(pjmedia_rtcp_common), PJ_ETOOSMALL);\n\n    /* RPSI uses pt==RTCP_PSFB and FMT==3 */\n    if (hdr->pt != RTCP_PSFB || hdr->count != 3)\n\treturn PJ_ENOTFOUND;\n\n    rpsi_len = (pj_ntohs((pj_uint16_t)hdr->length)-2) * 4;\n    if (length < rpsi_len + 12)\n\treturn PJ_ETOOSMALL;\n\n    p = (pj_uint8_t*)hdr + sizeof(*hdr);\n    padlen = *p++;\n    rpsi->pt = (*p++ & 0x7F);\n    rpsi->rpsi_bit_len = rpsi_len*8 - 16 - padlen;\n    pj_strset(&rpsi->rpsi, (char*)p, (rpsi->rpsi_bit_len + 7)/8);\n\n    return PJ_SUCCESS;\n}", "func_hash": 36256848360171648205913357387602986017, "file_name": "rtcp_fb.c", "file_hash": 8904386284990700433551187598162654514, "cwe": ["CWE-200"], "cve": "CVE-2022-24786", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C. PJSIP versions 2.12 and prior do not parse incoming RTCP feedback RPSI (Reference Picture Selection Indication) packet, but any app that directly uses pjmedia_rtcp_fb_parse_rpsi() will be affected. A patch is available in the `master` branch of the `pjsip/pjproject` GitHub repository. There are currently no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24786"}
{"idx": 256441, "project": "pjproject", "commit_id": "11559e49e65bdf00922ad5ae28913ec6a198d508", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/11559e49e65bdf00922ad5ae28913ec6a198d508", "commit_message": "Merge pull request from GHSA-vhxv-phmx-g52q\n\n* Prevent OOB read/write when parsing RTCP FB RPSI\n\n* Add log information\n\n* Modification based on comments.", "target": 0, "func": "PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_rpsi(\n\t\t\t\t\tconst void *buf,\n\t\t\t\t\tpj_size_t length,\n\t\t\t\t\tpjmedia_rtcp_fb_rpsi *rpsi)\n{\n    pjmedia_rtcp_fb_common *hdr = (pjmedia_rtcp_fb_common*) buf;\n    pj_uint8_t *p;\n    pj_uint8_t padlen;\n    pj_size_t rpsi_len;\n\n    PJ_ASSERT_RETURN(buf && rpsi, PJ_EINVAL);\n    PJ_ASSERT_RETURN(length >= sizeof(pjmedia_rtcp_fb_common), PJ_ETOOSMALL);\n\n    /* RPSI uses pt==RTCP_PSFB and FMT==3 */\n    if (hdr->rtcp_common.pt != RTCP_PSFB || hdr->rtcp_common.count != 3)\n\treturn PJ_ENOTFOUND;\n\n    if (hdr->rtcp_common.length < 3) {    \n        PJ_PERROR(3, (THIS_FILE, PJ_ETOOSMALL,\n                      \"Failed parsing FB RPSI, invalid header length\"));\n\treturn PJ_ETOOSMALL;\n    }\n\n    rpsi_len = (pj_ntohs((pj_uint16_t)hdr->rtcp_common.length)-2) * 4;\n    if (length < rpsi_len + 12)\n\treturn PJ_ETOOSMALL;\n\n    p = (pj_uint8_t*)hdr + sizeof(*hdr);\n    padlen = *p++;\n\n    if (padlen >= 32) {\n        PJ_PERROR(3, (THIS_FILE, PJ_ETOOBIG,\n                      \"Failed parsing FB RPSI, invalid RPSI padding len\"));\n\treturn PJ_ETOOBIG;\n    }\n\n    if ((rpsi_len * 8) < (unsigned)(16 + padlen)) {\n        PJ_PERROR(3, (THIS_FILE, PJ_ETOOSMALL,\n                      \"Failed parsing FB RPSI, invalid RPSI bit len\"));\n\treturn PJ_ETOOSMALL;\n    }\n\n    rpsi->pt = (*p++ & 0x7F);\n    rpsi->rpsi_bit_len = rpsi_len*8 - 16 - padlen;\n    pj_strset(&rpsi->rpsi, (char*)p, (rpsi->rpsi_bit_len + 7)/8);\n\n    return PJ_SUCCESS;\n}", "func_hash": 124069603564950829711267554809235900949, "file_name": "rtcp_fb.c", "file_hash": 331052800319582176026781515649325160782, "cwe": ["CWE-200"], "cve": "CVE-2022-24786", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C. PJSIP versions 2.12 and prior do not parse incoming RTCP feedback RPSI (Reference Picture Selection Indication) packet, but any app that directly uses pjmedia_rtcp_fb_parse_rpsi() will be affected. A patch is available in the `master` branch of the `pjsip/pjproject` GitHub repository. There are currently no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24786"}
{"idx": 197318, "project": "tensorflow", "commit_id": "cff267650c6a1b266e4b4500f69fbc49cdd773c5", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/cff267650c6a1b266e4b4500f69fbc49cdd773c5", "commit_message": "Fix tf.raw_ops.DeleteSessionTensor vulnerability with invalid `handle`.\n\nCheck that `handle` input is actually a scalar before treating it as such.\n\nPiperOrigin-RevId: 445228994", "target": 1, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor& handle = ctx->input(0);\n    const string& name = handle.scalar()();\n    auto session_state = ctx->session_state();\n    OP_REQUIRES(ctx, session_state != nullptr,\n                errors::FailedPrecondition(\n                    \"DeleteSessionTensor called on null session state\"));\n    OP_REQUIRES_OK(ctx, session_state->DeleteTensor(name));\n  }", "func_hash": 169160525191336828594160871802042029438, "file_name": "session_ops.cc", "file_hash": 314434656782851829699760158294919826764, "cwe": ["CWE-703"], "cve": "CVE-2022-29194", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.DeleteSessionTensor` does not fully validate the input arguments. This results in a `CHECK`-failure which can be used to trigger a denial of service attack. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29194"}
{"idx": 256587, "project": "tensorflow", "commit_id": "cff267650c6a1b266e4b4500f69fbc49cdd773c5", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/cff267650c6a1b266e4b4500f69fbc49cdd773c5", "commit_message": "Fix tf.raw_ops.DeleteSessionTensor vulnerability with invalid `handle`.\n\nCheck that `handle` input is actually a scalar before treating it as such.\n\nPiperOrigin-RevId: 445228994", "target": 0, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor& handle = ctx->input(0);\n    OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(handle.shape()),\n                errors::InvalidArgument(\"`handle` must be scalar\"));\n    const string& name = handle.scalar()();\n    auto session_state = ctx->session_state();\n    OP_REQUIRES(ctx, session_state != nullptr,\n                errors::FailedPrecondition(\n                    \"DeleteSessionTensor called on null session state\"));\n    OP_REQUIRES_OK(ctx, session_state->DeleteTensor(name));\n  }", "func_hash": 206711037393129995970821103192159531680, "file_name": "session_ops.cc", "file_hash": 175671208479371306711458012027187883621, "cwe": ["CWE-703"], "cve": "CVE-2022-29194", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.DeleteSessionTensor` does not fully validate the input arguments. This results in a `CHECK`-failure which can be used to trigger a denial of service attack. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29194"}
{"idx": 197326, "project": "tensorflow", "commit_id": "f09caa532b6e1ac8d2aa61b7832c78c5b79300c6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f09caa532b6e1ac8d2aa61b7832c78c5b79300c6", "commit_message": "Fix EinsumHelper::ParseEquation to avoid uninitialized accesses.\n\nEinsumHelper::ParseEquation is supposed to return true or false in\ninput_has_ellipsis and output_has_ellipsis to indicate whether there is\nellipsis in the inputs and output. Previously, when there is no ellipsis in the\ninputs or output, the routine doesn't assign false to the variables. This\nchange initializes the two variables with false to fix the problem.\nPiperOrigin-RevId: 391772004\nChange-Id: I17b6c88aadef4131470378e48cced054bf252e86", "target": 1, "func": "  static Status ParseEquation(const string& equation,\n                              OperandLabels* input_labels,\n                              Labels* output_labels,\n                              std::vector* label_types,\n                              OperandLabelCounts* input_label_counts,\n                              LabelCounts* output_label_counts,\n                              gtl::InlinedVector* input_has_ellipsis,\n                              bool* output_has_ellipsis) {\n    gtl::InlinedVector input_str;\n    string output_str;\n    TF_RETURN_IF_ERROR(ParseEinsumEquation(equation, &input_str, &output_str));\n\n    // Temporary map from single character labels to (consecutive) integer\n    // labels.\n    absl::flat_hash_map label_mapping;\n    int num_inputs = input_str.size();\n    input_labels->resize(num_inputs);\n\n    // Map from single characters to integer labels.\n    for (int i = 0; i < num_inputs; ++i) {\n      MapToLabels(input_str[i], &input_labels->at(i), &label_mapping);\n    }\n    MapToLabels(output_str, output_labels, &label_mapping);\n\n    // Compute counts for input and output labels.\n    int num_labels = label_mapping.size();\n    input_label_counts->resize(num_inputs);\n    input_has_ellipsis->resize(num_inputs);\n    for (int i = 0; i < num_inputs; ++i) {\n      input_label_counts->at(i).resize(num_labels);\n      for (const int label : input_labels->at(i)) {\n        if (label != kEllipsisLabel)\n          input_label_counts->at(i)[label] += 1;\n        else\n          input_has_ellipsis->at(i) = true;\n      }\n    }\n    output_label_counts->resize(num_labels);\n    for (const int label : *output_labels) {\n      if (label != kEllipsisLabel)\n        output_label_counts->at(label) += 1;\n      else\n        *output_has_ellipsis = true;\n    }\n\n    // Map each label to a unique DimensionType.\n    label_types->resize(num_labels);\n    for (int label = 0; label < num_labels; ++label) {\n      if (label == kEllipsisLabel) continue;\n      bool removed = (*output_label_counts)[label] == 0;\n      bool unique = num_inputs == 1 || (*input_label_counts)[0][label] == 0 ||\n                    (*input_label_counts)[1][label] == 0;\n      (*label_types)[label] = GetDimensionType(removed, unique);\n    }\n    return Status::OK();\n  }", "func_hash": 245883315476396879421677768643467596549, "file_name": "einsum_op_impl.h", "file_hash": 325930431028150928108252149027684363493, "cwe": ["CWE-703"], "cve": "CVE-2021-41201", "cve_desc": "TensorFlow is an open source platform for machine learning. In affeced versions during execution, `EinsumHelper::ParseEquation()` is supposed to set the flags in `input_has_ellipsis` vector and `*output_has_ellipsis` boolean to indicate whether there is ellipsis in the corresponding inputs and output. However, the code only changes these flags to `true` and never assigns `false`. This results in unitialized variable access if callers assume that `EinsumHelper::ParseEquation()` always sets these flags. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41201"}
{"idx": 256947, "project": "tensorflow", "commit_id": "f09caa532b6e1ac8d2aa61b7832c78c5b79300c6", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/f09caa532b6e1ac8d2aa61b7832c78c5b79300c6", "commit_message": "Fix EinsumHelper::ParseEquation to avoid uninitialized accesses.\n\nEinsumHelper::ParseEquation is supposed to return true or false in\ninput_has_ellipsis and output_has_ellipsis to indicate whether there is\nellipsis in the inputs and output. Previously, when there is no ellipsis in the\ninputs or output, the routine doesn't assign false to the variables. This\nchange initializes the two variables with false to fix the problem.\nPiperOrigin-RevId: 391772004\nChange-Id: I17b6c88aadef4131470378e48cced054bf252e86", "target": 0, "func": "  static Status ParseEquation(const string& equation,\n                              OperandLabels* input_labels,\n                              Labels* output_labels,\n                              std::vector* label_types,\n                              OperandLabelCounts* input_label_counts,\n                              LabelCounts* output_label_counts,\n                              gtl::InlinedVector* input_has_ellipsis,\n                              bool* output_has_ellipsis) {\n    gtl::InlinedVector input_str;\n    string output_str;\n    TF_RETURN_IF_ERROR(ParseEinsumEquation(equation, &input_str, &output_str));\n\n    // Temporary map from single character labels to (consecutive) integer\n    // labels.\n    absl::flat_hash_map label_mapping;\n    int num_inputs = input_str.size();\n    input_labels->resize(num_inputs);\n\n    // Map from single characters to integer labels.\n    for (int i = 0; i < num_inputs; ++i) {\n      MapToLabels(input_str[i], &input_labels->at(i), &label_mapping);\n    }\n    MapToLabels(output_str, output_labels, &label_mapping);\n\n    // Compute counts for input and output labels.\n    int num_labels = label_mapping.size();\n    input_label_counts->resize(num_inputs);\n    input_has_ellipsis->resize(num_inputs);\n    for (int i = 0; i < num_inputs; ++i) {\n      input_label_counts->at(i).resize(num_labels);\n      input_has_ellipsis->at(i) = false;\n      for (const int label : input_labels->at(i)) {\n        if (label != kEllipsisLabel)\n          input_label_counts->at(i)[label] += 1;\n        else\n          input_has_ellipsis->at(i) = true;\n      }\n    }\n    output_label_counts->resize(num_labels);\n    *output_has_ellipsis = false;\n    for (const int label : *output_labels) {\n      if (label != kEllipsisLabel)\n        output_label_counts->at(label) += 1;\n      else\n        *output_has_ellipsis = true;\n    }\n\n    // Map each label to a unique DimensionType.\n    label_types->resize(num_labels);\n    for (int label = 0; label < num_labels; ++label) {\n      if (label == kEllipsisLabel) continue;\n      bool removed = (*output_label_counts)[label] == 0;\n      bool unique = num_inputs == 1 || (*input_label_counts)[0][label] == 0 ||\n                    (*input_label_counts)[1][label] == 0;\n      (*label_types)[label] = GetDimensionType(removed, unique);\n    }\n    return Status::OK();\n  }", "func_hash": 228212953693539342712398927899777742190, "file_name": "einsum_op_impl.h", "file_hash": 62458496214900513409618845321239996805, "cwe": ["CWE-703"], "cve": "CVE-2021-41201", "cve_desc": "TensorFlow is an open source platform for machine learning. In affeced versions during execution, `EinsumHelper::ParseEquation()` is supposed to set the flags in `input_has_ellipsis` vector and `*output_has_ellipsis` boolean to indicate whether there is ellipsis in the corresponding inputs and output. However, the code only changes these flags to `true` and never assigns `false`. This results in unitialized variable access if callers assume that `EinsumHelper::ParseEquation()` always sets these flags. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41201"}
{"idx": 197359, "project": "tensorflow", "commit_id": "68867bf01239d9e1048f98cbad185bf4761bedd3", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/68867bf01239d9e1048f98cbad185bf4761bedd3", "commit_message": "Prevent unitialized variable use in grappler.\n\nPiperOrigin-RevId: 399702928\nChange-Id: Id7e75451fbff297692dfb687f60ea04b25c96b24", "target": 1, "func": "Status AutoParallel::Initialize(const GrapplerItem& item) {\n  num_gpus_ = GetNumAvailableGPUs();\n  LOG(INFO) << \"Number of GPUs: \" << num_gpus_;\n  item_ = &item;\n  graph_ = item.graph;\n  LOG(INFO) << \"Original graph size: \" << graph_.node_size();\n  if (item.fetch.empty()) {\n    return Status(error::INVALID_ARGUMENT, \"No fetch nodes provided.\");\n  }\n\n  if (item.MainVariables().empty()) {\n    return Status(error::INVALID_ARGUMENT, \"No variables provided.\");\n  }\n\n  for (const auto& init : item.init_ops) {\n    VLOG(1) << \"Init node: \" << init;\n  }\n\n  for (const auto& fetch : item.fetch) {\n    VLOG(1) << \"Fetch node: \" << fetch;\n  }\n\n  for (const auto& var : item.MainVariables()) {\n    VLOG(2) << \"Variable: \" << var->name();\n  }\n\n  const std::set apply_gradients_ops = {\"ApplyGradientDescent\",\n                                                \"ApplyProximalGradientDescent\",\n                                                \"ApplyAdadelta\",\n                                                \"ApplyAdagrad\",\n                                                \"ApplyProximalAdagrad\",\n                                                \"ApplyAdagradDA\",\n                                                \"ApplyFtrl\",\n                                                \"ApplyMomentum\",\n                                                \"ApplyAdam\",\n                                                \"ApplyRMSProp\",\n                                                \"ApplyCenteredRMSProp\"};\n  for (int i = 0; i < graph_.node_size(); i++) {\n    all_nodes_.insert(\n        std::make_pair(graph_.node(i).name(), graph_.mutable_node(i)));\n    if (apply_gradients_ops.find(graph_.node(i).op()) !=\n        apply_gradients_ops.end()) {\n      apply_gradients_nodes_.insert(graph_.node(i).name());\n      VLOG(2) << \"Apply gradients node: \" << graph_.node(i).name();\n    }\n  }\n\n  auto div_const_node = AddNodeDivConst();\n  all_nodes_.insert(std::make_pair(div_const_node->name(), div_const_node));\n  std::map gradient_pos = {{\"ApplyGradientDescent\", 2},\n                                        {\"ApplyProximalGradientDescent\", 4},\n                                        {\"ApplyAdadelta\", 6},\n                                        {\"ApplyAdagrad\", 3},\n                                        {\"ApplyProximalAdagrad\", 5},\n                                        {\"ApplyAdagradDA\", 3},\n                                        {\"ApplyFtrl\", 3},\n                                        {\"ApplyMomentum\", 3},\n                                        {\"ApplyAdam\", 9},\n                                        {\"ApplyRMSProp\", 7},\n                                        {\"ApplyCenteredRMSProp\", 8}};\n  for (const auto& apply_gradient_node_name : apply_gradients_nodes_) {\n    auto apply_gradients_op = all_nodes_[apply_gradient_node_name]->op();\n    auto apply_gradients_node = all_nodes_[apply_gradient_node_name];\n\n    auto div_node = AddNodeDiv(\n        apply_gradient_node_name,\n        apply_gradients_node->input(gradient_pos[apply_gradients_op]),\n        div_const_node->name());\n    all_nodes_.insert(std::make_pair(div_node->name(), div_node));\n    *apply_gradients_node->mutable_input(gradient_pos[apply_gradients_op]) =\n        div_node->name();\n  }\n  LOG(INFO) << \"Graph size after adding div nodes: \" << all_nodes_.size();\n\n  std::vector train_nodes;\n  TF_RETURN_IF_ERROR(ComputeTransitiveFanin(graph_, item.fetch, &train_nodes));\n  LOG(INFO) << \"Number of training nodes: \" << train_nodes.size();\n\n  const NodeDef* dequeue_node;\n  for (const auto& train_node : train_nodes) {\n    if (IsDequeueOp(*train_node)) {\n      dequeue_node = train_node;\n      break;\n    }\n  }\n\n  std::vector input_nodes;\n  if (dequeue_node) {\n    LOG(INFO) << \"Dequeue node: \" << dequeue_node->name();\n    TF_RETURN_IF_ERROR(ComputeTransitiveFanin(graph_, {dequeue_node->name()},\n                                              {}, &input_nodes));\n  }\n  LOG(INFO) << \"Number of input nodes: \" << input_nodes.size();\n\n  std::set dont_replicate_nodes;\n  for (const auto& variable : item.MainVariables()) {\n    dont_replicate_nodes.insert(variable->name());\n  }\n\n  for (const auto& init : item.init_ops) {\n    dont_replicate_nodes.insert(NodeName(init));\n  }\n\n  // Don't replicate all input nodes, except the dequeue node.\n  for (const auto& input_node : input_nodes) {\n    if (input_node->name() != dequeue_node->name()) {\n      dont_replicate_nodes.insert(input_node->name());\n    }\n  }\n\n  for (const auto& node : train_nodes) {\n    if (dont_replicate_nodes.find(node->name()) == dont_replicate_nodes.end()) {\n      replica_nodes_.insert(node->name());\n    }\n  }\n  LOG(INFO) << \"Number of replica nodes: \" << replica_nodes_.size();\n\n  for (const auto& node : all_nodes_) {\n    if (replica_nodes_.find(node.first) == replica_nodes_.end()) {\n      shared_nodes_.insert(node.first);\n    }\n  }\n  LOG(INFO) << \"Number of shared nodes: \" << shared_nodes_.size();\n  return Status::OK();\n}", "func_hash": 251567762309539032923316029186493191559, "file_name": "auto_parallel.cc", "file_hash": 291637818016549468794962575194747709507, "cwe": ["CWE-703"], "cve": "CVE-2021-41225", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions TensorFlow's Grappler optimizer has a use of unitialized variable. If the `train_nodes` vector (obtained from the saved model that gets optimized) does not contain a `Dequeue` node, then `dequeue_node` is left unitialized. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41225"}
{"idx": 257461, "project": "tensorflow", "commit_id": "68867bf01239d9e1048f98cbad185bf4761bedd3", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/68867bf01239d9e1048f98cbad185bf4761bedd3", "commit_message": "Prevent unitialized variable use in grappler.\n\nPiperOrigin-RevId: 399702928\nChange-Id: Id7e75451fbff297692dfb687f60ea04b25c96b24", "target": 0, "func": "Status AutoParallel::Initialize(const GrapplerItem& item) {\n  num_gpus_ = GetNumAvailableGPUs();\n  LOG(INFO) << \"Number of GPUs: \" << num_gpus_;\n  item_ = &item;\n  graph_ = item.graph;\n  LOG(INFO) << \"Original graph size: \" << graph_.node_size();\n  if (item.fetch.empty()) {\n    return Status(error::INVALID_ARGUMENT, \"No fetch nodes provided.\");\n  }\n\n  if (item.MainVariables().empty()) {\n    return Status(error::INVALID_ARGUMENT, \"No variables provided.\");\n  }\n\n  for (const auto& init : item.init_ops) {\n    VLOG(1) << \"Init node: \" << init;\n  }\n\n  for (const auto& fetch : item.fetch) {\n    VLOG(1) << \"Fetch node: \" << fetch;\n  }\n\n  for (const auto& var : item.MainVariables()) {\n    VLOG(2) << \"Variable: \" << var->name();\n  }\n\n  const std::set apply_gradients_ops = {\"ApplyGradientDescent\",\n                                                \"ApplyProximalGradientDescent\",\n                                                \"ApplyAdadelta\",\n                                                \"ApplyAdagrad\",\n                                                \"ApplyProximalAdagrad\",\n                                                \"ApplyAdagradDA\",\n                                                \"ApplyFtrl\",\n                                                \"ApplyMomentum\",\n                                                \"ApplyAdam\",\n                                                \"ApplyRMSProp\",\n                                                \"ApplyCenteredRMSProp\"};\n  for (int i = 0; i < graph_.node_size(); i++) {\n    all_nodes_.insert(\n        std::make_pair(graph_.node(i).name(), graph_.mutable_node(i)));\n    if (apply_gradients_ops.find(graph_.node(i).op()) !=\n        apply_gradients_ops.end()) {\n      apply_gradients_nodes_.insert(graph_.node(i).name());\n      VLOG(2) << \"Apply gradients node: \" << graph_.node(i).name();\n    }\n  }\n\n  auto div_const_node = AddNodeDivConst();\n  all_nodes_.insert(std::make_pair(div_const_node->name(), div_const_node));\n  std::map gradient_pos = {{\"ApplyGradientDescent\", 2},\n                                        {\"ApplyProximalGradientDescent\", 4},\n                                        {\"ApplyAdadelta\", 6},\n                                        {\"ApplyAdagrad\", 3},\n                                        {\"ApplyProximalAdagrad\", 5},\n                                        {\"ApplyAdagradDA\", 3},\n                                        {\"ApplyFtrl\", 3},\n                                        {\"ApplyMomentum\", 3},\n                                        {\"ApplyAdam\", 9},\n                                        {\"ApplyRMSProp\", 7},\n                                        {\"ApplyCenteredRMSProp\", 8}};\n  for (const auto& apply_gradient_node_name : apply_gradients_nodes_) {\n    auto apply_gradients_op = all_nodes_[apply_gradient_node_name]->op();\n    auto apply_gradients_node = all_nodes_[apply_gradient_node_name];\n\n    auto div_node = AddNodeDiv(\n        apply_gradient_node_name,\n        apply_gradients_node->input(gradient_pos[apply_gradients_op]),\n        div_const_node->name());\n    all_nodes_.insert(std::make_pair(div_node->name(), div_node));\n    *apply_gradients_node->mutable_input(gradient_pos[apply_gradients_op]) =\n        div_node->name();\n  }\n  LOG(INFO) << \"Graph size after adding div nodes: \" << all_nodes_.size();\n\n  std::vector train_nodes;\n  TF_RETURN_IF_ERROR(ComputeTransitiveFanin(graph_, item.fetch, &train_nodes));\n  LOG(INFO) << \"Number of training nodes: \" << train_nodes.size();\n\n  const NodeDef* dequeue_node = nullptr;\n  for (const auto& train_node : train_nodes) {\n    if (IsDequeueOp(*train_node)) {\n      dequeue_node = train_node;\n      break;\n    }\n  }\n\n  std::vector input_nodes;\n  if (dequeue_node) {\n    LOG(INFO) << \"Dequeue node: \" << dequeue_node->name();\n    TF_RETURN_IF_ERROR(ComputeTransitiveFanin(graph_, {dequeue_node->name()},\n                                              {}, &input_nodes));\n  }\n  LOG(INFO) << \"Number of input nodes: \" << input_nodes.size();\n\n  std::set dont_replicate_nodes;\n  for (const auto& variable : item.MainVariables()) {\n    dont_replicate_nodes.insert(variable->name());\n  }\n\n  for (const auto& init : item.init_ops) {\n    dont_replicate_nodes.insert(NodeName(init));\n  }\n\n  // Don't replicate all input nodes, except the dequeue node.\n  for (const auto& input_node : input_nodes) {\n    if (input_node->name() != dequeue_node->name()) {\n      dont_replicate_nodes.insert(input_node->name());\n    }\n  }\n\n  for (const auto& node : train_nodes) {\n    if (dont_replicate_nodes.find(node->name()) == dont_replicate_nodes.end()) {\n      replica_nodes_.insert(node->name());\n    }\n  }\n  LOG(INFO) << \"Number of replica nodes: \" << replica_nodes_.size();\n\n  for (const auto& node : all_nodes_) {\n    if (replica_nodes_.find(node.first) == replica_nodes_.end()) {\n      shared_nodes_.insert(node.first);\n    }\n  }\n  LOG(INFO) << \"Number of shared nodes: \" << shared_nodes_.size();\n  return Status::OK();\n}", "func_hash": 239400794091887748487635505232463109682, "file_name": "auto_parallel.cc", "file_hash": 250375078296494886105234781412804054984, "cwe": ["CWE-703"], "cve": "CVE-2021-41225", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions TensorFlow's Grappler optimizer has a use of unitialized variable. If the `train_nodes` vector (obtained from the saved model that gets optimized) does not contain a `Dequeue` node, then `dequeue_node` is left unitialized. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41225"}
{"idx": 197395, "project": "tensorflow", "commit_id": "4071d8e2f6c45c1955a811fee757ca2adbe462c1", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4071d8e2f6c45c1955a811fee757ca2adbe462c1", "commit_message": "Fix FPE issue with `tf.raw_ops.Reverse`.\n\nPiperOrigin-RevId: 371176973\nChange-Id: Ic6d483bfc95313ec2299c2d1c956cfe96c96626c", "target": 1, "func": "  void Compute(OpKernelContext* context) override {\n    const Tensor& input = context->input(0);\n    const Tensor& dims = context->input(1);\n\n    if (TensorShapeUtils::IsScalar(input.shape())) {\n      context->set_output(0, input);\n    } else {\n      const int input_dims = input.dims();\n      OP_REQUIRES(context, TensorShapeUtils::IsVector(dims.shape()),\n                  errors::InvalidArgument(\"'dims' must be 1-dimension, not \",\n                                          dims.dims()));\n\n      OP_REQUIRES(\n          context, input_dims == dims.dim_size(0),\n          errors::InvalidArgument(\n              \"'dims' must have the same number of values as 'input' has \"\n              \"dimensions. 'input' has \",\n              input_dims, \"'dims' has \", dims.dim_size(0), \" values\"));\n      OP_REQUIRES(context, input_dims <= 8,\n                  errors::Unimplemented(\n                      \"reverse is not implemented for tensors of rank > 8.\"));\n\n      Tensor* output = nullptr;\n      OP_REQUIRES_OK(context,\n                     context->allocate_output(0, input.shape(), &output));\n\n#define HANDLE_REVERSE(NDIMS)                                               \\\n  case NDIMS:                                                               \\\n    HandleReverseCase(context, dims.vec(), output); \\\n    return;\n\n      switch (input_dims) {\n        HANDLE_REVERSE(0);\n        HANDLE_REVERSE(1);\n        HANDLE_REVERSE(2);\n        HANDLE_REVERSE(3);\n        HANDLE_REVERSE(4);\n        HANDLE_REVERSE(5);\n        HANDLE_REVERSE(6);\n        HANDLE_REVERSE(7);\n        HANDLE_REVERSE(8);\n      }\n#undef HANDLE_REVERSE\n    }\n  }", "func_hash": 320359893140451578623172737965362672352, "file_name": "reverse_op.cc", "file_hash": 11850357512767152498311955295464965693, "cwe": ["CWE-369"], "cve": "CVE-2021-29556", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a denial of service via a FPE runtime error in `tf.raw_ops.Reverse`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/36229ea9e9451dac14a8b1f4711c435a1d84a594/tensorflow/core/kernels/reverse_op.cc#L75-L76) performs a division based on the first dimension of the tensor argument. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29556"}
{"idx": 258082, "project": "tensorflow", "commit_id": "4071d8e2f6c45c1955a811fee757ca2adbe462c1", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4071d8e2f6c45c1955a811fee757ca2adbe462c1", "commit_message": "Fix FPE issue with `tf.raw_ops.Reverse`.\n\nPiperOrigin-RevId: 371176973\nChange-Id: Ic6d483bfc95313ec2299c2d1c956cfe96c96626c", "target": 0, "func": "  void Compute(OpKernelContext* context) override {\n    const Tensor& input = context->input(0);\n    // If input is provided, check to make sure the first dimension is valid.\n    if (input.dims() > 0) {\n      OP_REQUIRES(\n          context, input.dim_size(0) != 0,\n          errors::InvalidArgument(\"Invalid input first dimension. Found 0.\"));\n    }\n    const Tensor& dims = context->input(1);\n\n    if (TensorShapeUtils::IsScalar(input.shape())) {\n      context->set_output(0, input);\n    } else {\n      const int input_dims = input.dims();\n      OP_REQUIRES(context, TensorShapeUtils::IsVector(dims.shape()),\n                  errors::InvalidArgument(\"'dims' must be 1-dimension, not \",\n                                          dims.dims()));\n\n      OP_REQUIRES(\n          context, input_dims == dims.dim_size(0),\n          errors::InvalidArgument(\n              \"'dims' must have the same number of values as 'input' has \"\n              \"dimensions. 'input' has \",\n              input_dims, \"'dims' has \", dims.dim_size(0), \" values\"));\n      OP_REQUIRES(context, input_dims <= 8,\n                  errors::Unimplemented(\n                      \"reverse is not implemented for tensors of rank > 8.\"));\n\n      Tensor* output = nullptr;\n      OP_REQUIRES_OK(context,\n                     context->allocate_output(0, input.shape(), &output));\n\n#define HANDLE_REVERSE(NDIMS)                                               \\\n  case NDIMS:                                                               \\\n    HandleReverseCase(context, dims.vec(), output); \\\n    return;\n\n      switch (input_dims) {\n        HANDLE_REVERSE(0);\n        HANDLE_REVERSE(1);\n        HANDLE_REVERSE(2);\n        HANDLE_REVERSE(3);\n        HANDLE_REVERSE(4);\n        HANDLE_REVERSE(5);\n        HANDLE_REVERSE(6);\n        HANDLE_REVERSE(7);\n        HANDLE_REVERSE(8);\n      }\n#undef HANDLE_REVERSE\n    }\n  }", "func_hash": 46291446365050561465946697163690877873, "file_name": "reverse_op.cc", "file_hash": 197535237441816623722096111592150464560, "cwe": ["CWE-369"], "cve": "CVE-2021-29556", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a denial of service via a FPE runtime error in `tf.raw_ops.Reverse`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/36229ea9e9451dac14a8b1f4711c435a1d84a594/tensorflow/core/kernels/reverse_op.cc#L75-L76) performs a division based on the first dimension of the tensor argument. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29556"}
{"idx": 197466, "project": "tensorflow", "commit_id": "9e82dce6e6bd1f36a57e08fa85af213e2b2f2622", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/9e82dce6e6bd1f36a57e08fa85af213e2b2f2622", "commit_message": "Fix NPE in restoring code.\n\nPiperOrigin-RevId: 388303253\nChange-Id: Ia8c68568cb854bca538909a182b31a618d68ce55", "target": 1, "func": "void RestoreTensor(OpKernelContext* context,\n                   checkpoint::TensorSliceReader::OpenTableFunction open_func,\n                   int preferred_shard, bool restore_slice, int restore_index) {\n  const Tensor& file_pattern_t = context->input(0);\n  {\n    const int64_t size = file_pattern_t.NumElements();\n    OP_REQUIRES(\n        context, size == 1,\n        errors::InvalidArgument(\n            \"Input 0 (file_pattern) must be a string scalar; got a tensor of \",\n            size, \"elements\"));\n  }\n  const string& file_pattern = file_pattern_t.flat()(0);\n\n  const Tensor& tensor_name_t = context->input(1);\n  const string& tensor_name = tensor_name_t.flat()(restore_index);\n\n  // If we cannot find a cached reader we will allocate our own.\n  std::unique_ptr allocated_reader;\n\n  const checkpoint::TensorSliceReader* reader = nullptr;\n\n  if (context->slice_reader_cache()) {\n    reader = context->slice_reader_cache()->GetReader(file_pattern, open_func,\n                                                      preferred_shard);\n  }\n  if (!reader) {\n    allocated_reader.reset(new checkpoint::TensorSliceReader(\n        file_pattern, open_func, preferred_shard));\n    reader = allocated_reader.get();\n  }\n  OP_REQUIRES_OK(context, CHECK_NOTNULL(reader)->status());\n\n  // Get the shape and type from the save file.\n  DataType type;\n  TensorShape saved_shape;\n  OP_REQUIRES(\n      context, reader->HasTensor(tensor_name, &saved_shape, &type),\n      errors::NotFound(\"Tensor name \\\"\", tensor_name,\n                       \"\\\" not found in checkpoint files \", file_pattern));\n  OP_REQUIRES(\n      context, type == context->expected_output_dtype(restore_index),\n      errors::InvalidArgument(\"Expected to restore a tensor of type \",\n                              DataTypeString(context->expected_output_dtype(0)),\n                              \", got a tensor of type \", DataTypeString(type),\n                              \" instead: tensor_name = \", tensor_name));\n\n  // Shape of the output and slice to load.\n  TensorShape output_shape(saved_shape);\n  TensorSlice slice_to_load(saved_shape.dims());\n  if (restore_slice) {\n    const tstring& shape_spec =\n        context->input(2).flat()(restore_index);\n    if (!shape_spec.empty()) {\n      TensorShape parsed_shape;\n      OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice(\n                                  shape_spec, &parsed_shape, &slice_to_load,\n                                  &output_shape));\n      OP_REQUIRES(\n          context, parsed_shape.IsSameSize(saved_shape),\n          errors::InvalidArgument(\n              \"Shape in shape_and_slice spec does not match the shape in the \"\n              \"save file: \",\n              parsed_shape.DebugString(),\n              \", save file shape: \", saved_shape.DebugString()));\n    }\n  }\n\n  Tensor* t = nullptr;\n  OP_REQUIRES_OK(context,\n                 context->allocate_output(restore_index, output_shape, &t));\n\n  if (output_shape.num_elements() == 0) return;\n\n#define READER_COPY(T)                                                \\\n  case DataTypeToEnum::value:                                      \\\n    OP_REQUIRES(context,                                              \\\n                reader->CopySliceData(tensor_name, slice_to_load,     \\\n                                      t->flat().data()),           \\\n                errors::InvalidArgument(\"Error copying slice data\")); \\\n    break;\n\n  switch (type) {\n    TF_CALL_SAVE_RESTORE_TYPES(READER_COPY)\n    default:\n      context->SetStatus(errors::Unimplemented(\n          \"Restoring data type \", DataTypeString(type), \" not yet supported\"));\n  }\n#undef READER_COPY\n}", "func_hash": 252467620619020665053463064048093339685, "file_name": "save_restore_tensor.cc", "file_hash": 5161981891248921294380940461341356456, "cwe": ["CWE-476"], "cve": "CVE-2021-37639", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. When restoring tensors via raw APIs, if the tensor name is not provided, TensorFlow can be tricked into dereferencing a null pointer. Alternatively, attackers can read memory outside the bounds of heap allocated data by providing some tensor names but not enough for a successful restoration. The [implementation](https://github.com/tensorflow/tensorflow/blob/47a06f40411a69c99f381495f490536972152ac0/tensorflow/core/kernels/save_restore_tensor.cc#L158-L159) retrieves the tensor list corresponding to the `tensor_name` user controlled input and immediately retrieves the tensor at the restoration index (controlled via `preferred_shard` argument). This occurs without validating that the provided list has enough values. If the list is empty this results in dereferencing a null pointer (undefined behavior). If, however, the list has some elements, if the restoration index is outside the bounds this results in heap OOB read. We have patched the issue in GitHub commit 9e82dce6e6bd1f36a57e08fa85af213e2b2f2622. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37639"}
{"idx": 259081, "project": "tensorflow", "commit_id": "9e82dce6e6bd1f36a57e08fa85af213e2b2f2622", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/9e82dce6e6bd1f36a57e08fa85af213e2b2f2622", "commit_message": "Fix NPE in restoring code.\n\nPiperOrigin-RevId: 388303253\nChange-Id: Ia8c68568cb854bca538909a182b31a618d68ce55", "target": 0, "func": "void RestoreTensor(OpKernelContext* context,\n                   checkpoint::TensorSliceReader::OpenTableFunction open_func,\n                   int preferred_shard, bool restore_slice, int restore_index) {\n  const Tensor& file_pattern_t = context->input(0);\n  {\n    const int64_t size = file_pattern_t.NumElements();\n    OP_REQUIRES(\n        context, size == 1,\n        errors::InvalidArgument(\n            \"Input 0 (file_pattern) must be a string scalar; got a tensor of \",\n            size, \" elements\"));\n  }\n  const string& file_pattern = file_pattern_t.flat()(0);\n\n  const Tensor& tensor_name_t = context->input(1);\n  {\n    const int64_t size = tensor_name_t.NumElements();\n    OP_REQUIRES(context, size > restore_index,\n                errors::InvalidArgument(\n                    \"Input 1 (file_pattern) must be a have at least \",\n                    restore_index + 1, \" elements\"));\n  }\n  const string& tensor_name = tensor_name_t.flat()(restore_index);\n\n  // If we cannot find a cached reader we will allocate our own.\n  std::unique_ptr allocated_reader;\n\n  const checkpoint::TensorSliceReader* reader = nullptr;\n\n  if (context->slice_reader_cache()) {\n    reader = context->slice_reader_cache()->GetReader(file_pattern, open_func,\n                                                      preferred_shard);\n  }\n  if (!reader) {\n    allocated_reader.reset(new checkpoint::TensorSliceReader(\n        file_pattern, open_func, preferred_shard));\n    reader = allocated_reader.get();\n  }\n  OP_REQUIRES_OK(context, CHECK_NOTNULL(reader)->status());\n\n  // Get the shape and type from the save file.\n  DataType type;\n  TensorShape saved_shape;\n  OP_REQUIRES(\n      context, reader->HasTensor(tensor_name, &saved_shape, &type),\n      errors::NotFound(\"Tensor name \\\"\", tensor_name,\n                       \"\\\" not found in checkpoint files \", file_pattern));\n  OP_REQUIRES(\n      context, type == context->expected_output_dtype(restore_index),\n      errors::InvalidArgument(\"Expected to restore a tensor of type \",\n                              DataTypeString(context->expected_output_dtype(0)),\n                              \", got a tensor of type \", DataTypeString(type),\n                              \" instead: tensor_name = \", tensor_name));\n\n  // Shape of the output and slice to load.\n  TensorShape output_shape(saved_shape);\n  TensorSlice slice_to_load(saved_shape.dims());\n  if (restore_slice) {\n    const tstring& shape_spec =\n        context->input(2).flat()(restore_index);\n    if (!shape_spec.empty()) {\n      TensorShape parsed_shape;\n      OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice(\n                                  shape_spec, &parsed_shape, &slice_to_load,\n                                  &output_shape));\n      OP_REQUIRES(\n          context, parsed_shape.IsSameSize(saved_shape),\n          errors::InvalidArgument(\n              \"Shape in shape_and_slice spec does not match the shape in the \"\n              \"save file: \",\n              parsed_shape.DebugString(),\n              \", save file shape: \", saved_shape.DebugString()));\n    }\n  }\n\n  Tensor* t = nullptr;\n  OP_REQUIRES_OK(context,\n                 context->allocate_output(restore_index, output_shape, &t));\n\n  if (output_shape.num_elements() == 0) return;\n\n#define READER_COPY(T)                                                \\\n  case DataTypeToEnum::value:                                      \\\n    OP_REQUIRES(context,                                              \\\n                reader->CopySliceData(tensor_name, slice_to_load,     \\\n                                      t->flat().data()),           \\\n                errors::InvalidArgument(\"Error copying slice data\")); \\\n    break;\n\n  switch (type) {\n    TF_CALL_SAVE_RESTORE_TYPES(READER_COPY)\n    default:\n      context->SetStatus(errors::Unimplemented(\n          \"Restoring data type \", DataTypeString(type), \" not yet supported\"));\n  }\n#undef READER_COPY\n}", "func_hash": 180098336466556354723257120420152514513, "file_name": "save_restore_tensor.cc", "file_hash": 177675182218356821099377926276239457736, "cwe": ["CWE-476"], "cve": "CVE-2021-37639", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. When restoring tensors via raw APIs, if the tensor name is not provided, TensorFlow can be tricked into dereferencing a null pointer. Alternatively, attackers can read memory outside the bounds of heap allocated data by providing some tensor names but not enough for a successful restoration. The [implementation](https://github.com/tensorflow/tensorflow/blob/47a06f40411a69c99f381495f490536972152ac0/tensorflow/core/kernels/save_restore_tensor.cc#L158-L159) retrieves the tensor list corresponding to the `tensor_name` user controlled input and immediately retrieves the tensor at the restoration index (controlled via `preferred_shard` argument). This occurs without validating that the provided list has enough values. If the list is empty this results in dereferencing a null pointer (undefined behavior). If, however, the list has some elements, if the restoration index is outside the bounds this results in heap OOB read. We have patched the issue in GitHub commit 9e82dce6e6bd1f36a57e08fa85af213e2b2f2622. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37639"}
{"idx": 197499, "project": "gpac", "commit_id": "dc7de8d3d604426c7a6e628d90cb9fb88e7b4c2c", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/dc7de8d3d604426c7a6e628d90cb9fb88e7b4c2c", "commit_message": "fixed #2212", "target": 1, "func": "GF_Err BD_DecMFFieldVec(GF_BifsDecoder * codec, GF_BitStream *bs, GF_Node *node, GF_FieldInfo *field, Bool is_mem_com)\n{\n\tGF_Err e;\n\tu32 NbBits, nbFields;\n\tu32 i;\n\tGF_ChildNodeItem *last;\n\tu8 qp_local, qp_on, initial_qp;\n\tGF_FieldInfo sffield;\n\n\tmemset(&sffield, 0, sizeof(GF_FieldInfo));\n\tsffield.fieldIndex = field->fieldIndex;\n\tsffield.fieldType = gf_sg_vrml_get_sf_type(field->fieldType);\n\tsffield.NDTtype = field->NDTtype;\n\tsffield.name = field->name;\n\n\tinitial_qp = qp_local = qp_on = 0;\n\n\t//vector description - alloc the MF size before\n\tNbBits = gf_bs_read_int(bs, 5);\n\tnbFields = gf_bs_read_int(bs, NbBits);\n\n\tif (codec->ActiveQP) {\n\t\tinitial_qp = 1;\n\t\t/*this is for QP 14*/\n\t\tgf_bifs_dec_qp14_set_length(codec, nbFields);\n\t}\n\n\tif (field->fieldType != GF_SG_VRML_MFNODE) {\n\t\te = gf_sg_vrml_mf_alloc(field->far_ptr, field->fieldType, nbFields);\n\t\tif (e) return e;\n\n\t\tfor (i=0; ifar_ptr, field->fieldType, & sffield.far_ptr, i);\n\t\t\tif (e) return e;\n\t\t\te = gf_bifs_dec_sf_field(codec, bs, node, &sffield, GF_FALSE);\n\t\t\tif (e) return e;\n\t\t}\n\t} else {\n\t\tlast = NULL;\n\t\tfor (i=0; iNDTtype);\n\t\t\tif (new_node) {\n\t\t\t\te = gf_node_register(new_node, is_mem_com ? NULL : node);\n\t\t\t\tif (e) return e;\n\n\t\t\t\tif (node) {\n\t\t\t\t\t/*special case for QP, register as the current QP*/\n\t\t\t\t\tif (gf_node_get_tag(new_node) == TAG_MPEG4_QuantizationParameter) {\n\t\t\t\t\t\tqp_local = ((M_QuantizationParameter *)new_node)->isLocal;\n\t\t\t\t\t\t/*we have a QP in the same scope, remove previous\n\t\t\t\t\t\tNB: we assume this is the right behavior, the spec doesn't say\n\t\t\t\t\t\twhether QP is cumulative or not*/\n\t\t\t\t\t\tif (qp_on) gf_bifs_dec_qp_remove(codec, GF_FALSE);\n\n\t\t\t\t\t\te = gf_bifs_dec_qp_set(codec, new_node);\n\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\tqp_on = 1;\n\t\t\t\t\t\tif (qp_local) qp_local = 2;\n\t\t\t\t\t\tif (codec->force_keep_qp) {\n\t\t\t\t\t\t\te = gf_node_list_add_child_last(field->far_ptr, new_node, &last);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tgf_node_register(new_node, NULL);\n\t\t\t\t\t\t\tgf_node_unregister(new_node, node);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\te = gf_node_list_add_child_last(field->far_ptr, new_node, &last);\n\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*proto coding*/\n\t\t\t\telse if (codec->pCurrentProto) {\n\t\t\t\t\t/*TO DO: what happens if this is a QP node on the interface ?*/\n\t\t\t\t\te = gf_node_list_add_child_last( (GF_ChildNodeItem **)field->far_ptr, new_node, &last);\n\t\t\t\t\tif (e) return e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn codec->LastError ? codec->LastError : GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t}\n\t\t/*according to the spec, the QP applies to the current node itself, not just children.\n\t\tIf IsLocal is TRUE remove the node*/\n\t\tif (qp_on && qp_local) {\n\t\t\tif (qp_local == 2) {\n//\t\t\t\tqp_local = 1;\n\t\t\t} else {\n\t\t\t\t//ask to get rid of QP and reactivate if we had a QP when entering the node\n\t\t\t\tgf_bifs_dec_qp_remove(codec, initial_qp);\n//\t\t\t\tqp_local = 0;\n\t\t\t}\n\t\t}\n\t}\n\t/*finally delete the QP if any (local or not) as we get out of this node*/\n\tif (qp_on) gf_bifs_dec_qp_remove(codec, GF_TRUE);\n\treturn GF_OK;\n}", "func_hash": 181633592491715085539951152559525218380, "file_name": "field_decode.c", "file_hash": 27053036293524314453415412309723108309, "cwe": ["CWE-416"], "cve": "CVE-2022-2453", "cve_desc": "Use After Free in GitHub repository gpac/gpac prior to 2.1-DEV.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2453"}
{"idx": 259515, "project": "gpac", "commit_id": "dc7de8d3d604426c7a6e628d90cb9fb88e7b4c2c", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/dc7de8d3d604426c7a6e628d90cb9fb88e7b4c2c", "commit_message": "fixed #2212", "target": 0, "func": "GF_Err BD_DecMFFieldVec(GF_BifsDecoder * codec, GF_BitStream *bs, GF_Node *node, GF_FieldInfo *field, Bool is_mem_com)\n{\n\tGF_Err e;\n\tu32 NbBits, nbFields;\n\tu32 i;\n\tGF_ChildNodeItem *last;\n\tu8 qp_local, qp_on, initial_qp;\n\tGF_FieldInfo sffield;\n\n\tmemset(&sffield, 0, sizeof(GF_FieldInfo));\n\tsffield.fieldIndex = field->fieldIndex;\n\tsffield.fieldType = gf_sg_vrml_get_sf_type(field->fieldType);\n\tsffield.NDTtype = field->NDTtype;\n\tsffield.name = field->name;\n\n\tinitial_qp = qp_local = qp_on = 0;\n\n\t//vector description - alloc the MF size before\n\tNbBits = gf_bs_read_int(bs, 5);\n\tnbFields = gf_bs_read_int(bs, NbBits);\n\n\tif (codec->ActiveQP) {\n\t\tinitial_qp = 1;\n\t\t/*this is for QP 14*/\n\t\tgf_bifs_dec_qp14_set_length(codec, nbFields);\n\t}\n\n\tif (field->fieldType != GF_SG_VRML_MFNODE) {\n\t\te = gf_sg_vrml_mf_alloc(field->far_ptr, field->fieldType, nbFields);\n\t\tif (e) return e;\n\n\t\tfor (i=0; ifar_ptr, field->fieldType, & sffield.far_ptr, i);\n\t\t\tif (e) return e;\n\t\t\te = gf_bifs_dec_sf_field(codec, bs, node, &sffield, GF_FALSE);\n\t\t\tif (e) return e;\n\t\t}\n\t\treturn GF_OK;\n\t}\n\n\te = GF_OK;\n\tlast = NULL;\n\tfor (i=0; iNDTtype);\n\t\tif (new_node) {\n\t\t\te = gf_node_register(new_node, is_mem_com ? NULL : node);\n\t\t\tif (e) goto exit;\n\n\t\t\tif (node) {\n\t\t\t\t/*special case for QP, register as the current QP*/\n\t\t\t\tif (gf_node_get_tag(new_node) == TAG_MPEG4_QuantizationParameter) {\n\t\t\t\t\tqp_local = ((M_QuantizationParameter *)new_node)->isLocal;\n\t\t\t\t\t/*we have a QP in the same scope, remove previous\n\t\t\t\t\tNB: we assume this is the right behavior, the spec doesn't say\n\t\t\t\t\twhether QP is cumulative or not*/\n\t\t\t\t\tif (qp_on) gf_bifs_dec_qp_remove(codec, GF_FALSE);\n\n\t\t\t\t\te = gf_bifs_dec_qp_set(codec, new_node);\n\t\t\t\t\tif (e) goto exit;\n\t\t\t\t\tqp_on = 1;\n\t\t\t\t\tif (qp_local) qp_local = 2;\n\t\t\t\t\tif (codec->force_keep_qp) {\n\t\t\t\t\t\te = gf_node_list_add_child_last(field->far_ptr, new_node, &last);\n\t\t\t\t\t\tif (e) goto exit;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgf_node_register(new_node, NULL);\n\t\t\t\t\t\tgf_node_unregister(new_node, node);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\te = gf_node_list_add_child_last(field->far_ptr, new_node, &last);\n\t\t\t\t\tif (e) goto exit;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*proto coding*/\n\t\t\telse if (codec->pCurrentProto) {\n\t\t\t\t/*TO DO: what happens if this is a QP node on the interface ?*/\n\t\t\t\te = gf_node_list_add_child_last( (GF_ChildNodeItem **)field->far_ptr, new_node, &last);\n\t\t\t\tif (e)goto exit;\n\t\t\t}\n\t\t} else {\n\t\t\te = codec->LastError ? codec->LastError : GF_NON_COMPLIANT_BITSTREAM;\n\t\t\tgoto exit;\n\t\t}\n\t}\n\nexit:\n\n\t/*according to the spec, the QP applies to the current node itself, not just children.\n\tIf IsLocal is TRUE remove the node*/\n\tif (qp_on && qp_local) {\n\t\tif (qp_local == 2) {\n//\t\t\t\tqp_local = 1;\n\t\t} else {\n\t\t\t//ask to get rid of QP and reactivate if we had a QP when entering the node\n\t\t\tgf_bifs_dec_qp_remove(codec, initial_qp);\n//\t\t\t\tqp_local = 0;\n\t\t}\n\t}\n\n\t/*finally delete the QP if any (local or not) as we get out of this node*/\n\tif (qp_on) gf_bifs_dec_qp_remove(codec, GF_TRUE);\n\treturn e;\n}", "func_hash": 87913328330334973477048870942232615519, "file_name": "field_decode.c", "file_hash": 151388572550638562891846673305217274829, "cwe": ["CWE-416"], "cve": "CVE-2022-2453", "cve_desc": "Use After Free in GitHub repository gpac/gpac prior to 2.1-DEV.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2453"}
{"idx": 197511, "project": "libjpeg", "commit_id": "187035b9726710b4fe11d565c7808975c930895d", "project_url": "https://github.com/thorfdbg/libjpeg", "commit_url": "https://github.com/thorfdbg/libjpeg/commit/187035b9726710b4fe11d565c7808975c930895d", "commit_message": "The code now checks for consistency of the MCU sizes across\nhierarchical levels, and fails in case they are different.", "target": 1, "func": "void HierarchicalBitmapRequester::PrepareForDecoding(void)\n{\n#if ACCUSOFT_CODE\n\n  UBYTE i;\n\n  BuildCommon();\n\n  if (m_ppDecodingMCU == NULL) {\n    m_ppDecodingMCU = (struct Line **)m_pEnviron->AllocMem(sizeof(struct Line *) * m_ucCount*8);\n    memset(m_ppDecodingMCU,0,sizeof(struct Line *) * m_ucCount * 8);\n  }\n\n  if (m_ppUpsampler == NULL) {\n    m_ppUpsampler = (class UpsamplerBase **)m_pEnviron->AllocMem(sizeof(class UpsamplerBase *) * m_ucCount);\n    memset(m_ppUpsampler,0,sizeof(class Upsampler *) * m_ucCount);\n\n    for(i = 0;i < m_ucCount;i++) {\n      class Component *comp = m_pFrame->ComponentOf(i);\n      UBYTE sx = comp->SubXOf();\n      UBYTE sy = comp->SubYOf();\n\n      if (sx > 1 || sy > 1) {\n        m_ppUpsampler[i] = UpsamplerBase::CreateUpsampler(m_pEnviron,sx,sy,\n                                                          m_ulPixelWidth,m_ulPixelHeight,\n                                                          m_pFrame->TablesOf()->isChromaCentered());\n        m_bSubsampling   = true;\n      }\n    }\n  }\n\n  if (m_pLargestScale)\n    m_pLargestScale->PrepareForDecoding();\n#endif\n}", "func_hash": 63468052144489012470048601021040613418, "file_name": "hierarchicalbitmaprequester.cpp", "file_hash": 34345221108539770458549868924228630502, "cwe": ["CWE-787"], "cve": "CVE-2022-31796", "cve_desc": "libjpeg 1.63 has a heap-based buffer over-read in HierarchicalBitmapRequester::FetchRegion in hierarchicalbitmaprequester.cpp because the MCU size can be different between allocation and use.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31796"}
{"idx": 259619, "project": "libjpeg", "commit_id": "187035b9726710b4fe11d565c7808975c930895d", "project_url": "https://github.com/thorfdbg/libjpeg", "commit_url": "https://github.com/thorfdbg/libjpeg/commit/187035b9726710b4fe11d565c7808975c930895d", "commit_message": "The code now checks for consistency of the MCU sizes across\nhierarchical levels, and fails in case they are different.", "target": 0, "func": "void HierarchicalBitmapRequester::PrepareForEncoding(void)\n{\n#if ACCUSOFT_CODE\n  \n  BuildCommon();\n\n  if (m_ppEncodingMCU == NULL) {\n    m_ppEncodingMCU = (struct Line **)m_pEnviron->AllocMem(sizeof(struct Line *) * m_ucCount *8);\n    memset(m_ppEncodingMCU,0,sizeof(struct Line *) * m_ucCount * 8);\n  }\n  \n  if (m_ppDownsampler == NULL) {\n    m_ppDownsampler = (class DownsamplerBase **)m_pEnviron->AllocMem(sizeof(class DownsamplerBase *) * m_ucCount);\n    memset(m_ppDownsampler,0,sizeof(class DownsamplerBase *) * m_ucCount);\n    \n    for(UBYTE i = 0;i < m_ucCount;i++) {\n      class Component *comp = m_pFrame->ComponentOf(i);\n      UBYTE sx = comp->SubXOf();\n      UBYTE sy = comp->SubYOf();\n\n      if (sx > 1 || sy > 1) {\n        m_ppDownsampler[i] = DownsamplerBase::CreateDownsampler(m_pEnviron,sx,sy,\n                                                                m_ulPixelWidth,m_ulPixelHeight,\n                                                                m_pFrame->TablesOf()->\n                                                                isDownsamplingInterpolated());\n        m_bSubsampling     = true;\n      }\n    }\n  }\n\n  if (m_pLargestScale)\n    m_pLargestScale->PrepareForEncoding();\n#endif\n}", "func_hash": 163837755851062573337491873573690435408, "file_name": "hierarchicalbitmaprequester.cpp", "file_hash": 103246407112165898630439185486735063817, "cwe": ["CWE-787"], "cve": "CVE-2022-31796", "cve_desc": "libjpeg 1.63 has a heap-based buffer over-read in HierarchicalBitmapRequester::FetchRegion in hierarchicalbitmaprequester.cpp because the MCU size can be different between allocation and use.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31796"}
{"idx": 197517, "project": "glewlwyd", "commit_id": "0efd112bb62f566877750ad62ee828bff579b4e2", "project_url": "https://github.com/babelouest/glewlwyd", "commit_url": "https://github.com/babelouest/glewlwyd/commit/0efd112bb62f566877750ad62ee828bff579b4e2", "commit_message": "Fix fido2 signature validation bug", "target": 1, "func": "static json_t * check_attestation_fido_u2f(json_t * j_params, unsigned char * credential_id, size_t credential_id_len, unsigned char * cert_x, size_t cert_x_len, unsigned char * cert_y, size_t cert_y_len, cbor_item_t * att_stmt, unsigned char * rpid_hash, size_t rpid_hash_len, const unsigned char * client_data) {\n  json_t * j_error = json_array(), * j_return;\n  cbor_item_t * key = NULL, * x5c = NULL, * sig = NULL, * att_cert = NULL;\n  int i, ret;\n  char * message = NULL;\n  gnutls_pubkey_t pubkey = NULL;\n  gnutls_x509_crt_t cert = NULL;\n  gnutls_datum_t cert_dat, data, signature, cert_issued_by;\n  unsigned char data_signed[200], client_data_hash[32], cert_export[32], cert_export_b64[64];\n  size_t data_signed_offset = 0, client_data_hash_len = 32, cert_export_len = 32, cert_export_b64_len = 0;\n  \n  if (j_error != NULL) {\n    do {\n      if (gnutls_x509_crt_init(&cert)) {\n        json_array_append_new(j_error, json_string(\"check_attestation_fido_u2f - Error gnutls_x509_crt_init\"));\n        break;\n      }\n      if (gnutls_pubkey_init(&pubkey)) {\n        json_array_append_new(j_error, json_string(\"check_attestation_fido_u2f - Error gnutls_pubkey_init\"));\n        break;\n      }\n      \n      // Step 1\n      if (att_stmt == NULL || !cbor_isa_map(att_stmt) || cbor_map_size(att_stmt) != 2) {\n        json_array_append_new(j_error, json_string(\"CBOR map value 'attStmt' invalid format\"));\n        break;\n      }\n      for (i=0; i<2; i++) {\n        key = cbor_map_handle(att_stmt)[i].key;\n        if (cbor_isa_string(key)) {\n          if (0 == o_strncmp((const char *)cbor_string_handle(key), \"x5c\", MIN(o_strlen(\"x5c\"), cbor_string_length(key)))) {\n            x5c = cbor_map_handle(att_stmt)[i].value;\n          } else if (0 == o_strncmp((const char *)cbor_string_handle(key), \"sig\", MIN(o_strlen(\"sig\"), cbor_string_length(key)))) {\n            sig = cbor_map_handle(att_stmt)[i].value;\n          } else {\n            message = msprintf(\"attStmt map element %d key is not valid: '%.*s'\", i, cbor_string_length(key), cbor_string_handle(key));\n            json_array_append_new(j_error, json_string(message));\n            o_free(message);\n            break;\n          }\n        } else {\n          message = msprintf(\"attStmt map element %d key is not a string\", i);\n          json_array_append_new(j_error, json_string(message));\n          o_free(message);\n          break;\n        }\n      }\n      if (x5c == NULL || !cbor_isa_array(x5c) || cbor_array_size(x5c) != 1) {\n        json_array_append_new(j_error, json_string(\"CBOR map value 'x5c' invalid format\"));\n        break;\n      }\n      att_cert = cbor_array_get(x5c, 0);\n      cert_dat.data = cbor_bytestring_handle(att_cert);\n      cert_dat.size = cbor_bytestring_length(att_cert);\n      if ((ret = gnutls_x509_crt_import(cert, &cert_dat, GNUTLS_X509_FMT_DER)) < 0) {\n        json_array_append_new(j_error, json_string(\"Error importing x509 certificate\"));\n        y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - Error gnutls_pcert_import_x509_raw: %d\", ret);\n        break;\n      }\n      if (json_object_get(j_params, \"root-ca-list\") != json_null() && validate_certificate_from_root(j_params, cert, x5c) != G_OK) {\n        json_array_append_new(j_error, json_string(\"Unrecognized certificate authority\"));\n        if (gnutls_x509_crt_get_issuer_dn2(cert, &cert_issued_by) >= 0) {\n          message = msprintf(\"Unrecognized certificate autohority: %.*s\", cert_issued_by.size, cert_issued_by.data);\n          y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - %s\", message);\n          o_free(message);\n          gnutls_free(cert_issued_by.data);\n        } else {\n          y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - Unrecognized certificate autohority (unable to get issuer dn)\");\n        }\n        break;\n      }\n      if ((ret = gnutls_pubkey_import_x509(pubkey, cert, 0)) < 0) {\n        json_array_append_new(j_error, json_string(\"Error importing x509 certificate\"));\n        y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - Error gnutls_pubkey_import_x509: %d\", ret);\n        break;\n      }\n      if ((ret = gnutls_x509_crt_get_key_id(cert, GNUTLS_KEYID_USE_SHA256, cert_export, &cert_export_len)) < 0) {\n        json_array_append_new(j_error, json_string(\"Error exporting x509 certificate\"));\n        y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - Error gnutls_x509_crt_get_key_id: %d\", ret);\n        break;\n      }\n      if (!o_base64_encode(cert_export, cert_export_len, cert_export_b64, &cert_export_b64_len)) {\n        json_array_append_new(j_error, json_string(\"Internal error\"));\n        y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - Error o_base64_encode cert_export\");\n        break;\n      }\n      if (!generate_digest_raw(digest_SHA256, client_data, o_strlen((char *)client_data), client_data_hash, &client_data_hash_len)) {\n        json_array_append_new(j_error, json_string(\"Internal error\"));\n        y_log_message(Y_LOG_LEVEL_ERROR, \"check_attestation_fido_u2f - Error generate_digest_raw client_data\");\n        break;\n      }\n\n      if (sig == NULL || !cbor_isa_bytestring(sig)) {\n        json_array_append_new(j_error, json_string(\"Error sig is not a bytestring\"));\n        break;\n      }\n      \n      // Build bytestring to verify signature\n      data_signed[0] = 0x0;\n      data_signed_offset = 1;\n      \n      memcpy(data_signed+data_signed_offset, rpid_hash, rpid_hash_len);\n      data_signed_offset += rpid_hash_len;\n      \n      memcpy(data_signed+data_signed_offset, client_data_hash, client_data_hash_len);\n      data_signed_offset+=client_data_hash_len;\n      \n      memcpy(data_signed+data_signed_offset, credential_id, credential_id_len);\n      data_signed_offset+=credential_id_len;\n      \n      data_signed[data_signed_offset] = 0x04;\n      data_signed_offset++;\n      \n      memcpy(data_signed+data_signed_offset, cert_x, cert_x_len);\n      data_signed_offset+=cert_x_len;\n      \n      memcpy(data_signed+data_signed_offset, cert_y, cert_y_len);\n      data_signed_offset+=cert_y_len;\n        \n      // Let's verify sig over data_signed\n      data.data = data_signed;\n      data.size = data_signed_offset;\n      \n      signature.data = cbor_bytestring_handle(sig);\n      signature.size = cbor_bytestring_length(sig);\n      \n      if (gnutls_pubkey_verify_data2(pubkey, GNUTLS_SIGN_ECDSA_SHA256, 0, &data, &signature)) {\n        json_array_append_new(j_error, json_string(\"Invalid signature\"));\n      }\n      \n    } while (0);\n    \n    if (json_array_size(j_error)) {\n      j_return = json_pack(\"{sisO}\", \"result\", G_ERROR_PARAM, \"error\", j_error);\n    } else {\n      j_return = json_pack(\"{sis{ss%}}\", \"result\", G_OK, \"data\", \"certificate\", cert_export_b64, cert_export_b64_len);\n    }\n    json_decref(j_error);\n    gnutls_pubkey_deinit(pubkey);\n    gnutls_x509_crt_deinit(cert);\n    if (att_cert != NULL) {\n      cbor_decref(&att_cert);\n    }\n    \n  } else {\n    y_log_message(Y_LOG_LEVEL_ERROR, \"check_attestation_fido_u2f - Error allocating resources for j_error\");\n    j_return = json_pack(\"{si}\", \"result\", G_ERROR);\n  }\n  return j_return;\n}", "func_hash": 49651774096588820525757021354786445533, "file_name": "webauthn.c", "file_hash": 936897033794891929844876941061119587, "cwe": ["CWE-787"], "cve": "CVE-2021-40818", "cve_desc": "scheme/webauthn.c in Glewlwyd SSO server through 2.5.3 has a buffer overflow during FIDO2 signature validation in webauthn registration.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40818"}
{"idx": 230147, "project": "glewlwyd", "commit_id": "4c5597c155bfbaf6491cf6b83479d241ae66940a", "project_url": "https://github.com/babelouest/glewlwyd", "commit_url": "https://github.com/babelouest/glewlwyd/commit/4c5597c155bfbaf6491cf6b83479d241ae66940a", "commit_message": "Fix possible buffer overflow", "target": 0, "func": "static json_t * check_attestation_fido_u2f(json_t * j_params, unsigned char * credential_id, size_t credential_id_len, unsigned char * cert_x, size_t cert_x_len, unsigned char * cert_y, size_t cert_y_len, cbor_item_t * att_stmt, unsigned char * rpid_hash, size_t rpid_hash_len, const unsigned char * client_data) {\n  json_t * j_error = json_array(), * j_return;\n  cbor_item_t * key = NULL, * x5c = NULL, * sig = NULL, * att_cert = NULL;\n  int i, ret;\n  char * message = NULL;\n  gnutls_pubkey_t pubkey = NULL;\n  gnutls_x509_crt_t cert = NULL;\n  gnutls_datum_t cert_dat, data, signature, cert_issued_by;\n  unsigned char * data_signed = NULL, client_data_hash[32], cert_export[32], cert_export_b64[64];\n  size_t data_signed_offset = 0, client_data_hash_len = 32, cert_export_len = 32, cert_export_b64_len = 0;\n\n  if (j_error != NULL) {\n    do {\n      if (gnutls_x509_crt_init(&cert)) {\n        json_array_append_new(j_error, json_string(\"check_attestation_fido_u2f - Error gnutls_x509_crt_init\"));\n        break;\n      }\n      if (gnutls_pubkey_init(&pubkey)) {\n        json_array_append_new(j_error, json_string(\"check_attestation_fido_u2f - Error gnutls_pubkey_init\"));\n        break;\n      }\n\n      // Step 1\n      if (att_stmt == NULL || !cbor_isa_map(att_stmt) || cbor_map_size(att_stmt) != 2) {\n        json_array_append_new(j_error, json_string(\"CBOR map value 'attStmt' invalid format\"));\n        break;\n      }\n      for (i=0; i<2; i++) {\n        key = cbor_map_handle(att_stmt)[i].key;\n        if (cbor_isa_string(key)) {\n          if (0 == o_strncmp((const char *)cbor_string_handle(key), \"x5c\", MIN(o_strlen(\"x5c\"), cbor_string_length(key)))) {\n            x5c = cbor_map_handle(att_stmt)[i].value;\n          } else if (0 == o_strncmp((const char *)cbor_string_handle(key), \"sig\", MIN(o_strlen(\"sig\"), cbor_string_length(key)))) {\n            sig = cbor_map_handle(att_stmt)[i].value;\n          } else {\n            message = msprintf(\"attStmt map element %d key is not valid: '%.*s'\", i, cbor_string_length(key), cbor_string_handle(key));\n            json_array_append_new(j_error, json_string(message));\n            o_free(message);\n            break;\n          }\n        } else {\n          message = msprintf(\"attStmt map element %d key is not a string\", i);\n          json_array_append_new(j_error, json_string(message));\n          o_free(message);\n          break;\n        }\n      }\n      if (x5c == NULL || !cbor_isa_array(x5c) || cbor_array_size(x5c) != 1) {\n        json_array_append_new(j_error, json_string(\"CBOR map value 'x5c' invalid format\"));\n        break;\n      }\n      att_cert = cbor_array_get(x5c, 0);\n      cert_dat.data = cbor_bytestring_handle(att_cert);\n      cert_dat.size = cbor_bytestring_length(att_cert);\n      if ((ret = gnutls_x509_crt_import(cert, &cert_dat, GNUTLS_X509_FMT_DER)) < 0) {\n        json_array_append_new(j_error, json_string(\"Error importing x509 certificate\"));\n        y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - Error gnutls_pcert_import_x509_raw: %d\", ret);\n        break;\n      }\n      if (json_object_get(j_params, \"root-ca-list\") != json_null() && validate_certificate_from_root(j_params, cert, x5c) != G_OK) {\n        json_array_append_new(j_error, json_string(\"Unrecognized certificate authority\"));\n        if (gnutls_x509_crt_get_issuer_dn2(cert, &cert_issued_by) >= 0) {\n          message = msprintf(\"Unrecognized certificate autohority: %.*s\", cert_issued_by.size, cert_issued_by.data);\n          y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - %s\", message);\n          o_free(message);\n          gnutls_free(cert_issued_by.data);\n        } else {\n          y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - Unrecognized certificate autohority (unable to get issuer dn)\");\n        }\n        break;\n      }\n      if ((ret = gnutls_pubkey_import_x509(pubkey, cert, 0)) < 0) {\n        json_array_append_new(j_error, json_string(\"Error importing x509 certificate\"));\n        y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - Error gnutls_pubkey_import_x509: %d\", ret);\n        break;\n      }\n      if ((ret = gnutls_x509_crt_get_key_id(cert, GNUTLS_KEYID_USE_SHA256, cert_export, &cert_export_len)) < 0) {\n        json_array_append_new(j_error, json_string(\"Error exporting x509 certificate\"));\n        y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - Error gnutls_x509_crt_get_key_id: %d\", ret);\n        break;\n      }\n      if (!o_base64_encode(cert_export, cert_export_len, cert_export_b64, &cert_export_b64_len)) {\n        json_array_append_new(j_error, json_string(\"Internal error\"));\n        y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - Error o_base64_encode cert_export\");\n        break;\n      }\n      if (!generate_digest_raw(digest_SHA256, client_data, o_strlen((char *)client_data), client_data_hash, &client_data_hash_len)) {\n        json_array_append_new(j_error, json_string(\"Internal error\"));\n        y_log_message(Y_LOG_LEVEL_ERROR, \"check_attestation_fido_u2f - Error generate_digest_raw client_data\");\n        break;\n      }\n\n      if (sig == NULL || !cbor_isa_bytestring(sig)) {\n        json_array_append_new(j_error, json_string(\"Error sig is not a bytestring\"));\n        break;\n      }\n\n      if ((data_signed = o_malloc(rpid_hash_len+client_data_hash_len+credential_id_len+cert_x_len+cert_y_len+2)) == NULL) {\n        y_log_message(Y_LOG_LEVEL_DEBUG, \"check_attestation_fido_u2f - Error allocating data_signed\");\n        json_array_append_new(j_error, json_string(\"Internal error\"));\n        break;\n      }\n\n      // Build bytestring to verify signature\n      data_signed[0] = 0x0;\n      data_signed_offset = 1;\n\n      memcpy(data_signed+data_signed_offset, rpid_hash, rpid_hash_len);\n      data_signed_offset += rpid_hash_len;\n\n      memcpy(data_signed+data_signed_offset, client_data_hash, client_data_hash_len);\n      data_signed_offset+=client_data_hash_len;\n\n      memcpy(data_signed+data_signed_offset, credential_id, credential_id_len);\n      data_signed_offset+=credential_id_len;\n\n      data_signed[data_signed_offset] = 0x04;\n      data_signed_offset++;\n\n      memcpy(data_signed+data_signed_offset, cert_x, cert_x_len);\n      data_signed_offset+=cert_x_len;\n\n      memcpy(data_signed+data_signed_offset, cert_y, cert_y_len);\n      data_signed_offset+=cert_y_len;\n\n      // Let's verify sig over data_signed\n      data.data = data_signed;\n      data.size = data_signed_offset;\n\n      signature.data = cbor_bytestring_handle(sig);\n      signature.size = cbor_bytestring_length(sig);\n\n      if (gnutls_pubkey_verify_data2(pubkey, GNUTLS_SIGN_ECDSA_SHA256, 0, &data, &signature)) {\n        json_array_append_new(j_error, json_string(\"Invalid signature\"));\n      }\n\n    } while (0);\n    o_free(data_signed);\n\n    if (json_array_size(j_error)) {\n      j_return = json_pack(\"{sisO}\", \"result\", G_ERROR_PARAM, \"error\", j_error);\n    } else {\n      j_return = json_pack(\"{sis{ss%}}\", \"result\", G_OK, \"data\", \"certificate\", cert_export_b64, cert_export_b64_len);\n    }\n    json_decref(j_error);\n    gnutls_pubkey_deinit(pubkey);\n    gnutls_x509_crt_deinit(cert);\n    if (att_cert != NULL) {\n      cbor_decref(&att_cert);\n    }\n\n  } else {\n    y_log_message(Y_LOG_LEVEL_ERROR, \"check_attestation_fido_u2f - Error allocating resources for j_error\");\n    j_return = json_pack(\"{si}\", \"result\", G_ERROR);\n  }\n  return j_return;\n}", "func_hash": 153050597349485144532525002399839092260, "file_name": "webauthn.c", "file_hash": 216375384994903278906574435563168883436, "cwe": ["CWE-787"], "cve": "None", "cve_desc": "None", "nvd_url": "https://nvd.nist.gov/vuln/detail/None"}
{"idx": 197518, "project": "tensorflow", "commit_id": "098e7762d909bac47ce1dbabe6dfd06294cb9d58", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/098e7762d909bac47ce1dbabe6dfd06294cb9d58", "commit_message": "Fix tf.raw_ops.QuantizeAndDequantizeV4Grad vulnerability with invalid input_min or input_max.\n\nCheck that argument is actually a scalar before treating it as such.\n\nPiperOrigin-RevId: 445198280", "target": 1, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor& gradient = ctx->input(0);\n    const Tensor& input = ctx->input(1);\n    Tensor* input_backprop = nullptr;\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(0, input.shape(), &input_backprop));\n    OP_REQUIRES(\n        ctx, axis_ >= -1,\n        errors::InvalidArgument(\"Axis must be at least -1. Found \", axis_));\n    OP_REQUIRES(ctx, (axis_ == -1 || axis_ < input.shape().dims()),\n                errors::InvalidArgument(\n                    \"Axis should be -1 or 0 or a positive value less than \",\n                    input.shape().dims(), \"but given axis value was \", axis_));\n\n    OP_REQUIRES(\n        ctx, input.IsSameSize(gradient),\n        errors::InvalidArgument(\"gradient and input must be the same size\"));\n    const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n    const Tensor& input_min_tensor = ctx->input(2);\n    OP_REQUIRES(ctx,\n                input_min_tensor.dims() == 0 || input_min_tensor.dims() == 1,\n                errors::InvalidArgument(\n                    \"Input min tensor must have dimension 1. Recieved \",\n                    input_min_tensor.dims(), \".\"));\n    const Tensor& input_max_tensor = ctx->input(3);\n    OP_REQUIRES(ctx,\n                input_max_tensor.dims() == 0 || input_max_tensor.dims() == 1,\n                errors::InvalidArgument(\n                    \"Input max tensor must have dimension 1. Recieved \",\n                    input_max_tensor.dims(), \".\"));\n    if (axis_ != -1) {\n      OP_REQUIRES(\n          ctx, input_min_tensor.dim_size(0) == depth,\n          errors::InvalidArgument(\"min has incorrect size, expected \", depth,\n                                  \" was \", input_min_tensor.dim_size(0)));\n      OP_REQUIRES(\n          ctx, input_max_tensor.dim_size(0) == depth,\n          errors::InvalidArgument(\"max has incorrect size, expected \", depth,\n                                  \" was \", input_max_tensor.dim_size(0)));\n    }\n\n    TensorShape min_max_shape(input_min_tensor.shape());\n    Tensor* input_min_backprop;\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(1, min_max_shape, &input_min_backprop));\n\n    Tensor* input_max_backprop;\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(2, min_max_shape, &input_max_backprop));\n\n    if (axis_ == -1) {\n      functor::QuantizeAndDequantizeOneScaleGradientFunctor f;\n      f(ctx->eigen_device(), gradient.template flat(),\n        input.template flat(), input_min_tensor.scalar(),\n        input_max_tensor.scalar(), input_backprop->template flat(),\n        input_min_backprop->template scalar(),\n        input_max_backprop->template scalar());\n    } else {\n      functor::QuantizeAndDequantizePerChannelGradientFunctor f;\n      f(ctx->eigen_device(),\n        gradient.template flat_inner_outer_dims(axis_ - 1),\n        input.template flat_inner_outer_dims(axis_ - 1),\n        &input_min_tensor, &input_max_tensor,\n        input_backprop->template flat_inner_outer_dims(axis_ - 1),\n        input_min_backprop->template flat(),\n        input_max_backprop->template flat());\n    }\n  }", "func_hash": 234673676615434385684756936171703208879, "file_name": "quantize_and_dequantize_op.cc", "file_hash": 339380707229520344979853528458088260159, "cwe": ["CWE-703"], "cve": "CVE-2022-29192", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.QuantizeAndDequantizeV4Grad` does not fully validate the input arguments. This results in a `CHECK`-failure which can be used to trigger a denial of service attack. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29192"}
{"idx": 259732, "project": "tensorflow", "commit_id": "098e7762d909bac47ce1dbabe6dfd06294cb9d58", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/098e7762d909bac47ce1dbabe6dfd06294cb9d58", "commit_message": "Fix tf.raw_ops.QuantizeAndDequantizeV4Grad vulnerability with invalid input_min or input_max.\n\nCheck that argument is actually a scalar before treating it as such.\n\nPiperOrigin-RevId: 445198280", "target": 0, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor& gradient = ctx->input(0);\n    const Tensor& input = ctx->input(1);\n    Tensor* input_backprop = nullptr;\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(0, input.shape(), &input_backprop));\n    OP_REQUIRES(\n        ctx, axis_ >= -1,\n        errors::InvalidArgument(\"Axis must be at least -1. Found \", axis_));\n    OP_REQUIRES(ctx, (axis_ == -1 || axis_ < input.shape().dims()),\n                errors::InvalidArgument(\n                    \"Axis should be -1 or 0 or a positive value less than \",\n                    input.shape().dims(), \"but given axis value was \", axis_));\n\n    OP_REQUIRES(\n        ctx, input.IsSameSize(gradient),\n        errors::InvalidArgument(\"gradient and input must be the same size\"));\n    const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n    const Tensor& input_min_tensor = ctx->input(2);\n    OP_REQUIRES(ctx,\n                input_min_tensor.dims() == 0 || input_min_tensor.dims() == 1,\n                errors::InvalidArgument(\n                    \"Input min tensor must have dimension 0 or 1. Received \",\n                    input_min_tensor.dims(), \".\"));\n    const Tensor& input_max_tensor = ctx->input(3);\n    OP_REQUIRES(ctx,\n                input_max_tensor.dims() == 0 || input_max_tensor.dims() == 1,\n                errors::InvalidArgument(\n                    \"Input max tensor must have dimension 0 or 1. Received \",\n                    input_max_tensor.dims(), \".\"));\n    if (axis_ != -1) {\n      OP_REQUIRES(\n          ctx, input_min_tensor.dim_size(0) == depth,\n          errors::InvalidArgument(\"min has incorrect size, expected \", depth,\n                                  \" was \", input_min_tensor.dim_size(0)));\n      OP_REQUIRES(\n          ctx, input_max_tensor.dim_size(0) == depth,\n          errors::InvalidArgument(\"max has incorrect size, expected \", depth,\n                                  \" was \", input_max_tensor.dim_size(0)));\n    }\n\n    TensorShape min_max_shape(input_min_tensor.shape());\n    Tensor* input_min_backprop;\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(1, min_max_shape, &input_min_backprop));\n\n    Tensor* input_max_backprop;\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_output(2, min_max_shape, &input_max_backprop));\n\n    if (axis_ == -1) {\n      OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(input_min_tensor.shape()),\n                  errors::InvalidArgument(\n                      \"input_min must be a scalar if axis is unspecified\"));\n      OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(input_max_tensor.shape()),\n                  errors::InvalidArgument(\n                      \"input_max must be a scalar if axis is unspecified\"));\n      functor::QuantizeAndDequantizeOneScaleGradientFunctor f;\n      f(ctx->eigen_device(), gradient.template flat(),\n        input.template flat(), input_min_tensor.scalar(),\n        input_max_tensor.scalar(), input_backprop->template flat(),\n        input_min_backprop->template scalar(),\n        input_max_backprop->template scalar());\n    } else {\n      functor::QuantizeAndDequantizePerChannelGradientFunctor f;\n      f(ctx->eigen_device(),\n        gradient.template flat_inner_outer_dims(axis_ - 1),\n        input.template flat_inner_outer_dims(axis_ - 1),\n        &input_min_tensor, &input_max_tensor,\n        input_backprop->template flat_inner_outer_dims(axis_ - 1),\n        input_min_backprop->template flat(),\n        input_max_backprop->template flat());\n    }\n  }", "func_hash": 287418587934128745776529470108188021327, "file_name": "quantize_and_dequantize_op.cc", "file_hash": 149077864405379849027595796830913818555, "cwe": ["CWE-703"], "cve": "CVE-2022-29192", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.QuantizeAndDequantizeV4Grad` does not fully validate the input arguments. This results in a `CHECK`-failure which can be used to trigger a denial of service attack. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29192"}
{"idx": 197565, "project": "wolfMQTT", "commit_id": "84d4b53122e0fa0280c7872350b89d5777dabbb2", "project_url": "https://github.com/wolfSSL/wolfMQTT", "commit_url": "https://github.com/wolfSSL/wolfMQTT/commit/84d4b53122e0fa0280c7872350b89d5777dabbb2", "commit_message": "Fix wolfmqtt-fuzzer: Null-dereference WRITE in MqttProps_Free", "target": 1, "func": "static int MqttClient_WaitType(MqttClient *client, void *packet_obj,\n    byte wait_type, word16 wait_packet_id, int timeout_ms)\n{\n    int rc;\n    word16 packet_id;\n    MqttPacketType packet_type;\n#ifdef WOLFMQTT_MULTITHREAD\n    MqttPendResp *pendResp;\n    int readLocked;\n#endif\n    MqttMsgStat* mms_stat;\n    int waitMatchFound;\n\n    if (client == NULL || packet_obj == NULL) {\n        return MQTT_CODE_ERROR_BAD_ARG;\n    }\n\n    /* all packet type structures must have MqttMsgStat at top */\n    mms_stat = (MqttMsgStat*)packet_obj;\n\nwait_again:\n\n    /* initialize variables */\n    packet_id = 0;\n    packet_type = MQTT_PACKET_TYPE_RESERVED;\n#ifdef WOLFMQTT_MULTITHREAD\n    pendResp = NULL;\n    readLocked = 0;\n#endif\n    waitMatchFound = 0;\n\n#ifdef WOLFMQTT_DEBUG_CLIENT\n    PRINTF(\"MqttClient_WaitType: Type %s (%d), ID %d\",\n        MqttPacket_TypeDesc((MqttPacketType)wait_type),\n            wait_type, wait_packet_id);\n#endif\n\n    switch ((int)*mms_stat)\n    {\n        case MQTT_MSG_BEGIN:\n        {\n        #ifdef WOLFMQTT_MULTITHREAD\n            /* Lock recv socket mutex */\n            rc = wm_SemLock(&client->lockRecv);\n            if (rc != 0) {\n                PRINTF(\"MqttClient_WaitType: recv lock error!\");\n                return rc;\n            }\n            readLocked = 1;\n        #endif\n\n            /* reset the packet state */\n            client->packet.stat = MQTT_PK_BEGIN;\n        }\n        FALL_THROUGH;\n\n    #ifdef WOLFMQTT_V5\n        case MQTT_MSG_AUTH:\n    #endif\n        case MQTT_MSG_WAIT:\n        {\n        #ifdef WOLFMQTT_MULTITHREAD\n            /* Check to see if packet type and id have already completed */\n            pendResp = NULL;\n            rc = wm_SemLock(&client->lockClient);\n            if (rc == 0) {\n                if (MqttClient_RespList_Find(client, (MqttPacketType)wait_type, \n                    wait_packet_id, &pendResp)) {\n                    if (pendResp->packetDone) {\n                        /* pending response is already done, so return */\n                        rc = pendResp->packet_ret;\n                    #ifdef WOLFMQTT_DEBUG_CLIENT\n                        PRINTF(\"PendResp already Done %p: Rc %d\", pendResp, rc);\n                    #endif\n                        MqttClient_RespList_Remove(client, pendResp);\n                        wm_SemUnlock(&client->lockClient);\n                        wm_SemUnlock(&client->lockRecv);\n                        return rc;\n                    }\n                }\n                wm_SemUnlock(&client->lockClient);\n            }\n            else {\n                break; /* error */\n            }\n        #endif /* WOLFMQTT_MULTITHREAD */\n\n            *mms_stat = MQTT_MSG_WAIT;\n\n            /* Wait for packet */\n            rc = MqttPacket_Read(client, client->rx_buf, client->rx_buf_len,\n                    timeout_ms);\n            /* handle failure */\n            if (rc <= 0) {\n                break;\n            }\n\n            /* capture length read */\n            client->packet.buf_len = rc;\n\n            /* Decode Packet - get type and id */\n            rc = MqttClient_DecodePacket(client, client->rx_buf,\n                client->packet.buf_len, NULL, &packet_type, NULL, &packet_id);\n            if (rc < 0) {\n                break;\n            }\n\n        #ifdef WOLFMQTT_DEBUG_CLIENT\n            PRINTF(\"Read Packet: Len %d, Type %d, ID %d\",\n                client->packet.buf_len, packet_type, packet_id);\n        #endif\n\n            *mms_stat = MQTT_MSG_READ;\n        }\n        FALL_THROUGH;\n\n        case MQTT_MSG_READ:\n        case MQTT_MSG_READ_PAYLOAD:\n        {\n            MqttPacketType use_packet_type;\n            void* use_packet_obj;\n\n        #ifdef WOLFMQTT_MULTITHREAD\n            readLocked = 1; /* if in this state read is locked */\n        #endif\n\n            /* read payload state only happens for publish messages */\n            if (*mms_stat == MQTT_MSG_READ_PAYLOAD) {\n                packet_type = MQTT_PACKET_TYPE_PUBLISH;\n            }\n\n            /* Determine if we received data for this request */\n            if ((wait_type == MQTT_PACKET_TYPE_ANY ||\n                 wait_type == packet_type ||\n                 MqttIsPubRespPacket(packet_type) == MqttIsPubRespPacket(wait_type)) &&\n               (wait_packet_id == 0 || wait_packet_id == packet_id))\n            {\n                use_packet_obj = packet_obj;\n                waitMatchFound = 1;\n            }\n            else {\n                /* use generic packet object */\n                use_packet_obj = &client->msg;\n            }\n            use_packet_type = packet_type;\n\n        #ifdef WOLFMQTT_MULTITHREAD\n            /* Check to see if we have a pending response for this packet */\n            pendResp = NULL;\n            rc = wm_SemLock(&client->lockClient);\n            if (rc == 0) {\n                if (MqttClient_RespList_Find(client, packet_type, packet_id,\n                                                               &pendResp)) {\n                    /* we found packet match this incoming read packet */\n                    pendResp->packetProcessing = 1;\n                    use_packet_obj = pendResp->packet_obj;\n                    use_packet_type = pendResp->packet_type;\n                    /* req from another thread... not a match */\n                    waitMatchFound = 0;\n                }\n                wm_SemUnlock(&client->lockClient);\n            }\n            else {\n                break; /* error */\n            }\n        #endif /* WOLFMQTT_MULTITHREAD */\n\n            /* Perform packet handling for publish callback and QoS */\n            rc = MqttClient_HandlePacket(client, use_packet_type,\n                use_packet_obj, timeout_ms);\n\n        #ifdef WOLFMQTT_NONBLOCK\n            if (rc == MQTT_CODE_CONTINUE) {\n                /* we have received some data, so keep the recv\n                    mutex lock active and return */\n                return rc;\n            }\n        #endif\n\n            /* handle success case */\n            if (rc >= 0) {\n                rc = MQTT_CODE_SUCCESS;\n            }\n\n        #ifdef WOLFMQTT_MULTITHREAD\n            if (pendResp) {\n                /* Mark pending response entry done */\n                if (wm_SemLock(&client->lockClient) == 0) {\n                    pendResp->packetDone = 1;\n                    pendResp->packet_ret = rc;\n                #ifdef WOLFMQTT_DEBUG_CLIENT\n                    PRINTF(\"PendResp Done %p\", pendResp);\n                #endif\n                    pendResp = NULL;\n                    wm_SemUnlock(&client->lockClient);\n                }\n            }\n        #endif /* WOLFMQTT_MULTITHREAD */\n            break;\n        }\n\n        case MQTT_MSG_WRITE:\n        case MQTT_MSG_WRITE_PAYLOAD:\n        default:\n        {\n        #ifdef WOLFMQTT_DEBUG_CLIENT\n            PRINTF(\"MqttClient_WaitType: Invalid state %d!\", *mms_stat);\n        #endif\n            rc = MQTT_CODE_ERROR_STAT;\n            break;\n        }\n    } /* switch (*mms_stat) */\n\n#ifdef WOLFMQTT_NONBLOCK\n    if (rc != MQTT_CODE_CONTINUE)\n#endif\n    {\n        /* reset state */\n        *mms_stat = MQTT_MSG_BEGIN;\n    }\n\n#ifdef WOLFMQTT_MULTITHREAD\n    if (readLocked) {\n        wm_SemUnlock(&client->lockRecv);\n    }\n#endif\n    if (rc < 0) {\n    #ifdef WOLFMQTT_DEBUG_CLIENT\n        PRINTF(\"MqttClient_WaitType: Failure: %s (%d)\",\n            MqttClient_ReturnCodeToString(rc), rc);\n    #endif\n        return rc;\n    }\n\n    if (!waitMatchFound) {\n        /* if we get here, then the we are still waiting for a packet */\n        goto wait_again;\n    }\n\n    return rc;\n}", "func_hash": 2988390772969394657723865827973366134, "file_name": "mqtt_client.c", "file_hash": 187905589318508952285873561463064501412, "cwe": ["CWE-787"], "cve": "CVE-2021-45936", "cve_desc": "wolfSSL wolfMQTT 1.9 has a heap-based buffer overflow in MqttDecode_Disconnect (called from MqttClient_DecodePacket and MqttClient_WaitType).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-45936"}
{"idx": 261220, "project": "wolfMQTT", "commit_id": "84d4b53122e0fa0280c7872350b89d5777dabbb2", "project_url": "https://github.com/wolfSSL/wolfMQTT", "commit_url": "https://github.com/wolfSSL/wolfMQTT/commit/84d4b53122e0fa0280c7872350b89d5777dabbb2", "commit_message": "Fix wolfmqtt-fuzzer: Null-dereference WRITE in MqttProps_Free", "target": 0, "func": "static int MqttClient_WaitType(MqttClient *client, void *packet_obj,\n    byte wait_type, word16 wait_packet_id, int timeout_ms)\n{\n    int rc;\n    word16 packet_id;\n    MqttPacketType packet_type;\n#ifdef WOLFMQTT_MULTITHREAD\n    MqttPendResp *pendResp;\n    int readLocked;\n#endif\n    MqttMsgStat* mms_stat;\n    int waitMatchFound;\n\n    if (client == NULL || packet_obj == NULL) {\n        return MQTT_CODE_ERROR_BAD_ARG;\n    }\n\n    /* all packet type structures must have MqttMsgStat at top */\n    mms_stat = (MqttMsgStat*)packet_obj;\n\nwait_again:\n\n    /* initialize variables */\n    packet_id = 0;\n    packet_type = MQTT_PACKET_TYPE_RESERVED;\n#ifdef WOLFMQTT_MULTITHREAD\n    pendResp = NULL;\n    readLocked = 0;\n#endif\n    waitMatchFound = 0;\n\n#ifdef WOLFMQTT_DEBUG_CLIENT\n    PRINTF(\"MqttClient_WaitType: Type %s (%d), ID %d\",\n        MqttPacket_TypeDesc((MqttPacketType)wait_type),\n            wait_type, wait_packet_id);\n#endif\n\n    switch ((int)*mms_stat)\n    {\n        case MQTT_MSG_BEGIN:\n        {\n        #ifdef WOLFMQTT_MULTITHREAD\n            /* Lock recv socket mutex */\n            rc = wm_SemLock(&client->lockRecv);\n            if (rc != 0) {\n                PRINTF(\"MqttClient_WaitType: recv lock error!\");\n                return rc;\n            }\n            readLocked = 1;\n        #endif\n\n            /* reset the packet state */\n            client->packet.stat = MQTT_PK_BEGIN;\n        }\n        FALL_THROUGH;\n\n    #ifdef WOLFMQTT_V5\n        case MQTT_MSG_AUTH:\n    #endif\n        case MQTT_MSG_WAIT:\n        {\n        #ifdef WOLFMQTT_MULTITHREAD\n            /* Check to see if packet type and id have already completed */\n            pendResp = NULL;\n            rc = wm_SemLock(&client->lockClient);\n            if (rc == 0) {\n                if (MqttClient_RespList_Find(client, (MqttPacketType)wait_type, \n                    wait_packet_id, &pendResp)) {\n                    if (pendResp->packetDone) {\n                        /* pending response is already done, so return */\n                        rc = pendResp->packet_ret;\n                    #ifdef WOLFMQTT_DEBUG_CLIENT\n                        PRINTF(\"PendResp already Done %p: Rc %d\", pendResp, rc);\n                    #endif\n                        MqttClient_RespList_Remove(client, pendResp);\n                        wm_SemUnlock(&client->lockClient);\n                        wm_SemUnlock(&client->lockRecv);\n                        return rc;\n                    }\n                }\n                wm_SemUnlock(&client->lockClient);\n            }\n            else {\n                break; /* error */\n            }\n        #endif /* WOLFMQTT_MULTITHREAD */\n\n            *mms_stat = MQTT_MSG_WAIT;\n\n            /* Wait for packet */\n            rc = MqttPacket_Read(client, client->rx_buf, client->rx_buf_len,\n                    timeout_ms);\n            /* handle failure */\n            if (rc <= 0) {\n                break;\n            }\n\n            /* capture length read */\n            client->packet.buf_len = rc;\n\n            /* Decode Packet - get type and id */\n            rc = MqttClient_DecodePacket(client, client->rx_buf,\n                client->packet.buf_len, NULL, &packet_type, NULL, &packet_id);\n            if (rc < 0) {\n                break;\n            }\n\n        #ifdef WOLFMQTT_DEBUG_CLIENT\n            PRINTF(\"Read Packet: Len %d, Type %d, ID %d\",\n                client->packet.buf_len, packet_type, packet_id);\n        #endif\n\n            *mms_stat = MQTT_MSG_READ;\n        }\n        FALL_THROUGH;\n\n        case MQTT_MSG_READ:\n        case MQTT_MSG_READ_PAYLOAD:\n        {\n            MqttPacketType use_packet_type;\n            void* use_packet_obj;\n\n        #ifdef WOLFMQTT_MULTITHREAD\n            readLocked = 1; /* if in this state read is locked */\n        #endif\n\n            /* read payload state only happens for publish messages */\n            if (*mms_stat == MQTT_MSG_READ_PAYLOAD) {\n                packet_type = MQTT_PACKET_TYPE_PUBLISH;\n            }\n\n            /* Determine if we received data for this request */\n            if ((wait_type == MQTT_PACKET_TYPE_ANY ||\n                 wait_type == packet_type ||\n                 (MqttIsPubRespPacket(packet_type) &&\n                  MqttIsPubRespPacket(wait_type))) &&\n                (wait_packet_id == 0 || wait_packet_id == packet_id))\n            {\n                use_packet_obj = packet_obj;\n                waitMatchFound = 1;\n            }\n            else {\n                /* use generic packet object */\n                use_packet_obj = &client->msg;\n            }\n            use_packet_type = packet_type;\n\n        #ifdef WOLFMQTT_MULTITHREAD\n            /* Check to see if we have a pending response for this packet */\n            pendResp = NULL;\n            rc = wm_SemLock(&client->lockClient);\n            if (rc == 0) {\n                if (MqttClient_RespList_Find(client, packet_type, packet_id,\n                                                               &pendResp)) {\n                    /* we found packet match this incoming read packet */\n                    pendResp->packetProcessing = 1;\n                    use_packet_obj = pendResp->packet_obj;\n                    use_packet_type = pendResp->packet_type;\n                    /* req from another thread... not a match */\n                    waitMatchFound = 0;\n                }\n                wm_SemUnlock(&client->lockClient);\n            }\n            else {\n                break; /* error */\n            }\n        #endif /* WOLFMQTT_MULTITHREAD */\n\n            /* Perform packet handling for publish callback and QoS */\n            rc = MqttClient_HandlePacket(client, use_packet_type,\n                use_packet_obj, timeout_ms);\n\n        #ifdef WOLFMQTT_NONBLOCK\n            if (rc == MQTT_CODE_CONTINUE) {\n                /* we have received some data, so keep the recv\n                    mutex lock active and return */\n                return rc;\n            }\n        #endif\n\n            /* handle success case */\n            if (rc >= 0) {\n                rc = MQTT_CODE_SUCCESS;\n            }\n\n        #ifdef WOLFMQTT_MULTITHREAD\n            if (pendResp) {\n                /* Mark pending response entry done */\n                if (wm_SemLock(&client->lockClient) == 0) {\n                    pendResp->packetDone = 1;\n                    pendResp->packet_ret = rc;\n                #ifdef WOLFMQTT_DEBUG_CLIENT\n                    PRINTF(\"PendResp Done %p\", pendResp);\n                #endif\n                    pendResp = NULL;\n                    wm_SemUnlock(&client->lockClient);\n                }\n            }\n        #endif /* WOLFMQTT_MULTITHREAD */\n            break;\n        }\n\n        case MQTT_MSG_WRITE:\n        case MQTT_MSG_WRITE_PAYLOAD:\n        default:\n        {\n        #ifdef WOLFMQTT_DEBUG_CLIENT\n            PRINTF(\"MqttClient_WaitType: Invalid state %d!\", *mms_stat);\n        #endif\n            rc = MQTT_CODE_ERROR_STAT;\n            break;\n        }\n    } /* switch (*mms_stat) */\n\n#ifdef WOLFMQTT_NONBLOCK\n    if (rc != MQTT_CODE_CONTINUE)\n#endif\n    {\n        /* reset state */\n        *mms_stat = MQTT_MSG_BEGIN;\n    }\n\n#ifdef WOLFMQTT_MULTITHREAD\n    if (readLocked) {\n        wm_SemUnlock(&client->lockRecv);\n    }\n#endif\n    if (rc < 0) {\n    #ifdef WOLFMQTT_DEBUG_CLIENT\n        PRINTF(\"MqttClient_WaitType: Failure: %s (%d)\",\n            MqttClient_ReturnCodeToString(rc), rc);\n    #endif\n        return rc;\n    }\n\n    if (!waitMatchFound) {\n        /* if we get here, then the we are still waiting for a packet */\n        goto wait_again;\n    }\n\n    return rc;\n}", "func_hash": 88286430385104780024208637044722033295, "file_name": "mqtt_client.c", "file_hash": 315446679366477562127453021881917079842, "cwe": ["CWE-787"], "cve": "CVE-2021-45936", "cve_desc": "wolfSSL wolfMQTT 1.9 has a heap-based buffer overflow in MqttDecode_Disconnect (called from MqttClient_DecodePacket and MqttClient_WaitType).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-45936"}
{"idx": 197593, "project": "njs", "commit_id": "ad48705bf1f04b4221a5f5b07715ac48b3160d53", "project_url": "https://github.com/nginx/njs", "commit_url": "https://github.com/nginx/njs/commit/ad48705bf1f04b4221a5f5b07715ac48b3160d53", "commit_message": "Fixed frame allocation from an awaited frame.\n\nnjs_function_frame_save() is used to save the awaited frame when \"await\"\ninstruction is encountered. The saving was done as a memcpy() of\nexisting runtime frame.\n\nnjs_function_frame_alloc() is used to alloc a new function frame, this\nfunction tries to use a spare preallocated memory from the previous\nframe first.  Previously, this function might result in \"use-after-free\"\nwhen invoked from a restored frame saved with njs_function_frame_save().\nBecause njs_function_frame_save() left pointers to the spare memory of\nthe original frame which may be already free when saved frame is\nrestored.\n\nThe fix is to erase fields for the spare memory from the saved frame.\n\nThis closes #469 issue on Github.", "target": 1, "func": "njs_function_frame_save(njs_vm_t *vm, njs_frame_t *frame, u_char *pc)\n{\n    size_t              value_count, n;\n    njs_value_t         *start, *end, *p, **new, *value, **local;\n    njs_function_t      *function;\n    njs_native_frame_t  *active, *native;\n\n    *frame = *vm->active_frame;\n    frame->previous_active_frame = NULL;\n\n    native = &frame->native;\n\n    active = &vm->active_frame->native;\n    value_count = njs_function_frame_value_count(active);\n\n    function = active->function;\n\n    new = (njs_value_t **) ((u_char *) native + NJS_FRAME_SIZE);\n    value = (njs_value_t *) (new + value_count\n                             + function->u.lambda->temp);\n\n\n    native->arguments = value;\n    native->arguments_offset = value + (function->args_offset - 1);\n    native->local = new + njs_function_frame_args_count(active);\n    native->temp = new + value_count;\n    native->pc = pc;\n\n    start = njs_function_frame_values(active, &end);\n    p = native->arguments;\n\n    while (start < end) {\n        *p = *start++;\n        *new++ = p++;\n    }\n\n    /* Move all arguments. */\n\n    p = native->arguments;\n    local = native->local + function->args_offset;\n\n    for (n = 0; n < function->args_count; n++) {\n        if (!njs_is_valid(p)) {\n            njs_set_undefined(p);\n        }\n\n        *local++ = p++;\n    }\n\n    return NJS_OK;\n}", "func_hash": 163196677430813133926152837345587363595, "file_name": "njs_function.c", "file_hash": 84952023387586829721392975850477495397, "cwe": ["CWE-416"], "cve": "CVE-2022-27007", "cve_desc": "nginx njs 0.7.2 is affected suffers from Use-after-free in njs_function_frame_alloc() when it try to invoke from a restored frame saved with njs_function_frame_save().", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27007"}
{"idx": 261769, "project": "njs", "commit_id": "ad48705bf1f04b4221a5f5b07715ac48b3160d53", "project_url": "https://github.com/nginx/njs", "commit_url": "https://github.com/nginx/njs/commit/ad48705bf1f04b4221a5f5b07715ac48b3160d53", "commit_message": "Fixed frame allocation from an awaited frame.\n\nnjs_function_frame_save() is used to save the awaited frame when \"await\"\ninstruction is encountered. The saving was done as a memcpy() of\nexisting runtime frame.\n\nnjs_function_frame_alloc() is used to alloc a new function frame, this\nfunction tries to use a spare preallocated memory from the previous\nframe first.  Previously, this function might result in \"use-after-free\"\nwhen invoked from a restored frame saved with njs_function_frame_save().\nBecause njs_function_frame_save() left pointers to the spare memory of\nthe original frame which may be already free when saved frame is\nrestored.\n\nThe fix is to erase fields for the spare memory from the saved frame.\n\nThis closes #469 issue on Github.", "target": 0, "func": "njs_function_frame_save(njs_vm_t *vm, njs_frame_t *frame, u_char *pc)\n{\n    size_t              value_count, n;\n    njs_value_t         *start, *end, *p, **new, *value, **local;\n    njs_function_t      *function;\n    njs_native_frame_t  *active, *native;\n\n    *frame = *vm->active_frame;\n\n    frame->previous_active_frame = NULL;\n\n    native = &frame->native;\n    native->size = 0;\n    native->free = NULL;\n    native->free_size = 0;\n\n    active = &vm->active_frame->native;\n    value_count = njs_function_frame_value_count(active);\n\n    function = active->function;\n\n    new = (njs_value_t **) ((u_char *) native + NJS_FRAME_SIZE);\n    value = (njs_value_t *) (new + value_count\n                             + function->u.lambda->temp);\n\n\n    native->arguments = value;\n    native->arguments_offset = value + (function->args_offset - 1);\n    native->local = new + njs_function_frame_args_count(active);\n    native->temp = new + value_count;\n    native->pc = pc;\n\n    start = njs_function_frame_values(active, &end);\n    p = native->arguments;\n\n    while (start < end) {\n        *p = *start++;\n        *new++ = p++;\n    }\n\n    /* Move all arguments. */\n\n    p = native->arguments;\n    local = native->local + function->args_offset;\n\n    for (n = 0; n < function->args_count; n++) {\n        if (!njs_is_valid(p)) {\n            njs_set_undefined(p);\n        }\n\n        *local++ = p++;\n    }\n\n    return NJS_OK;\n}", "func_hash": 189837450352856196976094747096042569901, "file_name": "njs_function.c", "file_hash": 202672725562392231743366783746381682256, "cwe": ["CWE-416"], "cve": "CVE-2022-27007", "cve_desc": "nginx njs 0.7.2 is affected suffers from Use-after-free in njs_function_frame_alloc() when it try to invoke from a restored frame saved with njs_function_frame_save().", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27007"}
{"idx": 197666, "project": "njs", "commit_id": "eafe4c7a326b163612f10861392622b5da5b1792", "project_url": "https://github.com/nginx/njs", "commit_url": "https://github.com/nginx/njs/commit/eafe4c7a326b163612f10861392622b5da5b1792", "commit_message": "Fixed Array.prototype.lastIndexOf() with unicode string as \"this\".\n\nPreviously, when lastIndexOf() was called with unicode string as \"this\"\nargument and a negative \"fromIndex\" argument null-pointer dererence\nmight occur because njs_string_offset() was called with invalid index\nvalue whereas njs_string_offset() should always be called with valid\nindex argument.\n\nThe fix is to verify that from index is valid.\n\nThis closes #482 issue on Github.", "target": 1, "func": "njs_object_iterate_reverse(njs_vm_t *vm, njs_iterator_args_t *args,\n    njs_iterator_handler_t handler)\n{\n    double              idx;\n    int64_t             i, from, to, length;\n    njs_int_t           ret;\n    njs_array_t         *array, *keys;\n    njs_value_t         *entry, *value, prop, character, string_obj;\n    const u_char        *p, *end, *pos;\n    njs_string_prop_t   string_prop;\n    njs_object_value_t  *object;\n\n    value = args->value;\n    from = args->from;\n    to = args->to;\n\n    if (njs_is_array(value)) {\n        array = njs_array(value);\n\n        from += 1;\n\n        while (from-- > to) {\n            if (njs_slow_path(!array->object.fast_array)) {\n                goto process_object;\n            }\n\n            if (njs_fast_path(from < array->length\n                              && njs_is_valid(&array->start[from])))\n            {\n                ret = handler(vm, args, &array->start[from], from);\n\n            } else {\n                entry = njs_value_arg(&njs_value_invalid);\n                ret = njs_value_property_i64(vm, value, from, &prop);\n                if (njs_slow_path(ret != NJS_DECLINED)) {\n                    if (ret == NJS_ERROR) {\n                        return NJS_ERROR;\n                    }\n\n                    entry = ∝\n                }\n\n                ret = handler(vm, args, entry, from);\n            }\n\n            if (njs_slow_path(ret != NJS_OK)) {\n                if (ret == NJS_DONE) {\n                    return NJS_DONE;\n                }\n\n                return NJS_ERROR;\n            }\n        }\n\n        return NJS_OK;\n    }\n\n    if (njs_is_string(value) || njs_is_object_string(value)) {\n\n        if (njs_is_string(value)) {\n            object = njs_object_value_alloc(vm, NJS_OBJ_TYPE_STRING, 0, value);\n            if (njs_slow_path(object == NULL)) {\n                return NJS_ERROR;\n            }\n\n            njs_set_object_value(&string_obj, object);\n\n            args->value = &string_obj;\n        }\n        else {\n            value = njs_object_value(value);\n        }\n\n        length = njs_string_prop(&string_prop, value);\n        end = string_prop.start + string_prop.size;\n\n        if ((size_t) length == string_prop.size) {\n            /* Byte or ASCII string. */\n\n            p = string_prop.start + from;\n\n            i = from + 1;\n\n            while (i-- > to) {\n                /* This cannot fail. */\n                (void) njs_string_new(vm, &character, p, 1, 1);\n\n                ret = handler(vm, args, &character, i);\n                if (njs_slow_path(ret != NJS_OK)) {\n                    if (ret == NJS_DONE) {\n                        return NJS_DONE;\n                    }\n\n                    return NJS_ERROR;\n                }\n\n                p--;\n            }\n\n        } else {\n            /* UTF-8 string. */\n\n            p = njs_string_offset(string_prop.start, end, from);\n            p = njs_utf8_next(p, end);\n\n            i = from + 1;\n\n            while (i-- > to) {\n                pos = njs_utf8_prev(p);\n\n                /* This cannot fail. */\n                (void) njs_string_new(vm, &character, pos, p - pos , 1);\n\n                ret = handler(vm, args, &character, i);\n                if (njs_slow_path(ret != NJS_OK)) {\n                    if (ret == NJS_DONE) {\n                        return NJS_DONE;\n                    }\n\n                    return NJS_ERROR;\n                }\n\n                p = pos;\n            }\n        }\n\n        return NJS_OK;\n    }\n\n    if (!njs_is_object(value)) {\n        return NJS_OK;\n    }\n\nprocess_object:\n\n    if (!njs_fast_object(from - to)) {\n        keys = njs_array_indices(vm, value);\n        if (njs_slow_path(keys == NULL)) {\n            return NJS_ERROR;\n        }\n\n        i = keys->length;\n\n        while (i > 0) {\n            idx = njs_string_to_index(&keys->start[--i]);\n\n            if (idx < to || idx > from) {\n                continue;\n            }\n\n            ret = njs_iterator_object_handler(vm, handler, args,\n                                              &keys->start[i], idx);\n            if (njs_slow_path(ret != NJS_OK)) {\n                njs_array_destroy(vm, keys);\n                return ret;\n            }\n        }\n\n        njs_array_destroy(vm, keys);\n\n        return NJS_OK;\n    }\n\n    i = from + 1;\n\n    while (i-- > to) {\n        ret = njs_iterator_object_handler(vm, handler, args, NULL, i);\n        if (njs_slow_path(ret != NJS_OK)) {\n            return ret;\n        }\n    }\n\n    return NJS_OK;\n}", "func_hash": 204015889704330628062672866949061415790, "file_name": "njs_iterator.c", "file_hash": 335799250908607269245401986160656951958, "cwe": ["CWE-703"], "cve": "CVE-2022-31307", "cve_desc": "Nginx NJS v0.7.2 was discovered to contain a segmentation violation in the function njs_string_offset at src/njs_string.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31307"}
{"idx": 262721, "project": "njs", "commit_id": "eafe4c7a326b163612f10861392622b5da5b1792", "project_url": "https://github.com/nginx/njs", "commit_url": "https://github.com/nginx/njs/commit/eafe4c7a326b163612f10861392622b5da5b1792", "commit_message": "Fixed Array.prototype.lastIndexOf() with unicode string as \"this\".\n\nPreviously, when lastIndexOf() was called with unicode string as \"this\"\nargument and a negative \"fromIndex\" argument null-pointer dererence\nmight occur because njs_string_offset() was called with invalid index\nvalue whereas njs_string_offset() should always be called with valid\nindex argument.\n\nThe fix is to verify that from index is valid.\n\nThis closes #482 issue on Github.", "target": 0, "func": "njs_object_iterate_reverse(njs_vm_t *vm, njs_iterator_args_t *args,\n    njs_iterator_handler_t handler)\n{\n    double              idx;\n    int64_t             i, from, to, length;\n    njs_int_t           ret;\n    njs_array_t         *array, *keys;\n    njs_value_t         *entry, *value, prop, character, string_obj;\n    const u_char        *p, *end, *pos;\n    njs_string_prop_t   string_prop;\n    njs_object_value_t  *object;\n\n    value = args->value;\n    from = args->from;\n    to = args->to;\n\n    if (njs_is_array(value)) {\n        array = njs_array(value);\n\n        from += 1;\n\n        while (from-- > to) {\n            if (njs_slow_path(!array->object.fast_array)) {\n                goto process_object;\n            }\n\n            if (njs_fast_path(from < array->length\n                              && njs_is_valid(&array->start[from])))\n            {\n                ret = handler(vm, args, &array->start[from], from);\n\n            } else {\n                entry = njs_value_arg(&njs_value_invalid);\n                ret = njs_value_property_i64(vm, value, from, &prop);\n                if (njs_slow_path(ret != NJS_DECLINED)) {\n                    if (ret == NJS_ERROR) {\n                        return NJS_ERROR;\n                    }\n\n                    entry = ∝\n                }\n\n                ret = handler(vm, args, entry, from);\n            }\n\n            if (njs_slow_path(ret != NJS_OK)) {\n                if (ret == NJS_DONE) {\n                    return NJS_DONE;\n                }\n\n                return NJS_ERROR;\n            }\n        }\n\n        return NJS_OK;\n    }\n\n    if (njs_is_string(value) || njs_is_object_string(value)) {\n\n        if (njs_is_string(value)) {\n            object = njs_object_value_alloc(vm, NJS_OBJ_TYPE_STRING, 0, value);\n            if (njs_slow_path(object == NULL)) {\n                return NJS_ERROR;\n            }\n\n            njs_set_object_value(&string_obj, object);\n\n            args->value = &string_obj;\n        }\n        else {\n            value = njs_object_value(value);\n        }\n\n        length = njs_string_prop(&string_prop, value);\n        end = string_prop.start + string_prop.size;\n\n        if ((size_t) length == string_prop.size) {\n            /* Byte or ASCII string. */\n\n            p = string_prop.start + from;\n\n            i = from + 1;\n\n            while (i-- > to) {\n                /* This cannot fail. */\n                (void) njs_string_new(vm, &character, p, 1, 1);\n\n                ret = handler(vm, args, &character, i);\n                if (njs_slow_path(ret != NJS_OK)) {\n                    if (ret == NJS_DONE) {\n                        return NJS_DONE;\n                    }\n\n                    return NJS_ERROR;\n                }\n\n                p--;\n            }\n\n        } else {\n            /* UTF-8 string. */\n\n            p = NULL;\n            i = from + 1;\n\n            if (i > to) {\n                p = njs_string_offset(string_prop.start, end, from);\n                p = njs_utf8_next(p, end);\n            }\n\n            while (i-- > to) {\n                pos = njs_utf8_prev(p);\n\n                /* This cannot fail. */\n                (void) njs_string_new(vm, &character, pos, p - pos , 1);\n\n                ret = handler(vm, args, &character, i);\n                if (njs_slow_path(ret != NJS_OK)) {\n                    if (ret == NJS_DONE) {\n                        return NJS_DONE;\n                    }\n\n                    return NJS_ERROR;\n                }\n\n                p = pos;\n            }\n        }\n\n        return NJS_OK;\n    }\n\n    if (!njs_is_object(value)) {\n        return NJS_OK;\n    }\n\nprocess_object:\n\n    if (!njs_fast_object(from - to)) {\n        keys = njs_array_indices(vm, value);\n        if (njs_slow_path(keys == NULL)) {\n            return NJS_ERROR;\n        }\n\n        i = keys->length;\n\n        while (i > 0) {\n            idx = njs_string_to_index(&keys->start[--i]);\n\n            if (idx < to || idx > from) {\n                continue;\n            }\n\n            ret = njs_iterator_object_handler(vm, handler, args,\n                                              &keys->start[i], idx);\n            if (njs_slow_path(ret != NJS_OK)) {\n                njs_array_destroy(vm, keys);\n                return ret;\n            }\n        }\n\n        njs_array_destroy(vm, keys);\n\n        return NJS_OK;\n    }\n\n    i = from + 1;\n\n    while (i-- > to) {\n        ret = njs_iterator_object_handler(vm, handler, args, NULL, i);\n        if (njs_slow_path(ret != NJS_OK)) {\n            return ret;\n        }\n    }\n\n    return NJS_OK;\n}", "func_hash": 126929931891431012577582567397865564778, "file_name": "njs_iterator.c", "file_hash": 301055713494261994912699784498872698249, "cwe": ["CWE-703"], "cve": "CVE-2022-31307", "cve_desc": "Nginx NJS v0.7.2 was discovered to contain a segmentation violation in the function njs_string_offset at src/njs_string.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31307"}
{"idx": 197719, "project": "tensorflow", "commit_id": "be7a4de6adfbd303ce08be4332554dff70362612", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/be7a4de6adfbd303ce08be4332554dff70362612", "commit_message": "Ensure non-empty rt_nested_splits in tf.raw_ops.RaggedTensorToVariant\n\nPiperOrigin-RevId: 387664237\nChange-Id: Ia1700c34b5610873d63561abc86e23b46ead93b3", "target": 1, "func": "  void Compute(OpKernelContext* context) override {\n    // Read ragged_splits inputs.\n    OpInputList ragged_nested_splits_in;\n    OP_REQUIRES_OK(context, context->input_list(\"rt_nested_splits\",\n                                                &ragged_nested_splits_in));\n    const int ragged_nested_splits_len = ragged_nested_splits_in.size();\n    RaggedTensorVariant batched_ragged_input;\n    // Read ragged_values input.\n    batched_ragged_input.set_values(context->input(ragged_nested_splits_len));\n    batched_ragged_input.mutable_nested_splits()->reserve(\n        ragged_nested_splits_len);\n    for (int i = 0; i < ragged_nested_splits_len; i++) {\n      batched_ragged_input.append_splits(ragged_nested_splits_in[i]);\n    }\n\n    if (!batched_input_) {\n      // Encode as a Scalar Variant Tensor.\n      Tensor* encoded_scalar;\n      OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({}),\n                                                       &encoded_scalar));\n      encoded_scalar->scalar()() = std::move(batched_ragged_input);\n      return;\n    }\n\n    // Unbatch the Ragged Tensor and encode the components.\n    std::vector unbatched_ragged_input;\n    auto batched_splits_top_vec =\n        batched_ragged_input.splits(0).vec();\n    int num_components = batched_splits_top_vec.size() - 1;\n    OP_REQUIRES(context, num_components >= 0,\n                errors::Internal(\"Invalid split argument.\"));\n    OP_REQUIRES_OK(context, UnbatchRaggedZerothDim(\n                                batched_ragged_input, &unbatched_ragged_input));\n\n    // Bundle the encoded scalar Variant Tensors into a rank-1 Variant Tensor.\n    Tensor* encoded_vector;\n    int output_size = unbatched_ragged_input.size();\n    OP_REQUIRES_OK(context,\n                   context->allocate_output(0, TensorShape({output_size}),\n                                            &encoded_vector));\n    auto encoded_vector_t = encoded_vector->vec();\n    for (int i = 0; i < output_size; i++) {\n      encoded_vector_t(i) = unbatched_ragged_input[i];\n    }\n  }", "func_hash": 87089111367695740407726211981017748791, "file_name": "ragged_tensor_to_variant_op.cc", "file_hash": 103790733078302023163492154550355279185, "cwe": ["CWE-125"], "cve": "CVE-2021-37666", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can cause undefined behavior via binding a reference to null pointer in `tf.raw_ops.RaggedTensorToVariant`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/ragged_tensor_to_variant_op.cc#L129) has an incomplete validation of the splits values, missing the case when the argument would be empty. We have patched the issue in GitHub commit be7a4de6adfbd303ce08be4332554dff70362612. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37666"}
{"idx": 262803, "project": "tensorflow", "commit_id": "be7a4de6adfbd303ce08be4332554dff70362612", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/be7a4de6adfbd303ce08be4332554dff70362612", "commit_message": "Ensure non-empty rt_nested_splits in tf.raw_ops.RaggedTensorToVariant\n\nPiperOrigin-RevId: 387664237\nChange-Id: Ia1700c34b5610873d63561abc86e23b46ead93b3", "target": 0, "func": "  void Compute(OpKernelContext* context) override {\n    // Read ragged_splits inputs.\n    OpInputList ragged_nested_splits_in;\n    OP_REQUIRES_OK(context, context->input_list(\"rt_nested_splits\",\n                                                &ragged_nested_splits_in));\n    const int ragged_nested_splits_len = ragged_nested_splits_in.size();\n    RaggedTensorVariant batched_ragged_input;\n    // Read ragged_values input.\n    batched_ragged_input.set_values(context->input(ragged_nested_splits_len));\n    batched_ragged_input.mutable_nested_splits()->reserve(\n        ragged_nested_splits_len);\n    for (int i = 0; i < ragged_nested_splits_len; i++) {\n      batched_ragged_input.append_splits(ragged_nested_splits_in[i]);\n    }\n\n    if (!batched_input_) {\n      // Encode as a Scalar Variant Tensor.\n      Tensor* encoded_scalar;\n      OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({}),\n                                                       &encoded_scalar));\n      encoded_scalar->scalar()() = std::move(batched_ragged_input);\n      return;\n    }\n\n    // Checked here instead of at input in case batched_input_ is false\n    OP_REQUIRES(context, ragged_nested_splits_len > 0,\n                errors::InvalidArgument(\n                    \"rt_nested_splits must be a list of one or more, but \"\n                    \"received rt_nested_splits of length 0.\"));\n\n    // Unbatch the Ragged Tensor and encode the components.\n    std::vector unbatched_ragged_input;\n    auto batched_splits_top_vec =\n        batched_ragged_input.splits(0).vec();\n    int num_components = batched_splits_top_vec.size() - 1;\n    OP_REQUIRES(context, num_components >= 0,\n                errors::Internal(\"Invalid split argument.\"));\n    OP_REQUIRES_OK(context, UnbatchRaggedZerothDim(\n                                batched_ragged_input, &unbatched_ragged_input));\n\n    // Bundle the encoded scalar Variant Tensors into a rank-1 Variant Tensor.\n    Tensor* encoded_vector;\n    int output_size = unbatched_ragged_input.size();\n    OP_REQUIRES_OK(context,\n                   context->allocate_output(0, TensorShape({output_size}),\n                                            &encoded_vector));\n    auto encoded_vector_t = encoded_vector->vec();\n    for (int i = 0; i < output_size; i++) {\n      encoded_vector_t(i) = unbatched_ragged_input[i];\n    }\n  }", "func_hash": 237493287424700681504663667406249273606, "file_name": "ragged_tensor_to_variant_op.cc", "file_hash": 123140748084438584715535064056963359547, "cwe": ["CWE-125"], "cve": "CVE-2021-37666", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can cause undefined behavior via binding a reference to null pointer in `tf.raw_ops.RaggedTensorToVariant`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/ragged_tensor_to_variant_op.cc#L129) has an incomplete validation of the splits values, missing the case when the argument would be empty. We have patched the issue in GitHub commit be7a4de6adfbd303ce08be4332554dff70362612. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37666"}
{"idx": 197748, "project": "tensorflow", "commit_id": "c79ba87153ee343401dbe9d1954d7f79e521eb14", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/c79ba87153ee343401dbe9d1954d7f79e521eb14", "commit_message": "Make Transpose's shape inference function validate that negative `perm` values are within the tensor's rank.\n\nPiperOrigin-RevId: 403252853\nChange-Id: Ia6b31b45b237312668bb31c2c3b3c7bbce2d2610", "target": 1, "func": "Status TransposeShapeFn(InferenceContext* c) {\n  ShapeHandle input = c->input(0);\n  ShapeHandle perm_shape = c->input(1);\n  const Tensor* perm = c->input_tensor(1);\n  DimensionHandle perm_elems = c->NumElements(perm_shape);\n  // If we don't have rank information on the input or value information on\n  // perm we can't return any shape information, otherwise we have enough\n  // information to at least find the rank of the output.\n  if (!c->RankKnown(input) && !c->ValueKnown(perm_elems) && perm == nullptr) {\n    c->set_output(0, c->UnknownShape());\n    return Status::OK();\n  }\n\n  // Find our value of the rank.\n  int64_t rank;\n  if (c->RankKnown(input)) {\n    rank = c->Rank(input);\n  } else if (c->ValueKnown(perm_elems)) {\n    rank = c->Value(perm_elems);\n  } else {\n    rank = perm->NumElements();\n  }\n  if (!c->RankKnown(input) && rank < 2) {\n    // A permutation array containing a single element is ambiguous. It could\n    // indicate either a scalar or a 1-dimensional array, both of which the\n    // transpose op returns unchanged.\n    c->set_output(0, input);\n    return Status::OK();\n  }\n\n  std::vector dims;\n  dims.resize(rank);\n  TF_RETURN_IF_ERROR(c->WithRank(input, rank, &input));\n  // Ensure that perm is a vector and has rank elements.\n  TF_RETURN_IF_ERROR(c->WithRank(perm_shape, 1, &perm_shape));\n  TF_RETURN_IF_ERROR(c->WithValue(perm_elems, rank, &perm_elems));\n\n  // If we know the rank of the input and the value of perm, we can return\n  // all shape information, otherwise we can only return rank information,\n  // but no information for the dimensions.\n  if (perm != nullptr) {\n    std::vector data;\n    if (perm->dtype() == DT_INT32) {\n      data = AsInt64(perm, rank);\n    } else {\n      data = AsInt64(perm, rank);\n    }\n\n    for (int32_t i = 0; i < rank; ++i) {\n      int64_t in_idx = data[i];\n      if (in_idx >= rank) {\n        return errors::InvalidArgument(\"perm dim \", in_idx,\n                                       \" is out of range of input rank \", rank);\n      }\n      dims[i] = c->Dim(input, in_idx);\n    }\n  } else {\n    for (int i = 0; i < rank; ++i) {\n      dims[i] = c->UnknownDim();\n    }\n  }\n\n  c->set_output(0, c->MakeShape(dims));\n  return Status::OK();\n}", "func_hash": 264434210200699405161022303469799474263, "file_name": "array_ops.cc", "file_hash": 212731692545100279573003636737252061446, "cwe": ["CWE-703"], "cve": "CVE-2021-41216", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions the shape inference function for `Transpose` is vulnerable to a heap buffer overflow. This occurs whenever `perm` contains negative elements. The shape inference function does not validate that the indices in `perm` are all valid. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41216"}
{"idx": 263382, "project": "tensorflow", "commit_id": "c79ba87153ee343401dbe9d1954d7f79e521eb14", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/c79ba87153ee343401dbe9d1954d7f79e521eb14", "commit_message": "Make Transpose's shape inference function validate that negative `perm` values are within the tensor's rank.\n\nPiperOrigin-RevId: 403252853\nChange-Id: Ia6b31b45b237312668bb31c2c3b3c7bbce2d2610", "target": 0, "func": "Status TransposeShapeFn(InferenceContext* c) {\n  ShapeHandle input = c->input(0);\n  ShapeHandle perm_shape = c->input(1);\n  const Tensor* perm = c->input_tensor(1);\n  DimensionHandle perm_elems = c->NumElements(perm_shape);\n  // If we don't have rank information on the input or value information on\n  // perm we can't return any shape information, otherwise we have enough\n  // information to at least find the rank of the output.\n  if (!c->RankKnown(input) && !c->ValueKnown(perm_elems) && perm == nullptr) {\n    c->set_output(0, c->UnknownShape());\n    return Status::OK();\n  }\n\n  // Find our value of the rank.\n  int64_t rank;\n  if (c->RankKnown(input)) {\n    rank = c->Rank(input);\n  } else if (c->ValueKnown(perm_elems)) {\n    rank = c->Value(perm_elems);\n  } else {\n    rank = perm->NumElements();\n  }\n  if (!c->RankKnown(input) && rank < 2) {\n    // A permutation array containing a single element is ambiguous. It could\n    // indicate either a scalar or a 1-dimensional array, both of which the\n    // transpose op returns unchanged.\n    c->set_output(0, input);\n    return Status::OK();\n  }\n\n  std::vector dims;\n  dims.resize(rank);\n  TF_RETURN_IF_ERROR(c->WithRank(input, rank, &input));\n  // Ensure that perm is a vector and has rank elements.\n  TF_RETURN_IF_ERROR(c->WithRank(perm_shape, 1, &perm_shape));\n  TF_RETURN_IF_ERROR(c->WithValue(perm_elems, rank, &perm_elems));\n\n  // If we know the rank of the input and the value of perm, we can return\n  // all shape information, otherwise we can only return rank information,\n  // but no information for the dimensions.\n  if (perm != nullptr) {\n    std::vector data;\n    if (perm->dtype() == DT_INT32) {\n      data = AsInt64(perm, rank);\n    } else {\n      data = AsInt64(perm, rank);\n    }\n\n    for (int32_t i = 0; i < rank; ++i) {\n      int64_t in_idx = data[i];\n      if (in_idx >= rank || in_idx <= -rank) {\n        return errors::InvalidArgument(\"perm dim \", in_idx,\n                                       \" is out of range of input rank \", rank);\n      }\n      dims[i] = c->Dim(input, in_idx);\n    }\n  } else {\n    for (int i = 0; i < rank; ++i) {\n      dims[i] = c->UnknownDim();\n    }\n  }\n\n  c->set_output(0, c->MakeShape(dims));\n  return Status::OK();\n}", "func_hash": 29167107704393377568596638979461909163, "file_name": "array_ops.cc", "file_hash": 283394420828634459233696628321427916283, "cwe": ["CWE-703"], "cve": "CVE-2021-41216", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions the shape inference function for `Transpose` is vulnerable to a heap buffer overflow. This occurs whenever `perm` contains negative elements. The shape inference function does not validate that the indices in `perm` are all valid. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41216"}
{"idx": 197760, "project": "tensorflow", "commit_id": "bb6a0383ed553c286f87ca88c207f6774d5c4a8f", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/bb6a0383ed553c286f87ca88c207f6774d5c4a8f", "commit_message": "Prevent heap OOB read in TFLite's `gather_nd.cc`.\n\nPassing negative indices is illegal but there was a missing check so that resulted in OOB accesses.\n\nPiperOrigin-RevId: 387208551\nChange-Id: I6b7a8a62d3e7c13a16d81619e5bc23ae2cdbc7fd", "target": 1, "func": "TfLiteStatus EvalGatherNd(TfLiteContext* context, const TfLiteTensor* params,\n                          const TfLiteTensor* indices, TfLiteTensor* output) {\n  switch (params->type) {\n    case kTfLiteFloat32:\n      return GatherNd(params, indices, output);\n    case kTfLiteUInt8:\n      return GatherNd(params, indices, output);\n    case kTfLiteInt8:\n      return GatherNd(params, indices, output);\n    case kTfLiteInt16:\n      return GatherNd(params, indices, output);\n    case kTfLiteInt32:\n      return GatherNd(params, indices, output);\n    case kTfLiteInt64:\n      return GatherNd(params, indices, output);\n    case kTfLiteString:\n      return GatherNdString(params, indices, output);\n    default:\n      context->ReportError(context,\n                           \"Params type '%s' are not supported by gather_nd.\",\n                           TfLiteTypeGetName(params->type));\n      return kTfLiteError;\n  }\n}", "func_hash": 33385980683805390111226215596644506391, "file_name": "gather_nd.cc", "file_hash": 316439389085787575038399494263818469682, "cwe": ["CWE-125"], "cve": "CVE-2021-37687", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions TFLite's [`GatherNd` implementation](https://github.com/tensorflow/tensorflow/blob/149562d49faa709ea80df1d99fc41d005b81082a/tensorflow/lite/kernels/gather_nd.cc#L124) does not support negative indices but there are no checks for this situation. Hence, an attacker can read arbitrary data from the heap by carefully crafting a model with negative values in `indices`. Similar issue exists in [`Gather` implementation](https://github.com/tensorflow/tensorflow/blob/149562d49faa709ea80df1d99fc41d005b81082a/tensorflow/lite/kernels/gather.cc). We have patched the issue in GitHub commits bb6a0383ed553c286f87ca88c207f6774d5c4a8f and eb921122119a6b6e470ee98b89e65d721663179d. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37687"}
{"idx": 263521, "project": "tensorflow", "commit_id": "bb6a0383ed553c286f87ca88c207f6774d5c4a8f", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/bb6a0383ed553c286f87ca88c207f6774d5c4a8f", "commit_message": "Prevent heap OOB read in TFLite's `gather_nd.cc`.\n\nPassing negative indices is illegal but there was a missing check so that resulted in OOB accesses.\n\nPiperOrigin-RevId: 387208551\nChange-Id: I6b7a8a62d3e7c13a16d81619e5bc23ae2cdbc7fd", "target": 0, "func": "TfLiteStatus EvalGatherNd(TfLiteContext* context, const TfLiteTensor* params,\n                          const TfLiteTensor* indices, TfLiteTensor* output) {\n  bool indices_has_only_positive_elements = true;\n  const auto* indices_values = GetTensorData(indices);\n  const size_t num_indices = indices->bytes / sizeof(IndicesT);\n  for (size_t i = 0; i < num_indices; i++) {\n    if (indices_values[i] < 0) {\n      indices_has_only_positive_elements = false;\n      break;\n    }\n  }\n  TF_LITE_ENSURE(context, indices_has_only_positive_elements);\n\n  switch (params->type) {\n    case kTfLiteFloat32:\n      return GatherNd(params, indices, output);\n    case kTfLiteUInt8:\n      return GatherNd(params, indices, output);\n    case kTfLiteInt8:\n      return GatherNd(params, indices, output);\n    case kTfLiteInt16:\n      return GatherNd(params, indices, output);\n    case kTfLiteInt32:\n      return GatherNd(params, indices, output);\n    case kTfLiteInt64:\n      return GatherNd(params, indices, output);\n    case kTfLiteString:\n      return GatherNdString(params, indices, output);\n    default:\n      context->ReportError(context,\n                           \"Params type '%s' are not supported by gather_nd.\",\n                           TfLiteTypeGetName(params->type));\n      return kTfLiteError;\n  }\n}", "func_hash": 279577390165387156722866411822496673151, "file_name": "gather_nd.cc", "file_hash": 142063643007794638174357713974685200472, "cwe": ["CWE-125"], "cve": "CVE-2021-37687", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions TFLite's [`GatherNd` implementation](https://github.com/tensorflow/tensorflow/blob/149562d49faa709ea80df1d99fc41d005b81082a/tensorflow/lite/kernels/gather_nd.cc#L124) does not support negative indices but there are no checks for this situation. Hence, an attacker can read arbitrary data from the heap by carefully crafting a model with negative values in `indices`. Similar issue exists in [`Gather` implementation](https://github.com/tensorflow/tensorflow/blob/149562d49faa709ea80df1d99fc41d005b81082a/tensorflow/lite/kernels/gather.cc). We have patched the issue in GitHub commits bb6a0383ed553c286f87ca88c207f6774d5c4a8f and eb921122119a6b6e470ee98b89e65d721663179d. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37687"}
{"idx": 197796, "project": "qemu", "commit_id": "f9a70e79391f6d7c2a912d785239ee8effc1922d", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://github.com/qemu/qemu/commit/f9a70e79391f6d7c2a912d785239ee8effc1922d", "commit_message": "ui/vnc: limit client_cut_text msg payload size\n\ncurrently a malicious client could define a payload\nsize of 2^32 - 1 bytes and send up to that size of\ndata to the vnc server. The server would allocated\nthat amount of memory which could easily create an\nout of memory condition.\n\nThis patch limits the payload size to 1MB max.\n\nPlease note that client_cut_text messages are currently\nsilently ignored.\n\nSigned-off-by: Peter Lieven \nSigned-off-by: Gerd Hoffmann ", "target": 1, "func": "static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)\n{\n    int i;\n    uint16_t limit;\n    VncDisplay *vd = vs->vd;\n\n    if (data[0] > 3) {\n        update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);\n    }\n\n    switch (data[0]) {\n    case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:\n        if (len == 1)\n            return 20;\n\n        set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),\n                         read_u8(data, 6), read_u8(data, 7),\n                         read_u16(data, 8), read_u16(data, 10),\n                         read_u16(data, 12), read_u8(data, 14),\n                         read_u8(data, 15), read_u8(data, 16));\n        break;\n    case VNC_MSG_CLIENT_SET_ENCODINGS:\n        if (len == 1)\n            return 4;\n\n        if (len == 4) {\n            limit = read_u16(data, 2);\n            if (limit > 0)\n                return 4 + (limit * 4);\n        } else\n            limit = read_u16(data, 2);\n\n        for (i = 0; i < limit; i++) {\n            int32_t val = read_s32(data, 4 + (i * 4));\n            memcpy(data + 4 + (i * 4), &val, sizeof(val));\n        }\n\n        set_encodings(vs, (int32_t *)(data + 4), limit);\n        break;\n    case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:\n        if (len == 1)\n            return 10;\n\n        framebuffer_update_request(vs,\n                                   read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),\n                                   read_u16(data, 6), read_u16(data, 8));\n        break;\n    case VNC_MSG_CLIENT_KEY_EVENT:\n        if (len == 1)\n            return 8;\n\n        key_event(vs, read_u8(data, 1), read_u32(data, 4));\n        break;\n    case VNC_MSG_CLIENT_POINTER_EVENT:\n        if (len == 1)\n            return 6;\n\n        pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));\n        break;\n    case VNC_MSG_CLIENT_CUT_TEXT:\n        if (len == 1)\n            return 8;\n\n        if (len == 8) {\n            uint32_t dlen = read_u32(data, 4);\n            if (dlen > 0)\n                return 8 + dlen;\n        }\n\n        client_cut_text(vs, read_u32(data, 4), data + 8);\n        break;\n    case VNC_MSG_CLIENT_QEMU:\n        if (len == 1)\n            return 2;\n\n        switch (read_u8(data, 1)) {\n        case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:\n            if (len == 2)\n                return 12;\n\n            ext_key_event(vs, read_u16(data, 2),\n                          read_u32(data, 4), read_u32(data, 8));\n            break;\n        case VNC_MSG_CLIENT_QEMU_AUDIO:\n            if (len == 2)\n                return 4;\n\n            switch (read_u16 (data, 2)) {\n            case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:\n                audio_add(vs);\n                break;\n            case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:\n                audio_del(vs);\n                break;\n            case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:\n                if (len == 4)\n                    return 10;\n                switch (read_u8(data, 4)) {\n                case 0: vs->as.fmt = AUD_FMT_U8; break;\n                case 1: vs->as.fmt = AUD_FMT_S8; break;\n                case 2: vs->as.fmt = AUD_FMT_U16; break;\n                case 3: vs->as.fmt = AUD_FMT_S16; break;\n                case 4: vs->as.fmt = AUD_FMT_U32; break;\n                case 5: vs->as.fmt = AUD_FMT_S32; break;\n                default:\n                    printf(\"Invalid audio format %d\\n\", read_u8(data, 4));\n                    vnc_client_error(vs);\n                    break;\n                }\n                vs->as.nchannels = read_u8(data, 5);\n                if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {\n                    printf(\"Invalid audio channel coount %d\\n\",\n                           read_u8(data, 5));\n                    vnc_client_error(vs);\n                    break;\n                }\n                vs->as.freq = read_u32(data, 6);\n                break;\n            default:\n                printf (\"Invalid audio message %d\\n\", read_u8(data, 4));\n                vnc_client_error(vs);\n                break;\n            }\n            break;\n\n        default:\n            printf(\"Msg: %d\\n\", read_u16(data, 0));\n            vnc_client_error(vs);\n            break;\n        }\n        break;\n    default:\n        printf(\"Msg: %d\\n\", data[0]);\n        vnc_client_error(vs);\n        break;\n    }\n\n    vnc_read_when(vs, protocol_client_msg, 1);\n    return 0;\n}", "func_hash": 26933609972946502173706391662270420555, "file_name": "vnc.c", "file_hash": 161585493204485691727376098595593068159, "cwe": ["CWE-703"], "cve": "CVE-2015-5239", "cve_desc": "Integer overflow in the VNC display driver in QEMU before 2.1.0 allows attachers to cause a denial of service (process crash) via a CLIENT_CUT_TEXT message, which triggers an infinite loop.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-5239"}
{"idx": 187732, "project": "qemu", "commit_id": "e6908bfe8e07f2b452e78e677da1b45b1c0f6829", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://git.qemu.org/?p=qemu.git;a=commit;h=e6908bfe8e07f2b452e78e677da1b45b1c0f6829", "commit_message": "vnc: sanitize bits_per_pixel from the client\n\nbits_per_pixel that are less than 8 could result in accessing\nnon-initialized buffers later in the code due to the expectation\nthat bytes_per_pixel value that is used to initialize these buffers is\nnever zero.\n\nTo fix this check that bits_per_pixel from the client is one of the\nvalues that the rfb protocol specification allows.\n\nThis is CVE-2014-7815.\n\nSigned-off-by: Petr Matousek \n\n[ kraxel: apply codestyle fix ]\n\nSigned-off-by: Gerd Hoffmann ", "target": 0, "func": "static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)\n{\n    int i;\n    uint16_t limit;\n    VncDisplay *vd = vs->vd;\n\n    if (data[0] > 3) {\n        update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);\n    }\n\n    switch (data[0]) {\n    case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:\n        if (len == 1)\n            return 20;\n\n        set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),\n                         read_u8(data, 6), read_u8(data, 7),\n                         read_u16(data, 8), read_u16(data, 10),\n                         read_u16(data, 12), read_u8(data, 14),\n                         read_u8(data, 15), read_u8(data, 16));\n        break;\n    case VNC_MSG_CLIENT_SET_ENCODINGS:\n        if (len == 1)\n            return 4;\n\n        if (len == 4) {\n            limit = read_u16(data, 2);\n            if (limit > 0)\n                return 4 + (limit * 4);\n        } else\n            limit = read_u16(data, 2);\n\n        for (i = 0; i < limit; i++) {\n            int32_t val = read_s32(data, 4 + (i * 4));\n            memcpy(data + 4 + (i * 4), &val, sizeof(val));\n        }\n\n        set_encodings(vs, (int32_t *)(data + 4), limit);\n        break;\n    case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:\n        if (len == 1)\n            return 10;\n\n        framebuffer_update_request(vs,\n                                   read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),\n                                   read_u16(data, 6), read_u16(data, 8));\n        break;\n    case VNC_MSG_CLIENT_KEY_EVENT:\n        if (len == 1)\n            return 8;\n\n        key_event(vs, read_u8(data, 1), read_u32(data, 4));\n        break;\n    case VNC_MSG_CLIENT_POINTER_EVENT:\n        if (len == 1)\n            return 6;\n\n        pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));\n        break;\n    case VNC_MSG_CLIENT_CUT_TEXT:\n        if (len == 1) {\n            return 8;\n        }\n        if (len == 8) {\n            uint32_t dlen = read_u32(data, 4);\n            if (dlen > (1 << 20)) {\n                error_report(\"vnc: client_cut_text msg payload has %u bytes\"\n                             \" which exceeds our limit of 1MB.\", dlen);\n                vnc_client_error(vs);\n                break;\n            }\n            if (dlen > 0) {\n                return 8 + dlen;\n            }\n        }\n\n        client_cut_text(vs, read_u32(data, 4), data + 8);\n        break;\n    case VNC_MSG_CLIENT_QEMU:\n        if (len == 1)\n            return 2;\n\n        switch (read_u8(data, 1)) {\n        case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:\n            if (len == 2)\n                return 12;\n\n            ext_key_event(vs, read_u16(data, 2),\n                          read_u32(data, 4), read_u32(data, 8));\n            break;\n        case VNC_MSG_CLIENT_QEMU_AUDIO:\n            if (len == 2)\n                return 4;\n\n            switch (read_u16 (data, 2)) {\n            case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:\n                audio_add(vs);\n                break;\n            case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:\n                audio_del(vs);\n                break;\n            case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:\n                if (len == 4)\n                    return 10;\n                switch (read_u8(data, 4)) {\n                case 0: vs->as.fmt = AUD_FMT_U8; break;\n                case 1: vs->as.fmt = AUD_FMT_S8; break;\n                case 2: vs->as.fmt = AUD_FMT_U16; break;\n                case 3: vs->as.fmt = AUD_FMT_S16; break;\n                case 4: vs->as.fmt = AUD_FMT_U32; break;\n                case 5: vs->as.fmt = AUD_FMT_S32; break;\n                default:\n                    printf(\"Invalid audio format %d\\n\", read_u8(data, 4));\n                    vnc_client_error(vs);\n                    break;\n                }\n                vs->as.nchannels = read_u8(data, 5);\n                if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {\n                    printf(\"Invalid audio channel coount %d\\n\",\n                           read_u8(data, 5));\n                    vnc_client_error(vs);\n                    break;\n                }\n                vs->as.freq = read_u32(data, 6);\n                break;\n            default:\n                printf (\"Invalid audio message %d\\n\", read_u8(data, 4));\n                vnc_client_error(vs);\n                break;\n            }\n            break;\n\n        default:\n            printf(\"Msg: %d\\n\", read_u16(data, 0));\n            vnc_client_error(vs);\n            break;\n        }\n        break;\n    default:\n        printf(\"Msg: %d\\n\", data[0]);\n        vnc_client_error(vs);\n        break;\n    }\n\n    vnc_read_when(vs, protocol_client_msg, 1);\n    return 0;\n}\n", "func_hash": 36184187579067934459760117493887101349, "file_name": "vnc.c", "file_hash": 252961112607641046911485916255107775979, "cwe": ["CWE-264"], "cve": "CVE-2014-7815", "cve_desc": "The set_pixel_format function in ui/vnc.c in QEMU allows remote attackers to cause a denial of service (crash) via a small bytes_per_pixel value.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-7815"}
{"idx": 197801, "project": "tensorflow", "commit_id": "368af875869a204b4ac552b9ddda59f6a46a56ec", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/368af875869a204b4ac552b9ddda59f6a46a56ec", "commit_message": "Avoid buffer overflow when loading tensors with insufficient data from checkpoints.\n\n`CopyDataFromTensorSliceToTensorSlice` does not (and cannot conveniently)\nprovide any bounds checking on its own, so the size is instead checked prior\nto passing unvalidated data to that function.\n\nPiperOrigin-RevId: 392971286\nChange-Id: If2073b36d4d5eedd386329f56729395fd7effee1", "target": 1, "func": "bool TensorSliceReader::CopySliceData(const string& name,\n                                      const TensorSlice& slice, T* data) const {\n  std::vector> details;\n  const TensorSliceSet* tss;\n  {\n    mutex_lock l(mu_);\n    tss = FindTensorSlice(name, slice, &details);\n    if (!tss && !all_shards_loaded_) {\n      VLOG(1) << \"Did not find slice in preferred shard, loading all shards.\"\n              << name << \": \" << slice.DebugString();\n      LoadAllShards();\n      tss = FindTensorSlice(name, slice, &details);\n    }\n    if (!tss) {\n      // No such tensor\n      return false;\n    }\n  }\n  // We have the data -- copy it over.\n  string value;\n  for (const auto& x : details) {\n    const TensorSlice& slice_s = x.first;\n    const string& fname = x.second;\n    int idx = gtl::FindWithDefault(fname_to_index_, fname, -1);\n    CHECK_GE(idx, 0) << \"Failed to find the index for filename \" << fname;\n    // We read a record in the corresponding sstable\n    const string key = EncodeTensorNameSlice(name, slice_s);\n    if (!sss_[idx]->Get(key, &value)) {\n      VLOG(1) << \"Failed to seek to the record for tensor \" << name\n              << \", slice \" << slice_s.DebugString()\n              << \": computed key = \" << key;\n      return false;\n    }\n    SavedTensorSlices sts;\n    if (!ParseProtoUnlimited(&sts, value)) {\n      VLOG(1) << \"Failed to parse the record for tensor \" << name << \", slice \"\n              << slice_s.DebugString() << \": computed key = \" << key;\n      return false;\n    }\n    CopyDataFromTensorSliceToTensorSlice(\n        tss->shape(), slice_s, slice,\n        checkpoint::TensorProtoData(sts.data().data()), data);\n  }\n  return true;\n}", "func_hash": 253938811692403617918500480067513726895, "file_name": "tensor_slice_reader.h", "file_hash": 240433137636754905402215095789731366712, "cwe": ["CWE-345"], "cve": "CVE-2021-41203", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions an attacker can trigger undefined behavior, integer overflows, segfaults and `CHECK`-fail crashes if they can change saved checkpoints from outside of TensorFlow. This is because the checkpoints loading infrastructure is missing validation for invalid file formats. The fixes will be included in TensorFlow 2.7.0. We will also cherrypick these commits on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41203"}
{"idx": 264367, "project": "tensorflow", "commit_id": "368af875869a204b4ac552b9ddda59f6a46a56ec", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/368af875869a204b4ac552b9ddda59f6a46a56ec", "commit_message": "Avoid buffer overflow when loading tensors with insufficient data from checkpoints.\n\n`CopyDataFromTensorSliceToTensorSlice` does not (and cannot conveniently)\nprovide any bounds checking on its own, so the size is instead checked prior\nto passing unvalidated data to that function.\n\nPiperOrigin-RevId: 392971286\nChange-Id: If2073b36d4d5eedd386329f56729395fd7effee1", "target": 0, "func": "bool TensorSliceReader::CopySliceData(const string& name,\n                                      const TensorSlice& slice, T* data) const {\n  std::vector> details;\n  const TensorSliceSet* tss;\n  {\n    mutex_lock l(mu_);\n    tss = FindTensorSlice(name, slice, &details);\n    if (!tss && !all_shards_loaded_) {\n      VLOG(1) << \"Did not find slice in preferred shard, loading all shards.\"\n              << name << \": \" << slice.DebugString();\n      LoadAllShards();\n      tss = FindTensorSlice(name, slice, &details);\n    }\n    if (!tss) {\n      // No such tensor\n      return false;\n    }\n  }\n  // We have the data -- copy it over.\n  string value;\n  for (const auto& x : details) {\n    const TensorSlice& slice_s = x.first;\n    const string& fname = x.second;\n    int idx = gtl::FindWithDefault(fname_to_index_, fname, -1);\n    CHECK_GE(idx, 0) << \"Failed to find the index for filename \" << fname;\n    // We read a record in the corresponding sstable\n    const string key = EncodeTensorNameSlice(name, slice_s);\n    if (!sss_[idx]->Get(key, &value)) {\n      VLOG(1) << \"Failed to seek to the record for tensor \" << name\n              << \", slice \" << slice_s.DebugString()\n              << \": computed key = \" << key;\n      return false;\n    }\n    SavedTensorSlices sts;\n    if (!ParseProtoUnlimited(&sts, value)) {\n      VLOG(1) << \"Failed to parse the record for tensor \" << name << \", slice \"\n              << slice_s.DebugString() << \": computed key = \" << key;\n      return false;\n    }\n    // Ensure the TensorSlice contains the expected amount of data.\n    TensorShape shp_s;\n    Status s = slice_s.SliceTensorShape(tss->shape(), &shp_s);\n    if (!s.ok()) {\n      VLOG(1) << \"Failed to slice tensor \" << name << \", slice \"\n              << slice_s.DebugString() << \": \" << s;\n      return false;\n    }\n    if (checkpoint::TensorProtoDataSize(sts.data().data()) !=\n        shp_s.num_elements()) {\n      VLOG(1) << \"Tensor \" << name << \", slice \" << slice_s.DebugString()\n              << \" had an unexpected amount of data: expected = \"\n              << shp_s.num_elements() << \", got = \"\n              << checkpoint::TensorProtoDataSize(sts.data().data());\n      return false;\n    }\n    CopyDataFromTensorSliceToTensorSlice(\n        tss->shape(), slice_s, slice,\n        checkpoint::TensorProtoData(sts.data().data()), data);\n  }\n  return true;\n}", "func_hash": 260958144262557057718377368328924715257, "file_name": "tensor_slice_reader.h", "file_hash": 20474431130261957581302899955079552996, "cwe": ["CWE-345"], "cve": "CVE-2021-41203", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions an attacker can trigger undefined behavior, integer overflows, segfaults and `CHECK`-fail crashes if they can change saved checkpoints from outside of TensorFlow. This is because the checkpoints loading infrastructure is missing validation for invalid file formats. The fixes will be included in TensorFlow 2.7.0. We will also cherrypick these commits on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41203"}
{"idx": 197824, "project": "gpac", "commit_id": "c535bad50d5812d27ee5b22b54371bddec411514", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/c535bad50d5812d27ee5b22b54371bddec411514", "commit_message": "fixed #2194", "target": 1, "func": "static GF_Err BM_ParseGlobalQuantizer(GF_BifsDecoder *codec, GF_BitStream *bs, GF_List *com_list)\n{\n\tGF_Node *node;\n\tGF_Command *com;\n\tGF_CommandField *inf;\n\tnode = gf_bifs_dec_node(codec, bs, NDT_SFWorldNode);\n\tif (!node) return GF_NON_COMPLIANT_BITSTREAM;\n\n\t/*reset global QP*/\n\tif (codec->scenegraph->global_qp) {\n\t\tgf_node_unregister(codec->scenegraph->global_qp, NULL);\n\t}\n\tcodec->ActiveQP = NULL;\n\tcodec->scenegraph->global_qp = NULL;\n\n\tif (gf_node_get_tag(node) != TAG_MPEG4_QuantizationParameter) {\n\t\tgf_node_unregister(node, NULL);\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\n\t/*register global QP*/\n\tcodec->ActiveQP = (M_QuantizationParameter *) node;\n\tcodec->ActiveQP->isLocal = 0;\n\tcodec->scenegraph->global_qp = node;\n\n\t/*register TWICE: once for the command, and for the scenegraph globalQP*/\n\tnode->sgprivate->num_instances = 2;\n\n\tcom = gf_sg_command_new(codec->current_graph, GF_SG_GLOBAL_QUANTIZER);\n\tinf = gf_sg_command_field_new(com);\n\tinf->new_node = node;\n\tinf->field_ptr = &inf->new_node;\n\tinf->fieldType = GF_SG_VRML_SFNODE;\n\tgf_list_add(com_list, com);\n\treturn GF_OK;\n}", "func_hash": 227330749119032349040137878791232526501, "file_name": "memory_decoder.c", "file_hash": 144617483436873036933597599292760665537, "cwe": ["CWE-416"], "cve": "CVE-2022-1795", "cve_desc": "Use After Free in GitHub repository gpac/gpac prior to v2.1.0-DEV.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1795"}
{"idx": 264657, "project": "gpac", "commit_id": "c535bad50d5812d27ee5b22b54371bddec411514", "project_url": "https://github.com/gpac/gpac", "commit_url": "https://github.com/gpac/gpac/commit/c535bad50d5812d27ee5b22b54371bddec411514", "commit_message": "fixed #2194", "target": 0, "func": "static GF_Err BM_ParseGlobalQuantizer(GF_BifsDecoder *codec, GF_BitStream *bs, GF_List *com_list)\n{\n\tGF_Node *node;\n\tGF_Command *com;\n\tGF_CommandField *inf;\n\tnode = gf_bifs_dec_node(codec, bs, NDT_SFWorldNode);\n\tif (!node) return GF_NON_COMPLIANT_BITSTREAM;\n\n\t/*reset global QP*/\n\tif (codec->scenegraph->global_qp) {\n\t\tgf_node_unregister(codec->scenegraph->global_qp, NULL);\n\t}\n\tcodec->ActiveQP = NULL;\n\tcodec->scenegraph->global_qp = NULL;\n\n\tif (gf_node_get_tag(node) != TAG_MPEG4_QuantizationParameter) {\n\t\t//if node was just created (num_instances == 0), unregister\n\t\t//otherwise (USE node) don't do anything\n\t\tif (!node->sgprivate->num_instances) {\n\t\t\tnode->sgprivate->num_instances = 1;\n\t\t\tgf_node_unregister(node, NULL);\n\t\t}\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\n\t/*register global QP*/\n\tcodec->ActiveQP = (M_QuantizationParameter *) node;\n\tcodec->ActiveQP->isLocal = 0;\n\tcodec->scenegraph->global_qp = node;\n\n\t/*register TWICE: once for the command, and for the scenegraph globalQP*/\n\tgf_node_unregister(node, NULL);\n\tgf_node_unregister(node, NULL);\n\n\tcom = gf_sg_command_new(codec->current_graph, GF_SG_GLOBAL_QUANTIZER);\n\tinf = gf_sg_command_field_new(com);\n\tinf->new_node = node;\n\tinf->field_ptr = &inf->new_node;\n\tinf->fieldType = GF_SG_VRML_SFNODE;\n\tgf_list_add(com_list, com);\n\treturn GF_OK;\n}", "func_hash": 121103708905571280232350867601982124843, "file_name": "memory_decoder.c", "file_hash": 38461926007506254402005076671567829745, "cwe": ["CWE-416"], "cve": "CVE-2022-1795", "cve_desc": "Use After Free in GitHub repository gpac/gpac prior to v2.1.0-DEV.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1795"}
{"idx": 197826, "project": "tensorflow", "commit_id": "7731e8dfbe4a56773be5dc94d631611211156659", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/7731e8dfbe4a56773be5dc94d631611211156659", "commit_message": "Don't constant-fold DT_RESOURCE constants.\n\nPiperOrigin-RevId: 391803952\nChange-Id: I0ea3ec31d3e7dfda0f03b4027a237f08d00a3091", "target": 1, "func": "bool IsConstantFoldable(\n    const Node* n,\n    const std::unordered_map>*\n        shape_map,\n    const std::function& consider,\n    int64_t max_constant_size_in_bytes,\n    std::unordered_map>*\n        shape_replacement_map) {\n  if (n->IsConstant()) {\n    return true;\n  }\n  if (MaybeReplaceShapeOp(n, shape_map, shape_replacement_map)) {\n    return true;\n  }\n  if (n->op_def().is_stateful()) {\n    return false;\n  }\n  if (consider && !consider(n)) {\n    return false;\n  }\n  if (shape_map != nullptr) {\n    // We can skip the node if an output is known to be oversized.\n    auto shape_it = shape_map->find(n->name());\n    if (shape_it != shape_map->end()) {\n      for (int64_t i = 0; i < shape_it->second.size(); ++i) {\n        const auto& out_shape = shape_it->second[i];\n        if (out_shape.IsFullyDefined() &&\n            out_shape.num_elements() * DataTypeSize(n->output_type(i)) >\n                max_constant_size_in_bytes) {\n          return false;\n        }\n      }\n    }\n  }\n  if (n->IsControlFlow() || n->IsSend() || n->IsRecv()) {\n    return false;\n  }\n  // TODO(yuanbyu): For now disable these session handle operations.\n  if (n->IsGetSessionHandle() || n->IsGetSessionTensor() ||\n      n->IsDeleteSessionTensor()) {\n    return false;\n  }\n  if (n->IsSource()) {\n    return false;\n  }\n  if (n->IsSink()) {\n    return false;\n  }\n  if (n->IsFakeParam()) {\n    return false;\n  }\n  // Since constant-folding runs on the CPU, do not attempt to constant-fold\n  // operators that have no CPU kernel. Also implies that we will not\n  // constant-fold functions.\n  // TODO(phawkins): allow constant-folding for functions; functions may\n  // be arbitrarily expensive to execute.\n  if (!KernelDefAvailable(DeviceType(DEVICE_CPU), n->def())) {\n    return false;\n  }\n  // Do not constant fold nodes which will be allocated by ScopedAllocator.\n  // This is because the constant-folding graph will not contain the\n  // `_ScopedAllocator` node, and that is necessary to be able to run a node\n  // that will use this allocator.\n  if (n->attrs().Find(kScopedAllocatorAttrName) != nullptr) {\n    VLOG(2) << \"Skip node [\" << n->DebugString()\n            << \"] for constant folding due to scoped allocator\";\n    return false;\n  }\n  return true;\n}", "func_hash": 116289485656616917830363077368123441202, "file_name": "constant_folding.cc", "file_hash": 46768745532828534791253050765124097339, "cwe": ["CWE-824"], "cve": "CVE-2021-41204", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions during TensorFlow's Grappler optimizer phase, constant folding might attempt to deep copy a resource tensor. This results in a segfault, as these tensors are supposed to not change. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41204"}
{"idx": 264715, "project": "tensorflow", "commit_id": "7731e8dfbe4a56773be5dc94d631611211156659", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/7731e8dfbe4a56773be5dc94d631611211156659", "commit_message": "Don't constant-fold DT_RESOURCE constants.\n\nPiperOrigin-RevId: 391803952\nChange-Id: I0ea3ec31d3e7dfda0f03b4027a237f08d00a3091", "target": 0, "func": "bool IsConstantFoldable(\n    const Node* n,\n    const std::unordered_map>*\n        shape_map,\n    const std::function& consider,\n    int64_t max_constant_size_in_bytes,\n    std::unordered_map>*\n        shape_replacement_map) {\n  if (n->IsConstant()) {\n    // Skip constant folding resources as they cannot be deep copied.\n    return n->output_type(0) != DT_RESOURCE;\n  }\n  if (MaybeReplaceShapeOp(n, shape_map, shape_replacement_map)) {\n    return true;\n  }\n  if (n->op_def().is_stateful()) {\n    return false;\n  }\n  if (consider && !consider(n)) {\n    return false;\n  }\n  if (shape_map != nullptr) {\n    // We can skip the node if an output is known to be oversized.\n    auto shape_it = shape_map->find(n->name());\n    if (shape_it != shape_map->end()) {\n      for (int64_t i = 0; i < shape_it->second.size(); ++i) {\n        const auto& out_shape = shape_it->second[i];\n        if (out_shape.IsFullyDefined() &&\n            out_shape.num_elements() * DataTypeSize(n->output_type(i)) >\n                max_constant_size_in_bytes) {\n          return false;\n        }\n      }\n    }\n  }\n  if (n->IsControlFlow() || n->IsSend() || n->IsRecv()) {\n    return false;\n  }\n  // TODO(yuanbyu): For now disable these session handle operations.\n  if (n->IsGetSessionHandle() || n->IsGetSessionTensor() ||\n      n->IsDeleteSessionTensor()) {\n    return false;\n  }\n  if (n->IsSource()) {\n    return false;\n  }\n  if (n->IsSink()) {\n    return false;\n  }\n  if (n->IsFakeParam()) {\n    return false;\n  }\n  // Since constant-folding runs on the CPU, do not attempt to constant-fold\n  // operators that have no CPU kernel. Also implies that we will not\n  // constant-fold functions.\n  // TODO(phawkins): allow constant-folding for functions; functions may\n  // be arbitrarily expensive to execute.\n  if (!KernelDefAvailable(DeviceType(DEVICE_CPU), n->def())) {\n    return false;\n  }\n  // Do not constant fold nodes which will be allocated by ScopedAllocator.\n  // This is because the constant-folding graph will not contain the\n  // `_ScopedAllocator` node, and that is necessary to be able to run a node\n  // that will use this allocator.\n  if (n->attrs().Find(kScopedAllocatorAttrName) != nullptr) {\n    VLOG(2) << \"Skip node [\" << n->DebugString()\n            << \"] for constant folding due to scoped allocator\";\n    return false;\n  }\n  return true;\n}", "func_hash": 319400414252695019518928506839820495961, "file_name": "constant_folding.cc", "file_hash": 129656680363802690204267718015734305272, "cwe": ["CWE-824"], "cve": "CVE-2021-41204", "cve_desc": "TensorFlow is an open source platform for machine learning. In affected versions during TensorFlow's Grappler optimizer phase, constant folding might attempt to deep copy a resource tensor. This results in a segfault, as these tensors are supposed to not change. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41204"}
{"idx": 197893, "project": "tensorflow", "commit_id": "eb921122119a6b6e470ee98b89e65d721663179d", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/eb921122119a6b6e470ee98b89e65d721663179d", "commit_message": "Prevent heap OOB read in TFLite's `gather.cc`.\n\nPassing negative indices is illegal but there was a missing check so that resulted in OOB accesses.\n\nPiperOrigin-RevId: 387231300\nChange-Id: I3111b54b2f232638d795be17efc46abe4ede6bf8", "target": 1, "func": "TfLiteStatus Gather(const TfLiteGatherParams& params, const TfLiteTensor* input,\n                    const TfLiteTensor* positions, TfLiteTensor* output) {\n  tflite::GatherParams op_params;\n  op_params.axis = params.axis;\n  op_params.batch_dims = params.batch_dims;\n  optimized_ops::Gather(op_params, GetTensorShape(input),\n                        GetTensorData(input), GetTensorShape(positions),\n                        GetTensorData(positions),\n                        GetTensorShape(output), GetTensorData(output));\n  return kTfLiteOk;\n}", "func_hash": 291153190876322119376469189416083053275, "file_name": "gather.cc", "file_hash": 109151045550446368977897795663338855851, "cwe": ["CWE-703"], "cve": "CVE-2021-37687", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions TFLite's [`GatherNd` implementation](https://github.com/tensorflow/tensorflow/blob/149562d49faa709ea80df1d99fc41d005b81082a/tensorflow/lite/kernels/gather_nd.cc#L124) does not support negative indices but there are no checks for this situation. Hence, an attacker can read arbitrary data from the heap by carefully crafting a model with negative values in `indices`. Similar issue exists in [`Gather` implementation](https://github.com/tensorflow/tensorflow/blob/149562d49faa709ea80df1d99fc41d005b81082a/tensorflow/lite/kernels/gather.cc). We have patched the issue in GitHub commits bb6a0383ed553c286f87ca88c207f6774d5c4a8f and eb921122119a6b6e470ee98b89e65d721663179d. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37687"}
{"idx": 265432, "project": "tensorflow", "commit_id": "eb921122119a6b6e470ee98b89e65d721663179d", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/eb921122119a6b6e470ee98b89e65d721663179d", "commit_message": "Prevent heap OOB read in TFLite's `gather.cc`.\n\nPassing negative indices is illegal but there was a missing check so that resulted in OOB accesses.\n\nPiperOrigin-RevId: 387231300\nChange-Id: I3111b54b2f232638d795be17efc46abe4ede6bf8", "target": 0, "func": "TfLiteStatus Gather(TfLiteContext* context, const TfLiteGatherParams& params,\n                    const TfLiteTensor* input, const TfLiteTensor* positions,\n                    TfLiteTensor* output) {\n  const PositionsT* indexes = GetTensorData(positions);\n  bool indices_has_only_positive_elements = true;\n  const size_t num_indices = positions->bytes / sizeof(PositionsT);\n  for (size_t i = 0; i < num_indices; i++) {\n    if (indexes[i] < 0) {\n      indices_has_only_positive_elements = false;\n      break;\n    }\n  }\n  TF_LITE_ENSURE(context, indices_has_only_positive_elements);\n\n  tflite::GatherParams op_params;\n  op_params.axis = params.axis;\n  op_params.batch_dims = params.batch_dims;\n  optimized_ops::Gather(op_params, GetTensorShape(input),\n                        GetTensorData(input), GetTensorShape(positions),\n                        GetTensorData(positions),\n                        GetTensorShape(output), GetTensorData(output));\n  return kTfLiteOk;\n}", "func_hash": 50062335077271405437756025482165294383, "file_name": "gather.cc", "file_hash": 61671770353303657730185852955159982272, "cwe": ["CWE-703"], "cve": "CVE-2021-37687", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions TFLite's [`GatherNd` implementation](https://github.com/tensorflow/tensorflow/blob/149562d49faa709ea80df1d99fc41d005b81082a/tensorflow/lite/kernels/gather_nd.cc#L124) does not support negative indices but there are no checks for this situation. Hence, an attacker can read arbitrary data from the heap by carefully crafting a model with negative values in `indices`. Similar issue exists in [`Gather` implementation](https://github.com/tensorflow/tensorflow/blob/149562d49faa709ea80df1d99fc41d005b81082a/tensorflow/lite/kernels/gather.cc). We have patched the issue in GitHub commits bb6a0383ed553c286f87ca88c207f6774d5c4a8f and eb921122119a6b6e470ee98b89e65d721663179d. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37687"}
{"idx": 197973, "project": "crun", "commit_id": "1aeeed2e4fdeffb4875c0d0b439915894594c8c6", "project_url": "https://github.com/containers/crun", "commit_url": "https://github.com/containers/crun/commit/1aeeed2e4fdeffb4875c0d0b439915894594c8c6", "commit_message": "exec: --cap do not set inheritable capabilities\n\nCloses: CVE-2022-27650\n\nSigned-off-by: Giuseppe Scrivano ", "target": 1, "func": "crun_command_exec (struct crun_global_arguments *global_args, int argc, char **argv, libcrun_error_t *err)\n{\n  int first_arg = 0, ret = 0;\n  libcrun_context_t crun_context = {\n    0,\n  };\n  cleanup_process_schema runtime_spec_schema_config_schema_process *process = NULL;\n  struct libcrun_container_exec_options_s exec_opts;\n\n  memset (&exec_opts, 0, sizeof (exec_opts));\n  exec_opts.struct_size = sizeof (exec_opts);\n\n  crun_context.preserve_fds = 0;\n  crun_context.listen_fds = 0;\n\n  argp_parse (&run_argp, argc, argv, ARGP_IN_ORDER, &first_arg, &exec_options);\n  crun_assert_n_args (argc - first_arg, exec_options.process ? 1 : 2, -1);\n\n  ret = init_libcrun_context (&crun_context, argv[first_arg], global_args, err);\n  if (UNLIKELY (ret < 0))\n    return ret;\n\n  crun_context.detach = exec_options.detach;\n  crun_context.console_socket = exec_options.console_socket;\n  crun_context.pid_file = exec_options.pid_file;\n  crun_context.preserve_fds = exec_options.preserve_fds;\n\n  if (getenv (\"LISTEN_FDS\"))\n    {\n      crun_context.listen_fds = strtoll (getenv (\"LISTEN_FDS\"), NULL, 10);\n      crun_context.preserve_fds += crun_context.listen_fds;\n    }\n\n  if (exec_options.process)\n    exec_opts.path = exec_options.process;\n  else\n    {\n      process = xmalloc0 (sizeof (*process));\n      int i;\n\n      process->args_len = argc;\n      process->args = xmalloc0 ((argc + 1) * sizeof (*process->args));\n      for (i = 0; i < argc - first_arg; i++)\n        process->args[i] = xstrdup (argv[first_arg + i + 1]);\n      process->args[i] = NULL;\n      if (exec_options.cwd)\n        process->cwd = exec_options.cwd;\n      process->terminal = exec_options.tty;\n      process->env = exec_options.env;\n      process->env_len = exec_options.env_size;\n      process->user = make_oci_process_user (exec_options.user);\n\n      if (exec_options.process_label != NULL)\n        process->selinux_label = exec_options.process_label;\n\n      if (exec_options.apparmor != NULL)\n        process->apparmor_profile = exec_options.apparmor;\n\n      if (exec_options.cap_size > 0)\n        {\n          runtime_spec_schema_config_schema_process_capabilities *capabilities\n              = xmalloc (sizeof (runtime_spec_schema_config_schema_process_capabilities));\n\n          capabilities->effective = exec_options.cap;\n          capabilities->effective_len = exec_options.cap_size;\n\n          capabilities->inheritable = dup_array (exec_options.cap, exec_options.cap_size);\n          capabilities->inheritable_len = exec_options.cap_size;\n\n          capabilities->bounding = dup_array (exec_options.cap, exec_options.cap_size);\n          capabilities->bounding_len = exec_options.cap_size;\n\n          capabilities->ambient = dup_array (exec_options.cap, exec_options.cap_size);\n          capabilities->ambient_len = exec_options.cap_size;\n\n          capabilities->permitted = dup_array (exec_options.cap, exec_options.cap_size);\n          capabilities->permitted_len = exec_options.cap_size;\n\n          process->capabilities = capabilities;\n        }\n\n      // noNewPriviledges will remain `false` if basespec has `false` unless specified\n      // Default is always `true` in generated basespec config\n      if (exec_options.no_new_privs)\n        process->no_new_privileges = 1;\n\n      exec_opts.process = process;\n    }\n\n  exec_opts.cgroup = exec_options.cgroup;\n\n  return libcrun_container_exec_with_options (&crun_context, argv[first_arg], &exec_opts, err);\n}", "func_hash": 202081994104919800529457023385761628896, "file_name": "exec.c", "file_hash": 10128723194506737000766570571290960247, "cwe": ["CWE-276"], "cve": "CVE-2022-27650", "cve_desc": "A flaw was found in crun where containers were incorrectly started with non-empty default permissions. A vulnerability was found in Moby (Docker Engine) where containers were started incorrectly with non-empty inheritable Linux process capabilities. This flaw allows an attacker with access to programs with inheritable file capabilities to elevate those capabilities to the permitted set when execve(2) runs.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27650"}
{"idx": 267357, "project": "crun", "commit_id": "1aeeed2e4fdeffb4875c0d0b439915894594c8c6", "project_url": "https://github.com/containers/crun", "commit_url": "https://github.com/containers/crun/commit/1aeeed2e4fdeffb4875c0d0b439915894594c8c6", "commit_message": "exec: --cap do not set inheritable capabilities\n\nCloses: CVE-2022-27650\n\nSigned-off-by: Giuseppe Scrivano ", "target": 0, "func": "crun_command_exec (struct crun_global_arguments *global_args, int argc, char **argv, libcrun_error_t *err)\n{\n  int first_arg = 0, ret = 0;\n  libcrun_context_t crun_context = {\n    0,\n  };\n  cleanup_process_schema runtime_spec_schema_config_schema_process *process = NULL;\n  struct libcrun_container_exec_options_s exec_opts;\n\n  memset (&exec_opts, 0, sizeof (exec_opts));\n  exec_opts.struct_size = sizeof (exec_opts);\n\n  crun_context.preserve_fds = 0;\n  crun_context.listen_fds = 0;\n\n  argp_parse (&run_argp, argc, argv, ARGP_IN_ORDER, &first_arg, &exec_options);\n  crun_assert_n_args (argc - first_arg, exec_options.process ? 1 : 2, -1);\n\n  ret = init_libcrun_context (&crun_context, argv[first_arg], global_args, err);\n  if (UNLIKELY (ret < 0))\n    return ret;\n\n  crun_context.detach = exec_options.detach;\n  crun_context.console_socket = exec_options.console_socket;\n  crun_context.pid_file = exec_options.pid_file;\n  crun_context.preserve_fds = exec_options.preserve_fds;\n\n  if (getenv (\"LISTEN_FDS\"))\n    {\n      crun_context.listen_fds = strtoll (getenv (\"LISTEN_FDS\"), NULL, 10);\n      crun_context.preserve_fds += crun_context.listen_fds;\n    }\n\n  if (exec_options.process)\n    exec_opts.path = exec_options.process;\n  else\n    {\n      process = xmalloc0 (sizeof (*process));\n      int i;\n\n      process->args_len = argc;\n      process->args = xmalloc0 ((argc + 1) * sizeof (*process->args));\n      for (i = 0; i < argc - first_arg; i++)\n        process->args[i] = xstrdup (argv[first_arg + i + 1]);\n      process->args[i] = NULL;\n      if (exec_options.cwd)\n        process->cwd = exec_options.cwd;\n      process->terminal = exec_options.tty;\n      process->env = exec_options.env;\n      process->env_len = exec_options.env_size;\n      process->user = make_oci_process_user (exec_options.user);\n\n      if (exec_options.process_label != NULL)\n        process->selinux_label = exec_options.process_label;\n\n      if (exec_options.apparmor != NULL)\n        process->apparmor_profile = exec_options.apparmor;\n\n      if (exec_options.cap_size > 0)\n        {\n          runtime_spec_schema_config_schema_process_capabilities *capabilities\n              = xmalloc (sizeof (runtime_spec_schema_config_schema_process_capabilities));\n\n          capabilities->effective = exec_options.cap;\n          capabilities->effective_len = exec_options.cap_size;\n\n          capabilities->inheritable = NULL;\n          capabilities->inheritable_len = 0;\n\n          capabilities->bounding = dup_array (exec_options.cap, exec_options.cap_size);\n          capabilities->bounding_len = exec_options.cap_size;\n\n          capabilities->ambient = dup_array (exec_options.cap, exec_options.cap_size);\n          capabilities->ambient_len = exec_options.cap_size;\n\n          capabilities->permitted = dup_array (exec_options.cap, exec_options.cap_size);\n          capabilities->permitted_len = exec_options.cap_size;\n\n          process->capabilities = capabilities;\n        }\n\n      // noNewPriviledges will remain `false` if basespec has `false` unless specified\n      // Default is always `true` in generated basespec config\n      if (exec_options.no_new_privs)\n        process->no_new_privileges = 1;\n\n      exec_opts.process = process;\n    }\n\n  exec_opts.cgroup = exec_options.cgroup;\n\n  return libcrun_container_exec_with_options (&crun_context, argv[first_arg], &exec_opts, err);\n}", "func_hash": 122856137879373398526993920566215406776, "file_name": "exec.c", "file_hash": 213004123111430302918491742718325619465, "cwe": ["CWE-276"], "cve": "CVE-2022-27650", "cve_desc": "A flaw was found in crun where containers were incorrectly started with non-empty default permissions. A vulnerability was found in Moby (Docker Engine) where containers were started incorrectly with non-empty inheritable Linux process capabilities. This flaw allows an attacker with access to programs with inheritable file capabilities to elevate those capabilities to the permitted set when execve(2) runs.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27650"}
{"idx": 197998, "project": "tensorflow", "commit_id": "704866eabe03a9aeda044ec91a8d0c83fc1ebdbe", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/704866eabe03a9aeda044ec91a8d0c83fc1ebdbe", "commit_message": "Fix overflow CHECK issue with `tf.raw_ops.UnsortedSegmentJoin`.\n\nPiperOrigin-RevId: 370766155\nChange-Id: I33e7c6626224e1060a8a4ab51ad5d861c6d4c63e", "target": 1, "func": "  void Compute(OpKernelContext* context) override {\n    const Tensor& input = context->input(0);\n    const TensorShape& input_shape = input.shape();\n    const int32 input_dims = input_shape.dims();\n\n    const Tensor& segment_id = context->input(1);\n    const TensorShape& segment_id_shape = segment_id.shape();\n    const int32 segment_dims = segment_id_shape.dims();\n\n    const Tensor& num_segments_tensor = context->input(2);\n    auto num_segments = num_segments_tensor.scalar()();\n\n    OP_REQUIRES(context, segment_dims != 0,\n                errors::InvalidArgument(\"Segment_id cannot have rank 0\"));\n\n    OP_REQUIRES(\n        context, segment_dims <= input_dims,\n        errors::OutOfRange(\"Invalid segment_id rank \", segment_dims,\n                           \" for input with \", input_dims, \" dimension(s)\"));\n    for (auto i = 0; i < segment_dims; i++) {\n      OP_REQUIRES(\n          context, segment_id_shape.dim_size(i) == input_shape.dim_size(i),\n          errors::InvalidArgument(\n              \"Segment dimension is \", segment_id_shape.dim_size(i),\n              \" while input dimension is \", input_dims, \" in rank \", i));\n    }\n\n    // Making output tensor.\n    Tensor* output_tensor = nullptr;\n    TensorShape output_shape =\n        GetOutputShape(input_shape, segment_id_shape, num_segments);\n    OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n                                                     &output_tensor));\n\n    // Preparating flat tensors.\n    auto output_flat = output_tensor->flat();\n    auto flat_segment_id = segment_id.flat();\n    auto flat_input = input.flat();\n\n    for (int i = 0; i < flat_segment_id.size(); i++) {\n      OP_REQUIRES(\n          context,\n          ((flat_segment_id(i) < num_segments) && (flat_segment_id(i) >= 0)),\n          errors::InvalidArgument(\n              \"segment_ids are not allowed to exceed num_segments or\"\n              \" to have negative values.\"));\n    }\n\n    int64 big_stride;\n    int64 small_stride;\n    std::tie(big_stride, small_stride) =\n        GetStrides(input_shape, segment_id_shape);\n    auto relative_offset_set =\n        GetFlattenedRelativeOffsets(small_stride, big_stride);\n    for (auto start_offset = 0; start_offset < big_stride; start_offset++) {\n      for (auto i = 0; i < relative_offset_set.size(); i++) {\n        auto output_index = start_offset + flat_segment_id(i) * big_stride;\n        auto offset = start_offset + relative_offset_set[i];\n        if (output_flat(output_index).length() != 0)\n          output_flat(output_index).append(separator_.c_str());\n        output_flat(output_index).append(flat_input(offset));\n      }\n    }\n  }", "func_hash": 25791049116451232925309470165962173994, "file_name": "unsorted_segment_join_op.cc", "file_hash": 172265001795447375510451213673230640731, "cwe": ["CWE-703"], "cve": "CVE-2021-29552", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a denial of service by controlling the values of `num_segments` tensor argument for `UnsortedSegmentJoin`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/a2a607db15c7cd01d754d37e5448d72a13491bdb/tensorflow/core/kernels/unsorted_segment_join_op.cc#L92-L93) assumes that the `num_segments` tensor is a valid scalar. Since the tensor is empty the `CHECK` involved in `.scalar()()` that checks that the number of elements is exactly 1 will be invalidated and this would result in process termination. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29552"}
{"idx": 267917, "project": "tensorflow", "commit_id": "704866eabe03a9aeda044ec91a8d0c83fc1ebdbe", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/704866eabe03a9aeda044ec91a8d0c83fc1ebdbe", "commit_message": "Fix overflow CHECK issue with `tf.raw_ops.UnsortedSegmentJoin`.\n\nPiperOrigin-RevId: 370766155\nChange-Id: I33e7c6626224e1060a8a4ab51ad5d861c6d4c63e", "target": 0, "func": "  void Compute(OpKernelContext* context) override {\n    const Tensor& input = context->input(0);\n    const TensorShape& input_shape = input.shape();\n    const int32 input_dims = input_shape.dims();\n\n    const Tensor& segment_id = context->input(1);\n    const TensorShape& segment_id_shape = segment_id.shape();\n    const int32 segment_dims = segment_id_shape.dims();\n\n    const Tensor& num_segments_tensor = context->input(2);\n    OP_REQUIRES(context, num_segments_tensor.NumElements() != 0,\n                errors::InvalidArgument(\"Number of segments cannot be empty.\"));\n    auto num_segments = num_segments_tensor.scalar()();\n\n    OP_REQUIRES(context, segment_dims != 0,\n                errors::InvalidArgument(\"Segment_id cannot have rank 0\"));\n\n    OP_REQUIRES(\n        context, segment_dims <= input_dims,\n        errors::OutOfRange(\"Invalid segment_id rank \", segment_dims,\n                           \" for input with \", input_dims, \" dimension(s)\"));\n    for (auto i = 0; i < segment_dims; i++) {\n      OP_REQUIRES(\n          context, segment_id_shape.dim_size(i) == input_shape.dim_size(i),\n          errors::InvalidArgument(\n              \"Segment dimension is \", segment_id_shape.dim_size(i),\n              \" while input dimension is \", input_dims, \" in rank \", i));\n    }\n\n    // Making output tensor.\n    Tensor* output_tensor = nullptr;\n    TensorShape output_shape =\n        GetOutputShape(input_shape, segment_id_shape, num_segments);\n    OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n                                                     &output_tensor));\n\n    // Preparating flat tensors.\n    auto output_flat = output_tensor->flat();\n    auto flat_segment_id = segment_id.flat();\n    auto flat_input = input.flat();\n\n    for (int i = 0; i < flat_segment_id.size(); i++) {\n      OP_REQUIRES(\n          context,\n          ((flat_segment_id(i) < num_segments) && (flat_segment_id(i) >= 0)),\n          errors::InvalidArgument(\n              \"segment_ids are not allowed to exceed num_segments or\"\n              \" to have negative values.\"));\n    }\n\n    int64 big_stride;\n    int64 small_stride;\n    std::tie(big_stride, small_stride) =\n        GetStrides(input_shape, segment_id_shape);\n    auto relative_offset_set =\n        GetFlattenedRelativeOffsets(small_stride, big_stride);\n    for (auto start_offset = 0; start_offset < big_stride; start_offset++) {\n      for (auto i = 0; i < relative_offset_set.size(); i++) {\n        auto output_index = start_offset + flat_segment_id(i) * big_stride;\n        auto offset = start_offset + relative_offset_set[i];\n        if (output_flat(output_index).length() != 0)\n          output_flat(output_index).append(separator_.c_str());\n        output_flat(output_index).append(flat_input(offset));\n      }\n    }\n  }", "func_hash": 121381278306100727199108934923052625999, "file_name": "unsorted_segment_join_op.cc", "file_hash": 154318946168889826410916454566893664101, "cwe": ["CWE-703"], "cve": "CVE-2021-29552", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. An attacker can cause a denial of service by controlling the values of `num_segments` tensor argument for `UnsortedSegmentJoin`. This is because the implementation(https://github.com/tensorflow/tensorflow/blob/a2a607db15c7cd01d754d37e5448d72a13491bdb/tensorflow/core/kernels/unsorted_segment_join_op.cc#L92-L93) assumes that the `num_segments` tensor is a valid scalar. Since the tensor is empty the `CHECK` involved in `.scalar()()` that checks that the number of elements is exactly 1 will be invalidated and this would result in process termination. The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29552"}
{"idx": 198010, "project": "radare2", "commit_id": "193f4fe01d7f626e2ea937450f2e0c4604420e9d", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/193f4fe01d7f626e2ea937450f2e0c4604420e9d", "commit_message": "Fix integer overflow in string search causing oobread ##crash\n\n* Reported by @greatergoodest via huntrdev\n* BountyID: 8a3dc5cb-08b3-4807-82b2-77f08c137a04\n* Reproducer bfileovf", "target": 1, "func": "static int string_scan_range(RList *list, RBinFile *bf, int min,\n\t\t\t      const ut64 from, const ut64 to, int type, int raw, RBinSection *section) {\n\tRBin *bin = bf->rbin;\n\tut8 tmp[R_STRING_SCAN_BUFFER_SIZE];\n\tut64 str_start, needle = from;\n\tint count = 0, i, rc, runes;\n\tint str_type = R_STRING_TYPE_DETECT;\n\n\t// if list is null it means its gonna dump\n\tr_return_val_if_fail (bf, -1);\n\n\tif (type == -1) {\n\t\ttype = R_STRING_TYPE_DETECT;\n\t}\n\tif (from == to) {\n\t\treturn 0;\n\t}\n\tif (from > to) {\n\t\teprintf (\"Invalid range to find strings 0x%\"PFMT64x\" .. 0x%\"PFMT64x\"\\n\", from, to);\n\t\treturn -1;\n\t}\n\tst64 len = (st64)(to - from);\n\tif (len < 1 || len > ST32_MAX) {\n\t\teprintf (\"String scan range is invalid (%\"PFMT64d\" bytes)\\n\", len);\n\t\treturn -1;\n\t}\n\tut8 *buf = calloc (len, 1);\n\tif (!buf || !min) {\n\t\tfree (buf);\n\t\treturn -1;\n\t}\n\tst64 vdelta = 0, pdelta = 0;\n\tRBinSection *s = NULL;\n\tbool ascii_only = false;\n\tPJ *pj = NULL;\n\tif (bf->strmode == R_MODE_JSON && !list) {\n\t\tpj = pj_new ();\n\t\tif (pj) {\n\t\t\tpj_a (pj);\n\t\t}\n\t}\n\tr_buf_read_at (bf->buf, from, buf, len);\n\tchar *charset = r_sys_getenv (\"RABIN2_CHARSET\");\n\tif (!R_STR_ISEMPTY (charset)) {\n\t\tRCharset *ch = r_charset_new ();\n\t\tif (r_charset_use (ch, charset)) {\n\t\t\tint outlen = len * 4;\n\t\t\tut8 *out = calloc (len, 4);\n\t\t\tif (out) {\n\t\t\t\tint res = r_charset_encode_str (ch, out, outlen, buf, len);\n\t\t\t\tint i;\n\t\t\t\t// TODO unknown chars should be translated to null bytes\n\t\t\t\tfor (i = 0; i < res; i++) {\n\t\t\t\t\tif (out[i] == '?') {\n\t\t\t\t\t\tout[i] = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlen = res;\n\t\t\t\tfree (buf);\n\t\t\t\tbuf = out;\n\t\t\t} else {\n\t\t\t\teprintf (\"Cannot allocate\\n\");\n\t\t\t}\n\t\t} else {\n\t\t\teprintf (\"Invalid value for RABIN2_CHARSET.\\n\");\n\t\t}\n\t\tr_charset_free (ch);\n\t}\n\tfree (charset);\n\tRConsIsBreaked is_breaked = (bin && bin->consb.is_breaked)? bin->consb.is_breaked: NULL;\n\t// may oobread\n\twhile (needle < to) {\n\t\tif (is_breaked && is_breaked ()) {\n\t\t\tbreak;\n\t\t}\n\t\t// smol optimization\n\t\tif (needle + 4 < to) {\n\t\t\tut32 n1 = r_read_le32 (buf + needle - from);\n\t\t\tif (!n1) {\n\t\t\t\tneedle += 4;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\trc = r_utf8_decode (buf + needle - from, to - needle, NULL);\n\t\tif (!rc) {\n\t\t\tneedle++;\n\t\t\tcontinue;\n\t\t}\n\t\tbool addr_aligned = !(needle % 4);\n\n\t\tif (type == R_STRING_TYPE_DETECT) {\n\t\t\tchar *w = (char *)buf + needle + rc - from;\n\t\t\tif (((to - needle) > 8 + rc)) {\n\t\t\t\t// TODO: support le and be\n\t\t\t\tbool is_wide32le = (needle + rc + 2 < to) && (!w[0] && !w[1] && !w[2] && w[3] && !w[4]);\n\t\t\t\t// reduce false positives\n\t\t\t\tif (is_wide32le) {\n\t\t\t\t\tif (!w[5] && !w[6] && w[7] && w[8]) {\n\t\t\t\t\t\tis_wide32le = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!addr_aligned) {\n\t\t\t\t\tis_wide32le = false;\n\t\t\t\t}\n\t\t\t\t///is_wide32be &= (n1 < 0xff && n11 < 0xff); // false; // n11 < 0xff;\n\t\t\t\tif (is_wide32le  && addr_aligned) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_WIDE32; // asume big endian,is there little endian w32?\n\t\t\t\t} else {\n\t\t\t\t\t// bool is_wide = (n1 && n2 && n1 < 0xff && (!n2 || n2 < 0xff));\n\t\t\t\t\tbool is_wide = needle + rc + 4 < to && !w[0] && w[1] && !w[2] && w[3] && !w[4];\n\t\t\t\t\tstr_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (rc > 1) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_UTF8; // could be charset if set :?\n\t\t\t\t} else {\n\t\t\t\t\tstr_type = R_STRING_TYPE_ASCII;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (type == R_STRING_TYPE_UTF8) {\n\t\t\tstr_type = R_STRING_TYPE_ASCII; // initial assumption\n\t\t} else {\n\t\t\tstr_type = type;\n\t\t}\n\t\trunes = 0;\n\t\tstr_start = needle;\n\n\t\t/* Eat a whole C string */\n\t\tfor (i = 0; i < sizeof (tmp) - 4 && needle < to; i += rc) {\n\t\t\tRRune r = {0};\n\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\trc = r_utf32le_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc) {\n\t\t\t\t\trc = 4;\n\t\t\t\t}\n\t\t\t} else if (str_type == R_STRING_TYPE_WIDE) {\n\t\t\t\trc = r_utf16le_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc == 1) {\n\t\t\t\t\trc = 2;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trc = r_utf8_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc > 1) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_UTF8;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Invalid sequence detected */\n\t\t\tif (!rc || (ascii_only && r > 0x7f)) {\n\t\t\t\tneedle++;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tneedle += rc;\n\n\t\t\tif (r_isprint (r) && r != '\\\\') {\n\t\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\t\tif (r == 0xff) {\n\t\t\t\t\t\tr = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trc = r_utf8_encode (tmp + i, r);\n\t\t\t\trunes++;\n\t\t\t\t/* Print the escape code */\n\t\t\t} else if (r && r < 0x100 && strchr (\"\\b\\v\\f\\n\\r\\t\\a\\033\\\\\", (char)r)) {\n\t\t\t\tif ((i + 32) < sizeof (tmp) && r < 93) {\n\t\t\t\t\ttmp[i + 0] = '\\\\';\n\t\t\t\t\ttmp[i + 1] = \"       abtnvfr             e  \"\n\t\t\t\t\t             \"                              \"\n\t\t\t\t\t             \"                              \"\n\t\t\t\t\t             \"  \\\\\"[r];\n\t\t\t\t} else {\n\t\t\t\t\t// string too long\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\trc = 2;\n\t\t\t\trunes++;\n\t\t\t} else {\n\t\t\t\t/* \\0 marks the end of C-strings */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\ttmp[i++] = '\\0';\n\n\t\tif (runes < min && runes >= 2 && str_type == R_STRING_TYPE_ASCII && needle < to) {\n\t\t\t// back up past the \\0 to the last char just in case it starts a wide string\n\t\t\tneedle -= 2;\n\t\t}\n\t\tif (runes >= min) {\n\t\t\t// reduce false positives\n\t\t\tint j, num_blocks, *block_list;\n\t\t\tint *freq_list = NULL, expected_ascii, actual_ascii, num_chars;\n\t\t\tif (str_type == R_STRING_TYPE_ASCII) {\n\t\t\t\tfor (j = 0; j < i; j++) {\n\t\t\t\t\tchar ch = tmp[j];\n\t\t\t\t\tif (ch != '\\n' && ch != '\\r' && ch != '\\t') {\n\t\t\t\t\t\tif (!IS_PRINTABLE (tmp[j])) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch (str_type) {\n\t\t\tcase R_STRING_TYPE_UTF8:\n\t\t\tcase R_STRING_TYPE_WIDE:\n\t\t\tcase R_STRING_TYPE_WIDE32:\n\t\t\t\tnum_blocks = 0;\n\t\t\t\tblock_list = r_utf_block_list ((const ut8*)tmp, i - 1,\n\t\t\t\t\t\tstr_type == R_STRING_TYPE_WIDE? &freq_list: NULL);\n\t\t\t\tif (block_list) {\n\t\t\t\t\tfor (j = 0; block_list[j] != -1; j++) {\n\t\t\t\t\t\tnum_blocks++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (freq_list) {\n\t\t\t\t\tnum_chars = 0;\n\t\t\t\t\tactual_ascii = 0;\n\t\t\t\t\tfor (j = 0; freq_list[j] != -1; j++) {\n\t\t\t\t\t\tnum_chars += freq_list[j];\n\t\t\t\t\t\tif (!block_list[j]) { // ASCII\n\t\t\t\t\t\t\tactual_ascii = freq_list[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfree (freq_list);\n\t\t\t\t\texpected_ascii = num_blocks ? num_chars / num_blocks : 0;\n\t\t\t\t\tif (actual_ascii > expected_ascii) {\n\t\t\t\t\t\tascii_only = true;\n\t\t\t\t\t\tneedle = str_start;\n\t\t\t\t\t\tfree (block_list);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfree (block_list);\n\t\t\t\tif (num_blocks > R_STRING_MAX_UNI_BLOCKS) {\n\t\t\t\t\tneedle++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tRBinString *bs = R_NEW0 (RBinString);\n\t\t\tif (!bs) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbs->type = str_type;\n\t\t\tbs->length = runes;\n\t\t\tbs->size = needle - str_start;\n\t\t\tbs->ordinal = count++;\n\t\t\t// TODO: move into adjust_offset\n\t\t\tswitch (str_type) {\n\t\t\tcase R_STRING_TYPE_WIDE:\n\t\t\t\tif (str_start - from > 1) {\n\t\t\t\t\tconst ut8 *p = buf + str_start - 2 - from;\n\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\tstr_start -= 2; // \\xff\\xfe\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase R_STRING_TYPE_WIDE32:\n\t\t\t\tif (str_start - from > 3) {\n\t\t\t\t\tconst ut8 *p = buf + str_start - 4 - from;\n\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\tstr_start -= 4; // \\xff\\xfe\\x00\\x00\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!s) {\n\t\t\t\tif (section) {\n\t\t\t\t\ts = section;\n\t\t\t\t} else if (bf->o) {\n\t\t\t\t\ts = r_bin_get_section_at (bf->o, str_start, false);\n\t\t\t\t}\n\t\t\t\tif (s) {\n\t\t\t\t\tvdelta = s->vaddr;\n\t\t\t\t\tpdelta = s->paddr;\n\t\t\t\t}\n\t\t\t}\n\t\t\tut64 baddr = bf->loadaddr && bf->o? bf->o->baddr: bf->loadaddr;\n\t\t\tbs->paddr = str_start + baddr;\n\t\t\tbs->vaddr = str_start - pdelta + vdelta + baddr;\n\t\t\tbs->string = r_str_ndup ((const char *)tmp, i);\n\t\t\tif (list) {\n\t\t\t\tr_list_append (list, bs);\n\t\t\t\tif (bf->o) {\n\t\t\t\t\tht_up_insert (bf->o->strings_db, bs->vaddr, bs);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tprint_string (bf, bs, raw, pj);\n\t\t\t\tr_bin_string_free (bs);\n\t\t\t}\n\t\t\tif (from == 0 && to == bf->size) {\n\t\t\t\t/* force lookup section at the next one */\n\t\t\t\ts = NULL;\n\t\t\t}\n\t\t}\n\t\tascii_only = false;\n\t}\n\tfree (buf);\n\tif (pj) {\n\t\tpj_end (pj);\n\t\tif (bin) {\n\t\t\tRIO *io = bin->iob.io;\n\t\t\tif (io) {\n\t\t\t\tio->cb_printf (\"%s\", pj_string (pj));\n\t\t\t}\n\t\t}\n\t\tpj_free (pj);\n\t}\n\treturn count;\n}", "func_hash": 327958810043229005935201535284879314576, "file_name": "bfile.c", "file_hash": 285505404053025817812791776020239027950, "cwe": ["CWE-125"], "cve": "CVE-2022-1899", "cve_desc": "Out-of-bounds Read in GitHub repository radareorg/radare2 prior to 5.7.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1899"}
{"idx": 267985, "project": "radare2", "commit_id": "193f4fe01d7f626e2ea937450f2e0c4604420e9d", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/193f4fe01d7f626e2ea937450f2e0c4604420e9d", "commit_message": "Fix integer overflow in string search causing oobread ##crash\n\n* Reported by @greatergoodest via huntrdev\n* BountyID: 8a3dc5cb-08b3-4807-82b2-77f08c137a04\n* Reproducer bfileovf", "target": 0, "func": "static int string_scan_range(RList *list, RBinFile *bf, int min,\n\t\t\t      const ut64 from, const ut64 to, int type, int raw, RBinSection *section) {\n\tRBin *bin = bf->rbin;\n\tut8 tmp[R_STRING_SCAN_BUFFER_SIZE];\n\tut64 str_start, needle = from;\n\tint count = 0, i, rc, runes;\n\tint str_type = R_STRING_TYPE_DETECT;\n\n\t// if list is null it means its gonna dump\n\tr_return_val_if_fail (bf, -1);\n\n\tif (type == -1) {\n\t\ttype = R_STRING_TYPE_DETECT;\n\t}\n\tif (from == to) {\n\t\treturn 0;\n\t}\n\tif (from > to) {\n\t\teprintf (\"Invalid range to find strings 0x%\"PFMT64x\" .. 0x%\"PFMT64x\"\\n\", from, to);\n\t\treturn -1;\n\t}\n\tst64 len = (st64)(to - from);\n\tif (len < 1 || len > ST32_MAX) {\n\t\teprintf (\"String scan range is invalid (%\"PFMT64d\" bytes)\\n\", len);\n\t\treturn -1;\n\t}\n\tut8 *buf = calloc (len, 1);\n\tif (!buf || !min) {\n\t\tfree (buf);\n\t\treturn -1;\n\t}\n\tst64 vdelta = 0, pdelta = 0;\n\tRBinSection *s = NULL;\n\tbool ascii_only = false;\n\tPJ *pj = NULL;\n\tif (bf->strmode == R_MODE_JSON && !list) {\n\t\tpj = pj_new ();\n\t\tif (pj) {\n\t\t\tpj_a (pj);\n\t\t}\n\t}\n\tr_buf_read_at (bf->buf, from, buf, len);\n\tchar *charset = r_sys_getenv (\"RABIN2_CHARSET\");\n\tif (!R_STR_ISEMPTY (charset)) {\n\t\tRCharset *ch = r_charset_new ();\n\t\tif (r_charset_use (ch, charset)) {\n\t\t\tint outlen = len * 4;\n\t\t\tut8 *out = calloc (len, 4);\n\t\t\tif (out) {\n\t\t\t\tint res = r_charset_encode_str (ch, out, outlen, buf, len);\n\t\t\t\tint i;\n\t\t\t\t// TODO unknown chars should be translated to null bytes\n\t\t\t\tfor (i = 0; i < res; i++) {\n\t\t\t\t\tif (out[i] == '?') {\n\t\t\t\t\t\tout[i] = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlen = res;\n\t\t\t\tfree (buf);\n\t\t\t\tbuf = out;\n\t\t\t} else {\n\t\t\t\teprintf (\"Cannot allocate\\n\");\n\t\t\t}\n\t\t} else {\n\t\t\teprintf (\"Invalid value for RABIN2_CHARSET.\\n\");\n\t\t}\n\t\tr_charset_free (ch);\n\t}\n\tfree (charset);\n\tRConsIsBreaked is_breaked = (bin && bin->consb.is_breaked)? bin->consb.is_breaked: NULL;\n\t// may oobread\n\twhile (needle < to && needle < UT64_MAX - 4) {\n\t\tif (is_breaked && is_breaked ()) {\n\t\t\tbreak;\n\t\t}\n\t\t// smol optimization\n\t\tif (needle < to - 4) {\n\t\t\tut32 n1 = r_read_le32 (buf + (needle - from));\n\t\t\tif (!n1) {\n\t\t\t\tneedle += 4;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\trc = r_utf8_decode (buf + (needle - from), to - needle, NULL);\n\t\tif (!rc) {\n\t\t\tneedle++;\n\t\t\tcontinue;\n\t\t}\n\t\tbool addr_aligned = !(needle % 4);\n\n\t\tif (type == R_STRING_TYPE_DETECT) {\n\t\t\tchar *w = (char *)buf + (needle + rc - from);\n\t\t\tif (((to - needle) > 8 + rc)) {\n\t\t\t\t// TODO: support le and be\n\t\t\t\tbool is_wide32le = (needle + rc + 2 < to) && (!w[0] && !w[1] && !w[2] && w[3] && !w[4]);\n\t\t\t\t// reduce false positives\n\t\t\t\tif (is_wide32le) {\n\t\t\t\t\tif (!w[5] && !w[6] && w[7] && w[8]) {\n\t\t\t\t\t\tis_wide32le = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!addr_aligned) {\n\t\t\t\t\tis_wide32le = false;\n\t\t\t\t}\n\t\t\t\t///is_wide32be &= (n1 < 0xff && n11 < 0xff); // false; // n11 < 0xff;\n\t\t\t\tif (is_wide32le  && addr_aligned) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_WIDE32; // asume big endian,is there little endian w32?\n\t\t\t\t} else {\n\t\t\t\t\t// bool is_wide = (n1 && n2 && n1 < 0xff && (!n2 || n2 < 0xff));\n\t\t\t\t\tbool is_wide = needle + rc + 4 < to && !w[0] && w[1] && !w[2] && w[3] && !w[4];\n\t\t\t\t\tstr_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (rc > 1) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_UTF8; // could be charset if set :?\n\t\t\t\t} else {\n\t\t\t\t\tstr_type = R_STRING_TYPE_ASCII;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (type == R_STRING_TYPE_UTF8) {\n\t\t\tstr_type = R_STRING_TYPE_ASCII; // initial assumption\n\t\t} else {\n\t\t\tstr_type = type;\n\t\t}\n\t\trunes = 0;\n\t\tstr_start = needle;\n\n\t\t/* Eat a whole C string */\n\t\tfor (i = 0; i < sizeof (tmp) - 4 && needle < to; i += rc) {\n\t\t\tRRune r = {0};\n\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\trc = r_utf32le_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc) {\n\t\t\t\t\trc = 4;\n\t\t\t\t}\n\t\t\t} else if (str_type == R_STRING_TYPE_WIDE) {\n\t\t\t\trc = r_utf16le_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc == 1) {\n\t\t\t\t\trc = 2;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trc = r_utf8_decode (buf + (needle - from), to - needle, &r);\n\t\t\t\tif (rc > 1) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_UTF8;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Invalid sequence detected */\n\t\t\tif (!rc || (ascii_only && r > 0x7f)) {\n\t\t\t\tneedle++;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tneedle += rc;\n\n\t\t\tif (r_isprint (r) && r != '\\\\') {\n\t\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\t\tif (r == 0xff) {\n\t\t\t\t\t\tr = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trc = r_utf8_encode (tmp + i, r);\n\t\t\t\trunes++;\n\t\t\t\t/* Print the escape code */\n\t\t\t} else if (r && r < 0x100 && strchr (\"\\b\\v\\f\\n\\r\\t\\a\\033\\\\\", (char)r)) {\n\t\t\t\tif ((i + 32) < sizeof (tmp) && r < 93) {\n\t\t\t\t\ttmp[i + 0] = '\\\\';\n\t\t\t\t\ttmp[i + 1] = \"       abtnvfr             e  \"\n\t\t\t\t\t             \"                              \"\n\t\t\t\t\t             \"                              \"\n\t\t\t\t\t             \"  \\\\\"[r];\n\t\t\t\t} else {\n\t\t\t\t\t// string too long\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\trc = 2;\n\t\t\t\trunes++;\n\t\t\t} else {\n\t\t\t\t/* \\0 marks the end of C-strings */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\ttmp[i++] = '\\0';\n\n\t\tif (runes < min && runes >= 2 && str_type == R_STRING_TYPE_ASCII && needle < to) {\n\t\t\t// back up past the \\0 to the last char just in case it starts a wide string\n\t\t\tneedle -= 2;\n\t\t}\n\t\tif (runes >= min) {\n\t\t\t// reduce false positives\n\t\t\tint j, num_blocks, *block_list;\n\t\t\tint *freq_list = NULL, expected_ascii, actual_ascii, num_chars;\n\t\t\tif (str_type == R_STRING_TYPE_ASCII) {\n\t\t\t\tfor (j = 0; j < i; j++) {\n\t\t\t\t\tchar ch = tmp[j];\n\t\t\t\t\tif (ch != '\\n' && ch != '\\r' && ch != '\\t') {\n\t\t\t\t\t\tif (!IS_PRINTABLE (tmp[j])) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch (str_type) {\n\t\t\tcase R_STRING_TYPE_UTF8:\n\t\t\tcase R_STRING_TYPE_WIDE:\n\t\t\tcase R_STRING_TYPE_WIDE32:\n\t\t\t\tnum_blocks = 0;\n\t\t\t\tblock_list = r_utf_block_list ((const ut8*)tmp, i - 1,\n\t\t\t\t\t\tstr_type == R_STRING_TYPE_WIDE? &freq_list: NULL);\n\t\t\t\tif (block_list) {\n\t\t\t\t\tfor (j = 0; block_list[j] != -1; j++) {\n\t\t\t\t\t\tnum_blocks++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (freq_list) {\n\t\t\t\t\tnum_chars = 0;\n\t\t\t\t\tactual_ascii = 0;\n\t\t\t\t\tfor (j = 0; freq_list[j] != -1; j++) {\n\t\t\t\t\t\tnum_chars += freq_list[j];\n\t\t\t\t\t\tif (!block_list[j]) { // ASCII\n\t\t\t\t\t\t\tactual_ascii = freq_list[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfree (freq_list);\n\t\t\t\t\texpected_ascii = num_blocks ? num_chars / num_blocks : 0;\n\t\t\t\t\tif (actual_ascii > expected_ascii) {\n\t\t\t\t\t\tascii_only = true;\n\t\t\t\t\t\tneedle = str_start;\n\t\t\t\t\t\tfree (block_list);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfree (block_list);\n\t\t\t\tif (num_blocks > R_STRING_MAX_UNI_BLOCKS) {\n\t\t\t\t\tneedle++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tRBinString *bs = R_NEW0 (RBinString);\n\t\t\tif (!bs) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbs->type = str_type;\n\t\t\tbs->length = runes;\n\t\t\tbs->size = needle - str_start;\n\t\t\tbs->ordinal = count++;\n\t\t\t// TODO: move into adjust_offset\n\t\t\tswitch (str_type) {\n\t\t\tcase R_STRING_TYPE_WIDE:\n\t\t\t\tif (str_start - from > 1) {\n\t\t\t\t\tconst ut8 *p = buf + str_start - 2 - from;\n\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\tstr_start -= 2; // \\xff\\xfe\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase R_STRING_TYPE_WIDE32:\n\t\t\t\tif (str_start - from > 3) {\n\t\t\t\t\tconst ut8 *p = buf + str_start - 4 - from;\n\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\tstr_start -= 4; // \\xff\\xfe\\x00\\x00\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!s) {\n\t\t\t\tif (section) {\n\t\t\t\t\ts = section;\n\t\t\t\t} else if (bf->o) {\n\t\t\t\t\ts = r_bin_get_section_at (bf->o, str_start, false);\n\t\t\t\t}\n\t\t\t\tif (s) {\n\t\t\t\t\tvdelta = s->vaddr;\n\t\t\t\t\tpdelta = s->paddr;\n\t\t\t\t}\n\t\t\t}\n\t\t\tut64 baddr = bf->loadaddr && bf->o? bf->o->baddr: bf->loadaddr;\n\t\t\tbs->paddr = str_start + baddr;\n\t\t\tbs->vaddr = str_start - pdelta + vdelta + baddr;\n\t\t\tbs->string = r_str_ndup ((const char *)tmp, i);\n\t\t\tif (list) {\n\t\t\t\tr_list_append (list, bs);\n\t\t\t\tif (bf->o) {\n\t\t\t\t\tht_up_insert (bf->o->strings_db, bs->vaddr, bs);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tprint_string (bf, bs, raw, pj);\n\t\t\t\tr_bin_string_free (bs);\n\t\t\t}\n\t\t\tif (from == 0 && to == bf->size) {\n\t\t\t\t/* force lookup section at the next one */\n\t\t\t\ts = NULL;\n\t\t\t}\n\t\t}\n\t\tascii_only = false;\n\t}\n\tfree (buf);\n\tif (pj) {\n\t\tpj_end (pj);\n\t\tif (bin) {\n\t\t\tRIO *io = bin->iob.io;\n\t\t\tif (io) {\n\t\t\t\tio->cb_printf (\"%s\", pj_string (pj));\n\t\t\t}\n\t\t}\n\t\tpj_free (pj);\n\t}\n\treturn count;\n}", "func_hash": 198406980128053005896085428351460738080, "file_name": "bfile.c", "file_hash": 44900440862235442449646494909197314048, "cwe": ["CWE-125"], "cve": "CVE-2022-1899", "cve_desc": "Out-of-bounds Read in GitHub repository radareorg/radare2 prior to 5.7.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1899"}
{"idx": 198013, "project": "tensorflow", "commit_id": "3150642acbbe254e3c3c5d2232143fa591855ac9", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/3150642acbbe254e3c3c5d2232143fa591855ac9", "commit_message": "Fix tf.raw_ops.LoadAndRemapMatrix vulnerability with invalid `row_remapping`.\n\nCheck that `row_remapping` has the correct dims().\n\nPiperOrigin-RevId: 445522800", "target": 1, "func": "  void Compute(OpKernelContext* context) override {\n    // Checks what we're remapping and inverts the relevant remapping Tensors to\n    // be maps with key = old ID, value = new ID.\n    std::unordered_map old_row_to_new_row_map;\n    std::vector row_id_present;\n    const Tensor* row_remapping_t;\n    OP_REQUIRES_OK(context, context->input(\"row_remapping\", &row_remapping_t));\n    const auto row_remapping = row_remapping_t->vec();\n    OP_REQUIRES(context, row_remapping.size() == num_rows_,\n                errors::InvalidArgument(strings::StrCat(\n                    \"Size of row_remapping is \", row_remapping.size(),\n                    \" instead of being equal to num_rows=\", num_rows_)));\n    OP_REQUIRES_OK(context, RemapVectorToMap(row_remapping, &row_id_present,\n                                             &old_row_to_new_row_map));\n\n    // Calculates the min/max old row ID that we need to read, to save us from\n    // reading some unnecessary slices of the old tensor.\n    int64_t min_old_row = -1;\n    int64_t max_old_row = -1;\n    for (int i = 0; i < row_remapping.size(); ++i) {\n      if (min_old_row < 0 ||\n          (row_remapping(i) >= 0 && row_remapping(i) < min_old_row)) {\n        min_old_row = row_remapping(i);\n      }\n      if (max_old_row < 0 ||\n          (row_remapping(i) >= 0 && row_remapping(i) > max_old_row)) {\n        max_old_row = row_remapping(i);\n      }\n    }\n\n    // Processes the remapping for columns.\n    std::unordered_map old_col_to_new_col_map;\n    std::vector col_id_present;\n    const Tensor* col_remapping_t;\n    OP_REQUIRES_OK(context, context->input(\"col_remapping\", &col_remapping_t));\n    const auto col_remapping = col_remapping_t->vec();\n    // Note that we always \"remap rows\", even when the row vocabulary does\n    // not change, because partitioning requires a mapping from partitioned\n    // Variables to the full checkpoints we load.\n    const bool remap_cols = col_remapping.size() > 0;\n    if (remap_cols) {\n      OP_REQUIRES(\n          context, col_remapping.size() == num_cols_,\n          errors::InvalidArgument(strings::StrCat(\n              \"Provided col_remapping, but its size is \", col_remapping.size(),\n              \" instead of being equal to num_cols=\", num_cols_)));\n      OP_REQUIRES_OK(context, RemapVectorToMap(col_remapping, &col_id_present,\n                                               &old_col_to_new_col_map));\n    } else {\n      col_id_present.clear();\n      col_id_present.resize(num_cols_, true);\n    }\n\n    // Processes the checkpoint source and the provided Tensor name.\n    const Tensor* ckpt_path_t;\n    OP_REQUIRES_OK(context, context->input(\"ckpt_path\", &ckpt_path_t));\n    OP_REQUIRES(\n        context, ckpt_path_t->NumElements() == 1,\n        errors::InvalidArgument(\"The `ckpt_path` tensor must have exactly one \"\n                                \"element, got tensor of shape \",\n                                ckpt_path_t->shape().DebugString()));\n    const string& ckpt_path = ckpt_path_t->scalar()();\n    const Tensor* old_tensor_name_t;\n    OP_REQUIRES_OK(context,\n                   context->input(\"old_tensor_name\", &old_tensor_name_t));\n    const string& old_tensor_name = old_tensor_name_t->scalar()();\n\n    LOG(INFO) << \"Processing checkpoint : \" << ckpt_path;\n    BundleReader reader(context->env(), ckpt_path);\n    OP_REQUIRES_OK(context, reader.status());\n\n    DataType tensor_type;\n    TensorShape tensor_shape;\n    OP_REQUIRES_OK(context, reader.LookupDtypeAndShape(\n                                old_tensor_name, &tensor_type, &tensor_shape));\n    OP_REQUIRES(context, tensor_type == DT_FLOAT,\n                errors::InvalidArgument(strings::StrCat(\n                    \"Tensor \", old_tensor_name, \" has invalid type \",\n                    DataTypeString(tensor_type), \" instead of expected type \",\n                    DataTypeString(DT_FLOAT))));\n    // This op is limited to loading Tensors of rank 2 (matrices).\n    OP_REQUIRES(\n        context, tensor_shape.dims() == 2,\n        errors::InvalidArgument(strings::StrCat(\n            \"Tensor \", old_tensor_name, \" has shape \",\n            tensor_shape.DebugString(), \" of invalid rank \",\n            tensor_shape.dims(), \" instead of expected shape of rank 2.\")));\n\n    if (!remap_cols) {\n      // TODO(weiho): Consider relaxing this restriction to allow partial column\n      // loading (even when no column remapping is specified) if there turns out\n      // to be a use case for it.\n      OP_REQUIRES(context, num_cols_ == tensor_shape.dim_size(1),\n                  errors::InvalidArgument(strings::StrCat(\n                      \"Tensor \", old_tensor_name, \" has shape \",\n                      tensor_shape.DebugString(),\n                      \", where the size of its 2nd dimension is \",\n                      tensor_shape.dim_size(1),\n                      \" instead of being equal to num_cols=\", num_cols_)));\n    }\n\n    // Uses TensorSlice to potentially load the old tensor in chunks in case\n    // memory usage is a concern.\n    std::vector tensor_slices;\n    TensorSlice slice(tensor_shape.dims());\n    if (min_old_row >= 0 && max_old_row >= 0) {\n      int64_t row_start = min_old_row;\n      // TODO(weiho): Given the list of old row IDs of interest (the keys of\n      // old_row_to_new_row_map), we could also try something smarter to\n      // find some minimal set of covering ranges for the list of old row IDs\n      // such that the size of each range is less than max_rows_in_memory_.\n      while (row_start <= max_old_row) {\n        const int64_t slice_length =\n            max_rows_in_memory_ <= 0\n                // If max_rows_in_memory_ <= 0, we just load the entire chunk.\n                ? max_old_row - row_start + 1\n                : std::min(max_rows_in_memory_, max_old_row - row_start + 1);\n        slice.set_start(0, row_start);\n        slice.set_length(0, slice_length);\n        tensor_slices.push_back(slice);\n        row_start += slice_length;\n      }\n    }\n\n    // Allocates the output matrix.\n    Tensor* output_matrix_t = nullptr;\n    OP_REQUIRES_OK(context,\n                   context->allocate_output(\"output_matrix\",\n                                            TensorShape({num_rows_, num_cols_}),\n                                            &output_matrix_t));\n    auto output_matrix = output_matrix_t->matrix();\n\n    // Iterates through tensor slices and copies over values from the old tensor\n    // to the output matrix.\n    int64_t row_index = min_old_row;\n    int64_t rows_copied = 0;\n    Tensor loaded_tensor_t;\n    for (const TensorSlice& tensor_slice : tensor_slices) {\n      LOG(INFO) << \"Loading slice \" << tensor_slice.DebugString();\n      TensorShape slice_shape;\n      OP_REQUIRES_OK(context,\n                     tensor_slice.SliceTensorShape(tensor_shape, &slice_shape));\n      // Potentially re-allocates the tensor buffer since the last slice may\n      // have fewer rows than the other slices.\n      if (loaded_tensor_t.shape() != slice_shape) {\n        loaded_tensor_t = Tensor(DT_FLOAT, slice_shape);\n      }\n      OP_REQUIRES_OK(context, reader.LookupSlice(old_tensor_name, tensor_slice,\n                                                 &loaded_tensor_t));\n\n      // Iterates through the old loaded tensor slice row-by-row.\n      for (int row = 0; row < loaded_tensor_t.dim_size(0); ++row, ++row_index) {\n        if (row_index % 500000 == min_old_row) {\n          LOG(INFO) << \"Processing old row \" << row_index;\n        }\n\n        // If the old row ID is not found in old_row_to_new_row_map, continue\n        // to the next row; otherwise, copy it to the output matrix.\n        const int64_t* new_row_ptr =\n            gtl::FindOrNull(old_row_to_new_row_map, row_index);\n        if (new_row_ptr == nullptr) {\n          continue;\n        }\n        ++rows_copied;\n        const int64_t new_row = *new_row_ptr;\n\n        // Copies over the row element-by-element, in case remapping is needed\n        // along the column axis.\n        const auto& loaded_tensor = loaded_tensor_t.matrix();\n        for (int old_col = 0; old_col < loaded_tensor_t.dim_size(1);\n             ++old_col) {\n          int64_t new_col = old_col;\n          if (remap_cols) {\n            const int64_t* new_col_ptr =\n                gtl::FindOrNull(old_col_to_new_col_map, old_col);\n            if (new_col_ptr == nullptr) {\n              // Column remapping is specified, but this column is not found in\n              // old_col_to_new_col_map, so we leave it uninitialized, to be\n              // filled in with initializing_values later.\n              continue;\n            }\n            new_col = *new_col_ptr;\n          }\n\n          OP_REQUIRES(context,\n                      new_row < num_rows_ && new_col < num_cols_ &&\n                          new_row >= 0 && new_col >= 0,\n                      errors::Internal(strings::StrCat(\n                          \"new_row=\", new_row, \" and new_col=\", new_col,\n                          \" should have been less than num_rows_=\", num_rows_,\n                          \" and num_cols_=\", num_cols_,\n                          \" and non-negative. This should never have happened \"\n                          \"if the code were correct. Please file a bug.\")));\n          output_matrix(new_row, new_col) = loaded_tensor(row, old_col);\n        }\n      }\n    }\n    LOG(INFO) << \"Copied \" << rows_copied << \" rows from old matrix (with \"\n              << tensor_shape.dim_size(0) << \" rows) to new matrix (with \"\n              << num_rows_ << \" rows).\";\n\n    // At this point, there are potentially whole rows/columns uninitialized\n    // (corresponding to the indices where row_id_present/col_id_present are\n    // false). We fill this in cell-by-cell using row_id_present and\n    // col_id_present while dequeuing from the initializing_values vector.\n    const Tensor* initializing_values_t;\n    OP_REQUIRES_OK(\n        context, context->input(\"initializing_values\", &initializing_values_t));\n    const auto initializing_values = initializing_values_t->flat();\n    int64_t initializing_values_index = 0;\n    for (int i = 0; i < num_rows_; ++i) {\n      for (int j = 0; j < num_cols_; ++j) {\n        if (row_id_present[i] && col_id_present[j]) continue;\n        OP_REQUIRES(\n            context, initializing_values_index < initializing_values.size(),\n            errors::InvalidArgument(\n                \"initializing_values contained \", initializing_values.size(),\n                \" elements, but more missing values remain.\"));\n        output_matrix(i, j) = initializing_values(initializing_values_index);\n        ++initializing_values_index;\n      }\n    }\n\n    // Checks that we used all the given initializing values.\n    OP_REQUIRES(\n        context, initializing_values_index == initializing_values.size(),\n        errors::InvalidArgument(\n            \"initializing_values contained \", initializing_values.size(),\n            \" elements, but only \", initializing_values_index,\n            \" elements were used to fill in missing values.\"));\n  }", "func_hash": 219722258688637064068607537553301810412, "file_name": "load_and_remap_matrix_op.cc", "file_hash": 213297145030896672862854801534820332645, "cwe": ["CWE-703"], "cve": "CVE-2022-29199", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.LoadAndRemapMatrix does not fully validate the input arguments. This results in a `CHECK`-failure which can be used to trigger a denial of service attack. The code assumes `initializing_values` is a vector but there is no validation for this before accessing its value. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29199"}
{"idx": 268104, "project": "tensorflow", "commit_id": "3150642acbbe254e3c3c5d2232143fa591855ac9", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/3150642acbbe254e3c3c5d2232143fa591855ac9", "commit_message": "Fix tf.raw_ops.LoadAndRemapMatrix vulnerability with invalid `row_remapping`.\n\nCheck that `row_remapping` has the correct dims().\n\nPiperOrigin-RevId: 445522800", "target": 0, "func": "  void Compute(OpKernelContext* context) override {\n    // Checks what we're remapping and inverts the relevant remapping Tensors to\n    // be maps with key = old ID, value = new ID.\n    std::unordered_map old_row_to_new_row_map;\n    std::vector row_id_present;\n    const Tensor* row_remapping_t;\n    OP_REQUIRES_OK(context, context->input(\"row_remapping\", &row_remapping_t));\n    OP_REQUIRES(\n        context, row_remapping_t->dims() == 1,\n        errors::InvalidArgument(\"The `row_remapping` tensor must be 1-D, got \"\n                                \"a tensor of shape \",\n                                row_remapping_t->shape().DebugString()));\n    const auto row_remapping = row_remapping_t->vec();\n    OP_REQUIRES(context, row_remapping.size() == num_rows_,\n                errors::InvalidArgument(strings::StrCat(\n                    \"Size of row_remapping is \", row_remapping.size(),\n                    \" instead of being equal to num_rows=\", num_rows_)));\n    OP_REQUIRES_OK(context, RemapVectorToMap(row_remapping, &row_id_present,\n                                             &old_row_to_new_row_map));\n\n    // Calculates the min/max old row ID that we need to read, to save us from\n    // reading some unnecessary slices of the old tensor.\n    int64_t min_old_row = -1;\n    int64_t max_old_row = -1;\n    for (int i = 0; i < row_remapping.size(); ++i) {\n      if (min_old_row < 0 ||\n          (row_remapping(i) >= 0 && row_remapping(i) < min_old_row)) {\n        min_old_row = row_remapping(i);\n      }\n      if (max_old_row < 0 ||\n          (row_remapping(i) >= 0 && row_remapping(i) > max_old_row)) {\n        max_old_row = row_remapping(i);\n      }\n    }\n\n    // Processes the remapping for columns.\n    std::unordered_map old_col_to_new_col_map;\n    std::vector col_id_present;\n    const Tensor* col_remapping_t;\n    OP_REQUIRES_OK(context, context->input(\"col_remapping\", &col_remapping_t));\n    const auto col_remapping = col_remapping_t->vec();\n    // Note that we always \"remap rows\", even when the row vocabulary does\n    // not change, because partitioning requires a mapping from partitioned\n    // Variables to the full checkpoints we load.\n    const bool remap_cols = col_remapping.size() > 0;\n    if (remap_cols) {\n      OP_REQUIRES(\n          context, col_remapping.size() == num_cols_,\n          errors::InvalidArgument(strings::StrCat(\n              \"Provided col_remapping, but its size is \", col_remapping.size(),\n              \" instead of being equal to num_cols=\", num_cols_)));\n      OP_REQUIRES_OK(context, RemapVectorToMap(col_remapping, &col_id_present,\n                                               &old_col_to_new_col_map));\n    } else {\n      col_id_present.clear();\n      col_id_present.resize(num_cols_, true);\n    }\n\n    // Processes the checkpoint source and the provided Tensor name.\n    const Tensor* ckpt_path_t;\n    OP_REQUIRES_OK(context, context->input(\"ckpt_path\", &ckpt_path_t));\n    OP_REQUIRES(\n        context, ckpt_path_t->NumElements() == 1,\n        errors::InvalidArgument(\"The `ckpt_path` tensor must have exactly one \"\n                                \"element, got tensor of shape \",\n                                ckpt_path_t->shape().DebugString()));\n    const string& ckpt_path = ckpt_path_t->scalar()();\n    const Tensor* old_tensor_name_t;\n    OP_REQUIRES_OK(context,\n                   context->input(\"old_tensor_name\", &old_tensor_name_t));\n    const string& old_tensor_name = old_tensor_name_t->scalar()();\n\n    LOG(INFO) << \"Processing checkpoint : \" << ckpt_path;\n    BundleReader reader(context->env(), ckpt_path);\n    OP_REQUIRES_OK(context, reader.status());\n\n    DataType tensor_type;\n    TensorShape tensor_shape;\n    OP_REQUIRES_OK(context, reader.LookupDtypeAndShape(\n                                old_tensor_name, &tensor_type, &tensor_shape));\n    OP_REQUIRES(context, tensor_type == DT_FLOAT,\n                errors::InvalidArgument(strings::StrCat(\n                    \"Tensor \", old_tensor_name, \" has invalid type \",\n                    DataTypeString(tensor_type), \" instead of expected type \",\n                    DataTypeString(DT_FLOAT))));\n    // This op is limited to loading Tensors of rank 2 (matrices).\n    OP_REQUIRES(\n        context, tensor_shape.dims() == 2,\n        errors::InvalidArgument(strings::StrCat(\n            \"Tensor \", old_tensor_name, \" has shape \",\n            tensor_shape.DebugString(), \" of invalid rank \",\n            tensor_shape.dims(), \" instead of expected shape of rank 2.\")));\n\n    if (!remap_cols) {\n      // TODO(weiho): Consider relaxing this restriction to allow partial column\n      // loading (even when no column remapping is specified) if there turns out\n      // to be a use case for it.\n      OP_REQUIRES(context, num_cols_ == tensor_shape.dim_size(1),\n                  errors::InvalidArgument(strings::StrCat(\n                      \"Tensor \", old_tensor_name, \" has shape \",\n                      tensor_shape.DebugString(),\n                      \", where the size of its 2nd dimension is \",\n                      tensor_shape.dim_size(1),\n                      \" instead of being equal to num_cols=\", num_cols_)));\n    }\n\n    // Uses TensorSlice to potentially load the old tensor in chunks in case\n    // memory usage is a concern.\n    std::vector tensor_slices;\n    TensorSlice slice(tensor_shape.dims());\n    if (min_old_row >= 0 && max_old_row >= 0) {\n      int64_t row_start = min_old_row;\n      // TODO(weiho): Given the list of old row IDs of interest (the keys of\n      // old_row_to_new_row_map), we could also try something smarter to\n      // find some minimal set of covering ranges for the list of old row IDs\n      // such that the size of each range is less than max_rows_in_memory_.\n      while (row_start <= max_old_row) {\n        const int64_t slice_length =\n            max_rows_in_memory_ <= 0\n                // If max_rows_in_memory_ <= 0, we just load the entire chunk.\n                ? max_old_row - row_start + 1\n                : std::min(max_rows_in_memory_, max_old_row - row_start + 1);\n        slice.set_start(0, row_start);\n        slice.set_length(0, slice_length);\n        tensor_slices.push_back(slice);\n        row_start += slice_length;\n      }\n    }\n\n    // Allocates the output matrix.\n    Tensor* output_matrix_t = nullptr;\n    OP_REQUIRES_OK(context,\n                   context->allocate_output(\"output_matrix\",\n                                            TensorShape({num_rows_, num_cols_}),\n                                            &output_matrix_t));\n    auto output_matrix = output_matrix_t->matrix();\n\n    // Iterates through tensor slices and copies over values from the old tensor\n    // to the output matrix.\n    int64_t row_index = min_old_row;\n    int64_t rows_copied = 0;\n    Tensor loaded_tensor_t;\n    for (const TensorSlice& tensor_slice : tensor_slices) {\n      LOG(INFO) << \"Loading slice \" << tensor_slice.DebugString();\n      TensorShape slice_shape;\n      OP_REQUIRES_OK(context,\n                     tensor_slice.SliceTensorShape(tensor_shape, &slice_shape));\n      // Potentially re-allocates the tensor buffer since the last slice may\n      // have fewer rows than the other slices.\n      if (loaded_tensor_t.shape() != slice_shape) {\n        loaded_tensor_t = Tensor(DT_FLOAT, slice_shape);\n      }\n      OP_REQUIRES_OK(context, reader.LookupSlice(old_tensor_name, tensor_slice,\n                                                 &loaded_tensor_t));\n\n      // Iterates through the old loaded tensor slice row-by-row.\n      for (int row = 0; row < loaded_tensor_t.dim_size(0); ++row, ++row_index) {\n        if (row_index % 500000 == min_old_row) {\n          LOG(INFO) << \"Processing old row \" << row_index;\n        }\n\n        // If the old row ID is not found in old_row_to_new_row_map, continue\n        // to the next row; otherwise, copy it to the output matrix.\n        const int64_t* new_row_ptr =\n            gtl::FindOrNull(old_row_to_new_row_map, row_index);\n        if (new_row_ptr == nullptr) {\n          continue;\n        }\n        ++rows_copied;\n        const int64_t new_row = *new_row_ptr;\n\n        // Copies over the row element-by-element, in case remapping is needed\n        // along the column axis.\n        const auto& loaded_tensor = loaded_tensor_t.matrix();\n        for (int old_col = 0; old_col < loaded_tensor_t.dim_size(1);\n             ++old_col) {\n          int64_t new_col = old_col;\n          if (remap_cols) {\n            const int64_t* new_col_ptr =\n                gtl::FindOrNull(old_col_to_new_col_map, old_col);\n            if (new_col_ptr == nullptr) {\n              // Column remapping is specified, but this column is not found in\n              // old_col_to_new_col_map, so we leave it uninitialized, to be\n              // filled in with initializing_values later.\n              continue;\n            }\n            new_col = *new_col_ptr;\n          }\n\n          OP_REQUIRES(context,\n                      new_row < num_rows_ && new_col < num_cols_ &&\n                          new_row >= 0 && new_col >= 0,\n                      errors::Internal(strings::StrCat(\n                          \"new_row=\", new_row, \" and new_col=\", new_col,\n                          \" should have been less than num_rows_=\", num_rows_,\n                          \" and num_cols_=\", num_cols_,\n                          \" and non-negative. This should never have happened \"\n                          \"if the code were correct. Please file a bug.\")));\n          output_matrix(new_row, new_col) = loaded_tensor(row, old_col);\n        }\n      }\n    }\n    LOG(INFO) << \"Copied \" << rows_copied << \" rows from old matrix (with \"\n              << tensor_shape.dim_size(0) << \" rows) to new matrix (with \"\n              << num_rows_ << \" rows).\";\n\n    // At this point, there are potentially whole rows/columns uninitialized\n    // (corresponding to the indices where row_id_present/col_id_present are\n    // false). We fill this in cell-by-cell using row_id_present and\n    // col_id_present while dequeuing from the initializing_values vector.\n    const Tensor* initializing_values_t;\n    OP_REQUIRES_OK(\n        context, context->input(\"initializing_values\", &initializing_values_t));\n    const auto initializing_values = initializing_values_t->flat();\n    int64_t initializing_values_index = 0;\n    for (int i = 0; i < num_rows_; ++i) {\n      for (int j = 0; j < num_cols_; ++j) {\n        if (row_id_present[i] && col_id_present[j]) continue;\n        OP_REQUIRES(\n            context, initializing_values_index < initializing_values.size(),\n            errors::InvalidArgument(\n                \"initializing_values contained \", initializing_values.size(),\n                \" elements, but more missing values remain.\"));\n        output_matrix(i, j) = initializing_values(initializing_values_index);\n        ++initializing_values_index;\n      }\n    }\n\n    // Checks that we used all the given initializing values.\n    OP_REQUIRES(\n        context, initializing_values_index == initializing_values.size(),\n        errors::InvalidArgument(\n            \"initializing_values contained \", initializing_values.size(),\n            \" elements, but only \", initializing_values_index,\n            \" elements were used to fill in missing values.\"));\n  }", "func_hash": 327012646245116178249898912195700700283, "file_name": "load_and_remap_matrix_op.cc", "file_hash": 176825367634149624360733361050584878598, "cwe": ["CWE-703"], "cve": "CVE-2022-29199", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.LoadAndRemapMatrix does not fully validate the input arguments. This results in a `CHECK`-failure which can be used to trigger a denial of service attack. The code assumes `initializing_values` is a vector but there is no validation for this before accessing its value. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29199"}
{"idx": 198116, "project": "tensorflow", "commit_id": "87158f43f05f2720a374f3e6d22a7aaa3a33f750", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/87158f43f05f2720a374f3e6d22a7aaa3a33f750", "commit_message": "Prevent heap OOB in sparse reduction ops.\n\nPiperOrigin-RevId: 387934524\nChange-Id: I894aa30f1e454f09b471d565b4a325da49322c1a", "target": 1, "func": "  void Compute(OpKernelContext *ctx) override {\n    const Tensor *indices_t, *values_t, *shape_t, *reduction_axes_t;\n    OP_REQUIRES_OK(ctx, ctx->input(\"input_indices\", &indices_t));\n    OP_REQUIRES_OK(ctx, ctx->input(\"input_values\", &values_t));\n    OP_REQUIRES_OK(ctx, ctx->input(\"input_shape\", &shape_t));\n    OP_REQUIRES_OK(ctx, ctx->input(\"reduction_axes\", &reduction_axes_t));\n\n    OP_REQUIRES_OK(ctx, ValidateInputs(shape_t, reduction_axes_t));\n\n    // TODO(zongheng): we will call Reorder() below, which will modify\n    // in-place the underlying indices and values buffers.  To avoid\n    // surprises of this kernel being stateful, we work around the above by\n    // making deep copies here.  Remove this if/when we change Reorder()'s\n    // semantics.\n    const auto shape_vec = shape_t->vec();\n    SparseTensor sp;\n    OP_REQUIRES_OK(ctx, SparseTensor::Create(\n        tensor::DeepCopy(*indices_t), tensor::DeepCopy(*values_t),\n                    TensorShape(shape_vec), &sp));\n    ReduceDetails reduction = SparseTensorReduceHelper(\n        sp, reduction_axes_t->flat(), keep_dims_);\n\n    Tensor *out_values;\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_output(0, reduction.reduced_shape, &out_values));\n    auto out_flat = out_values->flat();\n    out_flat.setZero();\n\n    Tensor tmp_reduced_val;\n    OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value,\n                                           TensorShape({}), &tmp_reduced_val));\n    auto reduced_val = tmp_reduced_val.scalar();\n\n    // Compute strides, and use it to convert coords to flat index.  The\n    // coordinates returned by .group() have the same ndims as group_by_dims.\n    gtl::InlinedVector output_strides(reduction.group_by_dims.size());\n    if (!output_strides.empty()) {  // Do this iff we don't reduce all.\n      output_strides.back() = 1;\n      for (int d = output_strides.size() - 2; d >= 0; --d) {\n        output_strides[d] =\n            output_strides[d + 1] * shape_vec(reduction.group_by_dims[d + 1]);\n      }\n    }\n\n    auto CoordinatesToFlatIndex = [](ArraySlice coords,\n                                     ArraySlice strides) -> int64 {\n      if (strides.empty()) {  // Reduce all.\n        return 0;\n      }\n      CHECK_EQ(coords.size(), strides.size());\n      int64_t idx = 0;\n      for (int i = 0; i < coords.size(); ++i) {\n        idx += coords[i] * strides[i];\n      }\n      return idx;\n    };\n\n    // Each group maps one-on-one onto a value in the reduced tensor.\n    // g.group() provides the coordinates of a particular reduced value.\n    sp.Reorder(reduction.reorder_dims);\n    for (const auto &g : sp.group(reduction.group_by_dims)) {\n      Op::template Run(ctx, reduced_val, g.template values());\n      const int64_t idx = CoordinatesToFlatIndex(g.group(), output_strides);\n      out_flat(idx) = reduced_val();\n      VLOG(2) << \"coords: \" << absl::StrJoin(g.group(), \",\")\n              << \"; idx: \" << idx << \"; group \" << Op::Name() << \": \"\n              << reduced_val();\n    }\n  }", "func_hash": 226769425429975920381040402527052798393, "file_name": "sparse_reduce_op.cc", "file_hash": 21049285234129890276227338943103143863, "cwe": ["CWE-125"], "cve": "CVE-2021-37635", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of sparse reduction operations in TensorFlow can trigger accesses outside of bounds of heap allocated data. The [implementation](https://github.com/tensorflow/tensorflow/blob/a1bc56203f21a5a4995311825ffaba7a670d7747/tensorflow/core/kernels/sparse_reduce_op.cc#L217-L228) fails to validate that each reduction group does not overflow and that each corresponding index does not point to outside the bounds of the input tensor. We have patched the issue in GitHub commit 87158f43f05f2720a374f3e6d22a7aaa3a33f750. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37635"}
{"idx": 269323, "project": "tensorflow", "commit_id": "87158f43f05f2720a374f3e6d22a7aaa3a33f750", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/87158f43f05f2720a374f3e6d22a7aaa3a33f750", "commit_message": "Prevent heap OOB in sparse reduction ops.\n\nPiperOrigin-RevId: 387934524\nChange-Id: I894aa30f1e454f09b471d565b4a325da49322c1a", "target": 0, "func": "  void Compute(OpKernelContext *ctx) override {\n    const Tensor *indices_t, *values_t, *shape_t, *reduction_axes_t;\n    OP_REQUIRES_OK(ctx, ctx->input(\"input_indices\", &indices_t));\n    OP_REQUIRES_OK(ctx, ctx->input(\"input_values\", &values_t));\n    OP_REQUIRES_OK(ctx, ctx->input(\"input_shape\", &shape_t));\n    OP_REQUIRES_OK(ctx, ctx->input(\"reduction_axes\", &reduction_axes_t));\n\n    OP_REQUIRES_OK(ctx, ValidateInputs(shape_t, reduction_axes_t));\n\n    // TODO(zongheng): we will call Reorder() below, which will modify\n    // in-place the underlying indices and values buffers.  To avoid\n    // surprises of this kernel being stateful, we work around the above by\n    // making deep copies here.  Remove this if/when we change Reorder()'s\n    // semantics.\n    const auto shape_vec = shape_t->vec();\n    SparseTensor sp;\n    OP_REQUIRES_OK(ctx, SparseTensor::Create(\n        tensor::DeepCopy(*indices_t), tensor::DeepCopy(*values_t),\n                    TensorShape(shape_vec), &sp));\n    ReduceDetails reduction = SparseTensorReduceHelper(\n        sp, reduction_axes_t->flat(), keep_dims_);\n\n    Tensor *out_values;\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_output(0, reduction.reduced_shape, &out_values));\n    auto out_flat = out_values->flat();\n    out_flat.setZero();\n\n    Tensor tmp_reduced_val;\n    OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value,\n                                           TensorShape({}), &tmp_reduced_val));\n    auto reduced_val = tmp_reduced_val.scalar();\n\n    // Compute strides, and use it to convert coords to flat index.  The\n    // coordinates returned by .group() have the same ndims as group_by_dims.\n    gtl::InlinedVector output_strides(reduction.group_by_dims.size());\n    if (!output_strides.empty()) {  // Do this iff we don't reduce all.\n      output_strides.back() = 1;\n      for (int d = output_strides.size() - 2; d >= 0; --d) {\n        output_strides[d] =\n            output_strides[d + 1] * shape_vec(reduction.group_by_dims[d + 1]);\n      }\n    }\n\n    auto CoordinatesToFlatIndex = [](ArraySlice coords,\n                                     ArraySlice strides) -> int64 {\n      if (strides.empty()) {  // Reduce all.\n        return 0;\n      }\n      CHECK_EQ(coords.size(), strides.size());\n      int64_t idx = 0;\n      for (int i = 0; i < coords.size(); ++i) {\n        idx += coords[i] * strides[i];\n      }\n      return idx;\n    };\n\n    // Each group maps one-on-one onto a value in the reduced tensor.\n    // g.group() provides the coordinates of a particular reduced value.\n    sp.Reorder(reduction.reorder_dims);\n    for (const auto &g : sp.group(reduction.group_by_dims)) {\n      Op::template Run(ctx, reduced_val, g.template values());\n      OP_REQUIRES(ctx,\n                  output_strides.empty() ||\n                  (g.group().size() == output_strides.size()),\n                  errors::Internal(\n                      \"Expected group size and output_strides size to match\",\n                      \", but got \", g.group().size(), \" and \",\n                      output_strides.size()));\n      const int64_t idx = CoordinatesToFlatIndex(g.group(), output_strides);\n      OP_REQUIRES(ctx,\n                  idx >= 0 && idx < out_flat.size(),\n                  errors::Internal(\n                      \"Obtained a write index of \", idx,\n                      \" which is outside of bounds of [0, \",\n                      out_flat.size(), \")\"));\n      out_flat(idx) = reduced_val();\n      VLOG(2) << \"coords: \" << absl::StrJoin(g.group(), \",\")\n              << \"; idx: \" << idx << \"; group \" << Op::Name() << \": \"\n              << reduced_val();\n    }\n  }", "func_hash": 101373936648548971871118830985437949443, "file_name": "sparse_reduce_op.cc", "file_hash": 180034479721260906291386673174160626569, "cwe": ["CWE-125"], "cve": "CVE-2021-37635", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of sparse reduction operations in TensorFlow can trigger accesses outside of bounds of heap allocated data. The [implementation](https://github.com/tensorflow/tensorflow/blob/a1bc56203f21a5a4995311825ffaba7a670d7747/tensorflow/core/kernels/sparse_reduce_op.cc#L217-L228) fails to validate that each reduction group does not overflow and that each corresponding index does not point to outside the bounds of the input tensor. We have patched the issue in GitHub commit 87158f43f05f2720a374f3e6d22a7aaa3a33f750. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37635"}
{"idx": 198117, "project": "tensorflow", "commit_id": "0f931751fb20f565c4e94aa6df58d54a003cdb30", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/0f931751fb20f565c4e94aa6df58d54a003cdb30", "commit_message": "Validate dimensions of input tensor in `FractionalAvgPoolGrad`\n\nPiperOrigin-RevId: 388286227\nChange-Id: Ieb7566155e92acc8993a2212c76deacadc0edc8a", "target": 1, "func": "  void Compute(OpKernelContext* context) override {\n    // Here's the basic idea:\n    // Batch and depth dimension are independent from row and col dimension. And\n    // because FractionalAvgPool currently only support pooling along row and\n    // col, we can basically think of this 4D tensor backpropagation as\n    // operation of a series of 2D planes.\n    //\n    // For each element of a 'slice' (2D plane) of output_backprop, we need to\n    // figure out its contributors when doing FractionalAvgPool operation. This\n    // can be done based on row_pooling_sequence, col_pooling_seq and\n    // overlapping.\n    // Once we figure out the original contributors, we just need to evenly\n    // divide the value of this element among these contributors.\n    //\n    // Internally, we divide the out_backprop tensor and store it in a temporary\n    // tensor of double type. And cast it to the corresponding type.\n    typedef Eigen::Map>\n        ConstEigenMatrixMap;\n    typedef Eigen::Map>\n        EigenDoubleMatrixMap;\n\n    // Grab the inputs.\n    const Tensor& orig_input_tensor_shape = context->input(0);\n    OP_REQUIRES(context,\n                orig_input_tensor_shape.dims() == 1 &&\n                    orig_input_tensor_shape.NumElements() == 4,\n                errors::InvalidArgument(\"original input tensor shape must be\"\n                                        \"1-dimensional and 4 elements\"));\n    const Tensor& out_backprop = context->input(1);\n    const Tensor& row_seq_tensor = context->input(2);\n    const Tensor& col_seq_tensor = context->input(3);\n\n    const int64_t out_batch = out_backprop.dim_size(0);\n    const int64_t out_rows = out_backprop.dim_size(1);\n    const int64_t out_cols = out_backprop.dim_size(2);\n    const int64_t out_depth = out_backprop.dim_size(3);\n\n    OP_REQUIRES(context, row_seq_tensor.NumElements() > out_rows,\n                errors::InvalidArgument(\"Given out_backprop shape \",\n                                        out_backprop.shape().DebugString(),\n                                        \", row_seq_tensor must have at least \",\n                                        out_rows + 1, \" elements, but got \",\n                                        row_seq_tensor.NumElements()));\n    OP_REQUIRES(context, col_seq_tensor.NumElements() > out_cols,\n                errors::InvalidArgument(\"Given out_backprop shape \",\n                                        out_backprop.shape().DebugString(),\n                                        \", col_seq_tensor must have at least \",\n                                        out_cols + 1, \" elements, but got \",\n                                        col_seq_tensor.NumElements()));\n\n    auto row_seq_tensor_flat = row_seq_tensor.flat();\n    auto col_seq_tensor_flat = col_seq_tensor.flat();\n    auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat();\n\n    const int64_t in_batch = orig_input_tensor_shape_flat(0);\n    const int64_t in_rows = orig_input_tensor_shape_flat(1);\n    const int64_t in_cols = orig_input_tensor_shape_flat(2);\n    const int64_t in_depth = orig_input_tensor_shape_flat(3);\n\n    constexpr int tensor_in_and_out_dims = 4;\n    // Transform orig_input_tensor_shape into TensorShape\n    TensorShape in_shape;\n    for (auto i = 0; i < tensor_in_and_out_dims; ++i) {\n      in_shape.AddDim(orig_input_tensor_shape_flat(i));\n    }\n\n    // Create intermediate in_backprop.\n    Tensor in_backprop_tensor_temp;\n    OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(\n                                {0}, DataTypeToEnum::v(), in_shape,\n                                &in_backprop_tensor_temp));\n    in_backprop_tensor_temp.flat().setZero();\n    // Transform 4D tensor to 2D matrix.\n    EigenDoubleMatrixMap in_backprop_tensor_temp_mat(\n        in_backprop_tensor_temp.flat().data(), in_depth,\n        in_cols * in_rows * in_batch);\n    ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(),\n                                         out_depth,\n                                         out_cols * out_rows * out_batch);\n    // Loop through each element of out_backprop and evenly distribute the\n    // element to the corresponding pooling cell.\n    const int64_t in_max_row_index = in_rows - 1;\n    const int64_t in_max_col_index = in_cols - 1;\n    for (int64_t b = 0; b < out_batch; ++b) {\n      for (int64_t r = 0; r < out_rows; ++r) {\n        const int64_t in_row_start = row_seq_tensor_flat(r);\n        int64_t in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)\n                                          : row_seq_tensor_flat(r + 1) - 1;\n        in_row_end = std::min(in_row_end, in_max_row_index);\n        for (int64_t c = 0; c < out_cols; ++c) {\n          const int64_t in_col_start = col_seq_tensor_flat(c);\n          int64_t in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)\n                                            : col_seq_tensor_flat(c + 1) - 1;\n          in_col_end = std::min(in_col_end, in_max_col_index);\n\n          const int64_t num_elements_in_pooling_cell =\n              (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);\n          const int64_t out_index = (b * out_rows + r) * out_cols + c;\n          // Now we can evenly distribute out_backprop(b, h, w, *) to\n          // in_backprop(b, hs:he, ws:we, *).\n          for (int64_t in_r = in_row_start; in_r <= in_row_end; ++in_r) {\n            for (int64_t in_c = in_col_start; in_c <= in_col_end; ++in_c) {\n              const int64_t in_index = (b * in_rows + in_r) * in_cols + in_c;\n              // Walk through each channel (depth).\n              for (int64_t d = 0; d < out_depth; ++d) {\n                const double out_backprop_element = static_cast(\n                    out_backprop_mat.coeffRef(d, out_index));\n                double& in_backprop_ref =\n                    in_backprop_tensor_temp_mat.coeffRef(d, in_index);\n                in_backprop_ref +=\n                    out_backprop_element / num_elements_in_pooling_cell;\n              }\n            }\n          }\n        }\n      }\n    }\n\n    // Depending on the type, cast double to type T.\n    Tensor* in_backprop_tensor = nullptr;\n    OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n                                {0}, 0, in_shape, &in_backprop_tensor));\n    auto in_backprop_tensor_flat = in_backprop_tensor->flat();\n    auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat();\n    for (int64_t i = 0; i < in_backprop_tensor_flat.size(); ++i) {\n      in_backprop_tensor_flat(i) =\n          static_cast(in_backprop_tensor_temp_flat(i));\n    }\n  }", "func_hash": 1946187127976060435937085266146503817, "file_name": "fractional_avg_pool_op.cc", "file_hash": 123284094403203358257933187084228510511, "cwe": ["CWE-476"], "cve": "CVE-2021-37651", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation for `tf.raw_ops.FractionalAvgPoolGrad` can be tricked into accessing data outside of bounds of heap allocated buffers. The [implementation](https://github.com/tensorflow/tensorflow/blob/f24faa153ad31a4b51578f8181d3aaab77a1ddeb/tensorflow/core/kernels/fractional_avg_pool_op.cc#L205) does not validate that the input tensor is non-empty. Thus, code constructs an empty `EigenDoubleMatrixMap` and then accesses this buffer with indices that are outside of the empty area. We have patched the issue in GitHub commit 0f931751fb20f565c4e94aa6df58d54a003cdb30. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37651"}
{"idx": 269330, "project": "tensorflow", "commit_id": "0f931751fb20f565c4e94aa6df58d54a003cdb30", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/0f931751fb20f565c4e94aa6df58d54a003cdb30", "commit_message": "Validate dimensions of input tensor in `FractionalAvgPoolGrad`\n\nPiperOrigin-RevId: 388286227\nChange-Id: Ieb7566155e92acc8993a2212c76deacadc0edc8a", "target": 0, "func": "  void Compute(OpKernelContext* context) override {\n    // Here's the basic idea:\n    // Batch and depth dimension are independent from row and col dimension. And\n    // because FractionalAvgPool currently only support pooling along row and\n    // col, we can basically think of this 4D tensor backpropagation as\n    // operation of a series of 2D planes.\n    //\n    // For each element of a 'slice' (2D plane) of output_backprop, we need to\n    // figure out its contributors when doing FractionalAvgPool operation. This\n    // can be done based on row_pooling_sequence, col_pooling_seq and\n    // overlapping.\n    // Once we figure out the original contributors, we just need to evenly\n    // divide the value of this element among these contributors.\n    //\n    // Internally, we divide the out_backprop tensor and store it in a temporary\n    // tensor of double type. And cast it to the corresponding type.\n    typedef Eigen::Map>\n        ConstEigenMatrixMap;\n    typedef Eigen::Map>\n        EigenDoubleMatrixMap;\n\n    // Grab the inputs.\n    const Tensor& orig_input_tensor_shape = context->input(0);\n    OP_REQUIRES(context,\n                orig_input_tensor_shape.dims() == 1 &&\n                    orig_input_tensor_shape.NumElements() == 4,\n                errors::InvalidArgument(\"original input tensor shape must be\"\n                                        \"1-dimensional and 4 elements\"));\n    const Tensor& out_backprop = context->input(1);\n    const Tensor& row_seq_tensor = context->input(2);\n    const Tensor& col_seq_tensor = context->input(3);\n\n    const int64_t out_batch = out_backprop.dim_size(0);\n    const int64_t out_rows = out_backprop.dim_size(1);\n    const int64_t out_cols = out_backprop.dim_size(2);\n    const int64_t out_depth = out_backprop.dim_size(3);\n\n    OP_REQUIRES(context, row_seq_tensor.NumElements() > out_rows,\n                errors::InvalidArgument(\"Given out_backprop shape \",\n                                        out_backprop.shape().DebugString(),\n                                        \", row_seq_tensor must have at least \",\n                                        out_rows + 1, \" elements, but got \",\n                                        row_seq_tensor.NumElements()));\n    OP_REQUIRES(context, col_seq_tensor.NumElements() > out_cols,\n                errors::InvalidArgument(\"Given out_backprop shape \",\n                                        out_backprop.shape().DebugString(),\n                                        \", col_seq_tensor must have at least \",\n                                        out_cols + 1, \" elements, but got \",\n                                        col_seq_tensor.NumElements()));\n\n    auto row_seq_tensor_flat = row_seq_tensor.flat();\n    auto col_seq_tensor_flat = col_seq_tensor.flat();\n    auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat();\n\n    const int64_t in_batch = orig_input_tensor_shape_flat(0);\n    const int64_t in_rows = orig_input_tensor_shape_flat(1);\n    const int64_t in_cols = orig_input_tensor_shape_flat(2);\n    const int64_t in_depth = orig_input_tensor_shape_flat(3);\n    OP_REQUIRES(\n        context, in_batch != 0,\n        errors::InvalidArgument(\"Batch dimension of input must not be 0\"));\n    OP_REQUIRES(\n        context, in_rows != 0,\n        errors::InvalidArgument(\"Rows dimension of input must not be 0\"));\n    OP_REQUIRES(\n        context, in_cols != 0,\n        errors::InvalidArgument(\"Columns dimension of input must not be 0\"));\n    OP_REQUIRES(\n        context, in_depth != 0,\n        errors::InvalidArgument(\"Depth dimension of input must not be 0\"));\n\n    constexpr int tensor_in_and_out_dims = 4;\n    // Transform orig_input_tensor_shape into TensorShape\n    TensorShape in_shape;\n    for (auto i = 0; i < tensor_in_and_out_dims; ++i) {\n      in_shape.AddDim(orig_input_tensor_shape_flat(i));\n    }\n\n    // Create intermediate in_backprop.\n    Tensor in_backprop_tensor_temp;\n    OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(\n                                {0}, DataTypeToEnum::v(), in_shape,\n                                &in_backprop_tensor_temp));\n    in_backprop_tensor_temp.flat().setZero();\n    // Transform 4D tensor to 2D matrix.\n    EigenDoubleMatrixMap in_backprop_tensor_temp_mat(\n        in_backprop_tensor_temp.flat().data(), in_depth,\n        in_cols * in_rows * in_batch);\n    ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(),\n                                         out_depth,\n                                         out_cols * out_rows * out_batch);\n    // Loop through each element of out_backprop and evenly distribute the\n    // element to the corresponding pooling cell.\n    const int64_t in_max_row_index = in_rows - 1;\n    const int64_t in_max_col_index = in_cols - 1;\n    for (int64_t b = 0; b < out_batch; ++b) {\n      for (int64_t r = 0; r < out_rows; ++r) {\n        const int64_t in_row_start = row_seq_tensor_flat(r);\n        int64_t in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)\n                                          : row_seq_tensor_flat(r + 1) - 1;\n        in_row_end = std::min(in_row_end, in_max_row_index);\n        for (int64_t c = 0; c < out_cols; ++c) {\n          const int64_t in_col_start = col_seq_tensor_flat(c);\n          int64_t in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)\n                                            : col_seq_tensor_flat(c + 1) - 1;\n          in_col_end = std::min(in_col_end, in_max_col_index);\n\n          const int64_t num_elements_in_pooling_cell =\n              (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);\n          const int64_t out_index = (b * out_rows + r) * out_cols + c;\n          // Now we can evenly distribute out_backprop(b, h, w, *) to\n          // in_backprop(b, hs:he, ws:we, *).\n          for (int64_t in_r = in_row_start; in_r <= in_row_end; ++in_r) {\n            for (int64_t in_c = in_col_start; in_c <= in_col_end; ++in_c) {\n              const int64_t in_index = (b * in_rows + in_r) * in_cols + in_c;\n              // Walk through each channel (depth).\n              for (int64_t d = 0; d < out_depth; ++d) {\n                const double out_backprop_element = static_cast(\n                    out_backprop_mat.coeffRef(d, out_index));\n                double& in_backprop_ref =\n                    in_backprop_tensor_temp_mat.coeffRef(d, in_index);\n                in_backprop_ref +=\n                    out_backprop_element / num_elements_in_pooling_cell;\n              }\n            }\n          }\n        }\n      }\n    }\n\n    // Depending on the type, cast double to type T.\n    Tensor* in_backprop_tensor = nullptr;\n    OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n                                {0}, 0, in_shape, &in_backprop_tensor));\n    auto in_backprop_tensor_flat = in_backprop_tensor->flat();\n    auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat();\n    for (int64_t i = 0; i < in_backprop_tensor_flat.size(); ++i) {\n      in_backprop_tensor_flat(i) =\n          static_cast(in_backprop_tensor_temp_flat(i));\n    }\n  }", "func_hash": 156284103757458674959044655619775899657, "file_name": "fractional_avg_pool_op.cc", "file_hash": 240042973455174770184234530655849007197, "cwe": ["CWE-476"], "cve": "CVE-2021-37651", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation for `tf.raw_ops.FractionalAvgPoolGrad` can be tricked into accessing data outside of bounds of heap allocated buffers. The [implementation](https://github.com/tensorflow/tensorflow/blob/f24faa153ad31a4b51578f8181d3aaab77a1ddeb/tensorflow/core/kernels/fractional_avg_pool_op.cc#L205) does not validate that the input tensor is non-empty. Thus, code constructs an empty `EigenDoubleMatrixMap` and then accesses this buffer with indices that are outside of the empty area. We have patched the issue in GitHub commit 0f931751fb20f565c4e94aa6df58d54a003cdb30. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37651"}
{"idx": 198161, "project": "ImageMagick", "commit_id": "a6240a163cb787909703d9fc649cf861f60ddd7c", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/a6240a163cb787909703d9fc649cf861f60ddd7c", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/131", "target": 1, "func": "static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n  Image *image, *image2=NULL,\n   *rotated_image;\n  register Quantum *q;\n\n  unsigned int status;\n  MATHeader MATLAB_HDR;\n  size_t size;  \n  size_t CellType;\n  QuantumInfo *quantum_info;\n  ImageInfo *clone_info;\n  int i;\n  ssize_t ldblk;\n  unsigned char *BImgBuff = NULL;\n  double MinVal, MaxVal;\n  unsigned z, z2;\n  unsigned Frames;\n  int logging;\n  int sample_size;\n  MagickOffsetType filepos=0x80;\n  BlobInfo *blob;\n  size_t one;\n  \n  unsigned int (*ReadBlobXXXLong)(Image *image);\n  unsigned short (*ReadBlobXXXShort)(Image *image);\n  void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);\n  void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);\n\n\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  logging = LogMagickEvent(CoderEvent,GetMagickModule(),\"enter\"); \n\n  /*\n     Open image file.\n   */\n  image = AcquireImage(image_info,exception);\n\n  status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n     Read MATLAB image.\n   */\n  clone_info=CloneImageInfo(image_info);\n  if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  MATLAB_HDR.Version = ReadBlobLSBShort(image);\n  if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\"  Endian %c%c\",\n        MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);\n  if (!strncmp(MATLAB_HDR.EndianIndicator, \"IM\", 2))\n  {\n    ReadBlobXXXLong = ReadBlobLSBLong;\n    ReadBlobXXXShort = ReadBlobLSBShort;\n    ReadBlobDoublesXXX = ReadBlobDoublesLSB;\n    ReadBlobFloatsXXX = ReadBlobFloatsLSB;\n    image->endian = LSBEndian;\n  } \n  else if (!strncmp(MATLAB_HDR.EndianIndicator, \"MI\", 2))\n  {\n    ReadBlobXXXLong = ReadBlobMSBLong;\n    ReadBlobXXXShort = ReadBlobMSBShort;\n    ReadBlobDoublesXXX = ReadBlobDoublesMSB;\n    ReadBlobFloatsXXX = ReadBlobFloatsMSB;\n    image->endian = MSBEndian;\n  }\n  else \n    goto MATLAB_KO;    /* unsupported endian */\n\n  if (strncmp(MATLAB_HDR.identific, \"MATLAB\", 6))\nMATLAB_KO: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n  filepos = TellBlob(image);\n  while(!EOFBlob(image)) /* object parser loop */\n  {\n    Frames = 1;\n    (void) SeekBlob(image,filepos,SEEK_SET);\n    /* printf(\"pos=%X\\n\",TellBlob(image)); */\n\n    MATLAB_HDR.DataType = ReadBlobXXXLong(image);\n    if(EOFBlob(image)) break;\n    MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);\n    if(EOFBlob(image)) break;\n    filepos += MATLAB_HDR.ObjectSize + 4 + 4;\n\n    image2 = image;\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n    if(MATLAB_HDR.DataType == miCOMPRESSED)\n    {\n      image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);\n      if(image2==NULL) continue;\n      MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */\n    }\n#endif    \n\n    if(MATLAB_HDR.DataType!=miMATRIX) continue;  /* skip another objects. */\n \n    MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);\n    MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);  \n\n    MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);\n    MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;\n    MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;  \n\n    MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);\n    if(image!=image2)\n      MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);  /* ??? don't understand why ?? */\n    MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);\n    MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);\n    MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);\n    MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);  \n   \n\n    switch(MATLAB_HDR.DimFlag)\n    {     \n      case  8: z2=z=1; break;      /* 2D matrix*/\n      case 12: z2=z = ReadBlobXXXLong(image2);  /* 3D matrix RGB*/\n           (void) ReadBlobXXXLong(image2);\n         if(z!=3) ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n         break;\n      case 16: z2=z = ReadBlobXXXLong(image2);  /* 4D matrix animation */\n         if(z!=3 && z!=1)\n            ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n           Frames = ReadBlobXXXLong(image2);\n         break;\n      default: ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n    }  \n\n    MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);\n    MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);\n\n    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"MATLAB_HDR.StructureClass %d\",MATLAB_HDR.StructureClass);\n    if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && \n        MATLAB_HDR.StructureClass != mxSINGLE_CLASS &&    /* float + complex float */\n        MATLAB_HDR.StructureClass != mxDOUBLE_CLASS &&    /* double + complex double */\n        MATLAB_HDR.StructureClass != mxINT8_CLASS &&\n        MATLAB_HDR.StructureClass != mxUINT8_CLASS &&    /* uint8 + uint8 3D */\n        MATLAB_HDR.StructureClass != mxINT16_CLASS &&\n        MATLAB_HDR.StructureClass != mxUINT16_CLASS &&    /* uint16 + uint16 3D */\n        MATLAB_HDR.StructureClass != mxINT32_CLASS &&\n        MATLAB_HDR.StructureClass != mxUINT32_CLASS &&    /* uint32 + uint32 3D */\n        MATLAB_HDR.StructureClass != mxINT64_CLASS &&\n        MATLAB_HDR.StructureClass != mxUINT64_CLASS)    /* uint64 + uint64 3D */\n      ThrowReaderException(CoderError,\"UnsupportedCellTypeInTheMatrix\");\n\n    switch (MATLAB_HDR.NameFlag)\n    {\n      case 0:\n        size = ReadBlobXXXLong(image2);  /* Object name string size */\n        size = 4 * (ssize_t) ((size + 3 + 1) / 4);\n        (void) SeekBlob(image2, size, SEEK_CUR);\n        break;\n      case 1:\n      case 2:\n      case 3:\n      case 4:\n        (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */\n        break;\n      default:\n        goto MATLAB_KO;\n    }\n\n    CellType = ReadBlobXXXLong(image2);    /* Additional object type */\n    if (logging)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"MATLAB_HDR.CellType: %.20g\",(double) CellType);\n  \n    (void) ReadBlob(image2, 4, (unsigned char *) &size);     /* data size */\n\n    NEXT_FRAME:\n    switch (CellType)\n    {\n      case miINT8:\n      case miUINT8:\n        sample_size = 8;\n        if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) \n          image->depth = 1;\n        else\n          image->depth = 8;         /* Byte type cell */\n        ldblk = (ssize_t) MATLAB_HDR.SizeX;      \n        break;\n      case miINT16:\n      case miUINT16:\n        sample_size = 16;\n        image->depth = 16;        /* Word type cell */\n        ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);\n        break;\n      case miINT32:\n      case miUINT32:\n        sample_size = 32;\n        image->depth = 32;        /* Dword type cell */\n        ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);      \n        break;\n      case miINT64:\n      case miUINT64:\n        sample_size = 64;\n        image->depth = 64;        /* Qword type cell */\n        ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);      \n        break;   \n      case miSINGLE:\n        sample_size = 32;\n        image->depth = 32;        /* double type cell */\n        (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\n        if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n  {              /* complex float type cell */\n  }\n        ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n        break;\n      case miDOUBLE:\n        sample_size = 64; \n        image->depth = 64;        /* double type cell */\n        (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\nDisableMSCWarning(4127)\n        if (sizeof(double) != 8)\nRestoreMSCWarning\n          ThrowReaderException(CoderError, \"IncompatibleSizeOfDouble\");\n        if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n  {                         /* complex double type cell */        \n  }\n        ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n        break;\n      default:\n        ThrowReaderException(CoderError, \"UnsupportedCellTypeInTheMatrix\");\n    }\n    (void) sample_size;\n    image->columns = MATLAB_HDR.SizeX;\n    image->rows = MATLAB_HDR.SizeY;    \n    quantum_info=AcquireQuantumInfo(clone_info,image);\n    if (quantum_info == (QuantumInfo *) NULL)\n      ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n    one=1;\n    image->colors = one << image->depth;\n    if (image->columns == 0 || image->rows == 0)\n      goto MATLAB_KO;\n    /* Image is gray when no complex flag is set and 2D Matrix */\n    if ((MATLAB_HDR.DimFlag == 8) &&\n        ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n      {\n        image->type=GrayscaleType;\n        SetImageColorspace(image,GRAYColorspace,exception);\n      }\n\n\n    /*\n      If ping is true, then only set image size and colors without\n      reading any image data.\n    */\n    if (image_info->ping)\n    {\n      size_t temp = image->columns;\n      image->columns = image->rows;\n      image->rows = temp;\n      goto done_reading; /* !!!!!! BAD  !!!! */\n    }  \n    status=SetImageExtent(image,image->columns,image->rows,exception);\n    if (status == MagickFalse)\n      return(DestroyImageList(image));\n\n  /* ----- Load raster data ----- */\n    BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double));    /* Ldblk was set in the check phase */\n    if (BImgBuff == NULL)\n      ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n    MinVal = 0;\n    MaxVal = 0;\n    if (CellType==miDOUBLE || CellType==miSINGLE)        /* Find Min and Max Values for floats */\n    {\n      CalcMinMax(image2, image_info->endian,  MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);\n    }\n\n    /* Main loop for reading all scanlines */\n    if(z==1) z=0; /* read grey scanlines */\n    /* else read color scanlines */\n    do\n    {\n      for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n      {\n        q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);\n        if (q == (Quantum *) NULL)\n  {\n    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  MAT set image pixels returns unexpected NULL on a row %u.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n    goto done_reading;    /* Skip image rotation, when cannot set image pixels    */\n  }\n        if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)\n  {\n    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n             \"  MAT cannot read scanrow %u from a file.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n    goto ExitLoop;\n  }\n        if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))\n        {\n          FixLogical((unsigned char *)BImgBuff,ldblk);\n          if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n    {\nImportQuantumPixelsFailed:\n      if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  MAT failed to ImportQuantumPixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n      break;\n    }\n        }\n        else\n        {\n          if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n      goto ImportQuantumPixelsFailed;\n\n\n          if (z<=1 &&       /* fix only during a last pass z==0 || z==1 */\n          (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))\n      FixSignedValues(image,q,MATLAB_HDR.SizeX);\n        }\n\n        if (!SyncAuthenticPixels(image,exception))\n  {\n    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  MAT failed to sync image pixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n    goto ExitLoop;\n  }\n      }\n    } while(z-- >= 2);\nExitLoop:\n\n\n    /* Read complex part of numbers here */\n    if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n    {        /* Find Min and Max Values for complex parts of floats */\n      CellType = ReadBlobXXXLong(image2);    /* Additional object type */\n      i = ReadBlobXXXLong(image2);           /* size of a complex part - toss away*/\n\n      if (CellType==miDOUBLE || CellType==miSINGLE)\n      {\n        CalcMinMax(image2,  image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);      \n      }\n\n      if (CellType==miDOUBLE)\n        for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n  {\n          ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);\n          InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,\n            exception);\n  }\n\n      if (CellType==miSINGLE)\n        for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n  {\n          ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);\n          InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,\n            exception);\n  }    \n    }\n\n      /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */\n    if ((MATLAB_HDR.DimFlag == 8) &&\n        ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n      image->type=GrayscaleType;\n    if (image->depth == 1)\n      image->type=BilevelType;\n\n    if(image2==image)\n        image2 = NULL;    /* Remove shadow copy to an image before rotation. */\n\n      /*  Rotate image. */\n    rotated_image = RotateImage(image, 90.0, exception);\n    if (rotated_image != (Image *) NULL)\n    {\n        /* Remove page offsets added by RotateImage */\n      rotated_image->page.x=0;\n      rotated_image->page.y=0;\n\n      blob = rotated_image->blob;\n      rotated_image->blob = image->blob;\n      rotated_image->colors = image->colors;\n      image->blob = blob;\n      AppendImageToList(&image,rotated_image);      \n      DeleteImageFromList(&image);      \n    }\n\ndone_reading:\n\n    if(image2!=NULL)\n      if(image2!=image)\n      {\n        DeleteImageFromList(&image2); \n  if(clone_info)\n  {\n          if(clone_info->file)\n    {\n            fclose(clone_info->file);\n            clone_info->file = NULL;\n            (void) remove_utf8(clone_info->filename);\n    }\n        }    \n      }\n\n      /* Allocate next image structure. */    \n    AcquireNextImage(image_info,image,exception);\n    if (image->next == (Image *) NULL) break;                \n    image=SyncNextImageInList(image);\n    image->columns=image->rows=0;\n    image->colors=0;    \n\n      /* row scan buffer is no longer needed */\n    RelinquishMagickMemory(BImgBuff);\n    BImgBuff = NULL;\n\n    if(--Frames>0)\n    {\n      z = z2;\n      if(image2==NULL) image2 = image;\n      goto NEXT_FRAME;\n    }\n    if ((image2!=NULL) && (image2!=image))   /* Does shadow temporary decompressed image exist? */\n      {\n/*  CloseBlob(image2); */\n        DeleteImageFromList(&image2);\n        if(clone_info)\n        {\n          if(clone_info->file)\n          {\n            fclose(clone_info->file);\n            clone_info->file = NULL;\n            (void) remove_utf8(clone_info->filename);\n          }\n        }\n        }\n  }\n\n  clone_info=DestroyImageInfo(clone_info);\n  RelinquishMagickMemory(BImgBuff);\n  CloseBlob(image);\n\n\n  {\n    Image *p;    \n    ssize_t scene=0;\n    \n    /*\n      Rewind list, removing any empty images while rewinding.\n    */\n    p=image;\n    image=NULL;\n    while (p != (Image *) NULL)\n      {\n        Image *tmp=p;\n        if ((p->rows == 0) || (p->columns == 0)) {\n          p=p->previous;\n          DeleteImageFromList(&tmp);\n        } else {\n          image=p;\n          p=p->previous;\n        }\n      }\n    \n    /*\n      Fix scene numbers\n    */\n    for (p=image; p != (Image *) NULL; p=p->next)\n      p->scene=scene++;\n  }\n\n  if(clone_info != NULL)  /* cleanup garbage file from compression */\n  {\n    if(clone_info->file)\n    {\n      fclose(clone_info->file);\n      clone_info->file = NULL;\n      (void) remove_utf8(clone_info->filename);\n    }\n    DestroyImageInfo(clone_info);\n    clone_info = NULL;\n  }\n  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\"return\");\n  if(image==NULL)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  return (image);\n}", "func_hash": 123189732868835832469086799441508888909, "file_name": "mat.c", "file_hash": 184758751839368977736100938972533937602, "cwe": ["CWE-125"], "cve": "CVE-2016-10070", "cve_desc": "Heap-based buffer overflow in the CalcMinMax function in coders/mat.c in ImageMagick before 6.9.4-0 allows remote attackers to cause a denial of service (out-of-bounds read and application crash) via a crafted mat file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-10070"}
{"idx": 269941, "project": "ImageMagick", "commit_id": "a6240a163cb787909703d9fc649cf861f60ddd7c", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/a6240a163cb787909703d9fc649cf861f60ddd7c", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/131", "target": 0, "func": "static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n  Image *image, *image2=NULL,\n   *rotated_image;\n  register Quantum *q;\n\n  unsigned int status;\n  MATHeader MATLAB_HDR;\n  size_t size;  \n  size_t CellType;\n  QuantumInfo *quantum_info;\n  ImageInfo *clone_info;\n  int i;\n  ssize_t ldblk;\n  unsigned char *BImgBuff = NULL;\n  double MinVal, MaxVal;\n  unsigned z, z2;\n  unsigned Frames;\n  int logging;\n  int sample_size;\n  MagickOffsetType filepos=0x80;\n  BlobInfo *blob;\n  size_t one;\n  \n  unsigned int (*ReadBlobXXXLong)(Image *image);\n  unsigned short (*ReadBlobXXXShort)(Image *image);\n  void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);\n  void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);\n\n\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  logging = LogMagickEvent(CoderEvent,GetMagickModule(),\"enter\"); \n\n  /*\n     Open image file.\n   */\n  image = AcquireImage(image_info,exception);\n\n  status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n     Read MATLAB image.\n   */\n  clone_info=CloneImageInfo(image_info);\n  if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  MATLAB_HDR.Version = ReadBlobLSBShort(image);\n  if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\"  Endian %c%c\",\n        MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);\n  if (!strncmp(MATLAB_HDR.EndianIndicator, \"IM\", 2))\n  {\n    ReadBlobXXXLong = ReadBlobLSBLong;\n    ReadBlobXXXShort = ReadBlobLSBShort;\n    ReadBlobDoublesXXX = ReadBlobDoublesLSB;\n    ReadBlobFloatsXXX = ReadBlobFloatsLSB;\n    image->endian = LSBEndian;\n  } \n  else if (!strncmp(MATLAB_HDR.EndianIndicator, \"MI\", 2))\n  {\n    ReadBlobXXXLong = ReadBlobMSBLong;\n    ReadBlobXXXShort = ReadBlobMSBShort;\n    ReadBlobDoublesXXX = ReadBlobDoublesMSB;\n    ReadBlobFloatsXXX = ReadBlobFloatsMSB;\n    image->endian = MSBEndian;\n  }\n  else \n    goto MATLAB_KO;    /* unsupported endian */\n\n  if (strncmp(MATLAB_HDR.identific, \"MATLAB\", 6))\nMATLAB_KO: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n  filepos = TellBlob(image);\n  while(!EOFBlob(image)) /* object parser loop */\n  {\n    Frames = 1;\n    (void) SeekBlob(image,filepos,SEEK_SET);\n    /* printf(\"pos=%X\\n\",TellBlob(image)); */\n\n    MATLAB_HDR.DataType = ReadBlobXXXLong(image);\n    if(EOFBlob(image)) break;\n    MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);\n    if(EOFBlob(image)) break;\n    filepos += MATLAB_HDR.ObjectSize + 4 + 4;\n\n    image2 = image;\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n    if(MATLAB_HDR.DataType == miCOMPRESSED)\n    {\n      image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);\n      if(image2==NULL) continue;\n      MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */\n    }\n#endif    \n\n    if(MATLAB_HDR.DataType!=miMATRIX) continue;  /* skip another objects. */\n \n    MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);\n    MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);  \n\n    MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);\n    MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;\n    MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;  \n\n    MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);\n    if(image!=image2)\n      MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);  /* ??? don't understand why ?? */\n    MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);\n    MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);\n    MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);\n    MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);  \n   \n\n    switch(MATLAB_HDR.DimFlag)\n    {     \n      case  8: z2=z=1; break;      /* 2D matrix*/\n      case 12: z2=z = ReadBlobXXXLong(image2);  /* 3D matrix RGB*/\n           (void) ReadBlobXXXLong(image2);\n         if(z!=3) ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n         break;\n      case 16: z2=z = ReadBlobXXXLong(image2);  /* 4D matrix animation */\n         if(z!=3 && z!=1)\n            ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n           Frames = ReadBlobXXXLong(image2);\n         break;\n      default: ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n    }  \n\n    MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);\n    MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);\n\n    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"MATLAB_HDR.StructureClass %d\",MATLAB_HDR.StructureClass);\n    if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && \n        MATLAB_HDR.StructureClass != mxSINGLE_CLASS &&    /* float + complex float */\n        MATLAB_HDR.StructureClass != mxDOUBLE_CLASS &&    /* double + complex double */\n        MATLAB_HDR.StructureClass != mxINT8_CLASS &&\n        MATLAB_HDR.StructureClass != mxUINT8_CLASS &&    /* uint8 + uint8 3D */\n        MATLAB_HDR.StructureClass != mxINT16_CLASS &&\n        MATLAB_HDR.StructureClass != mxUINT16_CLASS &&    /* uint16 + uint16 3D */\n        MATLAB_HDR.StructureClass != mxINT32_CLASS &&\n        MATLAB_HDR.StructureClass != mxUINT32_CLASS &&    /* uint32 + uint32 3D */\n        MATLAB_HDR.StructureClass != mxINT64_CLASS &&\n        MATLAB_HDR.StructureClass != mxUINT64_CLASS)    /* uint64 + uint64 3D */\n      ThrowReaderException(CoderError,\"UnsupportedCellTypeInTheMatrix\");\n\n    switch (MATLAB_HDR.NameFlag)\n    {\n      case 0:\n        size = ReadBlobXXXLong(image2);  /* Object name string size */\n        size = 4 * (ssize_t) ((size + 3 + 1) / 4);\n        (void) SeekBlob(image2, size, SEEK_CUR);\n        break;\n      case 1:\n      case 2:\n      case 3:\n      case 4:\n        (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */\n        break;\n      default:\n        goto MATLAB_KO;\n    }\n\n    CellType = ReadBlobXXXLong(image2);    /* Additional object type */\n    if (logging)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n        \"MATLAB_HDR.CellType: %.20g\",(double) CellType);\n  \n    (void) ReadBlob(image2, 4, (unsigned char *) &size);     /* data size */\n\n    NEXT_FRAME:\n    switch (CellType)\n    {\n      case miINT8:\n      case miUINT8:\n        sample_size = 8;\n        if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) \n          image->depth = 1;\n        else\n          image->depth = 8;         /* Byte type cell */\n        ldblk = (ssize_t) MATLAB_HDR.SizeX;      \n        break;\n      case miINT16:\n      case miUINT16:\n        sample_size = 16;\n        image->depth = 16;        /* Word type cell */\n        ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);\n        break;\n      case miINT32:\n      case miUINT32:\n        sample_size = 32;\n        image->depth = 32;        /* Dword type cell */\n        ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);      \n        break;\n      case miINT64:\n      case miUINT64:\n        sample_size = 64;\n        image->depth = 64;        /* Qword type cell */\n        ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);      \n        break;   \n      case miSINGLE:\n        sample_size = 32;\n        image->depth = 32;        /* double type cell */\n        (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\n        if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n  {              /* complex float type cell */\n  }\n        ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n        break;\n      case miDOUBLE:\n        sample_size = 64; \n        image->depth = 64;        /* double type cell */\n        (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\nDisableMSCWarning(4127)\n        if (sizeof(double) != 8)\nRestoreMSCWarning\n          ThrowReaderException(CoderError, \"IncompatibleSizeOfDouble\");\n        if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n  {                         /* complex double type cell */        \n  }\n        ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n        break;\n      default:\n        ThrowReaderException(CoderError, \"UnsupportedCellTypeInTheMatrix\");\n    }\n    (void) sample_size;\n    image->columns = MATLAB_HDR.SizeX;\n    image->rows = MATLAB_HDR.SizeY;    \n    quantum_info=AcquireQuantumInfo(clone_info,image);\n    if (quantum_info == (QuantumInfo *) NULL)\n      ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n    one=1;\n    image->colors = one << image->depth;\n    if (image->columns == 0 || image->rows == 0)\n      goto MATLAB_KO;\n    /* Image is gray when no complex flag is set and 2D Matrix */\n    if ((MATLAB_HDR.DimFlag == 8) &&\n        ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n      {\n        image->type=GrayscaleType;\n        SetImageColorspace(image,GRAYColorspace,exception);\n      }\n\n\n    /*\n      If ping is true, then only set image size and colors without\n      reading any image data.\n    */\n    if (image_info->ping)\n    {\n      size_t temp = image->columns;\n      image->columns = image->rows;\n      image->rows = temp;\n      goto done_reading; /* !!!!!! BAD  !!!! */\n    }  \n    status=SetImageExtent(image,image->columns,image->rows,exception);\n    if (status == MagickFalse)\n      return(DestroyImageList(image));\n\n  /* ----- Load raster data ----- */\n    BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double));    /* Ldblk was set in the check phase */\n    if (BImgBuff == NULL)\n      ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n    MinVal = 0;\n    MaxVal = 0;\n    if (CellType==miDOUBLE || CellType==miSINGLE)        /* Find Min and Max Values for floats */\n    {\n      CalcMinMax(image2, image_info->endian,  MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);\n    }\n\n    /* Main loop for reading all scanlines */\n    if(z==1) z=0; /* read grey scanlines */\n    /* else read color scanlines */\n    do\n    {\n      for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n      {\n        q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);\n        if (q == (Quantum *) NULL)\n  {\n    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  MAT set image pixels returns unexpected NULL on a row %u.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n    goto done_reading;    /* Skip image rotation, when cannot set image pixels    */\n  }\n        if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)\n  {\n    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n             \"  MAT cannot read scanrow %u from a file.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n    goto ExitLoop;\n  }\n        if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))\n        {\n          FixLogical((unsigned char *)BImgBuff,ldblk);\n          if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n    {\nImportQuantumPixelsFailed:\n      if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  MAT failed to ImportQuantumPixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n      break;\n    }\n        }\n        else\n        {\n          if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n      goto ImportQuantumPixelsFailed;\n\n\n          if (z<=1 &&       /* fix only during a last pass z==0 || z==1 */\n          (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))\n      FixSignedValues(image,q,MATLAB_HDR.SizeX);\n        }\n\n        if (!SyncAuthenticPixels(image,exception))\n  {\n    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  MAT failed to sync image pixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n    goto ExitLoop;\n  }\n      }\n    } while(z-- >= 2);\n    quantum_info=DestroyQuantumInfo(quantum_info);\nExitLoop:\n\n\n    /* Read complex part of numbers here */\n    if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n    {        /* Find Min and Max Values for complex parts of floats */\n      CellType = ReadBlobXXXLong(image2);    /* Additional object type */\n      i = ReadBlobXXXLong(image2);           /* size of a complex part - toss away*/\n\n      if (CellType==miDOUBLE || CellType==miSINGLE)\n      {\n        CalcMinMax(image2,  image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);      \n      }\n\n      if (CellType==miDOUBLE)\n        for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n  {\n          ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);\n          InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,\n            exception);\n  }\n\n      if (CellType==miSINGLE)\n        for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n  {\n          ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);\n          InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,\n            exception);\n  }    \n    }\n\n      /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */\n    if ((MATLAB_HDR.DimFlag == 8) &&\n        ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n      image->type=GrayscaleType;\n    if (image->depth == 1)\n      image->type=BilevelType;\n\n    if(image2==image)\n        image2 = NULL;    /* Remove shadow copy to an image before rotation. */\n\n      /*  Rotate image. */\n    rotated_image = RotateImage(image, 90.0, exception);\n    if (rotated_image != (Image *) NULL)\n    {\n        /* Remove page offsets added by RotateImage */\n      rotated_image->page.x=0;\n      rotated_image->page.y=0;\n\n      blob = rotated_image->blob;\n      rotated_image->blob = image->blob;\n      rotated_image->colors = image->colors;\n      image->blob = blob;\n      AppendImageToList(&image,rotated_image);      \n      DeleteImageFromList(&image);      \n    }\n\ndone_reading:\n\n    if(image2!=NULL)\n      if(image2!=image)\n      {\n        DeleteImageFromList(&image2); \n  if(clone_info)\n  {\n          if(clone_info->file)\n    {\n            fclose(clone_info->file);\n            clone_info->file = NULL;\n            (void) remove_utf8(clone_info->filename);\n    }\n        }    \n      }\n\n      /* Allocate next image structure. */    \n    AcquireNextImage(image_info,image,exception);\n    if (image->next == (Image *) NULL) break;                \n    image=SyncNextImageInList(image);\n    image->columns=image->rows=0;\n    image->colors=0;    \n\n      /* row scan buffer is no longer needed */\n    RelinquishMagickMemory(BImgBuff);\n    BImgBuff = NULL;\n\n    if(--Frames>0)\n    {\n      z = z2;\n      if(image2==NULL) image2 = image;\n      goto NEXT_FRAME;\n    }\n    if ((image2!=NULL) && (image2!=image))   /* Does shadow temporary decompressed image exist? */\n      {\n/*  CloseBlob(image2); */\n        DeleteImageFromList(&image2);\n        if(clone_info)\n        {\n          if(clone_info->file)\n          {\n            fclose(clone_info->file);\n            clone_info->file = NULL;\n            (void) remove_utf8(clone_info->filename);\n          }\n        }\n        }\n  }\n\n  clone_info=DestroyImageInfo(clone_info);\n  RelinquishMagickMemory(BImgBuff);\n  CloseBlob(image);\n\n\n  {\n    Image *p;    \n    ssize_t scene=0;\n    \n    /*\n      Rewind list, removing any empty images while rewinding.\n    */\n    p=image;\n    image=NULL;\n    while (p != (Image *) NULL)\n      {\n        Image *tmp=p;\n        if ((p->rows == 0) || (p->columns == 0)) {\n          p=p->previous;\n          DeleteImageFromList(&tmp);\n        } else {\n          image=p;\n          p=p->previous;\n        }\n      }\n    \n    /*\n      Fix scene numbers\n    */\n    for (p=image; p != (Image *) NULL; p=p->next)\n      p->scene=scene++;\n  }\n\n  if(clone_info != NULL)  /* cleanup garbage file from compression */\n  {\n    if(clone_info->file)\n    {\n      fclose(clone_info->file);\n      clone_info->file = NULL;\n      (void) remove_utf8(clone_info->filename);\n    }\n    DestroyImageInfo(clone_info);\n    clone_info = NULL;\n  }\n  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\"return\");\n  if(image==NULL)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  return (image);\n}", "func_hash": 205922153843401929123471609593284641539, "file_name": "mat.c", "file_hash": 33852343362379814248025234856365636680, "cwe": ["CWE-125"], "cve": "CVE-2016-10070", "cve_desc": "Heap-based buffer overflow in the CalcMinMax function in coders/mat.c in ImageMagick before 6.9.4-0 allows remote attackers to cause a denial of service (out-of-bounds read and application crash) via a crafted mat file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-10070"}
{"idx": 198169, "project": "tensorflow", "commit_id": "5b048e87e4e55990dae6b547add4dae59f4e1c76", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/5b048e87e4e55990dae6b547add4dae59f4e1c76", "commit_message": "Fix a null pointer exception in SVDF\n\nThis is due to not checking that `GetVariableInput` returns non-null tensor.\n\nAlso fix a potential null pointer exception in `GetVariableInput`.\n\nPiperOrigin-RevId: 385160147\nChange-Id: Iadf3f0705b036a9014d27caa5a8bbd91f4c4c401", "target": 1, "func": "TfLiteTensor* GetVariableInput(TfLiteContext* context, const TfLiteNode* node,\n                               int index) {\n  TfLiteTensor* tensor = GetMutableInput(context, node, index);\n  return tensor->is_variable ? tensor : nullptr;\n}", "func_hash": 10926286429278682792722078244037344195, "file_name": "kernel_util.cc", "file_hash": 18607953596861130302659896453881171161, "cwe": ["CWE-369"], "cve": "CVE-2021-37681", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of SVDF in TFLite is [vulnerable to a null pointer error](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/lite/kernels/svdf.cc#L300-L313). The [`GetVariableInput` function](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/lite/kernels/kernel_util.cc#L115-L119) can return a null pointer but `GetTensorData` assumes that the argument is always a valid tensor. Furthermore, because `GetVariableInput` calls [`GetMutableInput`](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/lite/kernels/kernel_util.cc#L82-L90) which might return `nullptr`, the `tensor->is_variable` expression can also trigger a null pointer exception. We have patched the issue in GitHub commit 5b048e87e4e55990dae6b547add4dae59f4e1c76. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37681"}
{"idx": 270119, "project": "tensorflow", "commit_id": "5b048e87e4e55990dae6b547add4dae59f4e1c76", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/5b048e87e4e55990dae6b547add4dae59f4e1c76", "commit_message": "Fix a null pointer exception in SVDF\n\nThis is due to not checking that `GetVariableInput` returns non-null tensor.\n\nAlso fix a potential null pointer exception in `GetVariableInput`.\n\nPiperOrigin-RevId: 385160147\nChange-Id: Iadf3f0705b036a9014d27caa5a8bbd91f4c4c401", "target": 0, "func": "TfLiteTensor* GetVariableInput(TfLiteContext* context, const TfLiteNode* node,\n                               int index) {\n  TfLiteTensor* tensor = GetMutableInput(context, node, index);\n  if (tensor == nullptr) return nullptr;\n  return tensor->is_variable ? tensor : nullptr;\n}", "func_hash": 49925212590704154361310384417186854395, "file_name": "kernel_util.cc", "file_hash": 281364131026460345167544019199859453435, "cwe": ["CWE-369"], "cve": "CVE-2021-37681", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of SVDF in TFLite is [vulnerable to a null pointer error](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/lite/kernels/svdf.cc#L300-L313). The [`GetVariableInput` function](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/lite/kernels/kernel_util.cc#L115-L119) can return a null pointer but `GetTensorData` assumes that the argument is always a valid tensor. Furthermore, because `GetVariableInput` calls [`GetMutableInput`](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/lite/kernels/kernel_util.cc#L82-L90) which might return `nullptr`, the `tensor->is_variable` expression can also trigger a null pointer exception. We have patched the issue in GitHub commit 5b048e87e4e55990dae6b547add4dae59f4e1c76. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37681"}
{"idx": 198239, "project": "barebox", "commit_id": "a3337563c705bc8e0cf32f910b3e9e3c43d962ff", "project_url": "https://github.com/saschahauer/barebox", "commit_url": "https://github.com/saschahauer/barebox/commit/a3337563c705bc8e0cf32f910b3e9e3c43d962ff", "commit_message": "password: Use crypto_memneq() to compare hashes\n\nCryptographic verifications should be time-constant so that an attacker\ncannot get information about the secrets used by observing the system,\nso use crypto_memneq() rather than memcmp() to compare password hashes.\n\nSigned-off-by: Sascha Hauer ", "target": 1, "func": "static int check_passwd(unsigned char *passwd, size_t length)\n{\n\tstruct digest *d = NULL;\n\tunsigned char *passwd1_sum;\n\tunsigned char *passwd2_sum;\n\tint ret = 0;\n\tint hash_len;\n\n\tif (IS_ENABLED(CONFIG_PASSWD_CRYPTO_PBKDF2)) {\n\t\thash_len = PBKDF2_LENGTH;\n\t} else {\n\t\td = digest_alloc(PASSWD_SUM);\n\t\tif (!d) {\n\t\t\tpr_err(\"No such digest: %s\\n\",\n\t\t\t       PASSWD_SUM ? PASSWD_SUM : \"NULL\");\n\t\t\treturn -ENOENT;\n\t\t}\n\n\t\thash_len = digest_length(d);\n\t}\n\n\tpasswd1_sum = calloc(hash_len * 2, sizeof(unsigned char));\n\tif (!passwd1_sum)\n\t\treturn -ENOMEM;\n\n\tpasswd2_sum = passwd1_sum + hash_len;\n\n\tif (is_passwd_env_enable())\n\t\tret = read_env_passwd(passwd2_sum, hash_len);\n\telse if (is_passwd_default_enable())\n\t\tret = read_default_passwd(passwd2_sum, hash_len);\n\telse\n\t\tret = -EINVAL;\n\n\tif (ret < 0)\n\t\tgoto err;\n\n\tif (IS_ENABLED(CONFIG_PASSWD_CRYPTO_PBKDF2)) {\n\t\tchar *key = passwd2_sum + PBKDF2_SALT_LEN;\n\t\tchar *salt = passwd2_sum;\n\t\tint keylen = PBKDF2_LENGTH - PBKDF2_SALT_LEN;\n\n\t\tret = pkcs5_pbkdf2_hmac_sha1(passwd, length, salt,\n\t\t\tPBKDF2_SALT_LEN, PBKDF2_COUNT, keylen, passwd1_sum);\n\t\tif (ret)\n\t\t\tgoto err;\n\n\t\tif (strncmp(passwd1_sum, key, keylen) == 0)\n\t\t\tret = 1;\n\t} else {\n\t\tret = digest_digest(d, passwd, length, passwd1_sum);\n\n\t\tif (ret)\n\t\t\tgoto err;\n\n\t\tif (strncmp(passwd1_sum, passwd2_sum, hash_len) == 0)\n\t\t\tret = 1;\n\t}\n\nerr:\n\tfree(passwd1_sum);\n\tdigest_free(d);\n\n\treturn ret;\n}", "func_hash": 69404159605803282192043232030112739673, "file_name": "password.c", "file_hash": 155548681482248654497093234101023237595, "cwe": ["CWE-200"], "cve": "CVE-2021-37848", "cve_desc": "common/password.c in Pengutronix barebox through 2021.07.0 leaks timing information because strncmp is used during hash comparison.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37848"}
{"idx": 270767, "project": "barebox", "commit_id": "a3337563c705bc8e0cf32f910b3e9e3c43d962ff", "project_url": "https://github.com/saschahauer/barebox", "commit_url": "https://github.com/saschahauer/barebox/commit/a3337563c705bc8e0cf32f910b3e9e3c43d962ff", "commit_message": "password: Use crypto_memneq() to compare hashes\n\nCryptographic verifications should be time-constant so that an attacker\ncannot get information about the secrets used by observing the system,\nso use crypto_memneq() rather than memcmp() to compare password hashes.\n\nSigned-off-by: Sascha Hauer ", "target": 0, "func": "static int check_passwd(unsigned char *passwd, size_t length)\n{\n\tstruct digest *d = NULL;\n\tunsigned char *passwd1_sum;\n\tunsigned char *passwd2_sum;\n\tint ret = 0;\n\tint hash_len;\n\n\tif (IS_ENABLED(CONFIG_PASSWD_CRYPTO_PBKDF2)) {\n\t\thash_len = PBKDF2_LENGTH;\n\t} else {\n\t\td = digest_alloc(PASSWD_SUM);\n\t\tif (!d) {\n\t\t\tpr_err(\"No such digest: %s\\n\",\n\t\t\t       PASSWD_SUM ? PASSWD_SUM : \"NULL\");\n\t\t\treturn -ENOENT;\n\t\t}\n\n\t\thash_len = digest_length(d);\n\t}\n\n\tpasswd1_sum = calloc(hash_len * 2, sizeof(unsigned char));\n\tif (!passwd1_sum)\n\t\treturn -ENOMEM;\n\n\tpasswd2_sum = passwd1_sum + hash_len;\n\n\tif (is_passwd_env_enable())\n\t\tret = read_env_passwd(passwd2_sum, hash_len);\n\telse if (is_passwd_default_enable())\n\t\tret = read_default_passwd(passwd2_sum, hash_len);\n\telse\n\t\tret = -EINVAL;\n\n\tif (ret < 0)\n\t\tgoto err;\n\n\tif (IS_ENABLED(CONFIG_PASSWD_CRYPTO_PBKDF2)) {\n\t\tchar *key = passwd2_sum + PBKDF2_SALT_LEN;\n\t\tchar *salt = passwd2_sum;\n\t\tint keylen = PBKDF2_LENGTH - PBKDF2_SALT_LEN;\n\n\t\tret = pkcs5_pbkdf2_hmac_sha1(passwd, length, salt,\n\t\t\tPBKDF2_SALT_LEN, PBKDF2_COUNT, keylen, passwd1_sum);\n\t\tif (ret)\n\t\t\tgoto err;\n\n\t\tif (!crypto_memneq(passwd1_sum, key, keylen))\n\t\t\tret = 1;\n\t} else {\n\t\tret = digest_digest(d, passwd, length, passwd1_sum);\n\n\t\tif (ret)\n\t\t\tgoto err;\n\n\t\tif (!crypto_memneq(passwd1_sum, passwd2_sum, hash_len))\n\t\t\tret = 1;\n\t}\n\nerr:\n\tfree(passwd1_sum);\n\tdigest_free(d);\n\n\treturn ret;\n}", "func_hash": 302844013312241869650823093325226390405, "file_name": "password.c", "file_hash": 185444326340131244335688275872870296486, "cwe": ["CWE-200"], "cve": "CVE-2021-37848", "cve_desc": "common/password.c in Pengutronix barebox through 2021.07.0 leaks timing information because strncmp is used during hash comparison.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37848"}
{"idx": 198259, "project": "tensorflow", "commit_id": "a2b743f6017d7b97af1fe49087ae15f0ac634373", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a2b743f6017d7b97af1fe49087ae15f0ac634373", "commit_message": "Fix heap OOB in `tf.raw_ops.RaggedGather`\n\nPiperOrigin-RevId: 388355464\nChange-Id: If14d96231d1cd7aad7c4d1c22c1bab1576b75717", "target": 1, "func": "  void Compute(OpKernelContext* context) override {\n    // Get the input Tensors.\n    OpInputList params_nested_splits_in;\n    OP_REQUIRES_OK(context, context->input_list(\"params_nested_splits\",\n                                                ¶ms_nested_splits_in));\n    const Tensor& params_dense_values_in =\n        context->input(params_nested_splits_in.size());\n    const Tensor& indices_in =\n        context->input(params_nested_splits_in.size() + 1);\n\n    DCHECK_GT(params_nested_splits_in.size(), 0);  // Enforced by REGISTER_OP.\n    SPLITS_TYPE num_params = params_nested_splits_in[0].dim_size(0) - 1;\n    OP_REQUIRES_OK(context, ValidateIndices(indices_in, num_params));\n\n    OP_REQUIRES(context, params_dense_values_in.dims() > 0,\n                errors::InvalidArgument(\"params.rank must be nonzero\"));\n    SPLITS_TYPE num_params_dense_values = params_dense_values_in.dim_size(0);\n\n    // Calculate the `splits`, and store the value slices that we need to\n    // copy in `value_slices`.\n    std::vector> value_slices;\n    SPLITS_TYPE num_values = 0;\n    std::vector> out_splits;\n    OP_REQUIRES_OK(context, MakeSplits(indices_in, params_nested_splits_in,\n                                       num_params_dense_values, &out_splits,\n                                       &value_slices, &num_values));\n\n    // Write the output tensors.\n    OP_REQUIRES_OK(context, WriteSplits(out_splits, context));\n    OP_REQUIRES_OK(context,\n                   WriteValues(params_dense_values_in, value_slices,\n                               out_splits.size(), num_values, context));\n  }", "func_hash": 307099744677498626698554862398752331906, "file_name": "ragged_gather_op.cc", "file_hash": 101959606941305621670893175769931334336, "cwe": ["CWE-369"], "cve": "CVE-2021-37641", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions if the arguments to `tf.raw_ops.RaggedGather` don't determine a valid ragged tensor code can trigger a read from outside of bounds of heap allocated buffers. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/ragged_gather_op.cc#L70) directly reads the first dimension of a tensor shape before checking that said tensor has rank of at least 1 (i.e., it is not a scalar). Furthermore, the implementation does not check that the list given by `params_nested_splits` is not an empty list of tensors. We have patched the issue in GitHub commit a2b743f6017d7b97af1fe49087ae15f0ac634373. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37641"}
{"idx": 270922, "project": "tensorflow", "commit_id": "a2b743f6017d7b97af1fe49087ae15f0ac634373", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a2b743f6017d7b97af1fe49087ae15f0ac634373", "commit_message": "Fix heap OOB in `tf.raw_ops.RaggedGather`\n\nPiperOrigin-RevId: 388355464\nChange-Id: If14d96231d1cd7aad7c4d1c22c1bab1576b75717", "target": 0, "func": "  void Compute(OpKernelContext* context) override {\n    // Get the input Tensors.\n\n    OpInputList params_nested_splits_in;\n    OP_REQUIRES_OK(context, context->input_list(\"params_nested_splits\",\n                                                ¶ms_nested_splits_in));\n    OP_REQUIRES(\n        context, params_nested_splits_in.size() > 0,\n        errors::InvalidArgument(\"params_nested_splits must be non empty\"));\n\n    const Tensor& params_dense_values_in =\n        context->input(params_nested_splits_in.size());\n    const Tensor& indices_in =\n        context->input(params_nested_splits_in.size() + 1);\n\n    OP_REQUIRES(context, params_nested_splits_in[0].dims() > 0,\n                errors::InvalidArgument(\"Split tensors must not be scalars\"));\n    SPLITS_TYPE num_params = params_nested_splits_in[0].dim_size(0) - 1;\n    OP_REQUIRES_OK(context, ValidateIndices(indices_in, num_params));\n\n    OP_REQUIRES(context, params_dense_values_in.dims() > 0,\n                errors::InvalidArgument(\"params.rank must be nonzero\"));\n    SPLITS_TYPE num_params_dense_values = params_dense_values_in.dim_size(0);\n\n    // Calculate the `splits`, and store the value slices that we need to\n    // copy in `value_slices`.\n    std::vector> value_slices;\n    SPLITS_TYPE num_values = 0;\n    std::vector> out_splits;\n    OP_REQUIRES_OK(context, MakeSplits(indices_in, params_nested_splits_in,\n                                       num_params_dense_values, &out_splits,\n                                       &value_slices, &num_values));\n\n    // Write the output tensors.\n    OP_REQUIRES_OK(context, WriteSplits(out_splits, context));\n    OP_REQUIRES_OK(context,\n                   WriteValues(params_dense_values_in, value_slices,\n                               out_splits.size(), num_values, context));\n  }", "func_hash": 304284468048103303443088360733960613826, "file_name": "ragged_gather_op.cc", "file_hash": 6259209335630890620694318717446398342, "cwe": ["CWE-369"], "cve": "CVE-2021-37641", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions if the arguments to `tf.raw_ops.RaggedGather` don't determine a valid ragged tensor code can trigger a read from outside of bounds of heap allocated buffers. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/ragged_gather_op.cc#L70) directly reads the first dimension of a tensor shape before checking that said tensor has rank of at least 1 (i.e., it is not a scalar). Furthermore, the implementation does not check that the list given by `params_nested_splits` is not an empty list of tensors. We have patched the issue in GitHub commit a2b743f6017d7b97af1fe49087ae15f0ac634373. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37641"}
{"idx": 198282, "project": "tensorflow", "commit_id": "4923de56ec94fff7770df259ab7f2288a74feb41", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4923de56ec94fff7770df259ab7f2288a74feb41", "commit_message": "Don't do any work when reshaping 0 elements sparse tensor.\n\nIf reshaping to 0 elements tensor, check that input has no elements.\nIf reshaping no elements input, check that output has no elements.\n\nPiperOrigin-RevId: 388296986\nChange-Id: Iadc9fe7252e14313ca987e69bf0d7042fd10232a", "target": 1, "func": "void ReshapeSparseTensor(OpKernelContext *context,\n                         const Tensor &input_indices_in,\n                         const Tensor &input_shape_in,\n                         const Tensor &target_shape_in, int output_indices_idx,\n                         int output_shape_idx) {\n  OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices_in.shape()),\n              errors::InvalidArgument(\n                  \"Input indices should be a matrix but received shape \",\n                  input_indices_in.shape().DebugString()));\n  OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape_in.shape()),\n              errors::InvalidArgument(\n                  \"Input shape should be a vector but received shape \",\n                  input_shape_in.shape().DebugString()));\n  OP_REQUIRES(context, TensorShapeUtils::IsVector(target_shape_in.shape()),\n              errors::InvalidArgument(\n                  \"Target shape should be a vector but received shape \",\n                  target_shape_in.shape().DebugString()));\n\n  const int64_t output_rank = target_shape_in.NumElements();\n  const TensorShape input_shape(input_shape_in.vec());\n  const int64_t dense_size = input_shape.num_elements();\n  const int64_t nnz = input_indices_in.shape().dim_size(0);\n\n  // Compute the output shape. Determine product of specified dimensions, and\n  // find the index of the unspecified one.\n  TensorShape output_shape;\n  int64_t product = 1;\n  int unknown_index = -1;\n  auto target_shape = target_shape_in.vec();\n  for (int d = 0; d < output_rank; ++d) {\n    const int64_t size = target_shape(d);\n    if (size == -1) {\n      OP_REQUIRES(\n          context, unknown_index == -1,\n          errors::InvalidArgument(\"only one output dimension may be -1, \"\n                                  \"not both \",\n                                  unknown_index, \" and \", d));\n      unknown_index = d;\n      output_shape.AddDim(1);\n    } else {\n      OP_REQUIRES(context, size >= 0,\n                  errors::InvalidArgument(\"size \", d,\n                                          \" must be non-negative, not \", size));\n      product *= size;\n      output_shape.AddDim(size);\n    }\n  }\n  if (unknown_index != -1) {\n    OP_REQUIRES(\n        context, product > 0,\n        errors::InvalidArgument(\"reshape cannot infer the missing \"\n                                \"input size for an empty tensor unless all \"\n                                \"specified input sizes are non-zero\"));\n    const int64_t missing = dense_size / product;\n    OP_REQUIRES(\n        context, product * missing == dense_size,\n        errors::InvalidArgument(\n            \"Input to reshape is a SparseTensor with \", dense_size,\n            \" dense values, but the requested shape requires a multiple of \",\n            product, \". input_shape=\", input_shape.DebugString(),\n            \" output_shape=\", output_shape.DebugString()));\n    output_shape.set_dim(unknown_index, missing);\n  }\n\n  OP_REQUIRES(\n      context, output_shape.num_elements() == dense_size,\n      errors::InvalidArgument(\"Input to reshape is a tensor with \", dense_size,\n                              \" dense values, but the requested shape has \",\n                              output_shape.num_elements(),\n                              \". input_shape=\", input_shape.DebugString(),\n                              \" output_shape=\", output_shape.DebugString()));\n\n  // Optimize for reshaping to the same shape.\n  if (input_shape == output_shape) {\n    context->set_output(output_indices_idx, input_indices_in);\n    context->set_output(output_shape_idx, input_shape_in);\n    return;\n  }\n\n  Tensor *result_shape = nullptr;\n  OP_REQUIRES_OK(context, context->allocate_output(output_shape_idx,\n                                                   TensorShape({output_rank}),\n                                                   &result_shape));\n  auto output_shape_vec = result_shape->vec();\n  for (int j = 0; j < output_shape.dims(); ++j) {\n    output_shape_vec(j) = output_shape.dim_size(j);\n  }\n\n  Tensor *result_indices = nullptr;\n  OP_REQUIRES_OK(context,\n                 context->allocate_output(output_indices_idx,\n                                          TensorShape({nnz, output_rank}),\n                                          &result_indices));\n  if (nnz > 0) {\n    OP_REQUIRES_OK(context, functor::ReshapeSparseTensorFunctor()(\n                                context, input_shape, output_shape,\n                                input_indices_in.matrix(),\n                                result_indices->matrix()));\n  }\n}", "func_hash": 228488147174937246000179946900319201208, "file_name": "reshape_util.cc", "file_hash": 224364433068010361888882257047924749715, "cwe": ["CWE-369"], "cve": "CVE-2021-37640", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of `tf.raw_ops.SparseReshape` can be made to trigger an integral division by 0 exception. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/reshape_util.cc#L176-L181) calls the reshaping functor whenever there is at least an index in the input but does not check that shape of the input or the target shape have both a non-zero number of elements. The [reshape functor](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/reshape_util.cc#L40-L78) blindly divides by the dimensions of the target shape. Hence, if this is not checked, code will result in a division by 0. We have patched the issue in GitHub commit 4923de56ec94fff7770df259ab7f2288a74feb41. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1 as this is the other affected version.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37640"}
{"idx": 271526, "project": "tensorflow", "commit_id": "4923de56ec94fff7770df259ab7f2288a74feb41", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/4923de56ec94fff7770df259ab7f2288a74feb41", "commit_message": "Don't do any work when reshaping 0 elements sparse tensor.\n\nIf reshaping to 0 elements tensor, check that input has no elements.\nIf reshaping no elements input, check that output has no elements.\n\nPiperOrigin-RevId: 388296986\nChange-Id: Iadc9fe7252e14313ca987e69bf0d7042fd10232a", "target": 0, "func": "void ReshapeSparseTensor(OpKernelContext *context,\n                         const Tensor &input_indices_in,\n                         const Tensor &input_shape_in,\n                         const Tensor &target_shape_in, int output_indices_idx,\n                         int output_shape_idx) {\n  OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices_in.shape()),\n              errors::InvalidArgument(\n                  \"Input indices should be a matrix but received shape \",\n                  input_indices_in.shape().DebugString()));\n  OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape_in.shape()),\n              errors::InvalidArgument(\n                  \"Input shape should be a vector but received shape \",\n                  input_shape_in.shape().DebugString()));\n  OP_REQUIRES(context, TensorShapeUtils::IsVector(target_shape_in.shape()),\n              errors::InvalidArgument(\n                  \"Target shape should be a vector but received shape \",\n                  target_shape_in.shape().DebugString()));\n\n  const int64_t output_rank = target_shape_in.NumElements();\n  const TensorShape input_shape(input_shape_in.vec());\n  const int64_t dense_size = input_shape.num_elements();\n  const int64_t nnz = input_indices_in.shape().dim_size(0);\n\n  // Compute the output shape. Determine product of specified dimensions, and\n  // find the index of the unspecified one.\n  TensorShape output_shape;\n  int64_t product = 1;\n  int unknown_index = -1;\n  auto target_shape = target_shape_in.vec();\n  for (int d = 0; d < output_rank; ++d) {\n    const int64_t size = target_shape(d);\n    if (size == -1) {\n      OP_REQUIRES(\n          context, unknown_index == -1,\n          errors::InvalidArgument(\"only one output dimension may be -1, \"\n                                  \"not both \",\n                                  unknown_index, \" and \", d));\n      unknown_index = d;\n      output_shape.AddDim(1);\n    } else {\n      OP_REQUIRES(context, size >= 0,\n                  errors::InvalidArgument(\"size \", d,\n                                          \" must be non-negative, not \", size));\n      product *= size;\n      output_shape.AddDim(size);\n    }\n  }\n  if (unknown_index != -1) {\n    OP_REQUIRES(\n        context, product > 0,\n        errors::InvalidArgument(\"reshape cannot infer the missing \"\n                                \"input size for an empty tensor unless all \"\n                                \"specified input sizes are non-zero\"));\n    const int64_t missing = dense_size / product;\n    OP_REQUIRES(\n        context, product * missing == dense_size,\n        errors::InvalidArgument(\n            \"Input to reshape is a SparseTensor with \", dense_size,\n            \" dense values, but the requested shape requires a multiple of \",\n            product, \". input_shape=\", input_shape.DebugString(),\n            \" output_shape=\", output_shape.DebugString()));\n    output_shape.set_dim(unknown_index, missing);\n  }\n\n  OP_REQUIRES(\n      context, output_shape.num_elements() == dense_size,\n      errors::InvalidArgument(\"Input to reshape is a tensor with \", dense_size,\n                              \" dense values, but the requested shape has \",\n                              output_shape.num_elements(),\n                              \". input_shape=\", input_shape.DebugString(),\n                              \" output_shape=\", output_shape.DebugString()));\n\n  // Optimize for reshaping to the same shape.\n  if (input_shape == output_shape) {\n    context->set_output(output_indices_idx, input_indices_in);\n    context->set_output(output_shape_idx, input_shape_in);\n    return;\n  }\n\n  Tensor *result_shape = nullptr;\n  OP_REQUIRES_OK(context, context->allocate_output(output_shape_idx,\n                                                   TensorShape({output_rank}),\n                                                   &result_shape));\n  auto output_shape_vec = result_shape->vec();\n  for (int j = 0; j < output_shape.dims(); ++j) {\n    output_shape_vec(j) = output_shape.dim_size(j);\n  }\n\n  Tensor *result_indices = nullptr;\n  OP_REQUIRES_OK(context,\n                 context->allocate_output(output_indices_idx,\n                                          TensorShape({nnz, output_rank}),\n                                          &result_indices));\n  if (nnz > 0) {\n    OP_REQUIRES(\n        context, dense_size > 0 && product > 0,\n        errors::InvalidArgument(\n            \"Input tensor has \", nnz, \" non zero elements but input shape (\",\n            input_shape.DebugString(), \") or output shape (\",\n            output_shape.DebugString(), \") is empty\"));\n    OP_REQUIRES_OK(context, functor::ReshapeSparseTensorFunctor()(\n                                context, input_shape, output_shape,\n                                input_indices_in.matrix(),\n                                result_indices->matrix()));\n  }\n}", "func_hash": 110342704301029445327548172085240958100, "file_name": "reshape_util.cc", "file_hash": 175969764047663062260521886402354193689, "cwe": ["CWE-369"], "cve": "CVE-2021-37640", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of `tf.raw_ops.SparseReshape` can be made to trigger an integral division by 0 exception. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/reshape_util.cc#L176-L181) calls the reshaping functor whenever there is at least an index in the input but does not check that shape of the input or the target shape have both a non-zero number of elements. The [reshape functor](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/reshape_util.cc#L40-L78) blindly divides by the dimensions of the target shape. Hence, if this is not checked, code will result in a division by 0. We have patched the issue in GitHub commit 4923de56ec94fff7770df259ab7f2288a74feb41. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1 as this is the other affected version.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37640"}
{"idx": 198350, "project": "owntone-server", "commit_id": "246d8ae0cef27377e5dfe9ee3ad87e864d6b6266", "project_url": "https://github.com/owntone/owntone-server", "commit_url": "https://github.com/owntone/owntone-server/commit/246d8ae0cef27377e5dfe9ee3ad87e864d6b6266", "commit_message": "[misc] Fix use-after-free in net_bind()\n\nThanks to Ba Jinsheng for reporting this bug", "target": 1, "func": "net_bind(short unsigned *port, int type, const char *log_service_name)\n{\n  struct addrinfo hints = { 0 };\n  struct addrinfo *servinfo;\n  struct addrinfo *ptr;\n  const char *cfgaddr;\n  char addr[INET6_ADDRSTRLEN];\n  char strport[8];\n  int yes = 1;\n  int no = 0;\n  int fd;\n  int ret;\n\n  cfgaddr = cfg_getstr(cfg_getsec(cfg, \"general\"), \"bind_address\");\n\n  hints.ai_socktype = (type & (SOCK_STREAM | SOCK_DGRAM)); // filter since type can be SOCK_STREAM | SOCK_NONBLOCK\n  hints.ai_family = (cfg_getbool(cfg_getsec(cfg, \"general\"), \"ipv6\")) ? AF_INET6 : AF_INET;\n  hints.ai_flags = cfgaddr ? 0 : AI_PASSIVE;\n\n  snprintf(strport, sizeof(strport), \"%hu\", *port);\n  ret = getaddrinfo(cfgaddr, strport, &hints, &servinfo);\n  if (ret < 0)\n    {\n      DPRINTF(E_LOG, L_MISC, \"Failure creating '%s' service, could not resolve '%s' (port %s): %s\\n\", log_service_name, cfgaddr ? cfgaddr : \"(ANY)\", strport, gai_strerror(ret));\n      return -1;\n    }\n\n  for (ptr = servinfo, fd = -1; ptr != NULL; ptr = ptr->ai_next)\n    {\n      if (fd >= 0)\n\tclose(fd);\n\n      fd = socket(ptr->ai_family, type | SOCK_CLOEXEC, ptr->ai_protocol);\n      if (fd < 0)\n\tcontinue;\n\n      // TODO libevent sets this, we do the same?\n      ret = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes));\n      if (ret < 0)\n\tcontinue;\n\n      ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));\n      if (ret < 0)\n\tcontinue;\n\n      if (ptr->ai_family == AF_INET6)\n\t{\n\t  // We want to be sure the service is dual stack\n\t  ret = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &no, sizeof(no));\n\t  if (ret < 0)\n\t    continue;\n\t}\n\n      ret = bind(fd, ptr->ai_addr, ptr->ai_addrlen);\n      if (ret < 0)\n\tcontinue;\n\n      break;\n    }\n\n  freeaddrinfo(servinfo);\n\n  if (!ptr)\n    {\n      DPRINTF(E_LOG, L_MISC, \"Could not create service '%s' with address %s, port %hu: %s\\n\", log_service_name, cfgaddr ? cfgaddr : \"(ANY)\", *port, strerror(errno));\n      goto error;\n    }\n\n  // Get the port that was assigned\n  ret = getsockname(fd, ptr->ai_addr, &ptr->ai_addrlen);\n  if (ret < 0)\n    {\n      DPRINTF(E_LOG, L_MISC, \"Could not find address of service '%s': %s\\n\", log_service_name, strerror(errno));\n      goto error;\n    }\n\n  net_port_get(port, (union net_sockaddr *)ptr->ai_addr);\n  net_address_get(addr, sizeof(addr), (union net_sockaddr *)ptr->ai_addr);\n\n  DPRINTF(E_DBG, L_MISC, \"Service '%s' bound to %s, port %hu, socket %d\\n\", log_service_name, addr, *port, fd);\n\n  return fd;\n\n error:\n  close(fd);\n  return -1;\n}", "func_hash": 32546260713202661418218833633405896143, "file_name": "misc.c", "file_hash": 105075321496416144885475599863207164581, "cwe": ["CWE-416"], "cve": "CVE-2021-38383", "cve_desc": "OwnTone (aka owntone-server) through 28.1 has a use-after-free in net_bind() in misc.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-38383"}
{"idx": 273091, "project": "owntone-server", "commit_id": "246d8ae0cef27377e5dfe9ee3ad87e864d6b6266", "project_url": "https://github.com/owntone/owntone-server", "commit_url": "https://github.com/owntone/owntone-server/commit/246d8ae0cef27377e5dfe9ee3ad87e864d6b6266", "commit_message": "[misc] Fix use-after-free in net_bind()\n\nThanks to Ba Jinsheng for reporting this bug", "target": 0, "func": "net_bind(short unsigned *port, int type, const char *log_service_name)\n{\n  struct addrinfo hints = { 0 };\n  struct addrinfo *servinfo;\n  struct addrinfo *ptr;\n  union net_sockaddr naddr = { 0 };\n  socklen_t naddr_len = sizeof(naddr);\n  const char *cfgaddr;\n  char addr[INET6_ADDRSTRLEN];\n  char strport[8];\n  int yes = 1;\n  int no = 0;\n  int fd;\n  int ret;\n\n  cfgaddr = cfg_getstr(cfg_getsec(cfg, \"general\"), \"bind_address\");\n\n  hints.ai_socktype = (type & (SOCK_STREAM | SOCK_DGRAM)); // filter since type can be SOCK_STREAM | SOCK_NONBLOCK\n  hints.ai_family = (cfg_getbool(cfg_getsec(cfg, \"general\"), \"ipv6\")) ? AF_INET6 : AF_INET;\n  hints.ai_flags = cfgaddr ? 0 : AI_PASSIVE;\n\n  snprintf(strport, sizeof(strport), \"%hu\", *port);\n  ret = getaddrinfo(cfgaddr, strport, &hints, &servinfo);\n  if (ret < 0)\n    {\n      DPRINTF(E_LOG, L_MISC, \"Failure creating '%s' service, could not resolve '%s' (port %s): %s\\n\", log_service_name, cfgaddr ? cfgaddr : \"(ANY)\", strport, gai_strerror(ret));\n      return -1;\n    }\n\n  for (ptr = servinfo, fd = -1; ptr != NULL; ptr = ptr->ai_next)\n    {\n      if (fd >= 0)\n\tclose(fd);\n\n      fd = socket(ptr->ai_family, type | SOCK_CLOEXEC, ptr->ai_protocol);\n      if (fd < 0)\n\tcontinue;\n\n      // TODO libevent sets this, we do the same?\n      ret = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes));\n      if (ret < 0)\n\tcontinue;\n\n      ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));\n      if (ret < 0)\n\tcontinue;\n\n      if (ptr->ai_family == AF_INET6)\n\t{\n\t  // We want to be sure the service is dual stack\n\t  ret = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &no, sizeof(no));\n\t  if (ret < 0)\n\t    continue;\n\t}\n\n      ret = bind(fd, ptr->ai_addr, ptr->ai_addrlen);\n      if (ret < 0)\n\tcontinue;\n\n      break;\n    }\n\n  freeaddrinfo(servinfo);\n\n  if (!ptr)\n    {\n      DPRINTF(E_LOG, L_MISC, \"Could not create service '%s' with address %s, port %hu: %s\\n\", log_service_name, cfgaddr ? cfgaddr : \"(ANY)\", *port, strerror(errno));\n      goto error;\n    }\n\n  // Get our address (as string) and the port that was assigned (necessary when\n  // caller didn't specify a port)\n  ret = getsockname(fd, &naddr.sa, &naddr_len);\n  if (ret < 0)\n    {\n      DPRINTF(E_LOG, L_MISC, \"Error finding address of service '%s': %s\\n\", log_service_name, strerror(errno));\n      goto error;\n    }\n  else if (naddr_len > sizeof(naddr))\n    {\n      DPRINTF(E_LOG, L_MISC, \"Unexpected address length of service '%s'\\n\", log_service_name);\n      goto error;\n    }\n\n  net_port_get(port, &naddr);\n  net_address_get(addr, sizeof(addr), &naddr);\n\n  DPRINTF(E_DBG, L_MISC, \"Service '%s' bound to %s, port %hu, socket %d\\n\", log_service_name, addr, *port, fd);\n\n  return fd;\n\n error:\n  close(fd);\n  return -1;\n}", "func_hash": 222091533748174549495589798239680166393, "file_name": "misc.c", "file_hash": 109030313181388769357445523159421396120, "cwe": ["CWE-416"], "cve": "CVE-2021-38383", "cve_desc": "OwnTone (aka owntone-server) through 28.1 has a use-after-free in net_bind() in misc.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-38383"}
{"idx": 198374, "project": "tensorflow", "commit_id": "803404044ae7a1efac48ba82d74111fce1ddb09a", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/803404044ae7a1efac48ba82d74111fce1ddb09a", "commit_message": "Fix security vulnerability with LSTMBlockCellOp\n\nPiperOrigin-RevId: 446028341", "target": 1, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor* x_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"x\", &x_tensor));\n\n    const Tensor* cs_prev_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"cs_prev\", &cs_prev_tensor));\n\n    const Tensor* h_prev_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"h_prev\", &h_prev_tensor));\n\n    const Tensor* w_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"w\", &w_tensor));\n\n    const Tensor* wci_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"wci\", &wci_tensor));\n\n    const Tensor* wcf_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"wcf\", &wcf_tensor));\n\n    const Tensor* wco_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"wco\", &wco_tensor));\n\n    const Tensor* b_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"b\", &b_tensor));\n\n    const int64_t batch_size = x_tensor->dim_size(0);\n    const int64_t input_size = x_tensor->dim_size(1);\n    const int64_t cell_size = cs_prev_tensor->dim_size(1);\n\n    // Sanity checks for our input shapes.\n    OP_REQUIRES(ctx, cs_prev_tensor->dim_size(0) == batch_size,\n                errors::InvalidArgument(\"cs_prev.dims(0) != batch_size: \",\n                                        cs_prev_tensor->dim_size(0), \" vs. \",\n                                        batch_size));\n    OP_REQUIRES(ctx, cs_prev_tensor->dim_size(1) == cell_size,\n                errors::InvalidArgument(\"cs_prev.dims(1) != cell_size: \",\n                                        cs_prev_tensor->dim_size(1), \" vs. \",\n                                        cell_size));\n\n    OP_REQUIRES(ctx, h_prev_tensor->dim_size(0) == batch_size,\n                errors::InvalidArgument(\"h_prev.dims(0) != batch_size: \",\n                                        h_prev_tensor->dim_size(0), \" vs. \",\n                                        batch_size));\n    OP_REQUIRES(ctx, h_prev_tensor->dim_size(1) == cell_size,\n                errors::InvalidArgument(\n                    \"h_prev.dims(1) != cell_size: \", h_prev_tensor->dim_size(1),\n                    \" vs. \", cell_size));\n\n    OP_REQUIRES(ctx, w_tensor->dim_size(0) == input_size + cell_size,\n                errors::InvalidArgument(\n                    \"w.dim_size(0) != input_size + cell_size: \",\n                    w_tensor->dim_size(0), \" vs. \", input_size + cell_size));\n    OP_REQUIRES(ctx, w_tensor->dim_size(1) == cell_size * 4,\n                errors::InvalidArgument(\n                    \"w.dim_size(1) != cell_size * 4: \", w_tensor->dim_size(1),\n                    \" vs. \", cell_size * 4));\n\n    OP_REQUIRES(ctx, b_tensor->dim_size(0) == cell_size * 4,\n                errors::InvalidArgument(\n                    \"b.dim_size(0) != cell_size * 4: \", b_tensor->dim_size(0),\n                    \" vs. \", cell_size * 4));\n\n    // Allocate our output tensors.\n    Tensor* i_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output(\n                            {\"h_prev\"}, \"i\",\n                            TensorShape({batch_size, cell_size}), &i_tensor));\n\n    Tensor* cs_tensor = nullptr;\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_output(\"cs\", TensorShape({batch_size, cell_size}),\n                                  &cs_tensor));\n\n    Tensor* f_tensor = nullptr;\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_output(\"f\", TensorShape({batch_size, cell_size}),\n                                  &f_tensor));\n\n    Tensor* o_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output(\n                            {\"cs_prev\"}, \"o\",\n                            TensorShape({batch_size, cell_size}), &o_tensor));\n\n    Tensor* ci_tensor = nullptr;\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_output(\"ci\", TensorShape({batch_size, cell_size}),\n                                  &ci_tensor));\n\n    Tensor* co_tensor = nullptr;\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_output(\"co\", TensorShape({batch_size, cell_size}),\n                                  &co_tensor));\n\n    Tensor* h_tensor = nullptr;\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_output(\"h\", TensorShape({batch_size, cell_size}),\n                                  &h_tensor));\n\n    // Allocate our temp tensors.\n    Tensor xh_tensor;\n    OP_REQUIRES_OK(ctx, ctx->allocate_temp(\n                            DataTypeToEnum::v(),\n                            TensorShape({batch_size, input_size + cell_size}),\n                            &xh_tensor));\n\n    Tensor gates_tensor;\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_temp(DataTypeToEnum::v(),\n                                      TensorShape({batch_size, cell_size * 4}),\n                                      &gates_tensor));\n\n    const Device& device = ctx->eigen_device();\n\n    functor::LSTMBlockCellFprop(\n        batch_size, input_size, cell_size)(\n        ctx, device, forget_bias_, cell_clip_, use_peephole_,\n        x_tensor->matrix(), cs_prev_tensor->matrix(),\n        h_prev_tensor->matrix(), w_tensor->matrix(), wci_tensor->vec(),\n        wcf_tensor->vec(), wco_tensor->vec(), b_tensor->vec(),\n        xh_tensor.matrix(), i_tensor->matrix(), cs_tensor->matrix(),\n        f_tensor->matrix(), o_tensor->matrix(), ci_tensor->matrix(),\n        co_tensor->matrix(), gates_tensor.matrix(),\n        h_tensor->matrix());\n  }", "func_hash": 332787893197526379241591780916041422587, "file_name": "lstm_ops.cc", "file_hash": 94555141575162353468670590418949369497, "cwe": ["CWE-703"], "cve": "CVE-2022-29200", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.LSTMBlockCell` does not fully validate the input arguments. This results in a `CHECK`-failure which can be used to trigger a denial of service attack. The code does not validate the ranks of any of the arguments to this API call. This results in `CHECK`-failures when the elements of the tensor are accessed. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29200"}
{"idx": 273407, "project": "tensorflow", "commit_id": "803404044ae7a1efac48ba82d74111fce1ddb09a", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/803404044ae7a1efac48ba82d74111fce1ddb09a", "commit_message": "Fix security vulnerability with LSTMBlockCellOp\n\nPiperOrigin-RevId: 446028341", "target": 0, "func": "  void Compute(OpKernelContext* ctx) override {\n    const Tensor* x_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"x\", &x_tensor));\n\n    const Tensor* cs_prev_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"cs_prev\", &cs_prev_tensor));\n\n    const Tensor* h_prev_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"h_prev\", &h_prev_tensor));\n\n    const Tensor* w_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"w\", &w_tensor));\n\n    const Tensor* wci_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"wci\", &wci_tensor));\n\n    const Tensor* wcf_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"wcf\", &wcf_tensor));\n\n    const Tensor* wco_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"wco\", &wco_tensor));\n\n    const Tensor* b_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->input(\"b\", &b_tensor));\n\n    const int64_t batch_size = x_tensor->dim_size(0);\n    const int64_t input_size = x_tensor->dim_size(1);\n    const int64_t cell_size = cs_prev_tensor->dim_size(1);\n\n    // Sanity checks for our input shapes.\n    OP_REQUIRES(ctx, cs_prev_tensor->dim_size(0) == batch_size,\n                errors::InvalidArgument(\"cs_prev.dims(0) != batch_size: \",\n                                        cs_prev_tensor->dim_size(0), \" vs. \",\n                                        batch_size));\n    OP_REQUIRES(ctx, cs_prev_tensor->dim_size(1) == cell_size,\n                errors::InvalidArgument(\"cs_prev.dims(1) != cell_size: \",\n                                        cs_prev_tensor->dim_size(1), \" vs. \",\n                                        cell_size));\n\n    OP_REQUIRES(ctx, h_prev_tensor->dim_size(0) == batch_size,\n                errors::InvalidArgument(\"h_prev.dims(0) != batch_size: \",\n                                        h_prev_tensor->dim_size(0), \" vs. \",\n                                        batch_size));\n    OP_REQUIRES(ctx, h_prev_tensor->dim_size(1) == cell_size,\n                errors::InvalidArgument(\n                    \"h_prev.dims(1) != cell_size: \", h_prev_tensor->dim_size(1),\n                    \" vs. \", cell_size));\n\n    OP_REQUIRES(ctx, w_tensor->dim_size(0) == input_size + cell_size,\n                errors::InvalidArgument(\n                    \"w.dim_size(0) != input_size + cell_size: \",\n                    w_tensor->dim_size(0), \" vs. \", input_size + cell_size));\n    OP_REQUIRES(ctx, w_tensor->dim_size(1) == cell_size * 4,\n                errors::InvalidArgument(\n                    \"w.dim_size(1) != cell_size * 4: \", w_tensor->dim_size(1),\n                    \" vs. \", cell_size * 4));\n\n    OP_REQUIRES(ctx, b_tensor->dim_size(0) == cell_size * 4,\n                errors::InvalidArgument(\n                    \"b.dim_size(0) != cell_size * 4: \", b_tensor->dim_size(0),\n                    \" vs. \", cell_size * 4));\n\n    // Allocate our output tensors.\n    Tensor* i_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output(\n                            {\"h_prev\"}, \"i\",\n                            TensorShape({batch_size, cell_size}), &i_tensor));\n\n    Tensor* cs_tensor = nullptr;\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_output(\"cs\", TensorShape({batch_size, cell_size}),\n                                  &cs_tensor));\n\n    Tensor* f_tensor = nullptr;\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_output(\"f\", TensorShape({batch_size, cell_size}),\n                                  &f_tensor));\n\n    Tensor* o_tensor = nullptr;\n    OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output(\n                            {\"cs_prev\"}, \"o\",\n                            TensorShape({batch_size, cell_size}), &o_tensor));\n\n    Tensor* ci_tensor = nullptr;\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_output(\"ci\", TensorShape({batch_size, cell_size}),\n                                  &ci_tensor));\n\n    Tensor* co_tensor = nullptr;\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_output(\"co\", TensorShape({batch_size, cell_size}),\n                                  &co_tensor));\n\n    Tensor* h_tensor = nullptr;\n    OP_REQUIRES_OK(\n        ctx, ctx->allocate_output(\"h\", TensorShape({batch_size, cell_size}),\n                                  &h_tensor));\n\n    // Allocate our temp tensors.\n    Tensor xh_tensor;\n    OP_REQUIRES_OK(ctx, ctx->allocate_temp(\n                            DataTypeToEnum::v(),\n                            TensorShape({batch_size, input_size + cell_size}),\n                            &xh_tensor));\n\n    Tensor gates_tensor;\n    OP_REQUIRES_OK(ctx,\n                   ctx->allocate_temp(DataTypeToEnum::v(),\n                                      TensorShape({batch_size, cell_size * 4}),\n                                      &gates_tensor));\n\n    const Device& device = ctx->eigen_device();\n\n    // Sanity check that each of the tensors have the required NDIMS.\n    OP_REQUIRES(ctx, x_tensor->dims() == 2,\n                errors::InvalidArgument(\"x_tensor must be rank 2 but is rank \",\n                                        x_tensor->dims(), \".\"));\n    OP_REQUIRES(\n        ctx, cs_prev_tensor->dims() == 2,\n        errors::InvalidArgument(\"cs_prev_tensor must be rank 2 but is rank \",\n                                cs_prev_tensor->dims(), \".\"));\n    OP_REQUIRES(\n        ctx, h_prev_tensor->dims() == 2,\n        errors::InvalidArgument(\"h_prev_tensor must be rank 2 but is rank \",\n                                h_prev_tensor->dims(), \".\"));\n    OP_REQUIRES(ctx, w_tensor->dims() == 2,\n                errors::InvalidArgument(\"w_tensor must be rank 2 but is rank \",\n                                        w_tensor->dims(), \".\"));\n    OP_REQUIRES(\n        ctx, wci_tensor->dims() == 1,\n        errors::InvalidArgument(\"wci_tensor must be rank 1 but is rank \",\n                                wci_tensor->dims(), \".\"));\n    OP_REQUIRES(\n        ctx, wcf_tensor->dims() == 1,\n        errors::InvalidArgument(\"wcf_tensor must be rank 1 but is rank \",\n                                wci_tensor->dims(), \".\"));\n    OP_REQUIRES(\n        ctx, wco_tensor->dims() == 1,\n        errors::InvalidArgument(\"wco_tensor must be rank 1 but is rank \",\n                                wco_tensor->dims(), \".\"));\n    OP_REQUIRES(ctx, b_tensor->dims() == 1,\n                errors::InvalidArgument(\"b_tensor must be rank 1 but is rank \",\n                                        b_tensor->dims(), \".\"));\n    OP_REQUIRES(ctx, xh_tensor.dims() == 2,\n                errors::InvalidArgument(\"xh_tensor must be rank 2 but is rank \",\n                                        xh_tensor.dims(), \".\"));\n    OP_REQUIRES(ctx, i_tensor->dims() == 2,\n                errors::InvalidArgument(\"i_tensor must be rank 2 but is rank \",\n                                        i_tensor->dims(), \".\"));\n    OP_REQUIRES(ctx, cs_tensor->dims() == 2,\n                errors::InvalidArgument(\"cs_tensor must be rank 2 but is rank \",\n                                        cs_tensor->dims(), \".\"));\n    OP_REQUIRES(ctx, f_tensor->dims() == 2,\n                errors::InvalidArgument(\"f_tensor must be rank 2 but is rank \",\n                                        f_tensor->dims(), \".\"));\n    OP_REQUIRES(ctx, o_tensor->dims() == 2,\n                errors::InvalidArgument(\"o_tensor must be rank 2 but is rank \",\n                                        o_tensor->dims(), \".\"));\n    OP_REQUIRES(ctx, ci_tensor->dims() == 2,\n                errors::InvalidArgument(\"ci_tensor must be rank 2 but is rank \",\n                                        ci_tensor->dims(), \".\"));\n    OP_REQUIRES(ctx, co_tensor->dims() == 2,\n                errors::InvalidArgument(\"co_tensor must be rank 2 but is rank \",\n                                        co_tensor->dims(), \".\"));\n    OP_REQUIRES(\n        ctx, gates_tensor.dims() == 2,\n        errors::InvalidArgument(\"gates_tensor must be rank 2 but is rank \",\n                                gates_tensor.dims(), \".\"));\n    OP_REQUIRES(ctx, h_tensor->dims() == 2,\n                errors::InvalidArgument(\"h_tensor must be rank 2 but is rank \",\n                                        h_tensor->dims(), \".\"));\n\n    functor::LSTMBlockCellFprop(\n        batch_size, input_size, cell_size)(\n        ctx, device, forget_bias_, cell_clip_, use_peephole_,\n        x_tensor->matrix(), cs_prev_tensor->matrix(),\n        h_prev_tensor->matrix(), w_tensor->matrix(), wci_tensor->vec(),\n        wcf_tensor->vec(), wco_tensor->vec(), b_tensor->vec(),\n        xh_tensor.matrix(), i_tensor->matrix(), cs_tensor->matrix(),\n        f_tensor->matrix(), o_tensor->matrix(), ci_tensor->matrix(),\n        co_tensor->matrix(), gates_tensor.matrix(),\n        h_tensor->matrix());\n  }", "func_hash": 258695141881627595709406834872901892471, "file_name": "lstm_ops.cc", "file_hash": 177796578902754451713518476941050283987, "cwe": ["CWE-703"], "cve": "CVE-2022-29200", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.LSTMBlockCell` does not fully validate the input arguments. This results in a `CHECK`-failure which can be used to trigger a denial of service attack. The code does not validate the ranks of any of the arguments to this API call. This results in `CHECK`-failures when the elements of the tensor are accessed. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29200"}
{"idx": 198399, "project": "uftpd", "commit_id": "0fb2c031ce0ace07cc19cd2cb2143c4b5a63c9dd", "project_url": "https://github.com/troglobit/uftpd", "commit_url": "https://github.com/troglobit/uftpd/commit/0fb2c031ce0ace07cc19cd2cb2143c4b5a63c9dd", "commit_message": "FTP: Fix buffer overflow in PORT parser, reported by Aaron Esau\n\nSigned-off-by: Joachim Nilsson ", "target": 1, "func": "static void handle_PORT(ctrl_t *ctrl, char *str)\n{\n\tint a, b, c, d, e, f;\n\tchar addr[INET_ADDRSTRLEN];\n\tstruct sockaddr_in sin;\n\n\tif (ctrl->data_sd > 0) {\n\t\tuev_io_stop(&ctrl->data_watcher);\n\t\tclose(ctrl->data_sd);\n\t\tctrl->data_sd = -1;\n\t}\n\n\t/* Convert PORT command's argument to IP address + port */\n\tsscanf(str, \"%d,%d,%d,%d,%d,%d\", &a, &b, &c, &d, &e, &f);\n\tsprintf(addr, \"%d.%d.%d.%d\", a, b, c, d);\n\n\t/* Check IPv4 address using inet_aton(), throw away converted result */\n\tif (!inet_aton(addr, &(sin.sin_addr))) {\n\t\tERR(0, \"Invalid address '%s' given to PORT command\", addr);\n\t\tsend_msg(ctrl->sd, \"500 Illegal PORT command.\\r\\n\");\n\t\treturn;\n\t}\n\n\tstrlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address));\n\tctrl->data_port = e * 256 + f;\n\n\tDBG(\"Client PORT command accepted for %s:%d\", ctrl->data_address, ctrl->data_port);\n\tsend_msg(ctrl->sd, \"200 PORT command successful.\\r\\n\");\n}", "func_hash": 5389607465091397932741652441661168107, "file_name": "ftpcmd.c", "file_hash": 13134413350440209021234166619599968419, "cwe": ["CWE-787"], "cve": "CVE-2020-20276", "cve_desc": "An unauthenticated stack-based buffer overflow vulnerability in common.c's handle_PORT in uftpd FTP server versions 2.10 and earlier can be abused to cause a crash and could potentially lead to remote code execution.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-20276"}
{"idx": 273880, "project": "uftpd", "commit_id": "0fb2c031ce0ace07cc19cd2cb2143c4b5a63c9dd", "project_url": "https://github.com/troglobit/uftpd", "commit_url": "https://github.com/troglobit/uftpd/commit/0fb2c031ce0ace07cc19cd2cb2143c4b5a63c9dd", "commit_message": "FTP: Fix buffer overflow in PORT parser, reported by Aaron Esau\n\nSigned-off-by: Joachim Nilsson ", "target": 0, "func": "static void handle_PORT(ctrl_t *ctrl, char *str)\n{\n\tint a, b, c, d, e, f;\n\tchar addr[INET_ADDRSTRLEN];\n\tstruct sockaddr_in sin;\n\n\tif (ctrl->data_sd > 0) {\n\t\tuev_io_stop(&ctrl->data_watcher);\n\t\tclose(ctrl->data_sd);\n\t\tctrl->data_sd = -1;\n\t}\n\n\t/* Convert PORT command's argument to IP address + port */\n\tsscanf(str, \"%d,%d,%d,%d,%d,%d\", &a, &b, &c, &d, &e, &f);\n\tsnprintf(addr, sizeof(addr), \"%d.%d.%d.%d\", a, b, c, d);\n\n\t/* Check IPv4 address using inet_aton(), throw away converted result */\n\tif (!inet_aton(addr, &(sin.sin_addr))) {\n\t\tERR(0, \"Invalid address '%s' given to PORT command\", addr);\n\t\tsend_msg(ctrl->sd, \"500 Illegal PORT command.\\r\\n\");\n\t\treturn;\n\t}\n\n\tstrlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address));\n\tctrl->data_port = e * 256 + f;\n\n\tDBG(\"Client PORT command accepted for %s:%d\", ctrl->data_address, ctrl->data_port);\n\tsend_msg(ctrl->sd, \"200 PORT command successful.\\r\\n\");\n}", "func_hash": 215142570245126978636842618721615711400, "file_name": "ftpcmd.c", "file_hash": 153621949674732808138354001734428365570, "cwe": ["CWE-787"], "cve": "CVE-2020-20276", "cve_desc": "An unauthenticated stack-based buffer overflow vulnerability in common.c's handle_PORT in uftpd FTP server versions 2.10 and earlier can be abused to cause a crash and could potentially lead to remote code execution.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-20276"}
{"idx": 198439, "project": "mruby", "commit_id": "3cf291f72224715942beaf8553e42ba8891ab3c6", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/3cf291f72224715942beaf8553e42ba8891ab3c6", "commit_message": "vm.c: create break object before clearing GC arena.\n\nOtherwise it possibly cause use-after-free.", "target": 1, "func": "mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc)\n{\n  /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */\n  const mrb_irep *irep = proc->body.irep;\n  const mrb_pool_value *pool = irep->pool;\n  const mrb_sym *syms = irep->syms;\n  mrb_code insn;\n  int ai = mrb_gc_arena_save(mrb);\n  struct mrb_jmpbuf *prev_jmp = mrb->jmp;\n  struct mrb_jmpbuf c_jmp;\n  uint32_t a;\n  uint16_t b;\n  uint16_t c;\n  mrb_sym mid;\n  const struct mrb_irep_catch_handler *ch;\n\n#ifdef DIRECT_THREADED\n  static const void * const optable[] = {\n#define OPCODE(x,_) &&L_OP_ ## x,\n#include \"mruby/ops.h\"\n#undef OPCODE\n  };\n#endif\n\n  mrb_bool exc_catched = FALSE;\nRETRY_TRY_BLOCK:\n\n  MRB_TRY(&c_jmp) {\n\n  if (exc_catched) {\n    exc_catched = FALSE;\n    mrb_gc_arena_restore(mrb, ai);\n    if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)\n      goto L_BREAK;\n    goto L_RAISE;\n  }\n  mrb->jmp = &c_jmp;\n  mrb_vm_ci_proc_set(mrb->c->ci, proc);\n\n#define regs (mrb->c->ci->stack)\n  INIT_DISPATCH {\n    CASE(OP_NOP, Z) {\n      /* do nothing */\n      NEXT;\n    }\n\n    CASE(OP_MOVE, BB) {\n      regs[a] = regs[b];\n      NEXT;\n    }\n\n    CASE(OP_LOADL, BB) {\n      switch (pool[b].tt) {   /* number */\n      case IREP_TT_INT32:\n        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32);\n        break;\n      case IREP_TT_INT64:\n#if defined(MRB_INT64)\n        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n        break;\n#else\n#if defined(MRB_64BIT)\n        if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) {\n          regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n          break;\n        }\n#endif\n        goto L_INT_OVERFLOW;\n#endif\n      case IREP_TT_BIGINT:\n        goto L_INT_OVERFLOW;\n#ifndef MRB_NO_FLOAT\n      case IREP_TT_FLOAT:\n        regs[a] = mrb_float_value(mrb, pool[b].u.f);\n        break;\n#endif\n      default:\n        /* should not happen (tt:string) */\n        regs[a] = mrb_nil_value();\n        break;\n      }\n      NEXT;\n    }\n\n    CASE(OP_LOADI, BB) {\n      SET_FIXNUM_VALUE(regs[a], b);\n      NEXT;\n    }\n\n    CASE(OP_LOADINEG, BB) {\n      SET_FIXNUM_VALUE(regs[a], -b);\n      NEXT;\n    }\n\n    CASE(OP_LOADI__1,B) goto L_LOADI;\n    CASE(OP_LOADI_0,B) goto L_LOADI;\n    CASE(OP_LOADI_1,B) goto L_LOADI;\n    CASE(OP_LOADI_2,B) goto L_LOADI;\n    CASE(OP_LOADI_3,B) goto L_LOADI;\n    CASE(OP_LOADI_4,B) goto L_LOADI;\n    CASE(OP_LOADI_5,B) goto L_LOADI;\n    CASE(OP_LOADI_6,B) goto L_LOADI;\n    CASE(OP_LOADI_7, B) {\n    L_LOADI:\n      SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0);\n      NEXT;\n    }\n\n    CASE(OP_LOADI16, BS) {\n      SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b);\n      NEXT;\n    }\n\n    CASE(OP_LOADI32, BSS) {\n      SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c));\n      NEXT;\n    }\n\n    CASE(OP_LOADSYM, BB) {\n      SET_SYM_VALUE(regs[a], syms[b]);\n      NEXT;\n    }\n\n    CASE(OP_LOADNIL, B) {\n      SET_NIL_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_LOADSELF, B) {\n      regs[a] = regs[0];\n      NEXT;\n    }\n\n    CASE(OP_LOADT, B) {\n      SET_TRUE_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_LOADF, B) {\n      SET_FALSE_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETGV, BB) {\n      mrb_value val = mrb_gv_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETGV, BB) {\n      mrb_gv_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETSV, BB) {\n      mrb_value val = mrb_vm_special_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETSV, BB) {\n      mrb_vm_special_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETIV, BB) {\n      regs[a] = mrb_iv_get(mrb, regs[0], syms[b]);\n      NEXT;\n    }\n\n    CASE(OP_SETIV, BB) {\n      mrb_iv_set(mrb, regs[0], syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETCV, BB) {\n      mrb_value val;\n      val = mrb_vm_cv_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETCV, BB) {\n      mrb_vm_cv_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETIDX, B) {\n      mrb_value va = regs[a], vb = regs[a+1];\n      switch (mrb_type(va)) {\n      case MRB_TT_ARRAY:\n        if (!mrb_integer_p(vb)) goto getidx_fallback;\n        regs[a] = mrb_ary_entry(va, mrb_integer(vb));\n        break;\n      case MRB_TT_HASH:\n        va = mrb_hash_get(mrb, va, vb);\n        regs[a] = va;\n        break;\n      case MRB_TT_STRING:\n        switch (mrb_type(vb)) {\n        case MRB_TT_INTEGER:\n        case MRB_TT_STRING:\n        case MRB_TT_RANGE:\n          va = mrb_str_aref(mrb, va, vb, mrb_undef_value());\n          regs[a] = va;\n          break;\n        default:\n          goto getidx_fallback;\n        }\n        break;\n      default:\n      getidx_fallback:\n        mid = MRB_OPSYM(aref);\n        goto L_SEND_SYM;\n      }\n      NEXT;\n    }\n\n    CASE(OP_SETIDX, B) {\n      c = 2;\n      mid = MRB_OPSYM(aset);\n      SET_NIL_VALUE(regs[a+3]);\n      goto L_SENDB_SYM;\n    }\n\n    CASE(OP_GETCONST, BB) {\n      mrb_value v = mrb_vm_const_get(mrb, syms[b]);\n      regs[a] = v;\n      NEXT;\n    }\n\n    CASE(OP_SETCONST, BB) {\n      mrb_vm_const_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETMCNST, BB) {\n      mrb_value v = mrb_const_get(mrb, regs[a], syms[b]);\n      regs[a] = v;\n      NEXT;\n    }\n\n    CASE(OP_SETMCNST, BB) {\n      mrb_const_set(mrb, regs[a+1], syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETUPVAR, BBB) {\n      mrb_value *regs_a = regs + a;\n      struct REnv *e = uvenv(mrb, c);\n\n      if (e && b < MRB_ENV_LEN(e)) {\n        *regs_a = e->stack[b];\n      }\n      else {\n        *regs_a = mrb_nil_value();\n      }\n      NEXT;\n    }\n\n    CASE(OP_SETUPVAR, BBB) {\n      struct REnv *e = uvenv(mrb, c);\n\n      if (e) {\n        mrb_value *regs_a = regs + a;\n\n        if (b < MRB_ENV_LEN(e)) {\n          e->stack[b] = *regs_a;\n          mrb_write_barrier(mrb, (struct RBasic*)e);\n        }\n      }\n      NEXT;\n    }\n\n    CASE(OP_JMP, S) {\n      pc += (int16_t)a;\n      JUMP;\n    }\n    CASE(OP_JMPIF, BS) {\n      if (mrb_test(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n    CASE(OP_JMPNOT, BS) {\n      if (!mrb_test(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n    CASE(OP_JMPNIL, BS) {\n      if (mrb_nil_p(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n\n    CASE(OP_JMPUW, S) {\n      a = (uint32_t)((pc - irep->iseq) + (int16_t)a);\n      CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) {\n        struct RBreak *brk = (struct RBreak*)mrb->exc;\n        mrb_value target = mrb_break_value_get(brk);\n        mrb_assert(mrb_integer_p(target));\n        a = (uint32_t)mrb_integer(target);\n        mrb_assert(a >= 0 && a < irep->ilen);\n      }\n      CHECKPOINT_MAIN(RBREAK_TAG_JUMP) {\n        ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE);\n        if (ch) {\n          /* avoiding a jump from a catch handler into the same handler */\n          if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) {\n            THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a));\n          }\n        }\n      }\n      CHECKPOINT_END(RBREAK_TAG_JUMP);\n\n      mrb->exc = NULL; /* clear break object */\n      pc = irep->iseq + a;\n      JUMP;\n    }\n\n    CASE(OP_EXCEPT, B) {\n      mrb_value exc;\n\n      if (mrb->exc == NULL) {\n        exc = mrb_nil_value();\n      }\n      else {\n        switch (mrb->exc->tt) {\n        case MRB_TT_BREAK:\n        case MRB_TT_EXCEPTION:\n          exc = mrb_obj_value(mrb->exc);\n          break;\n        default:\n          mrb_assert(!\"bad mrb_type\");\n          exc = mrb_nil_value();\n          break;\n        }\n        mrb->exc = NULL;\n      }\n      regs[a] = exc;\n      NEXT;\n    }\n    CASE(OP_RESCUE, BB) {\n      mrb_value exc = regs[a];  /* exc on stack */\n      mrb_value e = regs[b];\n      struct RClass *ec;\n\n      switch (mrb_type(e)) {\n      case MRB_TT_CLASS:\n      case MRB_TT_MODULE:\n        break;\n      default:\n        {\n          mrb_value exc;\n\n          exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n                                    \"class or module required for rescue clause\");\n          mrb_exc_set(mrb, exc);\n          goto L_RAISE;\n        }\n      }\n      ec = mrb_class_ptr(e);\n      regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));\n      NEXT;\n    }\n\n    CASE(OP_RAISEIF, B) {\n      mrb_value exc = regs[a];\n      if (mrb_break_p(exc)) {\n        mrb->exc = mrb_obj_ptr(exc);\n        goto L_BREAK;\n      }\n      mrb_exc_set(mrb, exc);\n      if (mrb->exc) {\n        goto L_RAISE;\n      }\n      NEXT;\n    }\n\n    CASE(OP_SSEND, BBB) {\n      regs[a] = regs[0];\n      insn = OP_SEND;\n    }\n    goto L_SENDB;\n\n    CASE(OP_SSENDB, BBB) {\n      regs[a] = regs[0];\n    }\n    goto L_SENDB;\n\n    CASE(OP_SEND, BBB)\n    goto L_SENDB;\n\n    L_SEND_SYM:\n    c = 1;\n    /* push nil after arguments */\n    SET_NIL_VALUE(regs[a+2]);\n    goto L_SENDB_SYM;\n\n    CASE(OP_SENDB, BBB)\n    L_SENDB:\n    mid = syms[b];\n    L_SENDB_SYM:\n    {\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_method_t m;\n      struct RClass *cls;\n      mrb_value recv, blk;\n\n      ARGUMENT_NORMALIZE(a, &c, insn);\n\n      recv = regs[a];\n      cls = mrb_class(mrb, recv);\n      m = mrb_method_search_vm(mrb, &cls, mid);\n      if (MRB_METHOD_UNDEF_P(m)) {\n        m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0);\n        mid = MRB_SYM(method_missing);\n      }\n\n      /* push callinfo */\n      ci = cipush(mrb, a, 0, cls, NULL, mid, c);\n\n      if (MRB_METHOD_CFUNC_P(m)) {\n        if (MRB_METHOD_PROC_P(m)) {\n          struct RProc *p = MRB_METHOD_PROC(m);\n\n          mrb_vm_ci_proc_set(ci, p);\n          recv = p->body.func(mrb, recv);\n        }\n        else {\n          if (MRB_METHOD_NOARG_P(m)) {\n            check_method_noarg(mrb, ci);\n          }\n          recv = MRB_METHOD_FUNC(m)(mrb, recv);\n        }\n        mrb_gc_arena_shrink(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        ci = mrb->c->ci;\n        if (mrb_proc_p(blk)) {\n          struct RProc *p = mrb_proc_ptr(blk);\n          if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n            p->flags |= MRB_PROC_ORPHAN;\n          }\n        }\n        if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */\n          if (ci->cci == CINFO_RESUMED) {\n            mrb->jmp = prev_jmp;\n            return recv;\n          }\n          else {\n            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n            proc = ci[-1].proc;\n            irep = proc->body.irep;\n            pool = irep->pool;\n            syms = irep->syms;\n          }\n        }\n        ci->stack[0] = recv;\n        /* pop stackpos */\n        ci = cipop(mrb);\n        pc = ci->pc;\n      }\n      else {\n        /* setup environment for calling method */\n        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n        pc = irep->iseq;\n      }\n    }\n    JUMP;\n\n    CASE(OP_CALL, Z) {\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_value recv = ci->stack[0];\n      struct RProc *m = mrb_proc_ptr(recv);\n\n      /* replace callinfo */\n      ci->u.target_class = MRB_PROC_TARGET_CLASS(m);\n      mrb_vm_ci_proc_set(ci, m);\n      if (MRB_PROC_ENV_P(m)) {\n        ci->mid = MRB_PROC_ENV(m)->mid;\n      }\n\n      /* prepare stack */\n      if (MRB_PROC_CFUNC_P(m)) {\n        recv = MRB_PROC_CFUNC(m)(mrb, recv);\n        mrb_gc_arena_shrink(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        /* pop stackpos */\n        ci = cipop(mrb);\n        pc = ci->pc;\n        ci[1].stack[0] = recv;\n        irep = mrb->c->ci->proc->body.irep;\n      }\n      else {\n        /* setup environment for calling method */\n        proc = m;\n        irep = m->body.irep;\n        if (!irep) {\n          mrb->c->ci->stack[0] = mrb_nil_value();\n          a = 0;\n          c = OP_R_NORMAL;\n          goto L_OP_RETURN_BODY;\n        }\n        mrb_int nargs = mrb_ci_bidx(ci)+1;\n        if (nargs < irep->nregs) {\n          mrb_stack_extend(mrb, irep->nregs);\n          stack_clear(regs+nargs, irep->nregs-nargs);\n        }\n        if (MRB_PROC_ENV_P(m)) {\n          regs[0] = MRB_PROC_ENV(m)->stack[0];\n        }\n        pc = irep->iseq;\n      }\n      pool = irep->pool;\n      syms = irep->syms;\n      JUMP;\n    }\n\n    CASE(OP_SUPER, BB) {\n      mrb_method_t m;\n      struct RClass *cls;\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_value recv, blk;\n      const struct RProc *p = ci->proc;\n      mrb_sym mid = ci->mid;\n      struct RClass* target_class = MRB_PROC_TARGET_CLASS(p);\n\n      if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */\n        mid = p->e.env->mid;    /* restore old mid */\n      }\n\n      if (mid == 0 || !target_class) {\n        mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n      if (target_class->flags & MRB_FL_CLASS_IS_PREPENDED) {\n        target_class = mrb_vm_ci_target_class(ci);\n      }\n      else if (target_class->tt == MRB_TT_MODULE) {\n        target_class = mrb_vm_ci_target_class(ci);\n        if (!target_class || target_class->tt != MRB_TT_ICLASS) {\n          goto super_typeerror;\n        }\n      }\n      recv = regs[0];\n      if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {\n      super_typeerror: ;\n        mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n                                            \"self has wrong type to call super in this context\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n\n      ARGUMENT_NORMALIZE(a, &b, OP_SUPER);\n\n      cls = target_class->super;\n      m = mrb_method_search_vm(mrb, &cls, mid);\n      if (MRB_METHOD_UNDEF_P(m)) {\n        m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1);\n        mid = MRB_SYM(method_missing);\n      }\n\n      /* push callinfo */\n      ci = cipush(mrb, a, 0, cls, NULL, mid, b);\n\n      /* prepare stack */\n      ci->stack[0] = recv;\n\n      if (MRB_METHOD_CFUNC_P(m)) {\n        mrb_value v;\n\n        if (MRB_METHOD_PROC_P(m)) {\n          mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m));\n        }\n        v = MRB_METHOD_CFUNC(m)(mrb, recv);\n        mrb_gc_arena_restore(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        ci = mrb->c->ci;\n        mrb_assert(!mrb_break_p(v));\n        if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */\n          if (ci->cci == CINFO_RESUMED) {\n            mrb->jmp = prev_jmp;\n            return v;\n          }\n          else {\n            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n            proc = ci[-1].proc;\n            irep = proc->body.irep;\n            pool = irep->pool;\n            syms = irep->syms;\n          }\n        }\n        mrb->c->ci->stack[0] = v;\n        ci = cipop(mrb);\n        pc = ci->pc;\n      }\n      else {\n        /* setup environment for calling method */\n        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n        pc = irep->iseq;\n      }\n      JUMP;\n    }\n\n    CASE(OP_ARGARY, BS) {\n      mrb_int m1 = (b>>11)&0x3f;\n      mrb_int r  = (b>>10)&0x1;\n      mrb_int m2 = (b>>5)&0x1f;\n      mrb_int kd = (b>>4)&0x1;\n      mrb_int lv = (b>>0)&0xf;\n      mrb_value *stack;\n\n      if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) {\n        mrb_value exc;\n\n      L_NOSUPER:\n        exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n      if (lv == 0) stack = regs + 1;\n      else {\n        struct REnv *e = uvenv(mrb, lv-1);\n        if (!e) goto L_NOSUPER;\n        if (MRB_ENV_LEN(e) <= m1+r+m2+1)\n          goto L_NOSUPER;\n        stack = e->stack + 1;\n      }\n      if (r == 0) {\n        regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);\n      }\n      else {\n        mrb_value *pp = NULL;\n        struct RArray *rest;\n        mrb_int len = 0;\n\n        if (mrb_array_p(stack[m1])) {\n          struct RArray *ary = mrb_ary_ptr(stack[m1]);\n\n          pp = ARY_PTR(ary);\n          len = ARY_LEN(ary);\n        }\n        regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);\n        rest = mrb_ary_ptr(regs[a]);\n        if (m1 > 0) {\n          stack_copy(ARY_PTR(rest), stack, m1);\n        }\n        if (len > 0) {\n          stack_copy(ARY_PTR(rest)+m1, pp, len);\n        }\n        if (m2 > 0) {\n          stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);\n        }\n        ARY_SET_LEN(rest, m1+len+m2);\n      }\n      if (kd) {\n        regs[a+1] = stack[m1+r+m2];\n        regs[a+2] = stack[m1+r+m2+1];\n      }\n      else {\n        regs[a+1] = stack[m1+r+m2];\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ENTER, W) {\n      mrb_int m1 = MRB_ASPEC_REQ(a);\n      mrb_int o  = MRB_ASPEC_OPT(a);\n      mrb_int r  = MRB_ASPEC_REST(a);\n      mrb_int m2 = MRB_ASPEC_POST(a);\n      mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0;\n      /* unused\n      int b  = MRB_ASPEC_BLOCK(a);\n      */\n      mrb_int const len = m1 + o + r + m2;\n\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_int argc = ci->n;\n      mrb_value *argv = regs+1;\n      mrb_value * const argv0 = argv;\n      mrb_int const kw_pos = len + kd;    /* where kwhash should be */\n      mrb_int const blk_pos = kw_pos + 1; /* where block should be */\n      mrb_value blk = regs[mrb_ci_bidx(ci)];\n      mrb_value kdict = mrb_nil_value();\n\n      /* keyword arguments */\n      if (ci->nk > 0) {\n        mrb_int kidx = mrb_ci_kidx(ci);\n        kdict = regs[kidx];\n        if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) {\n          kdict = mrb_nil_value();\n          ci->nk = 0;\n        }\n      }\n      if (!kd && !mrb_nil_p(kdict)) {\n        if (argc < 14) {\n          ci->n++;\n          argc++;    /* include kdict in normal arguments */\n        }\n        else if (argc == 14) {\n          /* pack arguments and kdict */\n          regs[1] = mrb_ary_new_from_values(mrb, argc+1, ®s[1]);\n          argc = ci->n = 15;\n        }\n        else {/* argc == 15 */\n          /* push kdict to packed arguments */\n          mrb_ary_push(mrb, regs[1], regs[2]);\n        }\n        ci->nk = 0;\n      }\n      if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) {\n        kdict = mrb_hash_dup(mrb, kdict);\n      }\n\n      /* arguments is passed with Array */\n      if (argc == 15) {\n        struct RArray *ary = mrb_ary_ptr(regs[1]);\n        argv = ARY_PTR(ary);\n        argc = (int)ARY_LEN(ary);\n        mrb_gc_protect(mrb, regs[1]);\n      }\n\n      /* strict argument check */\n      if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) {\n        if (argc < m1 + m2 || (r == 0 && argc > len)) {\n          argnum_error(mrb, m1+m2);\n          goto L_RAISE;\n        }\n      }\n      /* extract first argument array to arguments */\n      else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {\n        mrb_gc_protect(mrb, argv[0]);\n        argc = (int)RARRAY_LEN(argv[0]);\n        argv = RARRAY_PTR(argv[0]);\n      }\n\n      /* rest arguments */\n      mrb_value rest = mrb_nil_value();\n      if (argc < len) {\n        mrb_int mlen = m2;\n        if (argc < m1+m2) {\n          mlen = m1 < argc ? argc - m1 : 0;\n        }\n\n        /* copy mandatory and optional arguments */\n        if (argv0 != argv && argv) {\n          value_move(®s[1], argv, argc-mlen); /* m1 + o */\n        }\n        if (argc < m1) {\n          stack_clear(®s[argc+1], m1-argc);\n        }\n        /* copy post mandatory arguments */\n        if (mlen) {\n          value_move(®s[len-m2+1], &argv[argc-mlen], mlen);\n        }\n        if (mlen < m2) {\n          stack_clear(®s[len-m2+mlen+1], m2-mlen);\n        }\n        /* initialize rest arguments with empty Array */\n        if (r) {\n          rest = mrb_ary_new_capa(mrb, 0);\n          regs[m1+o+1] = rest;\n        }\n        /* skip initializer of passed arguments */\n        if (o > 0 && argc > m1+m2)\n          pc += (argc - m1 - m2)*3;\n      }\n      else {\n        mrb_int rnum = 0;\n        if (argv0 != argv) {\n          value_move(®s[1], argv, m1+o);\n        }\n        if (r) {\n          rnum = argc-m1-o-m2;\n          rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);\n          regs[m1+o+1] = rest;\n        }\n        if (m2 > 0 && argc-m2 > m1) {\n          value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);\n        }\n        pc += o*3;\n      }\n\n      /* need to be update blk first to protect blk from GC */\n      regs[blk_pos] = blk;              /* move block */\n      if (kd) {\n        if (mrb_nil_p(kdict))\n          kdict = mrb_hash_new_capa(mrb, 0);\n        regs[kw_pos] = kdict;           /* set kwhash */\n      }\n\n      /* format arguments for generated code */\n      mrb->c->ci->n = len;\n\n      /* clear local (but non-argument) variables */\n      if (irep->nlocals-blk_pos-1 > 0) {\n        stack_clear(®s[blk_pos+1], irep->nlocals-blk_pos-1);\n      }\n      JUMP;\n    }\n\n    CASE(OP_KARG, BB) {\n      mrb_value k = mrb_symbol_value(syms[b]);\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict, v;\n\n      if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) {\n        mrb_value str = mrb_format(mrb, \"missing keyword: %v\", k);\n        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n        goto L_RAISE;\n      }\n      v = mrb_hash_get(mrb, kdict, k);\n      regs[a] = v;\n      mrb_hash_delete_key(mrb, kdict, k);\n      NEXT;\n    }\n\n    CASE(OP_KEY_P, BB) {\n      mrb_value k = mrb_symbol_value(syms[b]);\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict;\n      mrb_bool key_p = FALSE;\n\n      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) {\n        key_p = mrb_hash_key_p(mrb, kdict, k);\n      }\n      regs[a] = mrb_bool_value(key_p);\n      NEXT;\n    }\n\n    CASE(OP_KEYEND, Z) {\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict;\n\n      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) {\n        mrb_value keys = mrb_hash_keys(mrb, kdict);\n        mrb_value key1 = RARRAY_PTR(keys)[0];\n        mrb_value str = mrb_format(mrb, \"unknown keyword: %v\", key1);\n        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n        goto L_RAISE;\n      }\n      NEXT;\n    }\n\n    CASE(OP_BREAK, B) {\n      c = OP_R_BREAK;\n      goto L_RETURN;\n    }\n    CASE(OP_RETURN_BLK, B) {\n      c = OP_R_RETURN;\n      goto L_RETURN;\n    }\n    CASE(OP_RETURN, B)\n    c = OP_R_NORMAL;\n    L_RETURN:\n    {\n      mrb_callinfo *ci;\n\n      ci = mrb->c->ci;\n      if (ci->mid) {\n        mrb_value blk = regs[mrb_ci_bidx(ci)];\n\n        if (mrb_proc_p(blk)) {\n          struct RProc *p = mrb_proc_ptr(blk);\n\n          if (!MRB_PROC_STRICT_P(p) &&\n              ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n            p->flags |= MRB_PROC_ORPHAN;\n          }\n        }\n      }\n\n      if (mrb->exc) {\n      L_RAISE:\n        ci = mrb->c->ci;\n        if (ci == mrb->c->cibase) {\n          ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n          if (ch == NULL) goto L_FTOP;\n          goto L_CATCH;\n        }\n        while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) {\n          ci = cipop(mrb);\n          if (ci[1].cci == CINFO_SKIP && prev_jmp) {\n            mrb->jmp = prev_jmp;\n            MRB_THROW(prev_jmp);\n          }\n          pc = ci[0].pc;\n          if (ci == mrb->c->cibase) {\n            ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n            if (ch == NULL) {\n            L_FTOP:             /* fiber top */\n              if (mrb->c == mrb->root_c) {\n                mrb->c->ci->stack = mrb->c->stbase;\n                goto L_STOP;\n              }\n              else {\n                struct mrb_context *c = mrb->c;\n\n                c->status = MRB_FIBER_TERMINATED;\n                mrb->c = c->prev;\n                c->prev = NULL;\n                goto L_RAISE;\n              }\n            }\n            break;\n          }\n        }\n      L_CATCH:\n        if (ch == NULL) goto L_STOP;\n        if (FALSE) {\n        L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */\n          ci = mrb->c->ci;\n        }\n        proc = ci->proc;\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, irep->nregs);\n        pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target);\n      }\n      else {\n        mrb_int acc;\n        mrb_value v;\n\n        ci = mrb->c->ci;\n        v = regs[a];\n        mrb_gc_protect(mrb, v);\n        switch (c) {\n        case OP_R_RETURN:\n          /* Fall through to OP_R_NORMAL otherwise */\n          if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {\n            const struct RProc *dst;\n            mrb_callinfo *cibase;\n            cibase = mrb->c->cibase;\n            dst = top_proc(mrb, proc);\n\n            if (MRB_PROC_ENV_P(dst)) {\n              struct REnv *e = MRB_PROC_ENV(dst);\n\n              if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) {\n                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n                goto L_RAISE;\n              }\n            }\n            /* check jump destination */\n            while (cibase <= ci && ci->proc != dst) {\n              if (ci->cci > CINFO_NONE) { /* jump cross C boundary */\n                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n                goto L_RAISE;\n              }\n              ci--;\n            }\n            if (ci <= cibase) { /* no jump destination */\n              localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n              goto L_RAISE;\n            }\n            ci = mrb->c->ci;\n            while (cibase <= ci && ci->proc != dst) {\n              CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) {\n                cibase = mrb->c->cibase;\n                dst = top_proc(mrb, proc);\n              }\n              CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) {\n                UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v);\n              }\n              CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK);\n              ci = cipop(mrb);\n              pc = ci->pc;\n            }\n            proc = ci->proc;\n            mrb->exc = NULL; /* clear break object */\n            break;\n          }\n          /* fallthrough */\n        case OP_R_NORMAL:\n        NORMAL_RETURN:\n          if (ci == mrb->c->cibase) {\n            struct mrb_context *c;\n            c = mrb->c;\n\n            if (!c->prev) { /* toplevel return */\n              regs[irep->nlocals] = v;\n              goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP);\n            }\n            if (!c->vmexec && c->prev->ci == c->prev->cibase) {\n              mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, \"double resume\");\n              mrb_exc_set(mrb, exc);\n              goto L_RAISE;\n            }\n            CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) {\n              c = mrb->c;\n            }\n            CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) {\n              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v);\n            }\n            CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL);\n            /* automatic yield at the end */\n            c->status = MRB_FIBER_TERMINATED;\n            mrb->c = c->prev;\n            mrb->c->status = MRB_FIBER_RUNNING;\n            c->prev = NULL;\n            if (c->vmexec) {\n              mrb_gc_arena_restore(mrb, ai);\n              c->vmexec = FALSE;\n              mrb->jmp = prev_jmp;\n              return v;\n            }\n            ci = mrb->c->ci;\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_RETURN) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_RETURN);\n          mrb->exc = NULL; /* clear break object */\n          break;\n        case OP_R_BREAK:\n          if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;\n          if (MRB_PROC_ORPHAN_P(proc)) {\n            mrb_value exc;\n\n          L_BREAK_ERROR:\n            exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR,\n                                      \"break from proc-closure\");\n            mrb_exc_set(mrb, exc);\n            goto L_RAISE;\n          }\n          if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) {\n            goto L_BREAK_ERROR;\n          }\n          else {\n            struct REnv *e = MRB_PROC_ENV(proc);\n\n            if (e->cxt != mrb->c) {\n              goto L_BREAK_ERROR;\n            }\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_BREAK) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_BREAK);\n          /* break from fiber block */\n          if (ci == mrb->c->cibase && ci->pc) {\n            struct mrb_context *c = mrb->c;\n\n            mrb->c = c->prev;\n            c->prev = NULL;\n            ci = mrb->c->ci;\n          }\n          if (ci->cci > CINFO_NONE) {\n            ci = cipop(mrb);\n            mrb_gc_arena_restore(mrb, ai);\n            mrb->c->vmexec = FALSE;\n            mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v);\n            mrb->jmp = prev_jmp;\n            MRB_THROW(prev_jmp);\n          }\n          if (FALSE) {\n            struct RBreak *brk;\n\n          L_BREAK:\n            brk = (struct RBreak*)mrb->exc;\n            proc = mrb_break_proc_get(brk);\n            v = mrb_break_value_get(brk);\n            ci = mrb->c->ci;\n\n            switch (mrb_break_tag_get(brk)) {\n#define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n);\n              RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS)\n#undef DISPATCH_CHECKPOINTS\n              default:\n                mrb_assert(!\"wrong break tag\");\n            }\n          }\n          while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) {\n            if (ci[-1].cci == CINFO_SKIP) {\n              goto L_BREAK_ERROR;\n            }\n            CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) {\n              /* do nothing */\n            }\n            CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) {\n              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v);\n            }\n            CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER);\n            ci = cipop(mrb);\n            pc = ci->pc;\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET);\n          if (ci == mrb->c->cibase) {\n            goto L_BREAK_ERROR;\n          }\n          mrb->exc = NULL; /* clear break object */\n          break;\n        default:\n          /* cannot happen */\n          break;\n        }\n        mrb_assert(ci == mrb->c->ci);\n        mrb_assert(mrb->exc == NULL);\n\n        if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) {\n          mrb_gc_arena_restore(mrb, ai);\n          mrb->c->vmexec = FALSE;\n          mrb->jmp = prev_jmp;\n          return v;\n        }\n        acc = ci->cci;\n        ci = cipop(mrb);\n        if (acc == CINFO_SKIP || acc == CINFO_DIRECT) {\n          mrb_gc_arena_restore(mrb, ai);\n          mrb->jmp = prev_jmp;\n          return v;\n        }\n        pc = ci->pc;\n        DEBUG(fprintf(stderr, \"from :%s\\n\", mrb_sym_name(mrb, ci->mid)));\n        proc = ci->proc;\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n\n        ci[1].stack[0] = v;\n        mrb_gc_arena_restore(mrb, ai);\n      }\n      JUMP;\n    }\n\n    CASE(OP_BLKPUSH, BS) {\n      int m1 = (b>>11)&0x3f;\n      int r  = (b>>10)&0x1;\n      int m2 = (b>>5)&0x1f;\n      int kd = (b>>4)&0x1;\n      int lv = (b>>0)&0xf;\n      mrb_value *stack;\n\n      if (lv == 0) stack = regs + 1;\n      else {\n        struct REnv *e = uvenv(mrb, lv-1);\n        if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) ||\n            MRB_ENV_LEN(e) <= m1+r+m2+1) {\n          localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n          goto L_RAISE;\n        }\n        stack = e->stack + 1;\n      }\n      if (mrb_nil_p(stack[m1+r+m2+kd])) {\n        localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n        goto L_RAISE;\n      }\n      regs[a] = stack[m1+r+m2+kd];\n      NEXT;\n    }\n\n  L_INT_OVERFLOW:\n    {\n      mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, \"integer overflow\");\n      mrb_exc_set(mrb, exc);\n    }\n    goto L_RAISE;\n\n#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))\n#define OP_MATH(op_name)                                                    \\\n  /* need to check if op is overridden */                                   \\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {                  \\\n    OP_MATH_CASE_INTEGER(op_name);                                          \\\n    OP_MATH_CASE_FLOAT(op_name, integer, float);                            \\\n    OP_MATH_CASE_FLOAT(op_name, float,  integer);                           \\\n    OP_MATH_CASE_FLOAT(op_name, float,  float);                             \\\n    OP_MATH_CASE_STRING_##op_name();                                        \\\n    default:                                                                \\\n      mid = MRB_OPSYM(op_name);                                             \\\n      goto L_SEND_SYM;                                                      \\\n  }                                                                         \\\n  NEXT;\n#define OP_MATH_CASE_INTEGER(op_name)                                       \\\n  case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER):                              \\\n    {                                                                       \\\n      mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z;      \\\n      if (mrb_int_##op_name##_overflow(x, y, &z))                           \\\n        OP_MATH_OVERFLOW_INT();                                             \\\n      else                                                                  \\\n        SET_INT_VALUE(mrb,regs[a], z);                                      \\\n    }                                                                       \\\n    break\n#ifdef MRB_NO_FLOAT\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0\n#else\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2)                                     \\\n  case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2):                                \\\n    {                                                                           \\\n      mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \\\n      SET_FLOAT_VALUE(mrb, regs[a], z);                                         \\\n    }                                                                           \\\n    break\n#endif\n#define OP_MATH_OVERFLOW_INT() goto L_INT_OVERFLOW\n#define OP_MATH_CASE_STRING_add()                                           \\\n  case TYPES2(MRB_TT_STRING, MRB_TT_STRING):                                \\\n    regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]);                        \\\n    mrb_gc_arena_restore(mrb, ai);                                          \\\n    break\n#define OP_MATH_CASE_STRING_sub() (void)0\n#define OP_MATH_CASE_STRING_mul() (void)0\n#define OP_MATH_OP_add +\n#define OP_MATH_OP_sub -\n#define OP_MATH_OP_mul *\n#define OP_MATH_TT_integer MRB_TT_INTEGER\n#define OP_MATH_TT_float   MRB_TT_FLOAT\n\n    CASE(OP_ADD, B) {\n      OP_MATH(add);\n    }\n\n    CASE(OP_SUB, B) {\n      OP_MATH(sub);\n    }\n\n    CASE(OP_MUL, B) {\n      OP_MATH(mul);\n    }\n\n    CASE(OP_DIV, B) {\n#ifndef MRB_NO_FLOAT\n      mrb_float x, y, f;\n#endif\n\n      /* need to check if op is overridden */\n      switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\n      case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\n        {\n          mrb_int x = mrb_integer(regs[a]);\n          mrb_int y = mrb_integer(regs[a+1]);\n          mrb_int div = mrb_div_int(mrb, x, y);\n          SET_INT_VALUE(mrb, regs[a], div);\n        }\n        NEXT;\n#ifndef MRB_NO_FLOAT\n      case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\n        x = (mrb_float)mrb_integer(regs[a]);\n        y = mrb_float(regs[a+1]);\n        break;\n      case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\n        x = mrb_float(regs[a]);\n        y = (mrb_float)mrb_integer(regs[a+1]);\n        break;\n      case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\n        x = mrb_float(regs[a]);\n        y = mrb_float(regs[a+1]);\n        break;\n#endif\n      default:\n        mid = MRB_OPSYM(div);\n        goto L_SEND_SYM;\n      }\n\n#ifndef MRB_NO_FLOAT\n      f = mrb_div_float(x, y);\n      SET_FLOAT_VALUE(mrb, regs[a], f);\n#endif\n      NEXT;\n    }\n\n#define OP_MATHI(op_name)                                                   \\\n  /* need to check if op is overridden */                                   \\\n  switch (mrb_type(regs[a])) {                                              \\\n    OP_MATHI_CASE_INTEGER(op_name);                                         \\\n    OP_MATHI_CASE_FLOAT(op_name);                                           \\\n    default:                                                                \\\n      SET_INT_VALUE(mrb,regs[a+1], b);                                      \\\n      mid = MRB_OPSYM(op_name);                                             \\\n      goto L_SEND_SYM;                                                      \\\n  }                                                                         \\\n  NEXT;\n#define OP_MATHI_CASE_INTEGER(op_name)                                      \\\n  case MRB_TT_INTEGER:                                                      \\\n    {                                                                       \\\n      mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z;                  \\\n      if (mrb_int_##op_name##_overflow(x, y, &z))                           \\\n        OP_MATH_OVERFLOW_INT();                                             \\\n      else                                                                  \\\n        SET_INT_VALUE(mrb,regs[a], z);                                      \\\n    }                                                                       \\\n    break\n#ifdef MRB_NO_FLOAT\n#define OP_MATHI_CASE_FLOAT(op_name) (void)0\n#else\n#define OP_MATHI_CASE_FLOAT(op_name)                                        \\\n  case MRB_TT_FLOAT:                                                        \\\n    {                                                                       \\\n      mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b;              \\\n      SET_FLOAT_VALUE(mrb, regs[a], z);                                     \\\n    }                                                                       \\\n    break\n#endif\n\n    CASE(OP_ADDI, BB) {\n      OP_MATHI(add);\n    }\n\n    CASE(OP_SUBI, BB) {\n      OP_MATHI(sub);\n    }\n\n#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))\n\n#ifdef MRB_NO_FLOAT\n#define OP_CMP(op,sym) do {\\\n  int result;\\\n  /* need to check if - is overridden */\\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n    break;\\\n  default:\\\n    mid = MRB_OPSYM(sym);\\\n    goto L_SEND_SYM;\\\n  }\\\n  if (result) {\\\n    SET_TRUE_VALUE(regs[a]);\\\n  }\\\n  else {\\\n    SET_FALSE_VALUE(regs[a]);\\\n  }\\\n} while(0)\n#else\n#define OP_CMP(op, sym) do {\\\n  int result;\\\n  /* need to check if - is overridden */\\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n    break;\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\\\n    break;\\\n  case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\\\n    break;\\\n  case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\\\n    result = OP_CMP_BODY(op,mrb_float,mrb_float);\\\n    break;\\\n  default:\\\n    mid = MRB_OPSYM(sym);\\\n    goto L_SEND_SYM;\\\n  }\\\n  if (result) {\\\n    SET_TRUE_VALUE(regs[a]);\\\n  }\\\n  else {\\\n    SET_FALSE_VALUE(regs[a]);\\\n  }\\\n} while(0)\n#endif\n\n    CASE(OP_EQ, B) {\n      if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {\n        SET_TRUE_VALUE(regs[a]);\n      }\n      else {\n        OP_CMP(==,eq);\n      }\n      NEXT;\n    }\n\n    CASE(OP_LT, B) {\n      OP_CMP(<,lt);\n      NEXT;\n    }\n\n    CASE(OP_LE, B) {\n      OP_CMP(<=,le);\n      NEXT;\n    }\n\n    CASE(OP_GT, B) {\n      OP_CMP(>,gt);\n      NEXT;\n    }\n\n    CASE(OP_GE, B) {\n      OP_CMP(>=,ge);\n      NEXT;\n    }\n\n    CASE(OP_ARRAY, BB) {\n      regs[a] = mrb_ary_new_from_values(mrb, b, ®s[a]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n    CASE(OP_ARRAY2, BBB) {\n      regs[a] = mrb_ary_new_from_values(mrb, c, ®s[b]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ARYCAT, B) {\n      mrb_value splat = mrb_ary_splat(mrb, regs[a+1]);\n      if (mrb_nil_p(regs[a])) {\n        regs[a] = splat;\n      }\n      else {\n        mrb_assert(mrb_array_p(regs[a]));\n        mrb_ary_concat(mrb, regs[a], splat);\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ARYPUSH, BB) {\n      mrb_assert(mrb_array_p(regs[a]));\n      for (mrb_int i=0; i pre + post) {\n        v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);\n        regs[a++] = v;\n        while (post--) {\n          regs[a++] = ARY_PTR(ary)[len-post-1];\n        }\n      }\n      else {\n        v = mrb_ary_new_capa(mrb, 0);\n        regs[a++] = v;\n        for (idx=0; idx+pre> 2;\n      if (pool[b].tt & IREP_TT_SFLAG) {\n        sym = mrb_intern_static(mrb, pool[b].u.str, len);\n      }\n      else {\n        sym  = mrb_intern(mrb, pool[b].u.str, len);\n      }\n      regs[a] = mrb_symbol_value(sym);\n      NEXT;\n    }\n\n    CASE(OP_STRING, BB) {\n      mrb_int len;\n\n      mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0);\n      len = pool[b].tt >> 2;\n      if (pool[b].tt & IREP_TT_SFLAG) {\n        regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len);\n      }\n      else {\n        regs[a] = mrb_str_new(mrb, pool[b].u.str, len);\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_STRCAT, B) {\n      mrb_assert(mrb_string_p(regs[a]));\n      mrb_str_concat(mrb, regs[a], regs[a+1]);\n      NEXT;\n    }\n\n    CASE(OP_HASH, BB) {\n      mrb_value hash = mrb_hash_new_capa(mrb, b);\n      int i;\n      int lim = a+b*2;\n\n      for (i=a; ireps[b];\n\n      if (c & OP_L_CAPTURE) {\n        p = mrb_closure_new(mrb, nirep);\n      }\n      else {\n        p = mrb_proc_new(mrb, nirep);\n        p->flags |= MRB_PROC_SCOPE;\n      }\n      if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;\n      regs[a] = mrb_obj_value(p);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n    CASE(OP_BLOCK, BB) {\n      c = OP_L_BLOCK;\n      goto L_MAKE_LAMBDA;\n    }\n    CASE(OP_METHOD, BB) {\n      c = OP_L_METHOD;\n      goto L_MAKE_LAMBDA;\n    }\n\n    CASE(OP_RANGE_INC, B) {\n      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE);\n      regs[a] = v;\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_RANGE_EXC, B) {\n      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE);\n      regs[a] = v;\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_OCLASS, B) {\n      regs[a] = mrb_obj_value(mrb->object_class);\n      NEXT;\n    }\n\n    CASE(OP_CLASS, BB) {\n      struct RClass *c = 0, *baseclass;\n      mrb_value base, super;\n      mrb_sym id = syms[b];\n\n      base = regs[a];\n      super = regs[a+1];\n      if (mrb_nil_p(base)) {\n        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n        if (!baseclass) baseclass = mrb->object_class;\n        base = mrb_obj_value(baseclass);\n      }\n      c = mrb_vm_define_class(mrb, base, super, id);\n      regs[a] = mrb_obj_value(c);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_MODULE, BB) {\n      struct RClass *cls = 0, *baseclass;\n      mrb_value base;\n      mrb_sym id = syms[b];\n\n      base = regs[a];\n      if (mrb_nil_p(base)) {\n        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n        if (!baseclass) baseclass = mrb->object_class;\n        base = mrb_obj_value(baseclass);\n      }\n      cls = mrb_vm_define_module(mrb, base, id);\n      regs[a] = mrb_obj_value(cls);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_EXEC, BB)\n    {\n      mrb_value recv = regs[a];\n      struct RProc *p;\n      const mrb_irep *nirep = irep->reps[b];\n\n      /* prepare closure */\n      p = mrb_proc_new(mrb, nirep);\n      p->c = NULL;\n      mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);\n      MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));\n      p->flags |= MRB_PROC_SCOPE;\n\n      /* prepare call stack */\n      cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0);\n\n      irep = p->body.irep;\n      pool = irep->pool;\n      syms = irep->syms;\n      mrb_stack_extend(mrb, irep->nregs);\n      stack_clear(regs+1, irep->nregs-1);\n      pc = irep->iseq;\n      JUMP;\n    }\n\n    CASE(OP_DEF, BB) {\n      struct RClass *target = mrb_class_ptr(regs[a]);\n      struct RProc *p = mrb_proc_ptr(regs[a+1]);\n      mrb_method_t m;\n      mrb_sym mid = syms[b];\n\n      MRB_METHOD_FROM_PROC(m, p);\n      mrb_define_method_raw(mrb, target, mid, m);\n      mrb_method_added(mrb, target, mid);\n      mrb_gc_arena_restore(mrb, ai);\n      regs[a] = mrb_symbol_value(mid);\n      NEXT;\n    }\n\n    CASE(OP_SCLASS, B) {\n      regs[a] = mrb_singleton_class(mrb, regs[a]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_TCLASS, B) {\n      struct RClass *target = check_target_class(mrb);\n      if (!target) goto L_RAISE;\n      regs[a] = mrb_obj_value(target);\n      NEXT;\n    }\n\n    CASE(OP_ALIAS, BB) {\n      struct RClass *target = check_target_class(mrb);\n\n      if (!target) goto L_RAISE;\n      mrb_alias_method(mrb, target, syms[a], syms[b]);\n      mrb_method_added(mrb, target, syms[a]);\n      NEXT;\n    }\n    CASE(OP_UNDEF, B) {\n      struct RClass *target = check_target_class(mrb);\n\n      if (!target) goto L_RAISE;\n      mrb_undef_method_id(mrb, target, syms[a]);\n      NEXT;\n    }\n\n    CASE(OP_DEBUG, Z) {\n      FETCH_BBB();\n#ifdef MRB_USE_DEBUG_HOOK\n      mrb->debug_op_hook(mrb, irep, pc, regs);\n#else\n#ifndef MRB_NO_STDIO\n      printf(\"OP_DEBUG %d %d %d\\n\", a, b, c);\n#else\n      abort();\n#endif\n#endif\n      NEXT;\n    }\n\n    CASE(OP_ERR, B) {\n      size_t len = pool[a].tt >> 2;\n      mrb_value exc;\n\n      mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0);\n      exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len);\n      mrb_exc_set(mrb, exc);\n      goto L_RAISE;\n    }\n\n    CASE(OP_EXT1, Z) {\n      insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n    CASE(OP_EXT2, Z) {\n      insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n    CASE(OP_EXT3, Z) {\n      uint8_t insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n\n    CASE(OP_STOP, Z) {\n      /*        stop VM */\n      CHECKPOINT_RESTORE(RBREAK_TAG_STOP) {\n        /* do nothing */\n      }\n      CHECKPOINT_MAIN(RBREAK_TAG_STOP) {\n        UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value());\n      }\n      CHECKPOINT_END(RBREAK_TAG_STOP);\n    L_STOP:\n      mrb->jmp = prev_jmp;\n      if (mrb->exc) {\n        mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION);\n        return mrb_obj_value(mrb->exc);\n      }\n      return regs[irep->nlocals];\n    }\n  }\n  END_DISPATCH;\n#undef regs\n  }\n  MRB_CATCH(&c_jmp) {\n    mrb_callinfo *ci = mrb->c->ci;\n    while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) {\n      ci = cipop(mrb);\n    }\n    exc_catched = TRUE;\n    pc = ci->pc;\n    goto RETRY_TRY_BLOCK;\n  }\n  MRB_END_EXC(&c_jmp);\n}", "func_hash": 109885974444796302561569813029771831944, "file_name": "vm.c", "file_hash": 83886473477345826235413068203214397377, "cwe": ["CWE-288"], "cve": "CVE-2022-1212", "cve_desc": "Use-After-Free in str_escape in mruby/mruby in GitHub repository mruby/mruby prior to 3.2. Possible arbitrary code execution if being exploited.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1212"}
{"idx": 274773, "project": "mruby", "commit_id": "3cf291f72224715942beaf8553e42ba8891ab3c6", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/3cf291f72224715942beaf8553e42ba8891ab3c6", "commit_message": "vm.c: create break object before clearing GC arena.\n\nOtherwise it possibly cause use-after-free.", "target": 0, "func": "mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc)\n{\n  /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */\n  const mrb_irep *irep = proc->body.irep;\n  const mrb_pool_value *pool = irep->pool;\n  const mrb_sym *syms = irep->syms;\n  mrb_code insn;\n  int ai = mrb_gc_arena_save(mrb);\n  struct mrb_jmpbuf *prev_jmp = mrb->jmp;\n  struct mrb_jmpbuf c_jmp;\n  uint32_t a;\n  uint16_t b;\n  uint16_t c;\n  mrb_sym mid;\n  const struct mrb_irep_catch_handler *ch;\n\n#ifdef DIRECT_THREADED\n  static const void * const optable[] = {\n#define OPCODE(x,_) &&L_OP_ ## x,\n#include \"mruby/ops.h\"\n#undef OPCODE\n  };\n#endif\n\n  mrb_bool exc_catched = FALSE;\nRETRY_TRY_BLOCK:\n\n  MRB_TRY(&c_jmp) {\n\n  if (exc_catched) {\n    exc_catched = FALSE;\n    mrb_gc_arena_restore(mrb, ai);\n    if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)\n      goto L_BREAK;\n    goto L_RAISE;\n  }\n  mrb->jmp = &c_jmp;\n  mrb_vm_ci_proc_set(mrb->c->ci, proc);\n\n#define regs (mrb->c->ci->stack)\n  INIT_DISPATCH {\n    CASE(OP_NOP, Z) {\n      /* do nothing */\n      NEXT;\n    }\n\n    CASE(OP_MOVE, BB) {\n      regs[a] = regs[b];\n      NEXT;\n    }\n\n    CASE(OP_LOADL, BB) {\n      switch (pool[b].tt) {   /* number */\n      case IREP_TT_INT32:\n        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32);\n        break;\n      case IREP_TT_INT64:\n#if defined(MRB_INT64)\n        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n        break;\n#else\n#if defined(MRB_64BIT)\n        if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) {\n          regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n          break;\n        }\n#endif\n        goto L_INT_OVERFLOW;\n#endif\n      case IREP_TT_BIGINT:\n        goto L_INT_OVERFLOW;\n#ifndef MRB_NO_FLOAT\n      case IREP_TT_FLOAT:\n        regs[a] = mrb_float_value(mrb, pool[b].u.f);\n        break;\n#endif\n      default:\n        /* should not happen (tt:string) */\n        regs[a] = mrb_nil_value();\n        break;\n      }\n      NEXT;\n    }\n\n    CASE(OP_LOADI, BB) {\n      SET_FIXNUM_VALUE(regs[a], b);\n      NEXT;\n    }\n\n    CASE(OP_LOADINEG, BB) {\n      SET_FIXNUM_VALUE(regs[a], -b);\n      NEXT;\n    }\n\n    CASE(OP_LOADI__1,B) goto L_LOADI;\n    CASE(OP_LOADI_0,B) goto L_LOADI;\n    CASE(OP_LOADI_1,B) goto L_LOADI;\n    CASE(OP_LOADI_2,B) goto L_LOADI;\n    CASE(OP_LOADI_3,B) goto L_LOADI;\n    CASE(OP_LOADI_4,B) goto L_LOADI;\n    CASE(OP_LOADI_5,B) goto L_LOADI;\n    CASE(OP_LOADI_6,B) goto L_LOADI;\n    CASE(OP_LOADI_7, B) {\n    L_LOADI:\n      SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0);\n      NEXT;\n    }\n\n    CASE(OP_LOADI16, BS) {\n      SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b);\n      NEXT;\n    }\n\n    CASE(OP_LOADI32, BSS) {\n      SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c));\n      NEXT;\n    }\n\n    CASE(OP_LOADSYM, BB) {\n      SET_SYM_VALUE(regs[a], syms[b]);\n      NEXT;\n    }\n\n    CASE(OP_LOADNIL, B) {\n      SET_NIL_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_LOADSELF, B) {\n      regs[a] = regs[0];\n      NEXT;\n    }\n\n    CASE(OP_LOADT, B) {\n      SET_TRUE_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_LOADF, B) {\n      SET_FALSE_VALUE(regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETGV, BB) {\n      mrb_value val = mrb_gv_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETGV, BB) {\n      mrb_gv_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETSV, BB) {\n      mrb_value val = mrb_vm_special_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETSV, BB) {\n      mrb_vm_special_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETIV, BB) {\n      regs[a] = mrb_iv_get(mrb, regs[0], syms[b]);\n      NEXT;\n    }\n\n    CASE(OP_SETIV, BB) {\n      mrb_iv_set(mrb, regs[0], syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETCV, BB) {\n      mrb_value val;\n      val = mrb_vm_cv_get(mrb, syms[b]);\n      regs[a] = val;\n      NEXT;\n    }\n\n    CASE(OP_SETCV, BB) {\n      mrb_vm_cv_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETIDX, B) {\n      mrb_value va = regs[a], vb = regs[a+1];\n      switch (mrb_type(va)) {\n      case MRB_TT_ARRAY:\n        if (!mrb_integer_p(vb)) goto getidx_fallback;\n        regs[a] = mrb_ary_entry(va, mrb_integer(vb));\n        break;\n      case MRB_TT_HASH:\n        va = mrb_hash_get(mrb, va, vb);\n        regs[a] = va;\n        break;\n      case MRB_TT_STRING:\n        switch (mrb_type(vb)) {\n        case MRB_TT_INTEGER:\n        case MRB_TT_STRING:\n        case MRB_TT_RANGE:\n          va = mrb_str_aref(mrb, va, vb, mrb_undef_value());\n          regs[a] = va;\n          break;\n        default:\n          goto getidx_fallback;\n        }\n        break;\n      default:\n      getidx_fallback:\n        mid = MRB_OPSYM(aref);\n        goto L_SEND_SYM;\n      }\n      NEXT;\n    }\n\n    CASE(OP_SETIDX, B) {\n      c = 2;\n      mid = MRB_OPSYM(aset);\n      SET_NIL_VALUE(regs[a+3]);\n      goto L_SENDB_SYM;\n    }\n\n    CASE(OP_GETCONST, BB) {\n      mrb_value v = mrb_vm_const_get(mrb, syms[b]);\n      regs[a] = v;\n      NEXT;\n    }\n\n    CASE(OP_SETCONST, BB) {\n      mrb_vm_const_set(mrb, syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETMCNST, BB) {\n      mrb_value v = mrb_const_get(mrb, regs[a], syms[b]);\n      regs[a] = v;\n      NEXT;\n    }\n\n    CASE(OP_SETMCNST, BB) {\n      mrb_const_set(mrb, regs[a+1], syms[b], regs[a]);\n      NEXT;\n    }\n\n    CASE(OP_GETUPVAR, BBB) {\n      mrb_value *regs_a = regs + a;\n      struct REnv *e = uvenv(mrb, c);\n\n      if (e && b < MRB_ENV_LEN(e)) {\n        *regs_a = e->stack[b];\n      }\n      else {\n        *regs_a = mrb_nil_value();\n      }\n      NEXT;\n    }\n\n    CASE(OP_SETUPVAR, BBB) {\n      struct REnv *e = uvenv(mrb, c);\n\n      if (e) {\n        mrb_value *regs_a = regs + a;\n\n        if (b < MRB_ENV_LEN(e)) {\n          e->stack[b] = *regs_a;\n          mrb_write_barrier(mrb, (struct RBasic*)e);\n        }\n      }\n      NEXT;\n    }\n\n    CASE(OP_JMP, S) {\n      pc += (int16_t)a;\n      JUMP;\n    }\n    CASE(OP_JMPIF, BS) {\n      if (mrb_test(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n    CASE(OP_JMPNOT, BS) {\n      if (!mrb_test(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n    CASE(OP_JMPNIL, BS) {\n      if (mrb_nil_p(regs[a])) {\n        pc += (int16_t)b;\n        JUMP;\n      }\n      NEXT;\n    }\n\n    CASE(OP_JMPUW, S) {\n      a = (uint32_t)((pc - irep->iseq) + (int16_t)a);\n      CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) {\n        struct RBreak *brk = (struct RBreak*)mrb->exc;\n        mrb_value target = mrb_break_value_get(brk);\n        mrb_assert(mrb_integer_p(target));\n        a = (uint32_t)mrb_integer(target);\n        mrb_assert(a >= 0 && a < irep->ilen);\n      }\n      CHECKPOINT_MAIN(RBREAK_TAG_JUMP) {\n        ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE);\n        if (ch) {\n          /* avoiding a jump from a catch handler into the same handler */\n          if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) {\n            THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a));\n          }\n        }\n      }\n      CHECKPOINT_END(RBREAK_TAG_JUMP);\n\n      mrb->exc = NULL; /* clear break object */\n      pc = irep->iseq + a;\n      JUMP;\n    }\n\n    CASE(OP_EXCEPT, B) {\n      mrb_value exc;\n\n      if (mrb->exc == NULL) {\n        exc = mrb_nil_value();\n      }\n      else {\n        switch (mrb->exc->tt) {\n        case MRB_TT_BREAK:\n        case MRB_TT_EXCEPTION:\n          exc = mrb_obj_value(mrb->exc);\n          break;\n        default:\n          mrb_assert(!\"bad mrb_type\");\n          exc = mrb_nil_value();\n          break;\n        }\n        mrb->exc = NULL;\n      }\n      regs[a] = exc;\n      NEXT;\n    }\n    CASE(OP_RESCUE, BB) {\n      mrb_value exc = regs[a];  /* exc on stack */\n      mrb_value e = regs[b];\n      struct RClass *ec;\n\n      switch (mrb_type(e)) {\n      case MRB_TT_CLASS:\n      case MRB_TT_MODULE:\n        break;\n      default:\n        {\n          mrb_value exc;\n\n          exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n                                    \"class or module required for rescue clause\");\n          mrb_exc_set(mrb, exc);\n          goto L_RAISE;\n        }\n      }\n      ec = mrb_class_ptr(e);\n      regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));\n      NEXT;\n    }\n\n    CASE(OP_RAISEIF, B) {\n      mrb_value exc = regs[a];\n      if (mrb_break_p(exc)) {\n        mrb->exc = mrb_obj_ptr(exc);\n        goto L_BREAK;\n      }\n      mrb_exc_set(mrb, exc);\n      if (mrb->exc) {\n        goto L_RAISE;\n      }\n      NEXT;\n    }\n\n    CASE(OP_SSEND, BBB) {\n      regs[a] = regs[0];\n      insn = OP_SEND;\n    }\n    goto L_SENDB;\n\n    CASE(OP_SSENDB, BBB) {\n      regs[a] = regs[0];\n    }\n    goto L_SENDB;\n\n    CASE(OP_SEND, BBB)\n    goto L_SENDB;\n\n    L_SEND_SYM:\n    c = 1;\n    /* push nil after arguments */\n    SET_NIL_VALUE(regs[a+2]);\n    goto L_SENDB_SYM;\n\n    CASE(OP_SENDB, BBB)\n    L_SENDB:\n    mid = syms[b];\n    L_SENDB_SYM:\n    {\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_method_t m;\n      struct RClass *cls;\n      mrb_value recv, blk;\n\n      ARGUMENT_NORMALIZE(a, &c, insn);\n\n      recv = regs[a];\n      cls = mrb_class(mrb, recv);\n      m = mrb_method_search_vm(mrb, &cls, mid);\n      if (MRB_METHOD_UNDEF_P(m)) {\n        m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0);\n        mid = MRB_SYM(method_missing);\n      }\n\n      /* push callinfo */\n      ci = cipush(mrb, a, 0, cls, NULL, mid, c);\n\n      if (MRB_METHOD_CFUNC_P(m)) {\n        if (MRB_METHOD_PROC_P(m)) {\n          struct RProc *p = MRB_METHOD_PROC(m);\n\n          mrb_vm_ci_proc_set(ci, p);\n          recv = p->body.func(mrb, recv);\n        }\n        else {\n          if (MRB_METHOD_NOARG_P(m)) {\n            check_method_noarg(mrb, ci);\n          }\n          recv = MRB_METHOD_FUNC(m)(mrb, recv);\n        }\n        mrb_gc_arena_shrink(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        ci = mrb->c->ci;\n        if (mrb_proc_p(blk)) {\n          struct RProc *p = mrb_proc_ptr(blk);\n          if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n            p->flags |= MRB_PROC_ORPHAN;\n          }\n        }\n        if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */\n          if (ci->cci == CINFO_RESUMED) {\n            mrb->jmp = prev_jmp;\n            return recv;\n          }\n          else {\n            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n            proc = ci[-1].proc;\n            irep = proc->body.irep;\n            pool = irep->pool;\n            syms = irep->syms;\n          }\n        }\n        ci->stack[0] = recv;\n        /* pop stackpos */\n        ci = cipop(mrb);\n        pc = ci->pc;\n      }\n      else {\n        /* setup environment for calling method */\n        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n        pc = irep->iseq;\n      }\n    }\n    JUMP;\n\n    CASE(OP_CALL, Z) {\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_value recv = ci->stack[0];\n      struct RProc *m = mrb_proc_ptr(recv);\n\n      /* replace callinfo */\n      ci->u.target_class = MRB_PROC_TARGET_CLASS(m);\n      mrb_vm_ci_proc_set(ci, m);\n      if (MRB_PROC_ENV_P(m)) {\n        ci->mid = MRB_PROC_ENV(m)->mid;\n      }\n\n      /* prepare stack */\n      if (MRB_PROC_CFUNC_P(m)) {\n        recv = MRB_PROC_CFUNC(m)(mrb, recv);\n        mrb_gc_arena_shrink(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        /* pop stackpos */\n        ci = cipop(mrb);\n        pc = ci->pc;\n        ci[1].stack[0] = recv;\n        irep = mrb->c->ci->proc->body.irep;\n      }\n      else {\n        /* setup environment for calling method */\n        proc = m;\n        irep = m->body.irep;\n        if (!irep) {\n          mrb->c->ci->stack[0] = mrb_nil_value();\n          a = 0;\n          c = OP_R_NORMAL;\n          goto L_OP_RETURN_BODY;\n        }\n        mrb_int nargs = mrb_ci_bidx(ci)+1;\n        if (nargs < irep->nregs) {\n          mrb_stack_extend(mrb, irep->nregs);\n          stack_clear(regs+nargs, irep->nregs-nargs);\n        }\n        if (MRB_PROC_ENV_P(m)) {\n          regs[0] = MRB_PROC_ENV(m)->stack[0];\n        }\n        pc = irep->iseq;\n      }\n      pool = irep->pool;\n      syms = irep->syms;\n      JUMP;\n    }\n\n    CASE(OP_SUPER, BB) {\n      mrb_method_t m;\n      struct RClass *cls;\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_value recv, blk;\n      const struct RProc *p = ci->proc;\n      mrb_sym mid = ci->mid;\n      struct RClass* target_class = MRB_PROC_TARGET_CLASS(p);\n\n      if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */\n        mid = p->e.env->mid;    /* restore old mid */\n      }\n\n      if (mid == 0 || !target_class) {\n        mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n      if (target_class->flags & MRB_FL_CLASS_IS_PREPENDED) {\n        target_class = mrb_vm_ci_target_class(ci);\n      }\n      else if (target_class->tt == MRB_TT_MODULE) {\n        target_class = mrb_vm_ci_target_class(ci);\n        if (!target_class || target_class->tt != MRB_TT_ICLASS) {\n          goto super_typeerror;\n        }\n      }\n      recv = regs[0];\n      if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {\n      super_typeerror: ;\n        mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n                                            \"self has wrong type to call super in this context\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n\n      ARGUMENT_NORMALIZE(a, &b, OP_SUPER);\n\n      cls = target_class->super;\n      m = mrb_method_search_vm(mrb, &cls, mid);\n      if (MRB_METHOD_UNDEF_P(m)) {\n        m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1);\n        mid = MRB_SYM(method_missing);\n      }\n\n      /* push callinfo */\n      ci = cipush(mrb, a, 0, cls, NULL, mid, b);\n\n      /* prepare stack */\n      ci->stack[0] = recv;\n\n      if (MRB_METHOD_CFUNC_P(m)) {\n        mrb_value v;\n\n        if (MRB_METHOD_PROC_P(m)) {\n          mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m));\n        }\n        v = MRB_METHOD_CFUNC(m)(mrb, recv);\n        mrb_gc_arena_restore(mrb, ai);\n        if (mrb->exc) goto L_RAISE;\n        ci = mrb->c->ci;\n        mrb_assert(!mrb_break_p(v));\n        if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */\n          if (ci->cci == CINFO_RESUMED) {\n            mrb->jmp = prev_jmp;\n            return v;\n          }\n          else {\n            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n            proc = ci[-1].proc;\n            irep = proc->body.irep;\n            pool = irep->pool;\n            syms = irep->syms;\n          }\n        }\n        mrb->c->ci->stack[0] = v;\n        ci = cipop(mrb);\n        pc = ci->pc;\n      }\n      else {\n        /* setup environment for calling method */\n        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n        pc = irep->iseq;\n      }\n      JUMP;\n    }\n\n    CASE(OP_ARGARY, BS) {\n      mrb_int m1 = (b>>11)&0x3f;\n      mrb_int r  = (b>>10)&0x1;\n      mrb_int m2 = (b>>5)&0x1f;\n      mrb_int kd = (b>>4)&0x1;\n      mrb_int lv = (b>>0)&0xf;\n      mrb_value *stack;\n\n      if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) {\n        mrb_value exc;\n\n      L_NOSUPER:\n        exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n        mrb_exc_set(mrb, exc);\n        goto L_RAISE;\n      }\n      if (lv == 0) stack = regs + 1;\n      else {\n        struct REnv *e = uvenv(mrb, lv-1);\n        if (!e) goto L_NOSUPER;\n        if (MRB_ENV_LEN(e) <= m1+r+m2+1)\n          goto L_NOSUPER;\n        stack = e->stack + 1;\n      }\n      if (r == 0) {\n        regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);\n      }\n      else {\n        mrb_value *pp = NULL;\n        struct RArray *rest;\n        mrb_int len = 0;\n\n        if (mrb_array_p(stack[m1])) {\n          struct RArray *ary = mrb_ary_ptr(stack[m1]);\n\n          pp = ARY_PTR(ary);\n          len = ARY_LEN(ary);\n        }\n        regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);\n        rest = mrb_ary_ptr(regs[a]);\n        if (m1 > 0) {\n          stack_copy(ARY_PTR(rest), stack, m1);\n        }\n        if (len > 0) {\n          stack_copy(ARY_PTR(rest)+m1, pp, len);\n        }\n        if (m2 > 0) {\n          stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);\n        }\n        ARY_SET_LEN(rest, m1+len+m2);\n      }\n      if (kd) {\n        regs[a+1] = stack[m1+r+m2];\n        regs[a+2] = stack[m1+r+m2+1];\n      }\n      else {\n        regs[a+1] = stack[m1+r+m2];\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ENTER, W) {\n      mrb_int m1 = MRB_ASPEC_REQ(a);\n      mrb_int o  = MRB_ASPEC_OPT(a);\n      mrb_int r  = MRB_ASPEC_REST(a);\n      mrb_int m2 = MRB_ASPEC_POST(a);\n      mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0;\n      /* unused\n      int b  = MRB_ASPEC_BLOCK(a);\n      */\n      mrb_int const len = m1 + o + r + m2;\n\n      mrb_callinfo *ci = mrb->c->ci;\n      mrb_int argc = ci->n;\n      mrb_value *argv = regs+1;\n      mrb_value * const argv0 = argv;\n      mrb_int const kw_pos = len + kd;    /* where kwhash should be */\n      mrb_int const blk_pos = kw_pos + 1; /* where block should be */\n      mrb_value blk = regs[mrb_ci_bidx(ci)];\n      mrb_value kdict = mrb_nil_value();\n\n      /* keyword arguments */\n      if (ci->nk > 0) {\n        mrb_int kidx = mrb_ci_kidx(ci);\n        kdict = regs[kidx];\n        if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) {\n          kdict = mrb_nil_value();\n          ci->nk = 0;\n        }\n      }\n      if (!kd && !mrb_nil_p(kdict)) {\n        if (argc < 14) {\n          ci->n++;\n          argc++;    /* include kdict in normal arguments */\n        }\n        else if (argc == 14) {\n          /* pack arguments and kdict */\n          regs[1] = mrb_ary_new_from_values(mrb, argc+1, ®s[1]);\n          argc = ci->n = 15;\n        }\n        else {/* argc == 15 */\n          /* push kdict to packed arguments */\n          mrb_ary_push(mrb, regs[1], regs[2]);\n        }\n        ci->nk = 0;\n      }\n      if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) {\n        kdict = mrb_hash_dup(mrb, kdict);\n      }\n\n      /* arguments is passed with Array */\n      if (argc == 15) {\n        struct RArray *ary = mrb_ary_ptr(regs[1]);\n        argv = ARY_PTR(ary);\n        argc = (int)ARY_LEN(ary);\n        mrb_gc_protect(mrb, regs[1]);\n      }\n\n      /* strict argument check */\n      if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) {\n        if (argc < m1 + m2 || (r == 0 && argc > len)) {\n          argnum_error(mrb, m1+m2);\n          goto L_RAISE;\n        }\n      }\n      /* extract first argument array to arguments */\n      else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {\n        mrb_gc_protect(mrb, argv[0]);\n        argc = (int)RARRAY_LEN(argv[0]);\n        argv = RARRAY_PTR(argv[0]);\n      }\n\n      /* rest arguments */\n      mrb_value rest = mrb_nil_value();\n      if (argc < len) {\n        mrb_int mlen = m2;\n        if (argc < m1+m2) {\n          mlen = m1 < argc ? argc - m1 : 0;\n        }\n\n        /* copy mandatory and optional arguments */\n        if (argv0 != argv && argv) {\n          value_move(®s[1], argv, argc-mlen); /* m1 + o */\n        }\n        if (argc < m1) {\n          stack_clear(®s[argc+1], m1-argc);\n        }\n        /* copy post mandatory arguments */\n        if (mlen) {\n          value_move(®s[len-m2+1], &argv[argc-mlen], mlen);\n        }\n        if (mlen < m2) {\n          stack_clear(®s[len-m2+mlen+1], m2-mlen);\n        }\n        /* initialize rest arguments with empty Array */\n        if (r) {\n          rest = mrb_ary_new_capa(mrb, 0);\n          regs[m1+o+1] = rest;\n        }\n        /* skip initializer of passed arguments */\n        if (o > 0 && argc > m1+m2)\n          pc += (argc - m1 - m2)*3;\n      }\n      else {\n        mrb_int rnum = 0;\n        if (argv0 != argv) {\n          value_move(®s[1], argv, m1+o);\n        }\n        if (r) {\n          rnum = argc-m1-o-m2;\n          rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);\n          regs[m1+o+1] = rest;\n        }\n        if (m2 > 0 && argc-m2 > m1) {\n          value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);\n        }\n        pc += o*3;\n      }\n\n      /* need to be update blk first to protect blk from GC */\n      regs[blk_pos] = blk;              /* move block */\n      if (kd) {\n        if (mrb_nil_p(kdict))\n          kdict = mrb_hash_new_capa(mrb, 0);\n        regs[kw_pos] = kdict;           /* set kwhash */\n      }\n\n      /* format arguments for generated code */\n      mrb->c->ci->n = len;\n\n      /* clear local (but non-argument) variables */\n      if (irep->nlocals-blk_pos-1 > 0) {\n        stack_clear(®s[blk_pos+1], irep->nlocals-blk_pos-1);\n      }\n      JUMP;\n    }\n\n    CASE(OP_KARG, BB) {\n      mrb_value k = mrb_symbol_value(syms[b]);\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict, v;\n\n      if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) {\n        mrb_value str = mrb_format(mrb, \"missing keyword: %v\", k);\n        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n        goto L_RAISE;\n      }\n      v = mrb_hash_get(mrb, kdict, k);\n      regs[a] = v;\n      mrb_hash_delete_key(mrb, kdict, k);\n      NEXT;\n    }\n\n    CASE(OP_KEY_P, BB) {\n      mrb_value k = mrb_symbol_value(syms[b]);\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict;\n      mrb_bool key_p = FALSE;\n\n      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) {\n        key_p = mrb_hash_key_p(mrb, kdict, k);\n      }\n      regs[a] = mrb_bool_value(key_p);\n      NEXT;\n    }\n\n    CASE(OP_KEYEND, Z) {\n      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n      mrb_value kdict;\n\n      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) {\n        mrb_value keys = mrb_hash_keys(mrb, kdict);\n        mrb_value key1 = RARRAY_PTR(keys)[0];\n        mrb_value str = mrb_format(mrb, \"unknown keyword: %v\", key1);\n        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n        goto L_RAISE;\n      }\n      NEXT;\n    }\n\n    CASE(OP_BREAK, B) {\n      c = OP_R_BREAK;\n      goto L_RETURN;\n    }\n    CASE(OP_RETURN_BLK, B) {\n      c = OP_R_RETURN;\n      goto L_RETURN;\n    }\n    CASE(OP_RETURN, B)\n    c = OP_R_NORMAL;\n    L_RETURN:\n    {\n      mrb_callinfo *ci;\n\n      ci = mrb->c->ci;\n      if (ci->mid) {\n        mrb_value blk = regs[mrb_ci_bidx(ci)];\n\n        if (mrb_proc_p(blk)) {\n          struct RProc *p = mrb_proc_ptr(blk);\n\n          if (!MRB_PROC_STRICT_P(p) &&\n              ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n            p->flags |= MRB_PROC_ORPHAN;\n          }\n        }\n      }\n\n      if (mrb->exc) {\n      L_RAISE:\n        ci = mrb->c->ci;\n        if (ci == mrb->c->cibase) {\n          ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n          if (ch == NULL) goto L_FTOP;\n          goto L_CATCH;\n        }\n        while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) {\n          ci = cipop(mrb);\n          if (ci[1].cci == CINFO_SKIP && prev_jmp) {\n            mrb->jmp = prev_jmp;\n            MRB_THROW(prev_jmp);\n          }\n          pc = ci[0].pc;\n          if (ci == mrb->c->cibase) {\n            ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n            if (ch == NULL) {\n            L_FTOP:             /* fiber top */\n              if (mrb->c == mrb->root_c) {\n                mrb->c->ci->stack = mrb->c->stbase;\n                goto L_STOP;\n              }\n              else {\n                struct mrb_context *c = mrb->c;\n\n                c->status = MRB_FIBER_TERMINATED;\n                mrb->c = c->prev;\n                c->prev = NULL;\n                goto L_RAISE;\n              }\n            }\n            break;\n          }\n        }\n      L_CATCH:\n        if (ch == NULL) goto L_STOP;\n        if (FALSE) {\n        L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */\n          ci = mrb->c->ci;\n        }\n        proc = ci->proc;\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n        mrb_stack_extend(mrb, irep->nregs);\n        pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target);\n      }\n      else {\n        mrb_int acc;\n        mrb_value v;\n\n        ci = mrb->c->ci;\n        v = regs[a];\n        mrb_gc_protect(mrb, v);\n        switch (c) {\n        case OP_R_RETURN:\n          /* Fall through to OP_R_NORMAL otherwise */\n          if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {\n            const struct RProc *dst;\n            mrb_callinfo *cibase;\n            cibase = mrb->c->cibase;\n            dst = top_proc(mrb, proc);\n\n            if (MRB_PROC_ENV_P(dst)) {\n              struct REnv *e = MRB_PROC_ENV(dst);\n\n              if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) {\n                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n                goto L_RAISE;\n              }\n            }\n            /* check jump destination */\n            while (cibase <= ci && ci->proc != dst) {\n              if (ci->cci > CINFO_NONE) { /* jump cross C boundary */\n                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n                goto L_RAISE;\n              }\n              ci--;\n            }\n            if (ci <= cibase) { /* no jump destination */\n              localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n              goto L_RAISE;\n            }\n            ci = mrb->c->ci;\n            while (cibase <= ci && ci->proc != dst) {\n              CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) {\n                cibase = mrb->c->cibase;\n                dst = top_proc(mrb, proc);\n              }\n              CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) {\n                UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v);\n              }\n              CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK);\n              ci = cipop(mrb);\n              pc = ci->pc;\n            }\n            proc = ci->proc;\n            mrb->exc = NULL; /* clear break object */\n            break;\n          }\n          /* fallthrough */\n        case OP_R_NORMAL:\n        NORMAL_RETURN:\n          if (ci == mrb->c->cibase) {\n            struct mrb_context *c;\n            c = mrb->c;\n\n            if (!c->prev) { /* toplevel return */\n              regs[irep->nlocals] = v;\n              goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP);\n            }\n            if (!c->vmexec && c->prev->ci == c->prev->cibase) {\n              mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, \"double resume\");\n              mrb_exc_set(mrb, exc);\n              goto L_RAISE;\n            }\n            CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) {\n              c = mrb->c;\n            }\n            CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) {\n              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v);\n            }\n            CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL);\n            /* automatic yield at the end */\n            c->status = MRB_FIBER_TERMINATED;\n            mrb->c = c->prev;\n            mrb->c->status = MRB_FIBER_RUNNING;\n            c->prev = NULL;\n            if (c->vmexec) {\n              mrb_gc_arena_restore(mrb, ai);\n              c->vmexec = FALSE;\n              mrb->jmp = prev_jmp;\n              return v;\n            }\n            ci = mrb->c->ci;\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_RETURN) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_RETURN);\n          mrb->exc = NULL; /* clear break object */\n          break;\n        case OP_R_BREAK:\n          if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;\n          if (MRB_PROC_ORPHAN_P(proc)) {\n            mrb_value exc;\n\n          L_BREAK_ERROR:\n            exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR,\n                                      \"break from proc-closure\");\n            mrb_exc_set(mrb, exc);\n            goto L_RAISE;\n          }\n          if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) {\n            goto L_BREAK_ERROR;\n          }\n          else {\n            struct REnv *e = MRB_PROC_ENV(proc);\n\n            if (e->cxt != mrb->c) {\n              goto L_BREAK_ERROR;\n            }\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_BREAK) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_BREAK);\n          /* break from fiber block */\n          if (ci == mrb->c->cibase && ci->pc) {\n            struct mrb_context *c = mrb->c;\n\n            mrb->c = c->prev;\n            c->prev = NULL;\n            ci = mrb->c->ci;\n          }\n          if (ci->cci > CINFO_NONE) {\n            ci = cipop(mrb);\n            mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v);\n            mrb_gc_arena_restore(mrb, ai);\n            mrb->c->vmexec = FALSE;\n            mrb->jmp = prev_jmp;\n            MRB_THROW(prev_jmp);\n          }\n          if (FALSE) {\n            struct RBreak *brk;\n\n          L_BREAK:\n            brk = (struct RBreak*)mrb->exc;\n            proc = mrb_break_proc_get(brk);\n            v = mrb_break_value_get(brk);\n            ci = mrb->c->ci;\n\n            switch (mrb_break_tag_get(brk)) {\n#define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n);\n              RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS)\n#undef DISPATCH_CHECKPOINTS\n              default:\n                mrb_assert(!\"wrong break tag\");\n            }\n          }\n          while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) {\n            if (ci[-1].cci == CINFO_SKIP) {\n              goto L_BREAK_ERROR;\n            }\n            CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) {\n              /* do nothing */\n            }\n            CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) {\n              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v);\n            }\n            CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER);\n            ci = cipop(mrb);\n            pc = ci->pc;\n          }\n          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) {\n            /* do nothing */\n          }\n          CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) {\n            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v);\n          }\n          CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET);\n          if (ci == mrb->c->cibase) {\n            goto L_BREAK_ERROR;\n          }\n          mrb->exc = NULL; /* clear break object */\n          break;\n        default:\n          /* cannot happen */\n          break;\n        }\n        mrb_assert(ci == mrb->c->ci);\n        mrb_assert(mrb->exc == NULL);\n\n        if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) {\n          mrb_gc_arena_restore(mrb, ai);\n          mrb->c->vmexec = FALSE;\n          mrb->jmp = prev_jmp;\n          return v;\n        }\n        acc = ci->cci;\n        ci = cipop(mrb);\n        if (acc == CINFO_SKIP || acc == CINFO_DIRECT) {\n          mrb_gc_arena_restore(mrb, ai);\n          mrb->jmp = prev_jmp;\n          return v;\n        }\n        pc = ci->pc;\n        DEBUG(fprintf(stderr, \"from :%s\\n\", mrb_sym_name(mrb, ci->mid)));\n        proc = ci->proc;\n        irep = proc->body.irep;\n        pool = irep->pool;\n        syms = irep->syms;\n\n        ci[1].stack[0] = v;\n        mrb_gc_arena_restore(mrb, ai);\n      }\n      JUMP;\n    }\n\n    CASE(OP_BLKPUSH, BS) {\n      int m1 = (b>>11)&0x3f;\n      int r  = (b>>10)&0x1;\n      int m2 = (b>>5)&0x1f;\n      int kd = (b>>4)&0x1;\n      int lv = (b>>0)&0xf;\n      mrb_value *stack;\n\n      if (lv == 0) stack = regs + 1;\n      else {\n        struct REnv *e = uvenv(mrb, lv-1);\n        if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) ||\n            MRB_ENV_LEN(e) <= m1+r+m2+1) {\n          localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n          goto L_RAISE;\n        }\n        stack = e->stack + 1;\n      }\n      if (mrb_nil_p(stack[m1+r+m2+kd])) {\n        localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n        goto L_RAISE;\n      }\n      regs[a] = stack[m1+r+m2+kd];\n      NEXT;\n    }\n\n  L_INT_OVERFLOW:\n    {\n      mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, \"integer overflow\");\n      mrb_exc_set(mrb, exc);\n    }\n    goto L_RAISE;\n\n#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))\n#define OP_MATH(op_name)                                                    \\\n  /* need to check if op is overridden */                                   \\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {                  \\\n    OP_MATH_CASE_INTEGER(op_name);                                          \\\n    OP_MATH_CASE_FLOAT(op_name, integer, float);                            \\\n    OP_MATH_CASE_FLOAT(op_name, float,  integer);                           \\\n    OP_MATH_CASE_FLOAT(op_name, float,  float);                             \\\n    OP_MATH_CASE_STRING_##op_name();                                        \\\n    default:                                                                \\\n      mid = MRB_OPSYM(op_name);                                             \\\n      goto L_SEND_SYM;                                                      \\\n  }                                                                         \\\n  NEXT;\n#define OP_MATH_CASE_INTEGER(op_name)                                       \\\n  case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER):                              \\\n    {                                                                       \\\n      mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z;      \\\n      if (mrb_int_##op_name##_overflow(x, y, &z))                           \\\n        OP_MATH_OVERFLOW_INT();                                             \\\n      else                                                                  \\\n        SET_INT_VALUE(mrb,regs[a], z);                                      \\\n    }                                                                       \\\n    break\n#ifdef MRB_NO_FLOAT\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0\n#else\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2)                                     \\\n  case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2):                                \\\n    {                                                                           \\\n      mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \\\n      SET_FLOAT_VALUE(mrb, regs[a], z);                                         \\\n    }                                                                           \\\n    break\n#endif\n#define OP_MATH_OVERFLOW_INT() goto L_INT_OVERFLOW\n#define OP_MATH_CASE_STRING_add()                                           \\\n  case TYPES2(MRB_TT_STRING, MRB_TT_STRING):                                \\\n    regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]);                        \\\n    mrb_gc_arena_restore(mrb, ai);                                          \\\n    break\n#define OP_MATH_CASE_STRING_sub() (void)0\n#define OP_MATH_CASE_STRING_mul() (void)0\n#define OP_MATH_OP_add +\n#define OP_MATH_OP_sub -\n#define OP_MATH_OP_mul *\n#define OP_MATH_TT_integer MRB_TT_INTEGER\n#define OP_MATH_TT_float   MRB_TT_FLOAT\n\n    CASE(OP_ADD, B) {\n      OP_MATH(add);\n    }\n\n    CASE(OP_SUB, B) {\n      OP_MATH(sub);\n    }\n\n    CASE(OP_MUL, B) {\n      OP_MATH(mul);\n    }\n\n    CASE(OP_DIV, B) {\n#ifndef MRB_NO_FLOAT\n      mrb_float x, y, f;\n#endif\n\n      /* need to check if op is overridden */\n      switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\n      case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\n        {\n          mrb_int x = mrb_integer(regs[a]);\n          mrb_int y = mrb_integer(regs[a+1]);\n          mrb_int div = mrb_div_int(mrb, x, y);\n          SET_INT_VALUE(mrb, regs[a], div);\n        }\n        NEXT;\n#ifndef MRB_NO_FLOAT\n      case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\n        x = (mrb_float)mrb_integer(regs[a]);\n        y = mrb_float(regs[a+1]);\n        break;\n      case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\n        x = mrb_float(regs[a]);\n        y = (mrb_float)mrb_integer(regs[a+1]);\n        break;\n      case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\n        x = mrb_float(regs[a]);\n        y = mrb_float(regs[a+1]);\n        break;\n#endif\n      default:\n        mid = MRB_OPSYM(div);\n        goto L_SEND_SYM;\n      }\n\n#ifndef MRB_NO_FLOAT\n      f = mrb_div_float(x, y);\n      SET_FLOAT_VALUE(mrb, regs[a], f);\n#endif\n      NEXT;\n    }\n\n#define OP_MATHI(op_name)                                                   \\\n  /* need to check if op is overridden */                                   \\\n  switch (mrb_type(regs[a])) {                                              \\\n    OP_MATHI_CASE_INTEGER(op_name);                                         \\\n    OP_MATHI_CASE_FLOAT(op_name);                                           \\\n    default:                                                                \\\n      SET_INT_VALUE(mrb,regs[a+1], b);                                      \\\n      mid = MRB_OPSYM(op_name);                                             \\\n      goto L_SEND_SYM;                                                      \\\n  }                                                                         \\\n  NEXT;\n#define OP_MATHI_CASE_INTEGER(op_name)                                      \\\n  case MRB_TT_INTEGER:                                                      \\\n    {                                                                       \\\n      mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z;                  \\\n      if (mrb_int_##op_name##_overflow(x, y, &z))                           \\\n        OP_MATH_OVERFLOW_INT();                                             \\\n      else                                                                  \\\n        SET_INT_VALUE(mrb,regs[a], z);                                      \\\n    }                                                                       \\\n    break\n#ifdef MRB_NO_FLOAT\n#define OP_MATHI_CASE_FLOAT(op_name) (void)0\n#else\n#define OP_MATHI_CASE_FLOAT(op_name)                                        \\\n  case MRB_TT_FLOAT:                                                        \\\n    {                                                                       \\\n      mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b;              \\\n      SET_FLOAT_VALUE(mrb, regs[a], z);                                     \\\n    }                                                                       \\\n    break\n#endif\n\n    CASE(OP_ADDI, BB) {\n      OP_MATHI(add);\n    }\n\n    CASE(OP_SUBI, BB) {\n      OP_MATHI(sub);\n    }\n\n#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))\n\n#ifdef MRB_NO_FLOAT\n#define OP_CMP(op,sym) do {\\\n  int result;\\\n  /* need to check if - is overridden */\\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n    break;\\\n  default:\\\n    mid = MRB_OPSYM(sym);\\\n    goto L_SEND_SYM;\\\n  }\\\n  if (result) {\\\n    SET_TRUE_VALUE(regs[a]);\\\n  }\\\n  else {\\\n    SET_FALSE_VALUE(regs[a]);\\\n  }\\\n} while(0)\n#else\n#define OP_CMP(op, sym) do {\\\n  int result;\\\n  /* need to check if - is overridden */\\\n  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n    break;\\\n  case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\\\n    result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\\\n    break;\\\n  case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\\\n    result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\\\n    break;\\\n  case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\\\n    result = OP_CMP_BODY(op,mrb_float,mrb_float);\\\n    break;\\\n  default:\\\n    mid = MRB_OPSYM(sym);\\\n    goto L_SEND_SYM;\\\n  }\\\n  if (result) {\\\n    SET_TRUE_VALUE(regs[a]);\\\n  }\\\n  else {\\\n    SET_FALSE_VALUE(regs[a]);\\\n  }\\\n} while(0)\n#endif\n\n    CASE(OP_EQ, B) {\n      if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {\n        SET_TRUE_VALUE(regs[a]);\n      }\n      else {\n        OP_CMP(==,eq);\n      }\n      NEXT;\n    }\n\n    CASE(OP_LT, B) {\n      OP_CMP(<,lt);\n      NEXT;\n    }\n\n    CASE(OP_LE, B) {\n      OP_CMP(<=,le);\n      NEXT;\n    }\n\n    CASE(OP_GT, B) {\n      OP_CMP(>,gt);\n      NEXT;\n    }\n\n    CASE(OP_GE, B) {\n      OP_CMP(>=,ge);\n      NEXT;\n    }\n\n    CASE(OP_ARRAY, BB) {\n      regs[a] = mrb_ary_new_from_values(mrb, b, ®s[a]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n    CASE(OP_ARRAY2, BBB) {\n      regs[a] = mrb_ary_new_from_values(mrb, c, ®s[b]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ARYCAT, B) {\n      mrb_value splat = mrb_ary_splat(mrb, regs[a+1]);\n      if (mrb_nil_p(regs[a])) {\n        regs[a] = splat;\n      }\n      else {\n        mrb_assert(mrb_array_p(regs[a]));\n        mrb_ary_concat(mrb, regs[a], splat);\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_ARYPUSH, BB) {\n      mrb_assert(mrb_array_p(regs[a]));\n      for (mrb_int i=0; i pre + post) {\n        v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);\n        regs[a++] = v;\n        while (post--) {\n          regs[a++] = ARY_PTR(ary)[len-post-1];\n        }\n      }\n      else {\n        v = mrb_ary_new_capa(mrb, 0);\n        regs[a++] = v;\n        for (idx=0; idx+pre> 2;\n      if (pool[b].tt & IREP_TT_SFLAG) {\n        sym = mrb_intern_static(mrb, pool[b].u.str, len);\n      }\n      else {\n        sym  = mrb_intern(mrb, pool[b].u.str, len);\n      }\n      regs[a] = mrb_symbol_value(sym);\n      NEXT;\n    }\n\n    CASE(OP_STRING, BB) {\n      mrb_int len;\n\n      mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0);\n      len = pool[b].tt >> 2;\n      if (pool[b].tt & IREP_TT_SFLAG) {\n        regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len);\n      }\n      else {\n        regs[a] = mrb_str_new(mrb, pool[b].u.str, len);\n      }\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_STRCAT, B) {\n      mrb_assert(mrb_string_p(regs[a]));\n      mrb_str_concat(mrb, regs[a], regs[a+1]);\n      NEXT;\n    }\n\n    CASE(OP_HASH, BB) {\n      mrb_value hash = mrb_hash_new_capa(mrb, b);\n      int i;\n      int lim = a+b*2;\n\n      for (i=a; ireps[b];\n\n      if (c & OP_L_CAPTURE) {\n        p = mrb_closure_new(mrb, nirep);\n      }\n      else {\n        p = mrb_proc_new(mrb, nirep);\n        p->flags |= MRB_PROC_SCOPE;\n      }\n      if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;\n      regs[a] = mrb_obj_value(p);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n    CASE(OP_BLOCK, BB) {\n      c = OP_L_BLOCK;\n      goto L_MAKE_LAMBDA;\n    }\n    CASE(OP_METHOD, BB) {\n      c = OP_L_METHOD;\n      goto L_MAKE_LAMBDA;\n    }\n\n    CASE(OP_RANGE_INC, B) {\n      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE);\n      regs[a] = v;\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_RANGE_EXC, B) {\n      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE);\n      regs[a] = v;\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_OCLASS, B) {\n      regs[a] = mrb_obj_value(mrb->object_class);\n      NEXT;\n    }\n\n    CASE(OP_CLASS, BB) {\n      struct RClass *c = 0, *baseclass;\n      mrb_value base, super;\n      mrb_sym id = syms[b];\n\n      base = regs[a];\n      super = regs[a+1];\n      if (mrb_nil_p(base)) {\n        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n        if (!baseclass) baseclass = mrb->object_class;\n        base = mrb_obj_value(baseclass);\n      }\n      c = mrb_vm_define_class(mrb, base, super, id);\n      regs[a] = mrb_obj_value(c);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_MODULE, BB) {\n      struct RClass *cls = 0, *baseclass;\n      mrb_value base;\n      mrb_sym id = syms[b];\n\n      base = regs[a];\n      if (mrb_nil_p(base)) {\n        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n        if (!baseclass) baseclass = mrb->object_class;\n        base = mrb_obj_value(baseclass);\n      }\n      cls = mrb_vm_define_module(mrb, base, id);\n      regs[a] = mrb_obj_value(cls);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_EXEC, BB)\n    {\n      mrb_value recv = regs[a];\n      struct RProc *p;\n      const mrb_irep *nirep = irep->reps[b];\n\n      /* prepare closure */\n      p = mrb_proc_new(mrb, nirep);\n      p->c = NULL;\n      mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);\n      MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));\n      p->flags |= MRB_PROC_SCOPE;\n\n      /* prepare call stack */\n      cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0);\n\n      irep = p->body.irep;\n      pool = irep->pool;\n      syms = irep->syms;\n      mrb_stack_extend(mrb, irep->nregs);\n      stack_clear(regs+1, irep->nregs-1);\n      pc = irep->iseq;\n      JUMP;\n    }\n\n    CASE(OP_DEF, BB) {\n      struct RClass *target = mrb_class_ptr(regs[a]);\n      struct RProc *p = mrb_proc_ptr(regs[a+1]);\n      mrb_method_t m;\n      mrb_sym mid = syms[b];\n\n      MRB_METHOD_FROM_PROC(m, p);\n      mrb_define_method_raw(mrb, target, mid, m);\n      mrb_method_added(mrb, target, mid);\n      mrb_gc_arena_restore(mrb, ai);\n      regs[a] = mrb_symbol_value(mid);\n      NEXT;\n    }\n\n    CASE(OP_SCLASS, B) {\n      regs[a] = mrb_singleton_class(mrb, regs[a]);\n      mrb_gc_arena_restore(mrb, ai);\n      NEXT;\n    }\n\n    CASE(OP_TCLASS, B) {\n      struct RClass *target = check_target_class(mrb);\n      if (!target) goto L_RAISE;\n      regs[a] = mrb_obj_value(target);\n      NEXT;\n    }\n\n    CASE(OP_ALIAS, BB) {\n      struct RClass *target = check_target_class(mrb);\n\n      if (!target) goto L_RAISE;\n      mrb_alias_method(mrb, target, syms[a], syms[b]);\n      mrb_method_added(mrb, target, syms[a]);\n      NEXT;\n    }\n    CASE(OP_UNDEF, B) {\n      struct RClass *target = check_target_class(mrb);\n\n      if (!target) goto L_RAISE;\n      mrb_undef_method_id(mrb, target, syms[a]);\n      NEXT;\n    }\n\n    CASE(OP_DEBUG, Z) {\n      FETCH_BBB();\n#ifdef MRB_USE_DEBUG_HOOK\n      mrb->debug_op_hook(mrb, irep, pc, regs);\n#else\n#ifndef MRB_NO_STDIO\n      printf(\"OP_DEBUG %d %d %d\\n\", a, b, c);\n#else\n      abort();\n#endif\n#endif\n      NEXT;\n    }\n\n    CASE(OP_ERR, B) {\n      size_t len = pool[a].tt >> 2;\n      mrb_value exc;\n\n      mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0);\n      exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len);\n      mrb_exc_set(mrb, exc);\n      goto L_RAISE;\n    }\n\n    CASE(OP_EXT1, Z) {\n      insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n    CASE(OP_EXT2, Z) {\n      insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n    CASE(OP_EXT3, Z) {\n      uint8_t insn = READ_B();\n      switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n      }\n      pc--;\n      NEXT;\n    }\n\n    CASE(OP_STOP, Z) {\n      /*        stop VM */\n      CHECKPOINT_RESTORE(RBREAK_TAG_STOP) {\n        /* do nothing */\n      }\n      CHECKPOINT_MAIN(RBREAK_TAG_STOP) {\n        UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value());\n      }\n      CHECKPOINT_END(RBREAK_TAG_STOP);\n    L_STOP:\n      mrb->jmp = prev_jmp;\n      if (mrb->exc) {\n        mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION);\n        return mrb_obj_value(mrb->exc);\n      }\n      return regs[irep->nlocals];\n    }\n  }\n  END_DISPATCH;\n#undef regs\n  }\n  MRB_CATCH(&c_jmp) {\n    mrb_callinfo *ci = mrb->c->ci;\n    while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) {\n      ci = cipop(mrb);\n    }\n    exc_catched = TRUE;\n    pc = ci->pc;\n    goto RETRY_TRY_BLOCK;\n  }\n  MRB_END_EXC(&c_jmp);\n}", "func_hash": 262390391813698997711941819907139112508, "file_name": "vm.c", "file_hash": 37245825949579697049526879083139270753, "cwe": ["CWE-288"], "cve": "CVE-2022-1212", "cve_desc": "Use-After-Free in str_escape in mruby/mruby in GitHub repository mruby/mruby prior to 3.2. Possible arbitrary code execution if being exploited.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1212"}
{"idx": 198449, "project": "pjproject", "commit_id": "450baca94f475345542c6953832650c390889202", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/450baca94f475345542c6953832650c390889202", "commit_message": "Merge pull request from GHSA-26j7-ww69-c4qj", "target": 1, "func": "PJ_DEF(pj_status_t) pjstun_parse_msg( void *buf, pj_size_t buf_len, \n\t\t\t\t      pjstun_msg *msg)\n{\n    pj_uint16_t msg_type, msg_len;\n    char *p_attr;\n\n    PJ_CHECK_STACK();\n\n    msg->hdr = (pjstun_msg_hdr*)buf;\n    msg_type = pj_ntohs(msg->hdr->type);\n\n    switch (msg_type) {\n    case PJSTUN_BINDING_REQUEST:\n    case PJSTUN_BINDING_RESPONSE:\n    case PJSTUN_BINDING_ERROR_RESPONSE:\n    case PJSTUN_SHARED_SECRET_REQUEST:\n    case PJSTUN_SHARED_SECRET_RESPONSE:\n    case PJSTUN_SHARED_SECRET_ERROR_RESPONSE:\n\tbreak;\n    default:\n\tPJ_LOG(4,(THIS_FILE, \"Error: unknown msg type %d\", msg_type));\n\treturn PJLIB_UTIL_ESTUNINMSGTYPE;\n    }\n\n    msg_len = pj_ntohs(msg->hdr->length);\n    if (msg_len != buf_len - sizeof(pjstun_msg_hdr)) {\n\tPJ_LOG(4,(THIS_FILE, \"Error: invalid msg_len %d (expecting %d)\", \n\t\t\t     msg_len, buf_len - sizeof(pjstun_msg_hdr)));\n\treturn PJLIB_UTIL_ESTUNINMSGLEN;\n    }\n\n    msg->attr_count = 0;\n    p_attr = (char*)buf + sizeof(pjstun_msg_hdr);\n\n    while (msg_len > 0) {\n\tpjstun_attr_hdr **attr = &msg->attr[msg->attr_count];\n\tpj_uint32_t len;\n\tpj_uint16_t attr_type;\n\n\t*attr = (pjstun_attr_hdr*)p_attr;\n\tlen = pj_ntohs((pj_uint16_t) ((*attr)->length)) + sizeof(pjstun_attr_hdr);\n\tlen = (len + 3) & ~3;\n\n\tif (msg_len < len) {\n\t    PJ_LOG(4,(THIS_FILE, \"Error: length mismatch in attr %d\", \n\t\t\t\t msg->attr_count));\n\t    return PJLIB_UTIL_ESTUNINATTRLEN;\n\t}\n\n\tattr_type = pj_ntohs((*attr)->type);\n\tif (attr_type > PJSTUN_ATTR_REFLECTED_FROM &&\n\t    attr_type != PJSTUN_ATTR_XOR_MAPPED_ADDR)\n\t{\n\t    PJ_LOG(5,(THIS_FILE, \"Warning: unknown attr type %x in attr %d. \"\n\t\t\t\t \"Attribute was ignored.\",\n\t\t\t\t attr_type, msg->attr_count));\n\t}\n\n\tmsg_len = (pj_uint16_t)(msg_len - len);\n\tp_attr += len;\n\t++msg->attr_count;\n    }\n\n    return PJ_SUCCESS;\n}", "func_hash": 324794898254091416853424941566787120064, "file_name": "stun_simple.c", "file_hash": 304268271857931505815837287097781884670, "cwe": ["CWE-787"], "cve": "CVE-2022-31031", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In versions prior to and including 2.12.1 a stack buffer overflow vulnerability affects PJSIP users that use STUN in their applications, either by: setting a STUN server in their account/media config in PJSUA/PJSUA2 level, or directly using `pjlib-util/stun_simple` API. A patch is available in commit 450baca which should be included in the next release. There are no known workarounds for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31031"}
{"idx": 274814, "project": "pjproject", "commit_id": "450baca94f475345542c6953832650c390889202", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/450baca94f475345542c6953832650c390889202", "commit_message": "Merge pull request from GHSA-26j7-ww69-c4qj", "target": 0, "func": "PJ_DEF(pj_status_t) pjstun_parse_msg( void *buf, pj_size_t buf_len, \n\t\t\t\t      pjstun_msg *msg)\n{\n    pj_uint16_t msg_type, msg_len;\n    char *p_attr;\n    int attr_max_cnt = PJ_ARRAY_SIZE(msg->attr);\n\n    PJ_CHECK_STACK();\n\n    msg->hdr = (pjstun_msg_hdr*)buf;\n    msg_type = pj_ntohs(msg->hdr->type);\n\n    switch (msg_type) {\n    case PJSTUN_BINDING_REQUEST:\n    case PJSTUN_BINDING_RESPONSE:\n    case PJSTUN_BINDING_ERROR_RESPONSE:\n    case PJSTUN_SHARED_SECRET_REQUEST:\n    case PJSTUN_SHARED_SECRET_RESPONSE:\n    case PJSTUN_SHARED_SECRET_ERROR_RESPONSE:\n\tbreak;\n    default:\n\tPJ_LOG(4,(THIS_FILE, \"Error: unknown msg type %d\", msg_type));\n\treturn PJLIB_UTIL_ESTUNINMSGTYPE;\n    }\n\n    msg_len = pj_ntohs(msg->hdr->length);\n    if (msg_len != buf_len - sizeof(pjstun_msg_hdr)) {\n\tPJ_LOG(4,(THIS_FILE, \"Error: invalid msg_len %d (expecting %d)\", \n\t\t\t     msg_len, buf_len - sizeof(pjstun_msg_hdr)));\n\treturn PJLIB_UTIL_ESTUNINMSGLEN;\n    }\n\n    msg->attr_count = 0;\n    p_attr = (char*)buf + sizeof(pjstun_msg_hdr);\n\n    while (msg_len > 0 && msg->attr_count < attr_max_cnt) {\n\tpjstun_attr_hdr **attr = &msg->attr[msg->attr_count];\n\tpj_uint32_t len;\n\tpj_uint16_t attr_type;\n\n\t*attr = (pjstun_attr_hdr*)p_attr;\n\tlen = pj_ntohs((pj_uint16_t) ((*attr)->length)) + sizeof(pjstun_attr_hdr);\n\tlen = (len + 3) & ~3;\n\n\tif (msg_len < len) {\n\t    PJ_LOG(4,(THIS_FILE, \"Error: length mismatch in attr %d\", \n\t\t\t\t msg->attr_count));\n\t    return PJLIB_UTIL_ESTUNINATTRLEN;\n\t}\n\n\tattr_type = pj_ntohs((*attr)->type);\n\tif (attr_type > PJSTUN_ATTR_REFLECTED_FROM &&\n\t    attr_type != PJSTUN_ATTR_XOR_MAPPED_ADDR)\n\t{\n\t    PJ_LOG(5,(THIS_FILE, \"Warning: unknown attr type %x in attr %d. \"\n\t\t\t\t \"Attribute was ignored.\",\n\t\t\t\t attr_type, msg->attr_count));\n\t}\n\n\tmsg_len = (pj_uint16_t)(msg_len - len);\n\tp_attr += len;\n\t++msg->attr_count;\n    }\n    if (msg->attr_count == attr_max_cnt) {\n\tPJ_LOG(4, (THIS_FILE, \"Warning: max number attribute %d reached.\",\n\t\t   attr_max_cnt));\n    }\n\n    return PJ_SUCCESS;\n}", "func_hash": 200469816079159611843255339356668630427, "file_name": "stun_simple.c", "file_hash": 232929880993033123827596664617421496425, "cwe": ["CWE-787"], "cve": "CVE-2022-31031", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In versions prior to and including 2.12.1 a stack buffer overflow vulnerability affects PJSIP users that use STUN in their applications, either by: setting a STUN server in their account/media config in PJSUA/PJSUA2 level, or directly using `pjlib-util/stun_simple` API. A patch is available in commit 450baca which should be included in the next release. There are no known workarounds for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31031"}
{"idx": 198452, "project": "tensorflow", "commit_id": "a989426ee1346693cc015792f11d715f6944f2b8", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a989426ee1346693cc015792f11d715f6944f2b8", "commit_message": "Improve to cover scale value greater than one\n\nPiperOrigin-RevId: 433050921", "target": 1, "func": "void ComparisonQuantized(const TfLiteTensor* input1, const TfLiteTensor* input2,\n                         TfLiteTensor* output, bool requires_broadcast) {\n  if (input1->type == kTfLiteUInt8 || input1->type == kTfLiteInt8) {\n    auto input1_offset = -input1->params.zero_point;\n    auto input2_offset = -input2->params.zero_point;\n    const int left_shift = 8;\n\n    int32 input1_multiplier;\n    int input1_shift;\n    QuantizeMultiplierSmallerThanOneExp(input1->params.scale,\n                                        &input1_multiplier, &input1_shift);\n    int32 input2_multiplier;\n    int input2_shift;\n    QuantizeMultiplierSmallerThanOneExp(input2->params.scale,\n                                        &input2_multiplier, &input2_shift);\n\n    ComparisonParams op_params;\n    op_params.left_shift = left_shift;\n    op_params.input1_offset = input1_offset;\n    op_params.input1_multiplier = input1_multiplier;\n    op_params.input1_shift = input1_shift;\n    op_params.input2_offset = input2_offset;\n    op_params.input2_multiplier = input2_multiplier;\n    op_params.input2_shift = input2_shift;\n    if (requires_broadcast) {\n      reference_ops::BroadcastComparison4DSlowWithScaling(\n          op_params, GetTensorShape(input1), GetTensorData(input1),\n          GetTensorShape(input2), GetTensorData(input2),\n          GetTensorShape(output), GetTensorData(output));\n    } else {\n      reference_ops::ComparisonWithScaling(\n          op_params, GetTensorShape(input1), GetTensorData(input1),\n          GetTensorShape(input2), GetTensorData(input2),\n          GetTensorShape(output), GetTensorData(output));\n    }\n  }\n}", "func_hash": 284336502909303651692457957640037138117, "file_name": "comparisons.cc", "file_hash": 224870261654956140630544765652331160875, "cwe": ["CWE-703"], "cve": "CVE-2022-29212", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, certain TFLite models that were created using TFLite model converter would crash when loaded in the TFLite interpreter. The culprit is that during quantization the scale of values could be greater than 1 but code was always assuming sub-unit scaling. Thus, since code was calling `QuantizeMultiplierSmallerThanOneExp`, the `TFLITE_CHECK_LT` assertion would trigger and abort the process. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29212"}
{"idx": 274865, "project": "tensorflow", "commit_id": "a989426ee1346693cc015792f11d715f6944f2b8", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/a989426ee1346693cc015792f11d715f6944f2b8", "commit_message": "Improve to cover scale value greater than one\n\nPiperOrigin-RevId: 433050921", "target": 0, "func": "void ComparisonQuantized(const TfLiteTensor* input1, const TfLiteTensor* input2,\n                         TfLiteTensor* output, bool requires_broadcast) {\n  if (input1->type == kTfLiteUInt8 || input1->type == kTfLiteInt8) {\n    auto input1_offset = -input1->params.zero_point;\n    auto input2_offset = -input2->params.zero_point;\n    const int left_shift = 8;\n\n    int32 input1_multiplier;\n    int32 input2_multiplier;\n    int input1_shift;\n    int input2_shift;\n    QuantizeMultiplier(input1->params.scale, &input1_multiplier, &input1_shift);\n    QuantizeMultiplier(input2->params.scale, &input2_multiplier, &input2_shift);\n\n    ComparisonParams op_params;\n    op_params.left_shift = left_shift;\n    op_params.input1_offset = input1_offset;\n    op_params.input1_multiplier = input1_multiplier;\n    op_params.input1_shift = input1_shift;\n    op_params.input2_offset = input2_offset;\n    op_params.input2_multiplier = input2_multiplier;\n    op_params.input2_shift = input2_shift;\n    if (requires_broadcast) {\n      reference_ops::BroadcastComparison4DSlowWithScaling(\n          op_params, GetTensorShape(input1), GetTensorData(input1),\n          GetTensorShape(input2), GetTensorData(input2),\n          GetTensorShape(output), GetTensorData(output));\n    } else {\n      reference_ops::ComparisonWithScaling(\n          op_params, GetTensorShape(input1), GetTensorData(input1),\n          GetTensorShape(input2), GetTensorData(input2),\n          GetTensorShape(output), GetTensorData(output));\n    }\n  }\n}", "func_hash": 213386004946249159247710639352470904167, "file_name": "comparisons.cc", "file_hash": 191046017812634874260331571010514719419, "cwe": ["CWE-703"], "cve": "CVE-2022-29212", "cve_desc": "TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, certain TFLite models that were created using TFLite model converter would crash when loaded in the TFLite interpreter. The culprit is that during quantization the scale of values could be greater than 1 but code was always assuming sub-unit scaling. Thus, since code was calling `QuantizeMultiplierSmallerThanOneExp`, the `TFLITE_CHECK_LT` assertion would trigger and abort the process. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29212"}
{"idx": 198476, "project": "njs", "commit_id": "6a07c2156a07ef307b6dcf3c2ca8571a5f1af7a6", "project_url": "https://github.com/nginx/njs", "commit_url": "https://github.com/nginx/njs/commit/6a07c2156a07ef307b6dcf3c2ca8571a5f1af7a6", "commit_message": "Fixed recursive async function calls.\n\nPreviously, PromiseCapability record was stored (function->context)\ndirectly in function object during a function invocation.  This is\nnot correct, because PromiseCapability record should be linked to\ncurrent execution context.  As a result, function->context is\noverwritten with consecutive recursive calls which results in\nuse-after-free.\n\nThis closes #451 issue on Github.", "target": 1, "func": "njs_await_fulfilled(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,\n    njs_index_t unused)\n{\n    njs_int_t           ret;\n    njs_value_t         **cur_local, **cur_closures, **cur_temp, *value;\n    njs_frame_t         *frame, *async_frame;\n    njs_function_t      *function;\n    njs_async_ctx_t     *ctx;\n    njs_native_frame_t  *top, *async;\n\n    ctx = vm->top_frame->function->context;\n\n    value = njs_arg(args, nargs, 1);\n    if (njs_is_error(value)) {\n        goto failed;\n    }\n\n    async_frame = ctx->await;\n    async = &async_frame->native;\n    async->previous = vm->top_frame;\n\n    function = async->function;\n\n    cur_local = vm->levels[NJS_LEVEL_LOCAL];\n    cur_closures = vm->levels[NJS_LEVEL_CLOSURE];\n    cur_temp = vm->levels[NJS_LEVEL_TEMP];\n    top = vm->top_frame;\n    frame = vm->active_frame;\n\n    vm->levels[NJS_LEVEL_LOCAL] = async->local;\n    vm->levels[NJS_LEVEL_CLOSURE] = njs_function_closures(async->function);\n    vm->levels[NJS_LEVEL_TEMP] = async->temp;\n\n    vm->top_frame = async;\n    vm->active_frame = async_frame;\n\n    *njs_scope_value(vm, ctx->index) = *value;\n    vm->retval = *value;\n\n    vm->top_frame->retval = &vm->retval;\n\n    function->context = ctx->capability;\n    function->await = ctx;\n\n    ret = njs_vmcode_interpreter(vm, ctx->pc);\n\n    function->context = NULL;\n    function->await = NULL;\n\n    vm->levels[NJS_LEVEL_LOCAL] = cur_local;\n    vm->levels[NJS_LEVEL_CLOSURE] = cur_closures;\n    vm->levels[NJS_LEVEL_TEMP] = cur_temp;\n\n    vm->top_frame = top;\n    vm->active_frame = frame;\n\n    if (ret == NJS_OK) {\n        ret = njs_function_call(vm, njs_function(&ctx->capability->resolve),\n                            &njs_value_undefined, &vm->retval, 1, &vm->retval);\n\n        njs_async_context_free(vm, ctx);\n\n    } else if (ret == NJS_AGAIN) {\n        ret = NJS_OK;\n\n    } else if (ret == NJS_ERROR) {\n        if (njs_is_memory_error(vm, &vm->retval)) {\n            return NJS_ERROR;\n        }\n\n        value = &vm->retval;\n\n        goto failed;\n    }\n\n    return ret;\n\nfailed:\n\n    (void) njs_function_call(vm, njs_function(&ctx->capability->reject),\n                             &njs_value_undefined, value, 1, &vm->retval);\n\n    njs_async_context_free(vm, ctx);\n\n    return NJS_ERROR;\n}", "func_hash": 241518720909355358001984532864321433833, "file_name": "njs_async.c", "file_hash": 139542101989914499952242434630508544825, "cwe": ["CWE-416"], "cve": "CVE-2022-25139", "cve_desc": "njs through 0.7.0, used in NGINX, was discovered to contain a heap use-after-free in njs_await_fulfilled.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-25139"}
{"idx": 275525, "project": "njs", "commit_id": "6a07c2156a07ef307b6dcf3c2ca8571a5f1af7a6", "project_url": "https://github.com/nginx/njs", "commit_url": "https://github.com/nginx/njs/commit/6a07c2156a07ef307b6dcf3c2ca8571a5f1af7a6", "commit_message": "Fixed recursive async function calls.\n\nPreviously, PromiseCapability record was stored (function->context)\ndirectly in function object during a function invocation.  This is\nnot correct, because PromiseCapability record should be linked to\ncurrent execution context.  As a result, function->context is\noverwritten with consecutive recursive calls which results in\nuse-after-free.\n\nThis closes #451 issue on Github.", "target": 0, "func": "njs_await_fulfilled(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,\n    njs_index_t unused)\n{\n    njs_int_t           ret;\n    njs_value_t         **cur_local, **cur_closures, **cur_temp, *value;\n    njs_frame_t         *frame, *async_frame;\n    njs_async_ctx_t     *ctx;\n    njs_native_frame_t  *top, *async;\n\n    ctx = vm->top_frame->function->context;\n\n    value = njs_arg(args, nargs, 1);\n    if (njs_is_error(value)) {\n        goto failed;\n    }\n\n    async_frame = ctx->await;\n    async = &async_frame->native;\n    async->previous = vm->top_frame;\n\n    cur_local = vm->levels[NJS_LEVEL_LOCAL];\n    cur_closures = vm->levels[NJS_LEVEL_CLOSURE];\n    cur_temp = vm->levels[NJS_LEVEL_TEMP];\n    top = vm->top_frame;\n    frame = vm->active_frame;\n\n    vm->levels[NJS_LEVEL_LOCAL] = async->local;\n    vm->levels[NJS_LEVEL_CLOSURE] = njs_function_closures(async->function);\n    vm->levels[NJS_LEVEL_TEMP] = async->temp;\n\n    vm->top_frame = async;\n    vm->active_frame = async_frame;\n\n    *njs_scope_value(vm, ctx->index) = *value;\n    vm->retval = *value;\n\n    vm->top_frame->retval = &vm->retval;\n\n    ret = njs_vmcode_interpreter(vm, ctx->pc, ctx->capability, ctx);\n\n    vm->levels[NJS_LEVEL_LOCAL] = cur_local;\n    vm->levels[NJS_LEVEL_CLOSURE] = cur_closures;\n    vm->levels[NJS_LEVEL_TEMP] = cur_temp;\n\n    vm->top_frame = top;\n    vm->active_frame = frame;\n\n    if (ret == NJS_OK) {\n        ret = njs_function_call(vm, njs_function(&ctx->capability->resolve),\n                            &njs_value_undefined, &vm->retval, 1, &vm->retval);\n\n        njs_async_context_free(vm, ctx);\n\n    } else if (ret == NJS_AGAIN) {\n        ret = NJS_OK;\n\n    } else if (ret == NJS_ERROR) {\n        if (njs_is_memory_error(vm, &vm->retval)) {\n            return NJS_ERROR;\n        }\n\n        value = &vm->retval;\n\n        goto failed;\n    }\n\n    return ret;\n\nfailed:\n\n    (void) njs_function_call(vm, njs_function(&ctx->capability->reject),\n                             &njs_value_undefined, value, 1, &vm->retval);\n\n    njs_async_context_free(vm, ctx);\n\n    return NJS_ERROR;\n}", "func_hash": 111576454892773184522255566086081823579, "file_name": "njs_async.c", "file_hash": 224952791495383164899496869298957477614, "cwe": ["CWE-416"], "cve": "CVE-2022-25139", "cve_desc": "njs through 0.7.0, used in NGINX, was discovered to contain a heap use-after-free in njs_await_fulfilled.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-25139"}
{"idx": 198499, "project": "micro-ecc", "commit_id": "1b5f5cea5145c96dd8791b9b2c41424fc74c2172", "project_url": "https://github.com/kmackay/micro-ecc", "commit_url": "https://github.com/kmackay/micro-ecc/commit/1b5f5cea5145c96dd8791b9b2c41424fc74c2172", "commit_message": "Fix for #168", "target": 1, "func": "static int uECC_sign_with_k(const uint8_t *private_key,\n                            const uint8_t *message_hash,\n                            unsigned hash_size,\n                            uECC_word_t *k,\n                            uint8_t *signature,\n                            uECC_Curve curve) {\n\n    uECC_word_t tmp[uECC_MAX_WORDS];\n    uECC_word_t s[uECC_MAX_WORDS];\n    uECC_word_t *k2[2] = {tmp, s};\n#if uECC_VLI_NATIVE_LITTLE_ENDIAN\n    uECC_word_t *p = (uECC_word_t *)signature;\n#else\n    uECC_word_t p[uECC_MAX_WORDS * 2];\n#endif\n    uECC_word_t carry;\n    wordcount_t num_words = curve->num_words;\n    wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);\n    bitcount_t num_n_bits = curve->num_n_bits;\n\n    /* Make sure 0 < k < curve_n */\n    if (uECC_vli_isZero(k, num_words) || uECC_vli_cmp(curve->n, k, num_n_words) != 1) {\n        return 0;\n    }\n\n    carry = regularize_k(k, tmp, s, curve);\n    EccPoint_mult(p, curve->G, k2[!carry], 0, num_n_bits + 1, curve);\n    if (uECC_vli_isZero(p, num_words)) {\n        return 0;\n    }\n\n    /* If an RNG function was specified, get a random number\n       to prevent side channel analysis of k. */\n    if (!g_rng_function) {\n        uECC_vli_clear(tmp, num_n_words);\n        tmp[0] = 1;\n    } else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) {\n        return 0;\n    }\n\n    /* Prevent side channel analysis of uECC_vli_modInv() to determine\n       bits of k / the private key by premultiplying by a random number */\n    uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */\n    uECC_vli_modInv(k, k, curve->n, num_n_words);       /* k = 1 / k' */\n    uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */\n\n#if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0\n    uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */\n#endif\n\n#if uECC_VLI_NATIVE_LITTLE_ENDIAN\n    bcopy((uint8_t *) tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));\n#else\n    uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits)); /* tmp = d */\n#endif\n\n    s[num_n_words - 1] = 0;\n    uECC_vli_set(s, p, num_words);\n    uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */\n\n    bits2int(tmp, message_hash, hash_size, curve);\n    uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */\n    uECC_vli_modMult(s, s, k, curve->n, num_n_words);  /* s = (e + r*d) / k */\n    if (uECC_vli_numBits(s, num_n_words) > (bitcount_t)curve->num_bytes * 8) {\n        return 0;\n    }\n#if uECC_VLI_NATIVE_LITTLE_ENDIAN\n    bcopy((uint8_t *) signature + curve->num_bytes, (uint8_t *) s, curve->num_bytes);\n#else\n    uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);\n#endif    \n    return 1;\n}", "func_hash": 250707445511654521220716932779019293116, "file_name": "uECC.c", "file_hash": 221730154760089899908262595980065132519, "cwe": ["CWE-415"], "cve": "CVE-2020-27209", "cve_desc": "The ECDSA operation of the micro-ecc library 1.0 is vulnerable to simple power analysis attacks which allows an adversary to extract the private ECC key.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27209"}
{"idx": 275987, "project": "micro-ecc", "commit_id": "1b5f5cea5145c96dd8791b9b2c41424fc74c2172", "project_url": "https://github.com/kmackay/micro-ecc", "commit_url": "https://github.com/kmackay/micro-ecc/commit/1b5f5cea5145c96dd8791b9b2c41424fc74c2172", "commit_message": "Fix for #168", "target": 0, "func": "static int uECC_sign_with_k(const uint8_t *private_key,\n                            const uint8_t *message_hash,\n                            unsigned hash_size,\n                            uECC_word_t *k,\n                            uint8_t *signature,\n                            uECC_Curve curve) {\n\n    uECC_word_t tmp[uECC_MAX_WORDS];\n    uECC_word_t s[uECC_MAX_WORDS];\n    uECC_word_t *k2[2] = {tmp, s};\n    uECC_word_t *initial_Z = 0;\n#if uECC_VLI_NATIVE_LITTLE_ENDIAN\n    uECC_word_t *p = (uECC_word_t *)signature;\n#else\n    uECC_word_t p[uECC_MAX_WORDS * 2];\n#endif\n    uECC_word_t carry;\n    wordcount_t num_words = curve->num_words;\n    wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);\n    bitcount_t num_n_bits = curve->num_n_bits;\n\n    /* Make sure 0 < k < curve_n */\n    if (uECC_vli_isZero(k, num_words) || uECC_vli_cmp(curve->n, k, num_n_words) != 1) {\n        return 0;\n    }\n\n    carry = regularize_k(k, tmp, s, curve);\n    /* If an RNG function was specified, try to get a random initial Z value to improve\n       protection against side-channel attacks. */\n    if (g_rng_function) {\n        if (!uECC_generate_random_int(k2[carry], curve->p, num_words)) {\n            return 0;\n        }\n        initial_Z = k2[carry];\n    }\n    EccPoint_mult(p, curve->G, k2[!carry], initial_Z, num_n_bits + 1, curve);\n    if (uECC_vli_isZero(p, num_words)) {\n        return 0;\n    }\n\n    /* If an RNG function was specified, get a random number\n       to prevent side channel analysis of k. */\n    if (!g_rng_function) {\n        uECC_vli_clear(tmp, num_n_words);\n        tmp[0] = 1;\n    } else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) {\n        return 0;\n    }\n\n    /* Prevent side channel analysis of uECC_vli_modInv() to determine\n       bits of k / the private key by premultiplying by a random number */\n    uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */\n    uECC_vli_modInv(k, k, curve->n, num_n_words);       /* k = 1 / k' */\n    uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */\n\n#if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0\n    uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */\n#endif\n\n#if uECC_VLI_NATIVE_LITTLE_ENDIAN\n    bcopy((uint8_t *) tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));\n#else\n    uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits)); /* tmp = d */\n#endif\n\n    s[num_n_words - 1] = 0;\n    uECC_vli_set(s, p, num_words);\n    uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */\n\n    bits2int(tmp, message_hash, hash_size, curve);\n    uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */\n    uECC_vli_modMult(s, s, k, curve->n, num_n_words);  /* s = (e + r*d) / k */\n    if (uECC_vli_numBits(s, num_n_words) > (bitcount_t)curve->num_bytes * 8) {\n        return 0;\n    }\n#if uECC_VLI_NATIVE_LITTLE_ENDIAN\n    bcopy((uint8_t *) signature + curve->num_bytes, (uint8_t *) s, curve->num_bytes);\n#else\n    uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);\n#endif\n    return 1;\n}", "func_hash": 118273926663441096280456772911326940472, "file_name": "uECC.c", "file_hash": 232283246719977371910544173978221438887, "cwe": ["CWE-415"], "cve": "CVE-2020-27209", "cve_desc": "The ECDSA operation of the micro-ecc library 1.0 is vulnerable to simple power analysis attacks which allows an adversary to extract the private ECC key.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27209"}
{"idx": 198523, "project": "tensorflow", "commit_id": "5ecec9c6fbdbc6be03295685190a45e7eee726ab", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/5ecec9c6fbdbc6be03295685190a45e7eee726ab", "commit_message": "Prevent use after free.\n\nA very old version of the code used `result` as a simple pointer to a resource. Two years later, the pointer got changed to a `unique_ptr` but author forgot to remove the call to `Unref`. Three years after that, we finally uncover the UAF.\n\nPiperOrigin-RevId: 387924872\nChange-Id: I70fb6f199164de49fac20c168132a07b84903f9b", "target": 1, "func": "  void Compute(OpKernelContext* context) override {\n    // Get the stamp token.\n    const Tensor* stamp_token_t;\n    OP_REQUIRES_OK(context, context->input(\"stamp_token\", &stamp_token_t));\n    int64_t stamp_token = stamp_token_t->scalar()();\n\n    // Get the tree ensemble proto.\n    const Tensor* tree_ensemble_serialized_t;\n    OP_REQUIRES_OK(context, context->input(\"tree_ensemble_serialized\",\n                                           &tree_ensemble_serialized_t));\n    std::unique_ptr result(\n        new BoostedTreesEnsembleResource());\n    if (!result->InitFromSerialized(\n            tree_ensemble_serialized_t->scalar()(), stamp_token)) {\n      result->Unref();\n      OP_REQUIRES(\n          context, false,\n          errors::InvalidArgument(\"Unable to parse tree ensemble proto.\"));\n    }\n\n    // Only create one, if one does not exist already. Report status for all\n    // other exceptions.\n    auto status =\n        CreateResource(context, HandleFromInput(context, 0), result.release());\n    if (status.code() != tensorflow::error::ALREADY_EXISTS) {\n      OP_REQUIRES_OK(context, status);\n    }\n  }", "func_hash": 151034027968901870222536100864741418474, "file_name": "resource_ops.cc", "file_hash": 40939400980967911969144269399937980796, "cwe": ["CWE-416"], "cve": "CVE-2021-37652", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation for `tf.raw_ops.BoostedTreesCreateEnsemble` can result in a use after free error if an attacker supplies specially crafted arguments. The [implementation](https://github.com/tensorflow/tensorflow/blob/f24faa153ad31a4b51578f8181d3aaab77a1ddeb/tensorflow/core/kernels/boosted_trees/resource_ops.cc#L55) uses a reference counted resource and decrements the refcount if the initialization fails, as it should. However, when the code was written, the resource was represented as a naked pointer but later refactoring has changed it to be a smart pointer. Thus, when the pointer leaves the scope, a subsequent `free`-ing of the resource occurs, but this fails to take into account that the refcount has already reached 0, thus the resource has been already freed. During this double-free process, members of the resource object are accessed for cleanup but they are invalid as the entire resource has been freed. We have patched the issue in GitHub commit 5ecec9c6fbdbc6be03295685190a45e7eee726ab. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37652"}
{"idx": 276447, "project": "tensorflow", "commit_id": "5ecec9c6fbdbc6be03295685190a45e7eee726ab", "project_url": "https://github.com/tensorflow/tensorflow", "commit_url": "https://github.com/tensorflow/tensorflow/commit/5ecec9c6fbdbc6be03295685190a45e7eee726ab", "commit_message": "Prevent use after free.\n\nA very old version of the code used `result` as a simple pointer to a resource. Two years later, the pointer got changed to a `unique_ptr` but author forgot to remove the call to `Unref`. Three years after that, we finally uncover the UAF.\n\nPiperOrigin-RevId: 387924872\nChange-Id: I70fb6f199164de49fac20c168132a07b84903f9b", "target": 0, "func": "  void Compute(OpKernelContext* context) override {\n    // Get the stamp token.\n    const Tensor* stamp_token_t;\n    OP_REQUIRES_OK(context, context->input(\"stamp_token\", &stamp_token_t));\n    int64_t stamp_token = stamp_token_t->scalar()();\n\n    // Get the tree ensemble proto.\n    const Tensor* tree_ensemble_serialized_t;\n    OP_REQUIRES_OK(context, context->input(\"tree_ensemble_serialized\",\n                                           &tree_ensemble_serialized_t));\n    std::unique_ptr result(\n        new BoostedTreesEnsembleResource());\n    if (!result->InitFromSerialized(\n            tree_ensemble_serialized_t->scalar()(), stamp_token)) {\n      result->Unref();\n      result.release();  // Needed due to the `->Unref` above, to prevent UAF\n      OP_REQUIRES(\n          context, false,\n          errors::InvalidArgument(\"Unable to parse tree ensemble proto.\"));\n    }\n\n    // Only create one, if one does not exist already. Report status for all\n    // other exceptions.\n    auto status =\n        CreateResource(context, HandleFromInput(context, 0), result.release());\n    if (status.code() != tensorflow::error::ALREADY_EXISTS) {\n      OP_REQUIRES_OK(context, status);\n    }\n  }", "func_hash": 115602178708451028825719002696661348197, "file_name": "resource_ops.cc", "file_hash": 61383399308207725848810164035477638721, "cwe": ["CWE-416"], "cve": "CVE-2021-37652", "cve_desc": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation for `tf.raw_ops.BoostedTreesCreateEnsemble` can result in a use after free error if an attacker supplies specially crafted arguments. The [implementation](https://github.com/tensorflow/tensorflow/blob/f24faa153ad31a4b51578f8181d3aaab77a1ddeb/tensorflow/core/kernels/boosted_trees/resource_ops.cc#L55) uses a reference counted resource and decrements the refcount if the initialization fails, as it should. However, when the code was written, the resource was represented as a naked pointer but later refactoring has changed it to be a smart pointer. Thus, when the pointer leaves the scope, a subsequent `free`-ing of the resource occurs, but this fails to take into account that the refcount has already reached 0, thus the resource has been already freed. During this double-free process, members of the resource object are accessed for cleanup but they are invalid as the entire resource has been freed. We have patched the issue in GitHub commit 5ecec9c6fbdbc6be03295685190a45e7eee726ab. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37652"}
{"idx": 198545, "project": "u-boot", "commit_id": "8f8c04bf1ebbd2f72f1643e7ad9617dafa6e5409", "project_url": "https://github.com/u-boot/u-boot", "commit_url": "https://github.com/u-boot/u-boot/commit/8f8c04bf1ebbd2f72f1643e7ad9617dafa6e5409", "commit_message": "i2c: fix stack buffer overflow vulnerability in i2c md command\n\nWhen running \"i2c md 0 0 80000100\", the function do_i2c_md parses the\nlength into an unsigned int variable named length. The value is then\nmoved to a signed variable:\n\n    int nbytes = length;\n    #define DISP_LINE_LEN 16\n    int linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes;\n    ret = dm_i2c_read(dev, addr, linebuf, linebytes);\n\nOn systems where integers are 32 bits wide, 0x80000100 is a negative\nvalue to \"nbytes > DISP_LINE_LEN\" is false and linebytes gets assigned\n0x80000100 instead of 16.\n\nThe consequence is that the function which reads from the i2c device\n(dm_i2c_read or i2c_read) is called with a 16-byte stack buffer to fill\nbut with a size parameter which is too large. In some cases, this could\ntrigger a crash. But with some i2c drivers, such as drivers/i2c/nx_i2c.c\n(used with \"nexell,s5pxx18-i2c\" bus), the size is actually truncated to\na 16-bit integer. This is because function i2c_transfer expects an\nunsigned short length. In such a case, an attacker who can control the\nresponse of an i2c device can overwrite the return address of a function\nand execute arbitrary code through Return-Oriented Programming.\n\nFix this issue by using unsigned integers types in do_i2c_md. While at\nit, make also alen unsigned, as signed sizes can cause vulnerabilities\nwhen people forgot to check that they can be negative.\n\nSigned-off-by: Nicolas Iooss \nReviewed-by: Heiko Schocher ", "target": 1, "func": "static int do_i2c_md(struct cmd_tbl *cmdtp, int flag, int argc,\n\t\t     char *const argv[])\n{\n\tuint\tchip;\n\tuint\taddr, length;\n\tint alen;\n\tint\tj, nbytes, linebytes;\n\tint ret;\n#if CONFIG_IS_ENABLED(DM_I2C)\n\tstruct udevice *dev;\n#endif\n\n\t/* We use the last specified parameters, unless new ones are\n\t * entered.\n\t */\n\tchip   = i2c_dp_last_chip;\n\taddr   = i2c_dp_last_addr;\n\talen   = i2c_dp_last_alen;\n\tlength = i2c_dp_last_length;\n\n\tif (argc < 3)\n\t\treturn CMD_RET_USAGE;\n\n\tif ((flag & CMD_FLAG_REPEAT) == 0) {\n\t\t/*\n\t\t * New command specified.\n\t\t */\n\n\t\t/*\n\t\t * I2C chip address\n\t\t */\n\t\tchip = hextoul(argv[1], NULL);\n\n\t\t/*\n\t\t * I2C data address within the chip.  This can be 1 or\n\t\t * 2 bytes long.  Some day it might be 3 bytes long :-).\n\t\t */\n\t\taddr = hextoul(argv[2], NULL);\n\t\talen = get_alen(argv[2], DEFAULT_ADDR_LEN);\n\t\tif (alen > 3)\n\t\t\treturn CMD_RET_USAGE;\n\n\t\t/*\n\t\t * If another parameter, it is the length to display.\n\t\t * Length is the number of objects, not number of bytes.\n\t\t */\n\t\tif (argc > 3)\n\t\t\tlength = hextoul(argv[3], NULL);\n\t}\n\n#if CONFIG_IS_ENABLED(DM_I2C)\n\tret = i2c_get_cur_bus_chip(chip, &dev);\n\tif (!ret && alen != -1)\n\t\tret = i2c_set_chip_offset_len(dev, alen);\n\tif (ret)\n\t\treturn i2c_report_err(ret, I2C_ERR_READ);\n#endif\n\n\t/*\n\t * Print the lines.\n\t *\n\t * We buffer all read data, so we can make sure data is read only\n\t * once.\n\t */\n\tnbytes = length;\n\tdo {\n\t\tunsigned char\tlinebuf[DISP_LINE_LEN];\n\t\tunsigned char\t*cp;\n\n\t\tlinebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes;\n\n#if CONFIG_IS_ENABLED(DM_I2C)\n\t\tret = dm_i2c_read(dev, addr, linebuf, linebytes);\n#else\n\t\tret = i2c_read(chip, addr, alen, linebuf, linebytes);\n#endif\n\t\tif (ret)\n\t\t\treturn i2c_report_err(ret, I2C_ERR_READ);\n\t\telse {\n\t\t\tprintf(\"%04x:\", addr);\n\t\t\tcp = linebuf;\n\t\t\tfor (j=0; j 0x7e))\n\t\t\t\t\tputs (\".\");\n\t\t\t\telse\n\t\t\t\t\tprintf(\"%c\", *cp);\n\t\t\t\tcp++;\n\t\t\t}\n\t\t\tputc ('\\n');\n\t\t}\n\t\tnbytes -= linebytes;\n\t} while (nbytes > 0);\n\n\ti2c_dp_last_chip   = chip;\n\ti2c_dp_last_addr   = addr;\n\ti2c_dp_last_alen   = alen;\n\ti2c_dp_last_length = length;\n\n\treturn 0;\n}", "func_hash": 336388644236353594568664801027238457577, "file_name": "i2c.c", "file_hash": 135764079202241918781821738561519186738, "cwe": ["CWE-787"], "cve": "CVE-2022-34835", "cve_desc": "In Das U-Boot through 2022.07-rc5, an integer signedness error and resultant stack-based buffer overflow in the \"i2c md\" command enables the corruption of the return address pointer of the do_i2c_md function.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-34835"}
{"idx": 276921, "project": "u-boot", "commit_id": "8f8c04bf1ebbd2f72f1643e7ad9617dafa6e5409", "project_url": "https://github.com/u-boot/u-boot", "commit_url": "https://github.com/u-boot/u-boot/commit/8f8c04bf1ebbd2f72f1643e7ad9617dafa6e5409", "commit_message": "i2c: fix stack buffer overflow vulnerability in i2c md command\n\nWhen running \"i2c md 0 0 80000100\", the function do_i2c_md parses the\nlength into an unsigned int variable named length. The value is then\nmoved to a signed variable:\n\n    int nbytes = length;\n    #define DISP_LINE_LEN 16\n    int linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes;\n    ret = dm_i2c_read(dev, addr, linebuf, linebytes);\n\nOn systems where integers are 32 bits wide, 0x80000100 is a negative\nvalue to \"nbytes > DISP_LINE_LEN\" is false and linebytes gets assigned\n0x80000100 instead of 16.\n\nThe consequence is that the function which reads from the i2c device\n(dm_i2c_read or i2c_read) is called with a 16-byte stack buffer to fill\nbut with a size parameter which is too large. In some cases, this could\ntrigger a crash. But with some i2c drivers, such as drivers/i2c/nx_i2c.c\n(used with \"nexell,s5pxx18-i2c\" bus), the size is actually truncated to\na 16-bit integer. This is because function i2c_transfer expects an\nunsigned short length. In such a case, an attacker who can control the\nresponse of an i2c device can overwrite the return address of a function\nand execute arbitrary code through Return-Oriented Programming.\n\nFix this issue by using unsigned integers types in do_i2c_md. While at\nit, make also alen unsigned, as signed sizes can cause vulnerabilities\nwhen people forgot to check that they can be negative.\n\nSigned-off-by: Nicolas Iooss \nReviewed-by: Heiko Schocher ", "target": 0, "func": "static int do_i2c_md(struct cmd_tbl *cmdtp, int flag, int argc,\n\t\t     char *const argv[])\n{\n\tuint\tchip;\n\tuint\taddr, length;\n\tuint\talen;\n\tuint\tj, nbytes, linebytes;\n\tint ret;\n#if CONFIG_IS_ENABLED(DM_I2C)\n\tstruct udevice *dev;\n#endif\n\n\t/* We use the last specified parameters, unless new ones are\n\t * entered.\n\t */\n\tchip   = i2c_dp_last_chip;\n\taddr   = i2c_dp_last_addr;\n\talen   = i2c_dp_last_alen;\n\tlength = i2c_dp_last_length;\n\n\tif (argc < 3)\n\t\treturn CMD_RET_USAGE;\n\n\tif ((flag & CMD_FLAG_REPEAT) == 0) {\n\t\t/*\n\t\t * New command specified.\n\t\t */\n\n\t\t/*\n\t\t * I2C chip address\n\t\t */\n\t\tchip = hextoul(argv[1], NULL);\n\n\t\t/*\n\t\t * I2C data address within the chip.  This can be 1 or\n\t\t * 2 bytes long.  Some day it might be 3 bytes long :-).\n\t\t */\n\t\taddr = hextoul(argv[2], NULL);\n\t\talen = get_alen(argv[2], DEFAULT_ADDR_LEN);\n\t\tif (alen > 3)\n\t\t\treturn CMD_RET_USAGE;\n\n\t\t/*\n\t\t * If another parameter, it is the length to display.\n\t\t * Length is the number of objects, not number of bytes.\n\t\t */\n\t\tif (argc > 3)\n\t\t\tlength = hextoul(argv[3], NULL);\n\t}\n\n#if CONFIG_IS_ENABLED(DM_I2C)\n\tret = i2c_get_cur_bus_chip(chip, &dev);\n\tif (!ret && alen != -1)\n\t\tret = i2c_set_chip_offset_len(dev, alen);\n\tif (ret)\n\t\treturn i2c_report_err(ret, I2C_ERR_READ);\n#endif\n\n\t/*\n\t * Print the lines.\n\t *\n\t * We buffer all read data, so we can make sure data is read only\n\t * once.\n\t */\n\tnbytes = length;\n\tdo {\n\t\tunsigned char\tlinebuf[DISP_LINE_LEN];\n\t\tunsigned char\t*cp;\n\n\t\tlinebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes;\n\n#if CONFIG_IS_ENABLED(DM_I2C)\n\t\tret = dm_i2c_read(dev, addr, linebuf, linebytes);\n#else\n\t\tret = i2c_read(chip, addr, alen, linebuf, linebytes);\n#endif\n\t\tif (ret)\n\t\t\treturn i2c_report_err(ret, I2C_ERR_READ);\n\t\telse {\n\t\t\tprintf(\"%04x:\", addr);\n\t\t\tcp = linebuf;\n\t\t\tfor (j=0; j 0x7e))\n\t\t\t\t\tputs (\".\");\n\t\t\t\telse\n\t\t\t\t\tprintf(\"%c\", *cp);\n\t\t\t\tcp++;\n\t\t\t}\n\t\t\tputc ('\\n');\n\t\t}\n\t\tnbytes -= linebytes;\n\t} while (nbytes > 0);\n\n\ti2c_dp_last_chip   = chip;\n\ti2c_dp_last_addr   = addr;\n\ti2c_dp_last_alen   = alen;\n\ti2c_dp_last_length = length;\n\n\treturn 0;\n}", "func_hash": 4295672649069929583389307772574603935, "file_name": "i2c.c", "file_hash": 148650655652553671361921673670735435868, "cwe": ["CWE-787"], "cve": "CVE-2022-34835", "cve_desc": "In Das U-Boot through 2022.07-rc5, an integer signedness error and resultant stack-based buffer overflow in the \"i2c md\" command enables the corruption of the return address pointer of the do_i2c_md function.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-34835"}
{"idx": 198556, "project": "mruby", "commit_id": "da48e7dbb20024c198493b8724adae1b842083aa", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/da48e7dbb20024c198493b8724adae1b842083aa", "commit_message": "fiber.c: should pack 15+ arguments in an array.", "target": 1, "func": "fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec)\n{\n  struct mrb_context *c = fiber_check(mrb, self);\n  struct mrb_context *old_c = mrb->c;\n  enum mrb_fiber_state status;\n  mrb_value value;\n\n  fiber_check_cfunc(mrb, c);\n  status = c->status;\n  switch (status) {\n  case MRB_FIBER_TRANSFERRED:\n    if (resume) {\n      mrb_raise(mrb, E_FIBER_ERROR, \"resuming transferred fiber\");\n    }\n    break;\n  case MRB_FIBER_RUNNING:\n  case MRB_FIBER_RESUMED:\n    mrb_raise(mrb, E_FIBER_ERROR, \"double resume\");\n    break;\n  case MRB_FIBER_TERMINATED:\n    mrb_raise(mrb, E_FIBER_ERROR, \"resuming dead fiber\");\n    break;\n  default:\n    break;\n  }\n  old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;\n  c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);\n  fiber_switch_context(mrb, c);\n  if (status == MRB_FIBER_CREATED) {\n    mrb_value *b, *e;\n\n    if (!c->ci->proc) {\n      mrb_raise(mrb, E_FIBER_ERROR, \"double resume (current)\");\n    }\n    mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */\n    b = c->stbase+1;\n    e = b + len;\n    while (bci--;                    /* pop dummy callinfo */\n    }\n    c->cibase->n = len;\n    value = c->stbase[0] = MRB_PROC_ENV(c->cibase->proc)->stack[0];\n  }\n  else {\n    value = fiber_result(mrb, a, len);\n    if (vmexec) {\n      c->ci[1].stack[0] = value;\n    }\n  }\n\n  if (vmexec) {\n    c->vmexec = TRUE;\n    value = mrb_vm_exec(mrb, c->ci->proc, c->ci->pc);\n    mrb->c = old_c;\n  }\n  else {\n    MARK_CONTEXT_MODIFY(c);\n  }\n  return value;\n}", "func_hash": 47008074931842386485122959067604053158, "file_name": "fiber.c", "file_hash": 246157146670999327331490014943475085458, "cwe": ["CWE-703"], "cve": "CVE-2022-0890", "cve_desc": "NULL Pointer Dereference in GitHub repository mruby/mruby prior to 3.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0890"}
{"idx": 276993, "project": "mruby", "commit_id": "da48e7dbb20024c198493b8724adae1b842083aa", "project_url": "https://github.com/mruby/mruby", "commit_url": "https://github.com/mruby/mruby/commit/da48e7dbb20024c198493b8724adae1b842083aa", "commit_message": "fiber.c: should pack 15+ arguments in an array.", "target": 0, "func": "fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec)\n{\n  struct mrb_context *c = fiber_check(mrb, self);\n  struct mrb_context *old_c = mrb->c;\n  enum mrb_fiber_state status;\n  mrb_value value;\n\n  fiber_check_cfunc(mrb, c);\n  status = c->status;\n  switch (status) {\n  case MRB_FIBER_TRANSFERRED:\n    if (resume) {\n      mrb_raise(mrb, E_FIBER_ERROR, \"resuming transferred fiber\");\n    }\n    break;\n  case MRB_FIBER_RUNNING:\n  case MRB_FIBER_RESUMED:\n    mrb_raise(mrb, E_FIBER_ERROR, \"double resume\");\n    break;\n  case MRB_FIBER_TERMINATED:\n    mrb_raise(mrb, E_FIBER_ERROR, \"resuming dead fiber\");\n    break;\n  default:\n    break;\n  }\n  old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;\n  c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);\n  fiber_switch_context(mrb, c);\n  if (status == MRB_FIBER_CREATED) {\n    mrb_value *b, *e;\n\n    if (!c->ci->proc) {\n      mrb_raise(mrb, E_FIBER_ERROR, \"double resume (current)\");\n    }\n    if (vmexec) {\n      c->ci--;                    /* pop dummy callinfo */\n    }\n    if (len >= 15) {\n      mrb_stack_extend(mrb, 3);   /* for receiver, args and (optional) block */\n      c->stbase[1] = mrb_ary_new_from_values(mrb, len, a);\n      len = 15;\n    }\n    else {\n      mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */\n      b = c->stbase+1;\n      e = b + len;\n      while (bcibase->n = len;\n    value = c->stbase[0] = MRB_PROC_ENV(c->cibase->proc)->stack[0];\n  }\n  else {\n    value = fiber_result(mrb, a, len);\n    if (vmexec) {\n      c->ci[1].stack[0] = value;\n    }\n  }\n\n  if (vmexec) {\n    c->vmexec = TRUE;\n    value = mrb_vm_exec(mrb, c->ci->proc, c->ci->pc);\n    mrb->c = old_c;\n  }\n  else {\n    MARK_CONTEXT_MODIFY(c);\n  }\n  return value;\n}", "func_hash": 103355671348819190033706386778999083640, "file_name": "fiber.c", "file_hash": 198318116371258140758763628769197309767, "cwe": ["CWE-703"], "cve": "CVE-2022-0890", "cve_desc": "NULL Pointer Dereference in GitHub repository mruby/mruby prior to 3.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0890"}
{"idx": 198566, "project": "libmobi", "commit_id": "eafc415bc6067e72577f70d6dd5acbf057ce6e6f", "project_url": "https://github.com/bfabiszewski/libmobi", "commit_url": "https://github.com/bfabiszewski/libmobi/commit/eafc415bc6067e72577f70d6dd5acbf057ce6e6f", "commit_message": "Fix wrong boundary checks in inflections parser resulting in stack buffer over-read with corrupt input", "target": 1, "func": "MOBI_RET mobi_decode_infl(unsigned char *decoded, int *decoded_size, const unsigned char *rule) {\n    int pos = *decoded_size;\n    char mod = 'i';\n    char dir = '<';\n    char olddir;\n    unsigned char c;\n    while ((c = *rule++)) {\n        if (c <= 4) {\n            mod = (c <= 2) ? 'i' : 'd'; /* insert, delete */\n            olddir = dir;\n            dir = (c & 2) ? '<' : '>'; /* left, right */\n            if (olddir != dir && olddir) {\n                pos = (c & 2) ? *decoded_size : 0;\n            }\n        }\n        else if (c > 10 && c < 20) {\n            if (dir == '>') {\n                pos = *decoded_size;\n            }\n            pos -= c - 10;\n            dir = 0;\n            if (pos < 0 || pos > *decoded_size) {\n                debug_print(\"Position setting failed (%s)\\n\", decoded);\n                return MOBI_DATA_CORRUPT;\n            }\n        }\n        else {\n            if (mod == 'i') {\n                const unsigned char *s = decoded + pos;\n                unsigned char *d = decoded + pos + 1;\n                const int l = *decoded_size - pos;\n                if (l < 0 || d + l > decoded + INDX_INFLBUF_SIZEMAX) {\n                    debug_print(\"Out of buffer in %s at pos: %i\\n\", decoded, pos);\n                    return MOBI_DATA_CORRUPT;\n                }\n                memmove(d, s, (size_t) l);\n                decoded[pos] = c;\n                (*decoded_size)++;\n                if (dir == '>') { pos++; }\n            } else {\n                if (dir == '<') { pos--; }\n                const unsigned char *s = decoded + pos + 1;\n                unsigned char *d = decoded + pos;\n                const int l = *decoded_size - pos;\n                if (l < 0 || d + l > decoded + INDX_INFLBUF_SIZEMAX) {\n                    debug_print(\"Out of buffer in %s at pos: %i\\n\", decoded, pos);\n                    return MOBI_DATA_CORRUPT;\n                }\n                if (decoded[pos] != c) {\n                    debug_print(\"Character mismatch in %s at pos: %i (%c != %c)\\n\", decoded, pos, decoded[pos], c);\n                    return MOBI_DATA_CORRUPT;\n                }\n                memmove(d, s, (size_t) l);\n                (*decoded_size)--;\n            }\n        }\n    }\n    return MOBI_SUCCESS;\n}", "func_hash": 38529228609046084805262566640890540140, "file_name": "index.c", "file_hash": 309095437889005741044332361577356993393, "cwe": ["CWE-787"], "cve": "CVE-2022-1533", "cve_desc": "Buffer Over-read in GitHub repository bfabiszewski/libmobi prior to 0.11. This vulnerability is capable of arbitrary code execution.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1533"}
{"idx": 277489, "project": "libmobi", "commit_id": "eafc415bc6067e72577f70d6dd5acbf057ce6e6f", "project_url": "https://github.com/bfabiszewski/libmobi", "commit_url": "https://github.com/bfabiszewski/libmobi/commit/eafc415bc6067e72577f70d6dd5acbf057ce6e6f", "commit_message": "Fix wrong boundary checks in inflections parser resulting in stack buffer over-read with corrupt input", "target": 0, "func": "MOBI_RET mobi_decode_infl(unsigned char *decoded, int *decoded_size, const unsigned char *rule) {\n    int pos = *decoded_size;\n    char mod = 'i';\n    char dir = '<';\n    char olddir;\n    unsigned char c;\n    while ((c = *rule++)) {\n        if (c <= 4) {\n            mod = (c <= 2) ? 'i' : 'd'; /* insert, delete */\n            olddir = dir;\n            dir = (c & 2) ? '<' : '>'; /* left, right */\n            if (olddir != dir && olddir) {\n                pos = (c & 2) ? *decoded_size : 0;\n            }\n        }\n        else if (c > 10 && c < 20) {\n            if (dir == '>') {\n                pos = *decoded_size;\n            }\n            pos -= c - 10;\n            dir = 0;\n        }\n        else {\n            if (mod == 'i') {\n                const unsigned char *s = decoded + pos;\n                unsigned char *d = decoded + pos + 1;\n                const int l = *decoded_size - pos;\n                if (pos < 0 || l < 0 || d + l > decoded + INDX_INFLBUF_SIZEMAX) {\n                    debug_print(\"Out of buffer in %s at pos: %i\\n\", decoded, pos);\n                    return MOBI_DATA_CORRUPT;\n                }\n                memmove(d, s, (size_t) l);\n                decoded[pos] = c;\n                (*decoded_size)++;\n                if (dir == '>') { pos++; }\n            } else {\n                if (dir == '<') { pos--; }\n                const unsigned char *s = decoded + pos + 1;\n                unsigned char *d = decoded + pos;\n                const int l = *decoded_size - pos;\n                if (pos < 0 || l < 0 || s + l > decoded + INDX_INFLBUF_SIZEMAX) {\n                    debug_print(\"Out of buffer in %s at pos: %i\\n\", decoded, pos);\n                    return MOBI_DATA_CORRUPT;\n                }\n                if (decoded[pos] != c) {\n                    debug_print(\"Character mismatch in %s at pos: %i (%c != %c)\\n\", decoded, pos, decoded[pos], c);\n                    return MOBI_DATA_CORRUPT;\n                }\n                memmove(d, s, (size_t) l);\n                (*decoded_size)--;\n            }\n        }\n    }\n    return MOBI_SUCCESS;\n}", "func_hash": 110952141184880818056037191705831585689, "file_name": "index.c", "file_hash": 108195340824579059268746364836110051712, "cwe": ["CWE-787"], "cve": "CVE-2022-1533", "cve_desc": "Buffer Over-read in GitHub repository bfabiszewski/libmobi prior to 0.11. This vulnerability is capable of arbitrary code execution.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1533"}
{"idx": 198662, "project": "vim", "commit_id": "dc5490e2cbc8c16022a23b449b48c1bd0083f366", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/dc5490e2cbc8c16022a23b449b48c1bd0083f366", "commit_message": "patch 8.2.4215: illegal memory access when copying lines in Visual mode\n\nProblem:    Illegal memory access when copying lines in Visual mode.\nSolution:   Adjust the Visual position after copying lines.", "target": 1, "func": "ex_copy(linenr_T line1, linenr_T line2, linenr_T n)\n{\n    linenr_T\tcount;\n    char_u\t*p;\n\n    count = line2 - line1 + 1;\n    if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)\n    {\n\tcurbuf->b_op_start.lnum = n + 1;\n\tcurbuf->b_op_end.lnum = n + count;\n\tcurbuf->b_op_start.col = curbuf->b_op_end.col = 0;\n    }\n\n    /*\n     * there are three situations:\n     * 1. destination is above line1\n     * 2. destination is between line1 and line2\n     * 3. destination is below line2\n     *\n     * n = destination (when starting)\n     * curwin->w_cursor.lnum = destination (while copying)\n     * line1 = start of source (while copying)\n     * line2 = end of source (while copying)\n     */\n    if (u_save(n, n + 1) == FAIL)\n\treturn;\n\n    curwin->w_cursor.lnum = n;\n    while (line1 <= line2)\n    {\n\t// need to use vim_strsave() because the line will be unlocked within\n\t// ml_append()\n\tp = vim_strsave(ml_get(line1));\n\tif (p != NULL)\n\t{\n\t    ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, FALSE);\n\t    vim_free(p);\n\t}\n\t// situation 2: skip already copied lines\n\tif (line1 == n)\n\t    line1 = curwin->w_cursor.lnum;\n\t++line1;\n\tif (curwin->w_cursor.lnum < line1)\n\t    ++line1;\n\tif (curwin->w_cursor.lnum < line2)\n\t    ++line2;\n\t++curwin->w_cursor.lnum;\n    }\n\n    appended_lines_mark(n, count);\n\n    msgmore((long)count);\n}", "func_hash": 97186272074546929960699343746519426256, "file_name": "ex_cmds.c", "file_hash": 233687213068218474878856624724146444666, "cwe": ["CWE-787"], "cve": "CVE-2022-0361", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0361"}
{"idx": 279948, "project": "vim", "commit_id": "dc5490e2cbc8c16022a23b449b48c1bd0083f366", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/dc5490e2cbc8c16022a23b449b48c1bd0083f366", "commit_message": "patch 8.2.4215: illegal memory access when copying lines in Visual mode\n\nProblem:    Illegal memory access when copying lines in Visual mode.\nSolution:   Adjust the Visual position after copying lines.", "target": 0, "func": "ex_copy(linenr_T line1, linenr_T line2, linenr_T n)\n{\n    linenr_T\tcount;\n    char_u\t*p;\n\n    count = line2 - line1 + 1;\n    if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)\n    {\n\tcurbuf->b_op_start.lnum = n + 1;\n\tcurbuf->b_op_end.lnum = n + count;\n\tcurbuf->b_op_start.col = curbuf->b_op_end.col = 0;\n    }\n\n    /*\n     * there are three situations:\n     * 1. destination is above line1\n     * 2. destination is between line1 and line2\n     * 3. destination is below line2\n     *\n     * n = destination (when starting)\n     * curwin->w_cursor.lnum = destination (while copying)\n     * line1 = start of source (while copying)\n     * line2 = end of source (while copying)\n     */\n    if (u_save(n, n + 1) == FAIL)\n\treturn;\n\n    curwin->w_cursor.lnum = n;\n    while (line1 <= line2)\n    {\n\t// need to use vim_strsave() because the line will be unlocked within\n\t// ml_append()\n\tp = vim_strsave(ml_get(line1));\n\tif (p != NULL)\n\t{\n\t    ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, FALSE);\n\t    vim_free(p);\n\t}\n\t// situation 2: skip already copied lines\n\tif (line1 == n)\n\t    line1 = curwin->w_cursor.lnum;\n\t++line1;\n\tif (curwin->w_cursor.lnum < line1)\n\t    ++line1;\n\tif (curwin->w_cursor.lnum < line2)\n\t    ++line2;\n\t++curwin->w_cursor.lnum;\n    }\n\n    appended_lines_mark(n, count);\n    if (VIsual_active)\n\tcheck_pos(curbuf, &VIsual);\n\n    msgmore((long)count);\n}", "func_hash": 145586714597549785258872355387518968620, "file_name": "ex_cmds.c", "file_hash": 316790051330868655972553819181856040285, "cwe": ["CWE-787"], "cve": "CVE-2022-0361", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0361"}
{"idx": 198692, "project": "ipsec", "commit_id": "7bab09631c2a303f87a7eb7e3d69e888673b9b7e", "project_url": "https://git.kernel.org/pub/scm/linux/kernel/git/klassert/ipsec", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/klassert/ipsec.git/commit/?id=7bab09631c2a303f87a7eb7e3d69e888673b9b7e", "commit_message": "xfrm: policy: check policy direction value\n\nThe 'dir' parameter in xfrm_migrate() is a user-controlled byte which is used\nas an array index. This can lead to an out-of-bound access, kernel lockup and\nDoS. Add a check for the 'dir' value.\n\nThis fixes CVE-2017-11600.\n\nReferences: https://bugzilla.redhat.com/show_bug.cgi?id=1474928\nFixes: 80c9abaabf42 (\"[XFRM]: Extension for dynamic update of endpoint address(es)\")\nCc:  # v2.6.21-rc1\nReported-by: \"bo Zhang\" \nSigned-off-by: Vladis Dronov \nSigned-off-by: Steffen Klassert ", "target": 1, "func": "int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,\n\t\t struct xfrm_migrate *m, int num_migrate,\n\t\t struct xfrm_kmaddress *k, struct net *net,\n\t\t struct xfrm_encap_tmpl *encap)\n{\n\tint i, err, nx_cur = 0, nx_new = 0;\n\tstruct xfrm_policy *pol = NULL;\n\tstruct xfrm_state *x, *xc;\n\tstruct xfrm_state *x_cur[XFRM_MAX_DEPTH];\n\tstruct xfrm_state *x_new[XFRM_MAX_DEPTH];\n\tstruct xfrm_migrate *mp;\n\n\tif ((err = xfrm_migrate_check(m, num_migrate)) < 0)\n\t\tgoto out;\n\n\t/* Stage 1 - find policy */\n\tif ((pol = xfrm_migrate_policy_find(sel, dir, type, net)) == NULL) {\n\t\terr = -ENOENT;\n\t\tgoto out;\n\t}\n\n\t/* Stage 2 - find and update state(s) */\n\tfor (i = 0, mp = m; i < num_migrate; i++, mp++) {\n\t\tif ((x = xfrm_migrate_state_find(mp, net))) {\n\t\t\tx_cur[nx_cur] = x;\n\t\t\tnx_cur++;\n\t\t\txc = xfrm_state_migrate(x, mp, encap);\n\t\t\tif (xc) {\n\t\t\t\tx_new[nx_new] = xc;\n\t\t\t\tnx_new++;\n\t\t\t} else {\n\t\t\t\terr = -ENODATA;\n\t\t\t\tgoto restore_state;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Stage 3 - update policy */\n\tif ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)\n\t\tgoto restore_state;\n\n\t/* Stage 4 - delete old state(s) */\n\tif (nx_cur) {\n\t\txfrm_states_put(x_cur, nx_cur);\n\t\txfrm_states_delete(x_cur, nx_cur);\n\t}\n\n\t/* Stage 5 - announce */\n\tkm_migrate(sel, dir, type, m, num_migrate, k, encap);\n\n\txfrm_pol_put(pol);\n\n\treturn 0;\nout:\n\treturn err;\n\nrestore_state:\n\tif (pol)\n\t\txfrm_pol_put(pol);\n\tif (nx_cur)\n\t\txfrm_states_put(x_cur, nx_cur);\n\tif (nx_new)\n\t\txfrm_states_delete(x_new, nx_new);\n\n\treturn err;\n}", "func_hash": 263415810499121443569228863944466057298, "file_name": "xfrm_policy.c", "file_hash": 279839085612343169676292983391622616816, "cwe": ["CWE-125"], "cve": "CVE-2017-11600", "cve_desc": "net/xfrm/xfrm_policy.c in the Linux kernel through 4.12.3, when CONFIG_XFRM_MIGRATE is enabled, does not ensure that the dir value of xfrm_userpolicy_id is XFRM_POLICY_MAX or less, which allows local users to cause a denial of service (out-of-bounds access) or possibly have unspecified other impact via an XFRM_MSG_MIGRATE xfrm Netlink message.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-11600"}
{"idx": 281119, "project": "ipsec", "commit_id": "7bab09631c2a303f87a7eb7e3d69e888673b9b7e", "project_url": "https://git.kernel.org/pub/scm/linux/kernel/git/klassert/ipsec", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/klassert/ipsec.git/commit/?id=7bab09631c2a303f87a7eb7e3d69e888673b9b7e", "commit_message": "xfrm: policy: check policy direction value\n\nThe 'dir' parameter in xfrm_migrate() is a user-controlled byte which is used\nas an array index. This can lead to an out-of-bound access, kernel lockup and\nDoS. Add a check for the 'dir' value.\n\nThis fixes CVE-2017-11600.\n\nReferences: https://bugzilla.redhat.com/show_bug.cgi?id=1474928\nFixes: 80c9abaabf42 (\"[XFRM]: Extension for dynamic update of endpoint address(es)\")\nCc:  # v2.6.21-rc1\nReported-by: \"bo Zhang\" \nSigned-off-by: Vladis Dronov \nSigned-off-by: Steffen Klassert ", "target": 0, "func": "int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,\n\t\t struct xfrm_migrate *m, int num_migrate,\n\t\t struct xfrm_kmaddress *k, struct net *net,\n\t\t struct xfrm_encap_tmpl *encap)\n{\n\tint i, err, nx_cur = 0, nx_new = 0;\n\tstruct xfrm_policy *pol = NULL;\n\tstruct xfrm_state *x, *xc;\n\tstruct xfrm_state *x_cur[XFRM_MAX_DEPTH];\n\tstruct xfrm_state *x_new[XFRM_MAX_DEPTH];\n\tstruct xfrm_migrate *mp;\n\n\t/* Stage 0 - sanity checks */\n\tif ((err = xfrm_migrate_check(m, num_migrate)) < 0)\n\t\tgoto out;\n\n\tif (dir >= XFRM_POLICY_MAX) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\t/* Stage 1 - find policy */\n\tif ((pol = xfrm_migrate_policy_find(sel, dir, type, net)) == NULL) {\n\t\terr = -ENOENT;\n\t\tgoto out;\n\t}\n\n\t/* Stage 2 - find and update state(s) */\n\tfor (i = 0, mp = m; i < num_migrate; i++, mp++) {\n\t\tif ((x = xfrm_migrate_state_find(mp, net))) {\n\t\t\tx_cur[nx_cur] = x;\n\t\t\tnx_cur++;\n\t\t\txc = xfrm_state_migrate(x, mp, encap);\n\t\t\tif (xc) {\n\t\t\t\tx_new[nx_new] = xc;\n\t\t\t\tnx_new++;\n\t\t\t} else {\n\t\t\t\terr = -ENODATA;\n\t\t\t\tgoto restore_state;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Stage 3 - update policy */\n\tif ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)\n\t\tgoto restore_state;\n\n\t/* Stage 4 - delete old state(s) */\n\tif (nx_cur) {\n\t\txfrm_states_put(x_cur, nx_cur);\n\t\txfrm_states_delete(x_cur, nx_cur);\n\t}\n\n\t/* Stage 5 - announce */\n\tkm_migrate(sel, dir, type, m, num_migrate, k, encap);\n\n\txfrm_pol_put(pol);\n\n\treturn 0;\nout:\n\treturn err;\n\nrestore_state:\n\tif (pol)\n\t\txfrm_pol_put(pol);\n\tif (nx_cur)\n\t\txfrm_states_put(x_cur, nx_cur);\n\tif (nx_new)\n\t\txfrm_states_delete(x_new, nx_new);\n\n\treturn err;\n}", "func_hash": 215751416433603359127168568868479758173, "file_name": "xfrm_policy.c", "file_hash": 14403382265138763697521162606727348451, "cwe": ["CWE-125"], "cve": "CVE-2017-11600", "cve_desc": "net/xfrm/xfrm_policy.c in the Linux kernel through 4.12.3, when CONFIG_XFRM_MIGRATE is enabled, does not ensure that the dir value of xfrm_userpolicy_id is XFRM_POLICY_MAX or less, which allows local users to cause a denial of service (out-of-bounds access) or possibly have unspecified other impact via an XFRM_MSG_MIGRATE xfrm Netlink message.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-11600"}
{"idx": 198695, "project": "MilkyTracker", "commit_id": "fd607a3439fcdd0992e5efded3c16fc79c804e34", "project_url": "https://github.com/milkytracker/MilkyTracker", "commit_url": "https://github.com/milkytracker/MilkyTracker/commit/fd607a3439fcdd0992e5efded3c16fc79c804e34", "commit_message": "Fix #184: Heap overflow in S3M loader", "target": 1, "func": "mp_sint32 LoaderS3M::load(XMFileBase& f, XModule* module)\n{\t\n\tmodule->cleanUp();\n\n\t// this will make code much easier to read\n\tTXMHeader*\t\theader = &module->header;\n\tTXMInstrument*\tinstr  = module->instr;\n\tTXMSample*\t\tsmp\t   = module->smp;\n\tTXMPattern*\t\tphead  = module->phead;\t\n\n\t// we're already out of memory here\n\tif (!phead || !instr || !smp)\n\t\treturn MP_OUT_OF_MEMORY;\n\t\n\tf.read(&header->name,1,28);\n\theader->whythis1a = f.readByte();\n\t\n\tif (f.readByte() != 16) \n\t\treturn MP_LOADER_FAILED;\t// no ST3 module\n\t\n\tf.readByte(); // skip something\n\tf.readByte(); // skip something\n\t\n\theader->ordnum = f.readWord(); // number of positions in order list (songlength)\n\t\n\tmp_ubyte* orders = new mp_ubyte[header->ordnum];\n\tif (orders == NULL) \n\t\treturn MP_OUT_OF_MEMORY;\n\t\n\theader->insnum = f.readWord(); // number of instruments\n\theader->patnum = f.readWord(); // number of patterns\t\n\t\n\tmp_sint32 flags = f.readWord(); // st3 flags\t\n\n\tmp_sint32 Cvt = f.readWord();\n\n\theader->flags = XModule::MODULE_ST3NEWINSTRUMENT | XModule::MODULE_ST3DUALCOMMANDS;\n\n\tif (Cvt == 0x1300 || (flags & 64))\n\t\theader->flags |= module->MODULE_OLDS3MVOLSLIDES;\n\t\t\n\theader->flags |= module->MODULE_ST3NOTECUT;\n\t\n\t/*mp_uword Ffi = */f.readWord();\n\t\n\tf.read(header->sig,1,4);\n\t\n\theader->mainvol = module->vol64to255(f.readByte()); // initial main volume\n\t\n\theader->tempo = f.readByte(); // tempo\n\t\n\theader->speed = f.readByte(); // speed\n\t\n\tf.readByte(); // global volume? skipped...\n\t\n\tf.readByte(); // ignore GUS click removal\n\t\n\t/*mp_ubyte dp = */f.readByte();\n\t\n\tf.readDword();\t// skip something\n\tf.readDword();\t// skip something\n\tf.readWord();\t// skip some more...\n\t\n\tmp_ubyte channelSettings[32];\n\tf.read(channelSettings,1,32);\n\t\n\tmp_sint32 numChannels = 0;\n\t\n\tfor (numChannels = 0; numChannels < 32; numChannels++)\n\t\tif (channelSettings[numChannels] == 255)\n\t\t\tbreak;\n\t\n\theader->channum = numChannels; // number of channels\n\t\n\tf.read(orders,1,header->ordnum);\n\t\n\tmp_sint32 j = 0, i = 0;\n\tfor (i = 0; i < header->ordnum; i++)\n\t{\n\t\tif (orders[i] == 255) \n\t\t\tbreak;\n\t\t\n\t\theader->ord[j++] = orders[i];\t\t\n\t}\n\t\n\theader->ordnum = j; // final songlength\n\t\n\tdelete[] orders;\n\t\n\tmp_uword* insParaPtrs = new mp_uword[header->insnum];\n\t\n\tif (insParaPtrs == NULL)\n\t\treturn MP_OUT_OF_MEMORY;\n\t\n\tf.readWords(insParaPtrs,header->insnum);\n\t\n\tmp_uword* patParaPtrs = new mp_uword[header->patnum];\n\t\n\tif (patParaPtrs == NULL)\n\t{\n\t\tdelete[] insParaPtrs;\n\t\treturn MP_OUT_OF_MEMORY;\n\t}\n\t\n\tf.readWords(patParaPtrs,header->patnum);\n\t\n\t//for (i = 0; i < header->insnum; i++)\n\t//{\n\t//\tprintf(\"%x\\n\",insParaPtrs[i]*16);\n\t//}\n\t\t\n\t//////////////////////\n\t// read instruments //\n\t//////////////////////\n\tmp_uint32* samplePtrs = new mp_uint32[header->insnum];\n\tif (samplePtrs == NULL)\n\t{\n\t\tdelete[] insParaPtrs;\n\t\tdelete[] patParaPtrs;\n\t\treturn MP_OUT_OF_MEMORY;\n\t}\n\t\n\tmemset(samplePtrs,0,sizeof(mp_uint32)*header->insnum);\n\t\n\tmp_sint32 s = 0;\n\tfor (i = 0; i < header->insnum; i++)\n\t{\n\t\tmp_uint32 insOffs = insParaPtrs[i]*16;\n\n\t\tif (insOffs)\n\t\t{\n\t\t\tf.seekWithBaseOffset(insOffs);\n\t\t\n\t\t\t// We can only read that if it's a sample\n\t\t\tmp_ubyte type = f.readByte();\n\t\t\t\n\t\t\tif (type == 1)\n\t\t\t{\n\t\t\t\tf.read(smp[s].name,1,12);\t// read dos filename\n\t\t\n\t\t\t\tmp_ubyte bOffs = f.readByte();\n\t\t\t\tmp_uword wOffs = f.readWord();\n\t\t\t\t\n\t\t\t\t// stupid fileoffsets\n\t\t\t\tsamplePtrs[i] = (((mp_uint32)bOffs<<16)+(mp_uint32)wOffs)*16;\n\t\t\t\t\n\t\t\t\tsmp[s].flags = 1;\n\t\t\t\tsmp[s].pan = 0x80;\n\t\t\t\t\n\t\t\t\tsmp[s].samplen = f.readDword();\n\t\t\t\tsmp[s].loopstart = f.readDword();\n\t\t\t\tmp_sint32 looplen = ((mp_sint32)f.readDword() - (mp_sint32)smp[s].loopstart);\n\t\t\t\tif (looplen < 0) \n\t\t\t\t\tlooplen = 0;\n\t\t\t\tsmp[s].looplen = looplen;\n\t\t\t\t\n\t\t\t\tsmp[s].vol = module->vol64to255(f.readByte());\n\t\t\t\t\n\t\t\t\tf.readByte(); // skip something\n\t\t\t\t\n\t\t\t\tsmp[s].res = f.readByte() == 0x04 ? 0xAD : 0; // packing\n\t\t\t\t\n\t\t\t\tmp_ubyte flags = f.readByte();\n\t\t\t\t\n\t\t\t\t// looping\n\t\t\t\tif (flags & 1)\n\t\t\t\t{\n\t\t\t\t\tsmp[s].type = 1;\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// 16 bit sample\n\t\t\t\tif (flags & 4)\n\t\t\t\t{\n\t\t\t\t\tsmp[s].type |= 16;\n\t\t\t\t\tsmp[s].samplen >>= 1;\n\t\t\t\t\tsmp[s].loopstart >>= 1;\n\t\t\t\t\tsmp[s].looplen >>= 1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmp_uint32 c4spd = f.readDword();\n\t\t\t\t\n\t\t\t\tXModule::convertc4spd(c4spd,&smp[s].finetune,&smp[s].relnote);\n\n#ifdef VERBOSE\n\t\t\t\tprintf(\"%i, %i\\n\",c4spd,module->getc4spd(smp[s].relnote,smp[s].finetune));\t\t\t\t\n#endif\n\n\t\t\t\tf.readDword(); // skip something\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip two internal words\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip internal dword\n\n\t\t\t\tf.read(instr[i].name,1,28); // instrument name\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip signature\n\t\t\t\t\n\t\t\t\tif (samplePtrs[i] && smp[s].samplen)\n\t\t\t\t{\n\t\t\t\t\tinstr[i].samp=1;\n\t\t\t\t\tfor (j=0;j<120;j++) \n\t\t\t\t\t\tinstr[i].snum[j] = s;\n\t\t\t\t\ts++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (type == 0)\n\t\t\t{\n\t\t\t\tsamplePtrs[i] = 0;\n\t\t\t\n\t\t\t\tmp_ubyte buffer[12];\n\t\t\t\tf.read(buffer,1,12);\t// read dos filename\n\t\t\n\t\t\t\tf.readByte();\n\t\t\t\tf.readWord();\n\t\t\t\t\n\t\t\t\tf.readDword();\n\t\t\t\tf.readDword();\n\t\t\t\tf.readDword();\n\t\t\t\tf.readByte();\n\t\t\t\tf.readByte(); // skip something\n\t\t\t\tf.readByte(); // skip packing\n\t\t\t\t\n\t\t\t\tf.readByte();\n\t\t\t\t\n\t\t\t\tf.readDword();\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip something\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip two internal words\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip internal dword\n\n\t\t\t\tf.read(instr[i].name,1,28); // instrument name\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip signature\t\t\t\t\n\t\t\t}\n\t\t\telse \n\t\t\t{\n\t\t\t\tsamplePtrs[i] = 0;\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t}\n\t\n\t//////////////////////\n\t// read patterns\t//\n\t//////////////////////\n\tmp_ubyte* pattern = new mp_ubyte[64*32*5];\n\tif (pattern == NULL)\n\t{\n\t\tdelete[] insParaPtrs;\n\t\tdelete[] patParaPtrs;\n\t\tdelete[] samplePtrs;\n\t\treturn MP_OUT_OF_MEMORY;\n\t}\n\t\n\tmp_uint32 songMaxChannels = 1;\n\t\n\tfor (i = 0; i < header->patnum; i++)\n\t{\n\t\tfor (j = 0; j < 32*64; j++)\n\t\t{\n\t\t\tpattern[j*5] = 0xFF;\n\t\t\tpattern[j*5+1] = 0;\n\t\t\tpattern[j*5+2] = 0xFF;\n\t\t\tpattern[j*5+3] = 0xFF;\n\t\t\tpattern[j*5+4] = 0;\n\t\t}\n\t\t\n\t\tmp_uint32 patOffs = patParaPtrs[i]*16;\n\t\t\n\t\tmp_uint32 maxChannels = 1;\t\t\t\n\t\t\n\t\tif (patOffs)\n\t\t{\n\t\t\tf.seekWithBaseOffset(patOffs);\n\t\t\t\n\t\t\tmp_uint32 size = f.readWord();\n\t\t\t\n\t\t\tif (size > 2)\n\t\t\t{\n\t\t\t\tsize-=2;\n\t\t\t\t\n\t\t\t\tmp_ubyte* packed = new mp_ubyte[size+5];\n\t\t\t\tif (packed == NULL)\n\t\t\t\t{\n\t\t\t\t\tdelete[] insParaPtrs;\n\t\t\t\t\tdelete[] patParaPtrs;\n\t\t\t\t\tdelete[] samplePtrs;\n\t\t\t\t\tdelete[] pattern;\n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmemset(packed, 0, size);\n\t\t\t\tf.read(packed, 1, size);\n\t\t\t\t\n\t\t\t\tmp_uint32 index = 0;\n\t\t\t\tmp_uint32 row = 0;\n\t\t\t\t\n\t\t\t\twhile (index= 64)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint i = 0;\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\ti--;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tmp_uint32 chn = pi&31;\n\t\t\t\t\t\n\t\t\t\t\tif (chn>maxChannels && (pi & (32+64+128)))\n\t\t\t\t\t{\n\t\t\t\t\t\tmaxChannels = chn;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tmp_ubyte* slot = pattern+(row*32*5)+chn*5;\n\t\t\t\t\t\n\t\t\t\t\tif (pi & 32)\n\t\t\t\t\t{\n\t\t\t\t\t\tslot[0] = safeRead(packed, index, size, 0xFF);\n\t\t\t\t\t\tslot[1] = safeRead(packed, index, size);\n\t\t\t\t\t}\n\t\t\t\t\tif (pi & 64)\n\t\t\t\t\t{\n\t\t\t\t\t\tslot[2] = safeRead(packed, index, size, 0xFF);\n\t\t\t\t\t}\n\t\t\t\t\tif (pi & 128)\n\t\t\t\t\t{\n\t\t\t\t\t\tslot[3] = safeRead(packed, index, size, 0xFF);\n\t\t\t\t\t\tslot[4] = safeRead(packed, index, size);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmaxChannels++;\n\t\t\t\t\n\t\t\t\tif (maxChannels > header->channum)\n\t\t\t\t\tmaxChannels = header->channum;\n\t\t\t\t\n\t\t\t\tdelete[] packed;\n\t\t\t}\n\t\t\t\n\t\t\tif (maxChannels > songMaxChannels)\n\t\t\t\tsongMaxChannels = maxChannels;\n\t\t\t\n\t\t}\n\t\t\n\t\tconvertS3MPattern(&phead[i], pattern, maxChannels, i);\n\t\t\n\t\t\n\t}\n\t\n\tif (header->channum > songMaxChannels)\n\t\theader->channum = songMaxChannels;\n\t\n\tdelete[] pattern;\n\tdelete[] insParaPtrs;\n\tdelete[] patParaPtrs;\n\t\n\ts = 0;\n\tfor (i = 0; i < header->insnum; i++)\n\t{\n\t\tmp_uint32 smpOffs = samplePtrs[i];\n\n\t\tif (smpOffs)\n\t\t{\n\t\t\tf.seekWithBaseOffset(smpOffs);\n\t\t\t\n\t\t\tif (!smp[s].samplen)\n\t\t\t\tcontinue;\n\n\t\t\tbool adpcm = (smp[s].res == 0xAD);\n\n\t\t\tmp_sint32 result = module->loadModuleSample(f, s, \n\t\t\t\t\t\t\t\t\t\t  adpcm ? XModule::ST_PACKING_ADPCM : XModule::ST_UNSIGNED, \n\t\t\t\t\t\t\t\t\t\t  adpcm ? (XModule::ST_16BIT | XModule::ST_PACKING_ADPCM) : (XModule::ST_16BIT | XModule::ST_UNSIGNED));\n\t\t\tif (result != MP_OK)\n\t\t\t{\n\t\t\t\tdelete[] samplePtrs;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\t\n\t\t\tif (adpcm)\n\t\t\t\t// no longer needed\n\t\t\t\tsmp[s].res = 0;\t\t\t\n\t\t\t\t\t\t\t\n\t\t\ts++;\n\t\t\t\n\t\t}\n\n\t}\n\t\n\tdelete[] samplePtrs;\n\t\n\theader->smpnum = s;\n\t\n\tstrcpy(header->tracker,\"Screamtracker 3\");\n\t\n\tmodule->setDefaultPanning();\n\t\n\tmodule->postProcessSamples();\n\t\n\treturn MP_OK;\t\n}", "func_hash": 83839366626583868665259951755341094581, "file_name": "LoaderS3M.cpp", "file_hash": 183144652101625968491560243513367539209, "cwe": ["CWE-787"], "cve": "CVE-2019-14464", "cve_desc": "XMFile::read in XMFile.cpp in milkyplay in MilkyTracker 1.02.00 has a heap-based buffer overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-14464"}
{"idx": 281247, "project": "MilkyTracker", "commit_id": "fd607a3439fcdd0992e5efded3c16fc79c804e34", "project_url": "https://github.com/milkytracker/MilkyTracker", "commit_url": "https://github.com/milkytracker/MilkyTracker/commit/fd607a3439fcdd0992e5efded3c16fc79c804e34", "commit_message": "Fix #184: Heap overflow in S3M loader", "target": 0, "func": "mp_sint32 LoaderS3M::load(XMFileBase& f, XModule* module)\n{\t\n\tmodule->cleanUp();\n\n\t// this will make code much easier to read\n\tTXMHeader*\t\theader = &module->header;\n\tTXMInstrument*\tinstr  = module->instr;\n\tTXMSample*\t\tsmp\t   = module->smp;\n\tTXMPattern*\t\tphead  = module->phead;\t\n\n\t// we're already out of memory here\n\tif (!phead || !instr || !smp)\n\t\treturn MP_OUT_OF_MEMORY;\n\t\n\tf.read(&header->name,1,28);\n\theader->whythis1a = f.readByte();\n\t\n\tif (f.readByte() != 16) \n\t\treturn MP_LOADER_FAILED;\t// no ST3 module\n\t\n\tf.readByte(); // skip something\n\tf.readByte(); // skip something\n\t\n\theader->ordnum = f.readWord(); // number of positions in order list (songlength)\n\t\n\tmp_ubyte* orders = new mp_ubyte[header->ordnum];\n\tif (orders == NULL) \n\t\treturn MP_OUT_OF_MEMORY;\n\t\n\theader->insnum = f.readWord(); // number of instruments\n\tif (header->insnum > MP_MAXINS)\n\t\treturn MP_LOADER_FAILED;\n\theader->patnum = f.readWord(); // number of patterns\n\tif (header->patnum > 256)\n\t\treturn MP_LOADER_FAILED;\n\t\n\tmp_sint32 flags = f.readWord(); // st3 flags\t\n\n\tmp_sint32 Cvt = f.readWord();\n\n\theader->flags = XModule::MODULE_ST3NEWINSTRUMENT | XModule::MODULE_ST3DUALCOMMANDS;\n\n\tif (Cvt == 0x1300 || (flags & 64))\n\t\theader->flags |= module->MODULE_OLDS3MVOLSLIDES;\n\t\t\n\theader->flags |= module->MODULE_ST3NOTECUT;\n\t\n\t/*mp_uword Ffi = */f.readWord();\n\t\n\tf.read(header->sig,1,4);\n\t\n\theader->mainvol = module->vol64to255(f.readByte()); // initial main volume\n\t\n\theader->tempo = f.readByte(); // tempo\n\t\n\theader->speed = f.readByte(); // speed\n\t\n\tf.readByte(); // global volume? skipped...\n\t\n\tf.readByte(); // ignore GUS click removal\n\t\n\t/*mp_ubyte dp = */f.readByte();\n\t\n\tf.readDword();\t// skip something\n\tf.readDword();\t// skip something\n\tf.readWord();\t// skip some more...\n\t\n\tmp_ubyte channelSettings[32];\n\tf.read(channelSettings,1,32);\n\t\n\tmp_sint32 numChannels = 0;\n\t\n\tfor (numChannels = 0; numChannels < 32; numChannels++)\n\t\tif (channelSettings[numChannels] == 255)\n\t\t\tbreak;\n\t\n\theader->channum = numChannels; // number of channels\n\t\n\tf.read(orders,1,header->ordnum);\n\t\n\tmp_sint32 j = 0, i = 0;\n\tfor (i = 0; i < header->ordnum; i++)\n\t{\n\t\tif (orders[i] == 255) \n\t\t\tbreak;\n\t\t\n\t\theader->ord[j++] = orders[i];\t\t\n\t}\n\t\n\theader->ordnum = j; // final songlength\n\t\n\tdelete[] orders;\n\t\n\tmp_uword* insParaPtrs = new mp_uword[header->insnum];\n\t\n\tif (insParaPtrs == NULL)\n\t\treturn MP_OUT_OF_MEMORY;\n\t\n\tf.readWords(insParaPtrs,header->insnum);\n\t\n\tmp_uword* patParaPtrs = new mp_uword[header->patnum];\n\t\n\tif (patParaPtrs == NULL)\n\t{\n\t\tdelete[] insParaPtrs;\n\t\treturn MP_OUT_OF_MEMORY;\n\t}\n\t\n\tf.readWords(patParaPtrs,header->patnum);\n\t\n\t//for (i = 0; i < header->insnum; i++)\n\t//{\n\t//\tprintf(\"%x\\n\",insParaPtrs[i]*16);\n\t//}\n\t\t\n\t//////////////////////\n\t// read instruments //\n\t//////////////////////\n\tmp_uint32* samplePtrs = new mp_uint32[header->insnum];\n\tif (samplePtrs == NULL)\n\t{\n\t\tdelete[] insParaPtrs;\n\t\tdelete[] patParaPtrs;\n\t\treturn MP_OUT_OF_MEMORY;\n\t}\n\t\n\tmemset(samplePtrs,0,sizeof(mp_uint32)*header->insnum);\n\t\n\tmp_sint32 s = 0;\n\tfor (i = 0; i < header->insnum; i++)\n\t{\n\t\tmp_uint32 insOffs = insParaPtrs[i]*16;\n\n\t\tif (insOffs)\n\t\t{\n\t\t\tf.seekWithBaseOffset(insOffs);\n\t\t\n\t\t\t// We can only read that if it's a sample\n\t\t\tmp_ubyte type = f.readByte();\n\t\t\t\n\t\t\tif (type == 1)\n\t\t\t{\n\t\t\t\tf.read(smp[s].name,1,12);\t// read dos filename\n\t\t\n\t\t\t\tmp_ubyte bOffs = f.readByte();\n\t\t\t\tmp_uword wOffs = f.readWord();\n\t\t\t\t\n\t\t\t\t// stupid fileoffsets\n\t\t\t\tsamplePtrs[i] = (((mp_uint32)bOffs<<16)+(mp_uint32)wOffs)*16;\n\t\t\t\t\n\t\t\t\tsmp[s].flags = 1;\n\t\t\t\tsmp[s].pan = 0x80;\n\t\t\t\t\n\t\t\t\tsmp[s].samplen = f.readDword();\n\t\t\t\tsmp[s].loopstart = f.readDword();\n\t\t\t\tmp_sint32 looplen = ((mp_sint32)f.readDword() - (mp_sint32)smp[s].loopstart);\n\t\t\t\tif (looplen < 0) \n\t\t\t\t\tlooplen = 0;\n\t\t\t\tsmp[s].looplen = looplen;\n\t\t\t\t\n\t\t\t\tsmp[s].vol = module->vol64to255(f.readByte());\n\t\t\t\t\n\t\t\t\tf.readByte(); // skip something\n\t\t\t\t\n\t\t\t\tsmp[s].res = f.readByte() == 0x04 ? 0xAD : 0; // packing\n\t\t\t\t\n\t\t\t\tmp_ubyte flags = f.readByte();\n\t\t\t\t\n\t\t\t\t// looping\n\t\t\t\tif (flags & 1)\n\t\t\t\t{\n\t\t\t\t\tsmp[s].type = 1;\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// 16 bit sample\n\t\t\t\tif (flags & 4)\n\t\t\t\t{\n\t\t\t\t\tsmp[s].type |= 16;\n\t\t\t\t\tsmp[s].samplen >>= 1;\n\t\t\t\t\tsmp[s].loopstart >>= 1;\n\t\t\t\t\tsmp[s].looplen >>= 1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmp_uint32 c4spd = f.readDword();\n\t\t\t\t\n\t\t\t\tXModule::convertc4spd(c4spd,&smp[s].finetune,&smp[s].relnote);\n\n#ifdef VERBOSE\n\t\t\t\tprintf(\"%i, %i\\n\",c4spd,module->getc4spd(smp[s].relnote,smp[s].finetune));\t\t\t\t\n#endif\n\n\t\t\t\tf.readDword(); // skip something\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip two internal words\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip internal dword\n\n\t\t\t\tf.read(instr[i].name,1,28); // instrument name\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip signature\n\t\t\t\t\n\t\t\t\tif (samplePtrs[i] && smp[s].samplen)\n\t\t\t\t{\n\t\t\t\t\tinstr[i].samp=1;\n\t\t\t\t\tfor (j=0;j<120;j++) \n\t\t\t\t\t\tinstr[i].snum[j] = s;\n\t\t\t\t\ts++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (type == 0)\n\t\t\t{\n\t\t\t\tsamplePtrs[i] = 0;\n\t\t\t\n\t\t\t\tmp_ubyte buffer[12];\n\t\t\t\tf.read(buffer,1,12);\t// read dos filename\n\t\t\n\t\t\t\tf.readByte();\n\t\t\t\tf.readWord();\n\t\t\t\t\n\t\t\t\tf.readDword();\n\t\t\t\tf.readDword();\n\t\t\t\tf.readDword();\n\t\t\t\tf.readByte();\n\t\t\t\tf.readByte(); // skip something\n\t\t\t\tf.readByte(); // skip packing\n\t\t\t\t\n\t\t\t\tf.readByte();\n\t\t\t\t\n\t\t\t\tf.readDword();\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip something\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip two internal words\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip internal dword\n\n\t\t\t\tf.read(instr[i].name,1,28); // instrument name\n\t\t\t\t\n\t\t\t\tf.readDword(); // skip signature\t\t\t\t\n\t\t\t}\n\t\t\telse \n\t\t\t{\n\t\t\t\tsamplePtrs[i] = 0;\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t}\n\t\n\t//////////////////////\n\t// read patterns\t//\n\t//////////////////////\n\tmp_ubyte* pattern = new mp_ubyte[64*32*5];\n\tif (pattern == NULL)\n\t{\n\t\tdelete[] insParaPtrs;\n\t\tdelete[] patParaPtrs;\n\t\tdelete[] samplePtrs;\n\t\treturn MP_OUT_OF_MEMORY;\n\t}\n\t\n\tmp_uint32 songMaxChannels = 1;\n\t\n\tfor (i = 0; i < header->patnum; i++)\n\t{\n\t\tfor (j = 0; j < 32*64; j++)\n\t\t{\n\t\t\tpattern[j*5] = 0xFF;\n\t\t\tpattern[j*5+1] = 0;\n\t\t\tpattern[j*5+2] = 0xFF;\n\t\t\tpattern[j*5+3] = 0xFF;\n\t\t\tpattern[j*5+4] = 0;\n\t\t}\n\t\t\n\t\tmp_uint32 patOffs = patParaPtrs[i]*16;\n\t\t\n\t\tmp_uint32 maxChannels = 1;\t\t\t\n\t\t\n\t\tif (patOffs)\n\t\t{\n\t\t\tf.seekWithBaseOffset(patOffs);\n\t\t\t\n\t\t\tmp_uint32 size = f.readWord();\n\t\t\t\n\t\t\tif (size > 2)\n\t\t\t{\n\t\t\t\tsize-=2;\n\t\t\t\t\n\t\t\t\tmp_ubyte* packed = new mp_ubyte[size+5];\n\t\t\t\tif (packed == NULL)\n\t\t\t\t{\n\t\t\t\t\tdelete[] insParaPtrs;\n\t\t\t\t\tdelete[] patParaPtrs;\n\t\t\t\t\tdelete[] samplePtrs;\n\t\t\t\t\tdelete[] pattern;\n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmemset(packed, 0, size);\n\t\t\t\tf.read(packed, 1, size);\n\t\t\t\t\n\t\t\t\tmp_uint32 index = 0;\n\t\t\t\tmp_uint32 row = 0;\n\t\t\t\t\n\t\t\t\twhile (index= 64)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint i = 0;\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\ti--;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tmp_uint32 chn = pi&31;\n\t\t\t\t\t\n\t\t\t\t\tif (chn>maxChannels && (pi & (32+64+128)))\n\t\t\t\t\t{\n\t\t\t\t\t\tmaxChannels = chn;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tmp_ubyte* slot = pattern+(row*32*5)+chn*5;\n\t\t\t\t\t\n\t\t\t\t\tif (pi & 32)\n\t\t\t\t\t{\n\t\t\t\t\t\tslot[0] = safeRead(packed, index, size, 0xFF);\n\t\t\t\t\t\tslot[1] = safeRead(packed, index, size);\n\t\t\t\t\t}\n\t\t\t\t\tif (pi & 64)\n\t\t\t\t\t{\n\t\t\t\t\t\tslot[2] = safeRead(packed, index, size, 0xFF);\n\t\t\t\t\t}\n\t\t\t\t\tif (pi & 128)\n\t\t\t\t\t{\n\t\t\t\t\t\tslot[3] = safeRead(packed, index, size, 0xFF);\n\t\t\t\t\t\tslot[4] = safeRead(packed, index, size);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmaxChannels++;\n\t\t\t\t\n\t\t\t\tif (maxChannels > header->channum)\n\t\t\t\t\tmaxChannels = header->channum;\n\t\t\t\t\n\t\t\t\tdelete[] packed;\n\t\t\t}\n\t\t\t\n\t\t\tif (maxChannels > songMaxChannels)\n\t\t\t\tsongMaxChannels = maxChannels;\n\t\t\t\n\t\t}\n\t\t\n\t\tconvertS3MPattern(&phead[i], pattern, maxChannels, i);\n\t\t\n\t\t\n\t}\n\t\n\tif (header->channum > songMaxChannels)\n\t\theader->channum = songMaxChannels;\n\t\n\tdelete[] pattern;\n\tdelete[] insParaPtrs;\n\tdelete[] patParaPtrs;\n\t\n\ts = 0;\n\tfor (i = 0; i < header->insnum; i++)\n\t{\n\t\tmp_uint32 smpOffs = samplePtrs[i];\n\n\t\tif (smpOffs)\n\t\t{\n\t\t\tf.seekWithBaseOffset(smpOffs);\n\t\t\t\n\t\t\tif (!smp[s].samplen)\n\t\t\t\tcontinue;\n\n\t\t\tbool adpcm = (smp[s].res == 0xAD);\n\n\t\t\tmp_sint32 result = module->loadModuleSample(f, s, \n\t\t\t\t\t\t\t\t\t\t  adpcm ? XModule::ST_PACKING_ADPCM : XModule::ST_UNSIGNED, \n\t\t\t\t\t\t\t\t\t\t  adpcm ? (XModule::ST_16BIT | XModule::ST_PACKING_ADPCM) : (XModule::ST_16BIT | XModule::ST_UNSIGNED));\n\t\t\tif (result != MP_OK)\n\t\t\t{\n\t\t\t\tdelete[] samplePtrs;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\t\n\t\t\tif (adpcm)\n\t\t\t\t// no longer needed\n\t\t\t\tsmp[s].res = 0;\t\t\t\n\t\t\t\t\t\t\t\n\t\t\ts++;\n\t\t\t\n\t\t}\n\n\t}\n\t\n\tdelete[] samplePtrs;\n\t\n\theader->smpnum = s;\n\t\n\tstrcpy(header->tracker,\"Screamtracker 3\");\n\t\n\tmodule->setDefaultPanning();\n\t\n\tmodule->postProcessSamples();\n\t\n\treturn MP_OK;\t\n}", "func_hash": 43770452708802506727115709874913360488, "file_name": "LoaderS3M.cpp", "file_hash": 201031335875612039718425244532999180036, "cwe": ["CWE-787"], "cve": "CVE-2019-14464", "cve_desc": "XMFile::read in XMFile.cpp in milkyplay in MilkyTracker 1.02.00 has a heap-based buffer overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-14464"}
{"idx": 198703, "project": "LibRaw", "commit_id": "4606c28f494a750892c5c1ac7903e62dd1c6fdb5", "project_url": "https://github.com/LibRaw/LibRaw", "commit_url": "https://github.com/LibRaw/LibRaw/commit/4606c28f494a750892c5c1ac7903e62dd1c6fdb5", "commit_message": "0.16.1: fix for dcraw ljpeg_start() vulnerability", "target": 1, "func": "int CLASS ljpeg_start (struct jhead *jh, int info_only)\n{\n  int c, tag, len;\n  uchar data[0x10000];\n  const uchar *dp;\n\n  memset (jh, 0, sizeof *jh);\n  jh->restart = INT_MAX;\n  fread (data, 2, 1, ifp);\n  if (data[1] != 0xd8) return 0;\n  do {\n    fread (data, 2, 2, ifp);\n    tag =  data[0] << 8 | data[1];\n    len = (data[2] << 8 | data[3]) - 2;\n    if (tag <= 0xff00) return 0;\n    fread (data, 1, len, ifp);\n    switch (tag) {\n      case 0xffc3:\n\tjh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;\n      case 0xffc0:\n\tjh->bits = data[0];\n\tjh->high = data[1] << 8 | data[2];\n\tjh->wide = data[3] << 8 | data[4];\n\tjh->clrs = data[5] + jh->sraw;\n\tif (len == 9 && !dng_version) getc(ifp);\n\tbreak;\n      case 0xffc4:\n\tif (info_only) break;\n\tfor (dp = data; dp < data+len && (c = *dp++) < 4; )\n\t  jh->free[c] = jh->huff[c] = make_decoder_ref (&dp);\n\tbreak;\n      case 0xffda:\n\tjh->psv = data[1+data[0]*2];\n\tjh->bits -= data[3+data[0]*2] & 15;\n\tbreak;\n      case 0xffdd:\n\tjh->restart = data[0] << 8 | data[1];\n    }\n  } while (tag != 0xffda);\n  if (info_only) return 1;\n  if (jh->clrs > 6 || !jh->huff[0]) return 0;\n  FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c];\n  if (jh->sraw) {\n    FORC(4)        jh->huff[2+c] = jh->huff[1];\n    FORC(jh->sraw) jh->huff[1+c] = jh->huff[0];\n  }\n  jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4);\n  merror (jh->row, \"ljpeg_start()\");\n  return zero_after_ff = 1;\n}", "func_hash": 130689334179908551360949370308005940309, "file_name": "dcraw.c", "file_hash": 16246307575535149063752681880088000458, "cwe": ["CWE-189"], "cve": "CVE-2015-3885", "cve_desc": "Integer overflow in the ljpeg_start function in dcraw 7.00 and earlier allows remote attackers to cause a denial of service (crash) via a crafted image, which triggers a buffer overflow, related to the len variable.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-3885"}
{"idx": 281662, "project": "LibRaw", "commit_id": "4606c28f494a750892c5c1ac7903e62dd1c6fdb5", "project_url": "https://github.com/LibRaw/LibRaw", "commit_url": "https://github.com/LibRaw/LibRaw/commit/4606c28f494a750892c5c1ac7903e62dd1c6fdb5", "commit_message": "0.16.1: fix for dcraw ljpeg_start() vulnerability", "target": 0, "func": "int CLASS ljpeg_start (struct jhead *jh, int info_only)\n{\n  int c, tag;\n  ushort len;\n  uchar data[0x10000];\n  const uchar *dp;\n\n  memset (jh, 0, sizeof *jh);\n  jh->restart = INT_MAX;\n  fread (data, 2, 1, ifp);\n  if (data[1] != 0xd8) return 0;\n  do {\n    fread (data, 2, 2, ifp);\n    tag =  data[0] << 8 | data[1];\n    len = (data[2] << 8 | data[3]) - 2;\n    if (tag <= 0xff00) return 0;\n    fread (data, 1, len, ifp);\n    switch (tag) {\n      case 0xffc3:\n\tjh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;\n      case 0xffc0:\n\tjh->bits = data[0];\n\tjh->high = data[1] << 8 | data[2];\n\tjh->wide = data[3] << 8 | data[4];\n\tjh->clrs = data[5] + jh->sraw;\n\tif (len == 9 && !dng_version) getc(ifp);\n\tbreak;\n      case 0xffc4:\n\tif (info_only) break;\n\tfor (dp = data; dp < data+len && (c = *dp++) < 4; )\n\t  jh->free[c] = jh->huff[c] = make_decoder_ref (&dp);\n\tbreak;\n      case 0xffda:\n\tjh->psv = data[1+data[0]*2];\n\tjh->bits -= data[3+data[0]*2] & 15;\n\tbreak;\n      case 0xffdd:\n\tjh->restart = data[0] << 8 | data[1];\n    }\n  } while (tag != 0xffda);\n  if (info_only) return 1;\n  if (jh->clrs > 6 || !jh->huff[0]) return 0;\n  FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c];\n  if (jh->sraw) {\n    FORC(4)        jh->huff[2+c] = jh->huff[1];\n    FORC(jh->sraw) jh->huff[1+c] = jh->huff[0];\n  }\n  jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4);\n  merror (jh->row, \"ljpeg_start()\");\n  return zero_after_ff = 1;\n}", "func_hash": 72339835961882099009562800572208643918, "file_name": "None", "file_hash": null, "cwe": ["CWE-189"], "cve": "CVE-2015-3885", "cve_desc": "Integer overflow in the ljpeg_start function in dcraw 7.00 and earlier allows remote attackers to cause a denial of service (crash) via a crafted image, which triggers a buffer overflow, related to the len variable.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-3885"}
{"idx": 198736, "project": "linux", "commit_id": "d563131ef23cbc756026f839a82598c8445bc45f", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/d563131ef23cbc756026f839a82598c8445bc45f", "commit_message": "rsi: release skb if rsi_prepare_beacon fails\n\nIn rsi_send_beacon, if rsi_prepare_beacon fails the allocated skb should\nbe released.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Kalle Valo ", "target": 1, "func": "static int rsi_send_beacon(struct rsi_common *common)\n{\n\tstruct sk_buff *skb = NULL;\n\tu8 dword_align_bytes = 0;\n\n\tskb = dev_alloc_skb(MAX_MGMT_PKT_SIZE);\n\tif (!skb)\n\t\treturn -ENOMEM;\n\n\tmemset(skb->data, 0, MAX_MGMT_PKT_SIZE);\n\n\tdword_align_bytes = ((unsigned long)skb->data & 0x3f);\n\tif (dword_align_bytes)\n\t\tskb_pull(skb, (64 - dword_align_bytes));\n\tif (rsi_prepare_beacon(common, skb)) {\n\t\trsi_dbg(ERR_ZONE, \"Failed to prepare beacon\\n\");\n\t\treturn -EINVAL;\n\t}\n\tskb_queue_tail(&common->tx_queue[MGMT_BEACON_Q], skb);\n\trsi_set_event(&common->tx_thread.event);\n\trsi_dbg(DATA_TX_ZONE, \"%s: Added to beacon queue\\n\", __func__);\n\n\treturn 0;\n}", "func_hash": 130931178778692254191224779038755080046, "file_name": "rsi_91x_mgmt.c", "file_hash": 125660046646447806158908760119804627111, "cwe": ["CWE-401"], "cve": "CVE-2019-19071", "cve_desc": "A memory leak in the rsi_send_beacon() function in drivers/net/wireless/rsi/rsi_91x_mgmt.c in the Linux kernel through 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering rsi_prepare_beacon() failures, aka CID-d563131ef23c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19071"}
{"idx": 282862, "project": "linux", "commit_id": "d563131ef23cbc756026f839a82598c8445bc45f", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/d563131ef23cbc756026f839a82598c8445bc45f", "commit_message": "rsi: release skb if rsi_prepare_beacon fails\n\nIn rsi_send_beacon, if rsi_prepare_beacon fails the allocated skb should\nbe released.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Kalle Valo ", "target": 0, "func": "static int rsi_send_beacon(struct rsi_common *common)\n{\n\tstruct sk_buff *skb = NULL;\n\tu8 dword_align_bytes = 0;\n\n\tskb = dev_alloc_skb(MAX_MGMT_PKT_SIZE);\n\tif (!skb)\n\t\treturn -ENOMEM;\n\n\tmemset(skb->data, 0, MAX_MGMT_PKT_SIZE);\n\n\tdword_align_bytes = ((unsigned long)skb->data & 0x3f);\n\tif (dword_align_bytes)\n\t\tskb_pull(skb, (64 - dword_align_bytes));\n\tif (rsi_prepare_beacon(common, skb)) {\n\t\trsi_dbg(ERR_ZONE, \"Failed to prepare beacon\\n\");\n\t\tdev_kfree_skb(skb);\n\t\treturn -EINVAL;\n\t}\n\tskb_queue_tail(&common->tx_queue[MGMT_BEACON_Q], skb);\n\trsi_set_event(&common->tx_thread.event);\n\trsi_dbg(DATA_TX_ZONE, \"%s: Added to beacon queue\\n\", __func__);\n\n\treturn 0;\n}", "func_hash": 202315144827915003727836614095080991835, "file_name": "rsi_91x_mgmt.c", "file_hash": 337039362328413232417752595040682703698, "cwe": ["CWE-401"], "cve": "CVE-2019-19071", "cve_desc": "A memory leak in the rsi_send_beacon() function in drivers/net/wireless/rsi/rsi_91x_mgmt.c in the Linux kernel through 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering rsi_prepare_beacon() failures, aka CID-d563131ef23c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19071"}
{"idx": 198743, "project": "LuaJIT", "commit_id": "53f82e6e2e858a0a62fd1a2ff47e9866693382e6", "project_url": "https://github.com/LuaJIT/LuaJIT", "commit_url": "https://github.com/LuaJIT/LuaJIT/commit/53f82e6e2e858a0a62fd1a2ff47e9866693382e6", "commit_message": "Fix frame traversal for __gc handler frames.\n\nReported by Changochen.", "target": 1, "func": "static ptrdiff_t finderrfunc(lua_State *L)\n{\n  cTValue *frame = L->base-1, *bot = tvref(L->stack);\n  void *cf = L->cframe;\n  while (frame > bot && cf) {\n    while (cframe_nres(cframe_raw(cf)) < 0) {  /* cframe without frame? */\n      if (frame >= restorestack(L, -cframe_nres(cf)))\n\tbreak;\n      if (cframe_errfunc(cf) >= 0)  /* Error handler not inherited (-1)? */\n\treturn cframe_errfunc(cf);\n      cf = cframe_prev(cf);  /* Else unwind cframe and continue searching. */\n      if (cf == NULL)\n\treturn 0;\n    }\n    switch (frame_typep(frame)) {\n    case FRAME_LUA:\n    case FRAME_LUAP:\n      frame = frame_prevl(frame);\n      break;\n    case FRAME_C:\n      cf = cframe_prev(cf);\n      /* fallthrough */\n    case FRAME_VARG:\n      frame = frame_prevd(frame);\n      break;\n    case FRAME_CONT:\n#if LJ_HASFFI\n      if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK)\n\tcf = cframe_prev(cf);\n#endif\n      frame = frame_prevd(frame);\n      break;\n    case FRAME_CP:\n      if (cframe_canyield(cf)) return 0;\n      if (cframe_errfunc(cf) >= 0)\n\treturn cframe_errfunc(cf);\n      frame = frame_prevd(frame);\n      break;\n    case FRAME_PCALL:\n    case FRAME_PCALLH:\n      if (frame_ftsz(frame) >= (ptrdiff_t)(2*sizeof(TValue)))  /* xpcall? */\n\treturn savestack(L, frame-1);  /* Point to xpcall's errorfunc. */\n      return 0;\n    default:\n      lua_assert(0);\n      return 0;\n    }\n  }\n  return 0;\n}", "func_hash": 309200300493568288549157158368440611870, "file_name": "lj_err.c", "file_hash": 339549767514658029818043680727253046808, "cwe": ["CWE-125"], "cve": "CVE-2020-15890", "cve_desc": "LuaJit through 2.1.0-beta3 has an out-of-bounds read because __gc handler frame traversal is mishandled.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15890"}
{"idx": 282984, "project": "LuaJIT", "commit_id": "53f82e6e2e858a0a62fd1a2ff47e9866693382e6", "project_url": "https://github.com/LuaJIT/LuaJIT", "commit_url": "https://github.com/LuaJIT/LuaJIT/commit/53f82e6e2e858a0a62fd1a2ff47e9866693382e6", "commit_message": "Fix frame traversal for __gc handler frames.\n\nReported by Changochen.", "target": 0, "func": "static ptrdiff_t finderrfunc(lua_State *L)\n{\n  cTValue *frame = L->base-1, *bot = tvref(L->stack);\n  void *cf = L->cframe;\n  while (frame > bot && cf) {\n    while (cframe_nres(cframe_raw(cf)) < 0) {  /* cframe without frame? */\n      if (frame >= restorestack(L, -cframe_nres(cf)))\n\tbreak;\n      if (cframe_errfunc(cf) >= 0)  /* Error handler not inherited (-1)? */\n\treturn cframe_errfunc(cf);\n      cf = cframe_prev(cf);  /* Else unwind cframe and continue searching. */\n      if (cf == NULL)\n\treturn 0;\n    }\n    switch (frame_typep(frame)) {\n    case FRAME_LUA:\n    case FRAME_LUAP:\n      frame = frame_prevl(frame);\n      break;\n    case FRAME_C:\n      cf = cframe_prev(cf);\n      /* fallthrough */\n    case FRAME_VARG:\n      frame = frame_prevd(frame);\n      break;\n    case FRAME_CONT:\n#if LJ_HASFFI\n      if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK)\n\tcf = cframe_prev(cf);\n#endif\n      frame = frame_prevd(frame);\n      break;\n    case FRAME_CP:\n      if (cframe_canyield(cf)) return 0;\n      if (cframe_errfunc(cf) >= 0)\n\treturn cframe_errfunc(cf);\n      cf = cframe_prev(cf);\n      frame = frame_prevd(frame);\n      break;\n    case FRAME_PCALL:\n    case FRAME_PCALLH:\n      if (frame_ftsz(frame) >= (ptrdiff_t)(2*sizeof(TValue)))  /* xpcall? */\n\treturn savestack(L, frame-1);  /* Point to xpcall's errorfunc. */\n      return 0;\n    default:\n      lua_assert(0);\n      return 0;\n    }\n  }\n  return 0;\n}", "func_hash": 135963737792819118980125175334737284274, "file_name": "lj_err.c", "file_hash": 198203473898814036407466574660463075188, "cwe": ["CWE-125"], "cve": "CVE-2020-15890", "cve_desc": "LuaJit through 2.1.0-beta3 has an out-of-bounds read because __gc handler frame traversal is mishandled.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15890"}
{"idx": 198927, "project": "radare2", "commit_id": "0a557045476a2969c7079aec9eeb29d02f2809c6", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/0a557045476a2969c7079aec9eeb29d02f2809c6", "commit_message": "Fix oobread and unaligned casts in the NE entrypoint logic ##crash\n\n* Reported by @hmsec via huntr.dev\n* Reproducer: nepocaligns\n* BountyID: ec538fa4-06c6-4050-a141-f60153ddeaac", "target": 1, "func": "RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {\n\tif (!bin->entry_table) {\n\t\treturn NULL;\n\t}\n\tRList *entries = r_list_newf (free);\n\tif (!entries) {\n\t\treturn NULL;\n\t}\n\tRList *segments = r_bin_ne_get_segments (bin);\n\tif (!segments) {\n\t\tr_list_free (entries);\n\t\treturn NULL;\n\t}\n\tif (bin->ne_header->csEntryPoint) {\n\t\tRBinAddr *entry = R_NEW0 (RBinAddr);\n\t\tif (!entry) {\n\t\t\tr_list_free (entries);\n\t\t\treturn NULL;\n\t\t}\n\t\tentry->bits = 16;\n\t\tut32 entry_cs = bin->ne_header->csEntryPoint;\n\t\tRBinSection *s = r_list_get_n (segments, entry_cs - 1);\n\t\tentry->paddr = bin->ne_header->ipEntryPoint + (s? s->paddr: 0);\n\n\t\tr_list_append (entries, entry);\n\t}\n\tint off = 0;\n\tsize_t tableat = bin->header_offset + bin->ne_header->EntryTableOffset;\n\twhile (off < bin->ne_header->EntryTableLength) {\n\t\tif (tableat + off >= r_buf_size (bin->buf)) {\n\t\t\tbreak;\n\t\t}\n\t\tut8 bundle_length = *(ut8 *)(bin->entry_table + off);\n\t\tif (!bundle_length) {\n\t\t\tbreak;\n\t\t}\n\t\toff++;\n\t\tut8 bundle_type = *(ut8 *)(bin->entry_table + off);\n\t\toff++;\n\t\tint i;\n\t\tfor (i = 0; i < bundle_length; i++) {\n\t\t\tif (tableat + off + 4 >= r_buf_size (bin->buf)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tRBinAddr *entry = R_NEW0 (RBinAddr);\n\t\t\tif (!entry) {\n\t\t\t\tr_list_free (entries);\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\toff++;\n\t\t\tif (!bundle_type) { // Skip\n\t\t\t\toff--;\n\t\t\t\tfree (entry);\n\t\t\t\tbreak;\n\t\t\t} else if (bundle_type == 0xff) { // moveable\n\t\t\t\toff += 2;\n\t\t\t\tut8 segnum = *(bin->entry_table + off);\n\t\t\t\toff++;\n\t\t\t\tut16 segoff = *(ut16 *)(bin->entry_table + off);\n\t\t\t\tif (segnum > 0) {\n\t\t\t\t\tentry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff;\n\t\t\t\t}\n\t\t\t} else { // Fixed\n\t\t\t\tif (bundle_type < bin->ne_header->SegCount) {\n\t\t\t\t\tentry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset\n\t\t\t\t\t\t* bin->alignment + *(ut16 *)(bin->entry_table + off);\n\t\t\t\t}\n\t\t\t}\n\t\t\toff += 2;\n\t\t\tr_list_append (entries, entry);\n\t\t}\n\t}\n\tr_list_free (segments);\n\tbin->entries = entries;\n\treturn entries;\n}", "func_hash": 128571297919304348712196386626162050665, "file_name": "ne.c", "file_hash": 267767472176864232009512780125221207666, "cwe": ["CWE-125"], "cve": "CVE-2022-1297", "cve_desc": "Out-of-bounds Read in r_bin_ne_get_entrypoints function in GitHub repository radareorg/radare2 prior to 5.6.8. This vulnerability may allow attackers to read sensitive information or cause a crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1297"}
{"idx": 285157, "project": "radare2", "commit_id": "0a557045476a2969c7079aec9eeb29d02f2809c6", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/0a557045476a2969c7079aec9eeb29d02f2809c6", "commit_message": "Fix oobread and unaligned casts in the NE entrypoint logic ##crash\n\n* Reported by @hmsec via huntr.dev\n* Reproducer: nepocaligns\n* BountyID: ec538fa4-06c6-4050-a141-f60153ddeaac", "target": 0, "func": "RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {\n\tif (!bin->entry_table) {\n\t\treturn NULL;\n\t}\n\tRList *entries = r_list_newf (free);\n\tif (!entries) {\n\t\treturn NULL;\n\t}\n\tRList *segments = r_bin_ne_get_segments (bin);\n\tif (!segments) {\n\t\tr_list_free (entries);\n\t\treturn NULL;\n\t}\n\tif (bin->ne_header->csEntryPoint) {\n\t\tRBinAddr *entry = R_NEW0 (RBinAddr);\n\t\tif (!entry) {\n\t\t\tr_list_free (entries);\n\t\t\treturn NULL;\n\t\t}\n\t\tentry->bits = 16;\n\t\tut32 entry_cs = bin->ne_header->csEntryPoint;\n\t\tRBinSection *s = r_list_get_n (segments, entry_cs - 1);\n\t\tentry->paddr = bin->ne_header->ipEntryPoint + (s? s->paddr: 0);\n\n\t\tr_list_append (entries, entry);\n\t}\n\tint off = 0;\n\tsize_t tableat = bin->header_offset + bin->ne_header->EntryTableOffset;\n\twhile (off < bin->ne_header->EntryTableLength) {\n\t\tif (tableat + off >= r_buf_size (bin->buf)) {\n\t\t\tbreak;\n\t\t}\n\t\tut8 bundle_length = *(ut8 *)(bin->entry_table + off);\n\t\tif (!bundle_length) {\n\t\t\tbreak;\n\t\t}\n\t\toff++;\n\t\tut8 bundle_type = *(ut8 *)(bin->entry_table + off);\n\t\toff++;\n\t\tint i;\n\t\tfor (i = 0; i < bundle_length; i++) {\n\t\t\tif (tableat + off + 4 >= r_buf_size (bin->buf)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tRBinAddr *entry = R_NEW0 (RBinAddr);\n\t\t\tif (!entry) {\n\t\t\t\tr_list_free (entries);\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\toff++;\n\t\t\tif (!bundle_type) { // Skip\n\t\t\t\toff--;\n\t\t\t\tfree (entry);\n\t\t\t\tbreak;\n\t\t\t} else if (bundle_type == 0xff) { // moveable\n\t\t\t\toff += 2;\n\t\t\t\tut8 segnum = *(bin->entry_table + off);\n\t\t\t\toff++;\n\t\t\t\tif (off > bin->ne_header->EntryTableLength) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tut16 segoff = r_read_le16 (bin->entry_table + off);\n\t\t\t\tif (segnum > 0 && segnum < bin->ne_header->SegCount) {\n\t\t\t\t\tentry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff;\n\t\t\t\t}\n\t\t\t} else { // Fixed\n\t\t\t\tif (off + 2 >= bin->ne_header->EntryTableLength) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tut16 delta = r_read_le16 (bin->entry_table + off);\n\t\t\t\tif (bundle_type < bin->ne_header->SegCount) {\n\t\t\t\t\tentry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset\n\t\t\t\t\t\t* bin->alignment + delta;\n\t\t\t\t}\n\t\t\t}\n\t\t\toff += 2;\n\t\t\tr_list_append (entries, entry);\n\t\t}\n\t}\n\tr_list_free (segments);\n\tbin->entries = entries;\n\treturn entries;\n}", "func_hash": 178596264562074967520508544999708304050, "file_name": "ne.c", "file_hash": 100978875788089844508151411517959063917, "cwe": ["CWE-125"], "cve": "CVE-2022-1297", "cve_desc": "Out-of-bounds Read in r_bin_ne_get_entrypoints function in GitHub repository radareorg/radare2 prior to 5.6.8. This vulnerability may allow attackers to read sensitive information or cause a crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1297"}
{"idx": 198983, "project": "swtpm", "commit_id": "9f740868fc36761de27df3935513bdebf8852d19", "project_url": "https://github.com/stefanberger/swtpm", "commit_url": "https://github.com/stefanberger/swtpm/commit/9f740868fc36761de27df3935513bdebf8852d19", "commit_message": "swtpm: Check header size indicator against expected size (CID 375869)\n\nThis fix addresses Coverity issue CID 375869.\n\nCheck the header size indicated in the header of the state against the\nexpected size and return an error code in case the header size indicator\nis different. There was only one header size so far since blobheader was\nintroduced, so we don't need to deal with different sizes.\n\nWithout this fix a specially craft header could have cause out-of-bounds\naccesses on the byte array containing the swtpm's state.\n\nSigned-off-by: Stefan Berger ", "target": 1, "func": "SWTPM_NVRAM_CheckHeader(unsigned char *data, uint32_t length,\n                        uint32_t *dataoffset, uint16_t *hdrflags,\n                        uint8_t *hdrversion, bool quiet)\n{\n    blobheader *bh = (blobheader *)data;\n\n    if (length < sizeof(bh)) {\n        if (!quiet)\n            logprintf(STDERR_FILENO,\n                      \"not enough bytes for header: %u\\n\", length);\n        return TPM_BAD_PARAMETER;\n    }\n\n    if (ntohl(bh->totlen) != length) {\n        if (!quiet)\n            logprintf(STDERR_FILENO,\n                      \"broken header: bh->totlen %u != %u\\n\",\n                      htonl(bh->totlen), length);\n        return TPM_BAD_PARAMETER;\n    }\n\n    if (bh->min_version > BLOB_HEADER_VERSION) {\n        if (!quiet)\n            logprintf(STDERR_FILENO,\n                      \"Minimum required version for the blob is %d, we \"\n                      \"only support version %d\\n\", bh->min_version,\n                      BLOB_HEADER_VERSION);\n        return TPM_BAD_VERSION;\n    }\n\n    *hdrversion = bh->version;\n    *dataoffset = ntohs(bh->hdrsize);\n    *hdrflags = ntohs(bh->flags);\n\n    return TPM_SUCCESS;\n}", "func_hash": 173394517357295307246184358296702159922, "file_name": "swtpm_nvfile.c", "file_hash": 132354630792840361852785968580616241078, "cwe": ["CWE-125"], "cve": "CVE-2022-23645", "cve_desc": "swtpm is a libtpms-based TPM emulator with socket, character device, and Linux CUSE interface. Versions prior to 0.5.3, 0.6.2, and 0.7.1 are vulnerable to out-of-bounds read. A specially crafted header of swtpm's state, where the blobheader's hdrsize indicator has an invalid value, may cause an out-of-bounds access when the byte array representing the state of the TPM is accessed. This will likely crash swtpm or prevent it from starting since the state cannot be understood. Users should upgrade to swtpm v0.5.3, v0.6.2, or v0.7.1 to receive a patch. There are currently no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23645"}
{"idx": 286739, "project": "swtpm", "commit_id": "9f740868fc36761de27df3935513bdebf8852d19", "project_url": "https://github.com/stefanberger/swtpm", "commit_url": "https://github.com/stefanberger/swtpm/commit/9f740868fc36761de27df3935513bdebf8852d19", "commit_message": "swtpm: Check header size indicator against expected size (CID 375869)\n\nThis fix addresses Coverity issue CID 375869.\n\nCheck the header size indicated in the header of the state against the\nexpected size and return an error code in case the header size indicator\nis different. There was only one header size so far since blobheader was\nintroduced, so we don't need to deal with different sizes.\n\nWithout this fix a specially craft header could have cause out-of-bounds\naccesses on the byte array containing the swtpm's state.\n\nSigned-off-by: Stefan Berger ", "target": 0, "func": "SWTPM_NVRAM_CheckHeader(unsigned char *data, uint32_t length,\n                        uint32_t *dataoffset, uint16_t *hdrflags,\n                        uint8_t *hdrversion, bool quiet)\n{\n    blobheader *bh = (blobheader *)data;\n    uint16_t hdrsize;\n\n    if (length < sizeof(bh)) {\n        if (!quiet)\n            logprintf(STDERR_FILENO,\n                      \"not enough bytes for header: %u\\n\", length);\n        return TPM_BAD_PARAMETER;\n    }\n\n    if (ntohl(bh->totlen) != length) {\n        if (!quiet)\n            logprintf(STDERR_FILENO,\n                      \"broken header: bh->totlen %u != %u\\n\",\n                      htonl(bh->totlen), length);\n        return TPM_BAD_PARAMETER;\n    }\n\n    if (bh->min_version > BLOB_HEADER_VERSION) {\n        if (!quiet)\n            logprintf(STDERR_FILENO,\n                      \"Minimum required version for the blob is %d, we \"\n                      \"only support version %d\\n\", bh->min_version,\n                      BLOB_HEADER_VERSION);\n        return TPM_BAD_VERSION;\n    }\n\n    hdrsize = ntohs(bh->hdrsize);\n    if (hdrsize != sizeof(blobheader)) {\n        logprintf(STDERR_FILENO,\n                  \"bad header size: %u != %zu\\n\",\n                  hdrsize, sizeof(blobheader));\n        return TPM_BAD_DATASIZE;\n    }\n\n    *hdrversion = bh->version;\n    *dataoffset = hdrsize;\n    *hdrflags = ntohs(bh->flags);\n\n    return TPM_SUCCESS;\n}", "func_hash": 285282572007511982258600873303228604021, "file_name": "swtpm_nvstore.c", "file_hash": 83066481150728701283019472792244832496, "cwe": ["CWE-125"], "cve": "CVE-2022-23645", "cve_desc": "swtpm is a libtpms-based TPM emulator with socket, character device, and Linux CUSE interface. Versions prior to 0.5.3, 0.6.2, and 0.7.1 are vulnerable to out-of-bounds read. A specially crafted header of swtpm's state, where the blobheader's hdrsize indicator has an invalid value, may cause an out-of-bounds access when the byte array representing the state of the TPM is accessed. This will likely crash swtpm or prevent it from starting since the state cannot be understood. Users should upgrade to swtpm v0.5.3, v0.6.2, or v0.7.1 to receive a patch. There are currently no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-23645"}
{"idx": 199159, "project": "linux", "commit_id": "8423f0b6d513b259fdab9c9bf4aaa6188d054c2d", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=8423f0b6d513b259fdab9c9bf4aaa6188d054c2d", "commit_message": "ALSA: pcm: oss: Fix race at SNDCTL_DSP_SYNC\n\nThere is a small race window at snd_pcm_oss_sync() that is called from\nOSS PCM SNDCTL_DSP_SYNC ioctl; namely the function calls\nsnd_pcm_oss_make_ready() at first, then takes the params_lock mutex\nfor the rest.  When the stream is set up again by another thread\nbetween them, it leads to inconsistency, and may result in unexpected\nresults such as NULL dereference of OSS buffer as a fuzzer spotted\nrecently.\n\nThe fix is simply to cover snd_pcm_oss_make_ready() call into the same\nparams_lock mutex with snd_pcm_oss_make_ready_locked() variant.\n\nReported-and-tested-by: butt3rflyh4ck \nReviewed-by: Jaroslav Kysela \nCc: \nLink: https://lore.kernel.org/r/CAFcO6XN7JDM4xSXGhtusQfS2mSBcx50VJKwQpCq=WeLt57aaZA@mail.gmail.com\nLink: https://lore.kernel.org/r/20220905060714.22549-1-tiwai@suse.de\nSigned-off-by: Takashi Iwai ", "target": 1, "func": "static int snd_pcm_oss_sync(struct snd_pcm_oss_file *pcm_oss_file)\n{\n\tint err = 0;\n\tunsigned int saved_f_flags;\n\tstruct snd_pcm_substream *substream;\n\tstruct snd_pcm_runtime *runtime;\n\tsnd_pcm_format_t format;\n\tunsigned long width;\n\tsize_t size;\n\n\tsubstream = pcm_oss_file->streams[SNDRV_PCM_STREAM_PLAYBACK];\n\tif (substream != NULL) {\n\t\truntime = substream->runtime;\n\t\tif (atomic_read(&substream->mmap_count))\n\t\t\tgoto __direct;\n\t\terr = snd_pcm_oss_make_ready(substream);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t\tatomic_inc(&runtime->oss.rw_ref);\n\t\tif (mutex_lock_interruptible(&runtime->oss.params_lock)) {\n\t\t\tatomic_dec(&runtime->oss.rw_ref);\n\t\t\treturn -ERESTARTSYS;\n\t\t}\n\t\tformat = snd_pcm_oss_format_from(runtime->oss.format);\n\t\twidth = snd_pcm_format_physical_width(format);\n\t\tif (runtime->oss.buffer_used > 0) {\n#ifdef OSS_DEBUG\n\t\t\tpcm_dbg(substream->pcm, \"sync: buffer_used\\n\");\n#endif\n\t\t\tsize = (8 * (runtime->oss.period_bytes - runtime->oss.buffer_used) + 7) / width;\n\t\t\tsnd_pcm_format_set_silence(format,\n\t\t\t\t\t\t   runtime->oss.buffer + runtime->oss.buffer_used,\n\t\t\t\t\t\t   size);\n\t\t\terr = snd_pcm_oss_sync1(substream, runtime->oss.period_bytes);\n\t\t\tif (err < 0)\n\t\t\t\tgoto unlock;\n\t\t} else if (runtime->oss.period_ptr > 0) {\n#ifdef OSS_DEBUG\n\t\t\tpcm_dbg(substream->pcm, \"sync: period_ptr\\n\");\n#endif\n\t\t\tsize = runtime->oss.period_bytes - runtime->oss.period_ptr;\n\t\t\tsnd_pcm_format_set_silence(format,\n\t\t\t\t\t\t   runtime->oss.buffer,\n\t\t\t\t\t\t   size * 8 / width);\n\t\t\terr = snd_pcm_oss_sync1(substream, size);\n\t\t\tif (err < 0)\n\t\t\t\tgoto unlock;\n\t\t}\n\t\t/*\n\t\t * The ALSA's period might be a bit large than OSS one.\n\t\t * Fill the remain portion of ALSA period with zeros.\n\t\t */\n\t\tsize = runtime->control->appl_ptr % runtime->period_size;\n\t\tif (size > 0) {\n\t\t\tsize = runtime->period_size - size;\n\t\t\tif (runtime->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED)\n\t\t\t\tsnd_pcm_lib_write(substream, NULL, size);\n\t\t\telse if (runtime->access == SNDRV_PCM_ACCESS_RW_NONINTERLEAVED)\n\t\t\t\tsnd_pcm_lib_writev(substream, NULL, size);\n\t\t}\nunlock:\n\t\tmutex_unlock(&runtime->oss.params_lock);\n\t\tatomic_dec(&runtime->oss.rw_ref);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t\t/*\n\t\t * finish sync: drain the buffer\n\t\t */\n\t      __direct:\n\t\tsaved_f_flags = substream->f_flags;\n\t\tsubstream->f_flags &= ~O_NONBLOCK;\n\t\terr = snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_DRAIN, NULL);\n\t\tsubstream->f_flags = saved_f_flags;\n\t\tif (err < 0)\n\t\t\treturn err;\n\t\tmutex_lock(&runtime->oss.params_lock);\n\t\truntime->oss.prepare = 1;\n\t\tmutex_unlock(&runtime->oss.params_lock);\n\t}\n\n\tsubstream = pcm_oss_file->streams[SNDRV_PCM_STREAM_CAPTURE];\n\tif (substream != NULL) {\n\t\terr = snd_pcm_oss_make_ready(substream);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t\truntime = substream->runtime;\n\t\terr = snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_DROP, NULL);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t\tmutex_lock(&runtime->oss.params_lock);\n\t\truntime->oss.buffer_used = 0;\n\t\truntime->oss.prepare = 1;\n\t\tmutex_unlock(&runtime->oss.params_lock);\n\t}\n\treturn 0;\n}", "func_hash": 331549555245265175479800423924118181234, "file_name": "None", "file_hash": null, "cwe": ["CWE-362"], "cve": "CVE-2022-3303", "cve_desc": "A race condition flaw was found in the Linux kernel sound subsystem due to improper locking. It could lead to a NULL pointer dereference while handling the SNDCTL_DSP_SYNC ioctl. A privileged local user (root or member of the audio group) could use this flaw to crash the system, resulting in a denial of service condition", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3303"}
{"idx": 289293, "project": "linux", "commit_id": "8423f0b6d513b259fdab9c9bf4aaa6188d054c2d", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=8423f0b6d513b259fdab9c9bf4aaa6188d054c2d", "commit_message": "ALSA: pcm: oss: Fix race at SNDCTL_DSP_SYNC\n\nThere is a small race window at snd_pcm_oss_sync() that is called from\nOSS PCM SNDCTL_DSP_SYNC ioctl; namely the function calls\nsnd_pcm_oss_make_ready() at first, then takes the params_lock mutex\nfor the rest.  When the stream is set up again by another thread\nbetween them, it leads to inconsistency, and may result in unexpected\nresults such as NULL dereference of OSS buffer as a fuzzer spotted\nrecently.\n\nThe fix is simply to cover snd_pcm_oss_make_ready() call into the same\nparams_lock mutex with snd_pcm_oss_make_ready_locked() variant.\n\nReported-and-tested-by: butt3rflyh4ck \nReviewed-by: Jaroslav Kysela \nCc: \nLink: https://lore.kernel.org/r/CAFcO6XN7JDM4xSXGhtusQfS2mSBcx50VJKwQpCq=WeLt57aaZA@mail.gmail.com\nLink: https://lore.kernel.org/r/20220905060714.22549-1-tiwai@suse.de\nSigned-off-by: Takashi Iwai ", "target": 0, "func": "static int snd_pcm_oss_sync(struct snd_pcm_oss_file *pcm_oss_file)\n{\n\tint err = 0;\n\tunsigned int saved_f_flags;\n\tstruct snd_pcm_substream *substream;\n\tstruct snd_pcm_runtime *runtime;\n\tsnd_pcm_format_t format;\n\tunsigned long width;\n\tsize_t size;\n\n\tsubstream = pcm_oss_file->streams[SNDRV_PCM_STREAM_PLAYBACK];\n\tif (substream != NULL) {\n\t\truntime = substream->runtime;\n\t\tif (atomic_read(&substream->mmap_count))\n\t\t\tgoto __direct;\n\t\tatomic_inc(&runtime->oss.rw_ref);\n\t\tif (mutex_lock_interruptible(&runtime->oss.params_lock)) {\n\t\t\tatomic_dec(&runtime->oss.rw_ref);\n\t\t\treturn -ERESTARTSYS;\n\t\t}\n\t\terr = snd_pcm_oss_make_ready_locked(substream);\n\t\tif (err < 0)\n\t\t\tgoto unlock;\n\t\tformat = snd_pcm_oss_format_from(runtime->oss.format);\n\t\twidth = snd_pcm_format_physical_width(format);\n\t\tif (runtime->oss.buffer_used > 0) {\n#ifdef OSS_DEBUG\n\t\t\tpcm_dbg(substream->pcm, \"sync: buffer_used\\n\");\n#endif\n\t\t\tsize = (8 * (runtime->oss.period_bytes - runtime->oss.buffer_used) + 7) / width;\n\t\t\tsnd_pcm_format_set_silence(format,\n\t\t\t\t\t\t   runtime->oss.buffer + runtime->oss.buffer_used,\n\t\t\t\t\t\t   size);\n\t\t\terr = snd_pcm_oss_sync1(substream, runtime->oss.period_bytes);\n\t\t\tif (err < 0)\n\t\t\t\tgoto unlock;\n\t\t} else if (runtime->oss.period_ptr > 0) {\n#ifdef OSS_DEBUG\n\t\t\tpcm_dbg(substream->pcm, \"sync: period_ptr\\n\");\n#endif\n\t\t\tsize = runtime->oss.period_bytes - runtime->oss.period_ptr;\n\t\t\tsnd_pcm_format_set_silence(format,\n\t\t\t\t\t\t   runtime->oss.buffer,\n\t\t\t\t\t\t   size * 8 / width);\n\t\t\terr = snd_pcm_oss_sync1(substream, size);\n\t\t\tif (err < 0)\n\t\t\t\tgoto unlock;\n\t\t}\n\t\t/*\n\t\t * The ALSA's period might be a bit large than OSS one.\n\t\t * Fill the remain portion of ALSA period with zeros.\n\t\t */\n\t\tsize = runtime->control->appl_ptr % runtime->period_size;\n\t\tif (size > 0) {\n\t\t\tsize = runtime->period_size - size;\n\t\t\tif (runtime->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED)\n\t\t\t\tsnd_pcm_lib_write(substream, NULL, size);\n\t\t\telse if (runtime->access == SNDRV_PCM_ACCESS_RW_NONINTERLEAVED)\n\t\t\t\tsnd_pcm_lib_writev(substream, NULL, size);\n\t\t}\nunlock:\n\t\tmutex_unlock(&runtime->oss.params_lock);\n\t\tatomic_dec(&runtime->oss.rw_ref);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t\t/*\n\t\t * finish sync: drain the buffer\n\t\t */\n\t      __direct:\n\t\tsaved_f_flags = substream->f_flags;\n\t\tsubstream->f_flags &= ~O_NONBLOCK;\n\t\terr = snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_DRAIN, NULL);\n\t\tsubstream->f_flags = saved_f_flags;\n\t\tif (err < 0)\n\t\t\treturn err;\n\t\tmutex_lock(&runtime->oss.params_lock);\n\t\truntime->oss.prepare = 1;\n\t\tmutex_unlock(&runtime->oss.params_lock);\n\t}\n\n\tsubstream = pcm_oss_file->streams[SNDRV_PCM_STREAM_CAPTURE];\n\tif (substream != NULL) {\n\t\terr = snd_pcm_oss_make_ready(substream);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t\truntime = substream->runtime;\n\t\terr = snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_DROP, NULL);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t\tmutex_lock(&runtime->oss.params_lock);\n\t\truntime->oss.buffer_used = 0;\n\t\truntime->oss.prepare = 1;\n\t\tmutex_unlock(&runtime->oss.params_lock);\n\t}\n\treturn 0;\n}", "func_hash": 1326761650975653611382443550395595187, "file_name": "None", "file_hash": null, "cwe": ["CWE-362"], "cve": "CVE-2022-3303", "cve_desc": "A race condition flaw was found in the Linux kernel sound subsystem due to improper locking. It could lead to a NULL pointer dereference while handling the SNDCTL_DSP_SYNC ioctl. A privileged local user (root or member of the audio group) could use this flaw to crash the system, resulting in a denial of service condition", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3303"}
{"idx": 199712, "project": "linux", "commit_id": "8700af2cc18c919b2a83e74e0479038fd113c15d", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/8700af2cc18c919b2a83e74e0479038fd113c15d", "commit_message": "RDMA/rtrs-clt: Fix possible double free in error case\n\nCallback function rtrs_clt_dev_release() for put_device() calls kfree(clt)\nto free memory. We shouldn't call kfree(clt) again, and we can't use the\nclt after kfree too.\n\nReplace device_register() with device_initialize() and device_add() so that\ndev_set_name can() be used appropriately.\n\nMove mutex_destroy() to the release function so it can be called in\nthe alloc_clt err path.\n\nFixes: eab098246625 (\"RDMA/rtrs-clt: Refactor the failure cases in alloc_clt\")\nLink: https://lore.kernel.org/r/20220217030929.323849-1-haris.iqbal@ionos.com\nReported-by: Miaoqian Lin \nSigned-off-by: Md Haris Iqbal \nReviewed-by: Jack Wang \nSigned-off-by: Jason Gunthorpe ", "target": 1, "func": "static void rtrs_clt_dev_release(struct device *dev)\n{\n\tstruct rtrs_clt_sess *clt = container_of(dev, struct rtrs_clt_sess,\n\t\t\t\t\t\t dev);\n\n\tkfree(clt);\n}", "func_hash": 64652297556654438298355501352205556509, "file_name": "rtrs-clt.c", "file_hash": 149775209474441169700962555059878991264, "cwe": ["CWE-415"], "cve": "CVE-2022-29156", "cve_desc": "drivers/infiniband/ulp/rtrs/rtrs-clt.c in the Linux kernel before 5.16.12 has a double free related to rtrs_clt_dev_release.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29156"}
{"idx": 291761, "project": "linux", "commit_id": "8700af2cc18c919b2a83e74e0479038fd113c15d", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/8700af2cc18c919b2a83e74e0479038fd113c15d", "commit_message": "RDMA/rtrs-clt: Fix possible double free in error case\n\nCallback function rtrs_clt_dev_release() for put_device() calls kfree(clt)\nto free memory. We shouldn't call kfree(clt) again, and we can't use the\nclt after kfree too.\n\nReplace device_register() with device_initialize() and device_add() so that\ndev_set_name can() be used appropriately.\n\nMove mutex_destroy() to the release function so it can be called in\nthe alloc_clt err path.\n\nFixes: eab098246625 (\"RDMA/rtrs-clt: Refactor the failure cases in alloc_clt\")\nLink: https://lore.kernel.org/r/20220217030929.323849-1-haris.iqbal@ionos.com\nReported-by: Miaoqian Lin \nSigned-off-by: Md Haris Iqbal \nReviewed-by: Jack Wang \nSigned-off-by: Jason Gunthorpe ", "target": 0, "func": "static void rtrs_clt_dev_release(struct device *dev)\n{\n\tstruct rtrs_clt_sess *clt = container_of(dev, struct rtrs_clt_sess,\n\t\t\t\t\t\t dev);\n\n\tmutex_destroy(&clt->paths_ev_mutex);\n\tmutex_destroy(&clt->paths_mutex);\n\tkfree(clt);\n}", "func_hash": 280791422344483990445186805760516988921, "file_name": "rtrs-clt.c", "file_hash": 123062054699569722257369072160789726422, "cwe": ["CWE-415"], "cve": "CVE-2022-29156", "cve_desc": "drivers/infiniband/ulp/rtrs/rtrs-clt.c in the Linux kernel before 5.16.12 has a double free related to rtrs_clt_dev_release.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29156"}
{"idx": 199767, "project": "hexchat", "commit_id": "4e061a43b3453a9856d34250c3913175c45afe9d", "project_url": "https://github.com/hexchat/hexchat", "commit_url": "https://github.com/hexchat/hexchat/commit/4e061a43b3453a9856d34250c3913175c45afe9d", "commit_message": "Clean up handling CAP LS", "target": 1, "func": "inbound_cap_ls (server *serv, char *nick, char *extensions_str,\n\t\t\t\t\t const message_tags_data *tags_data)\n{\n\tchar buffer[256];\t/* buffer for requesting capabilities and emitting the signal */\n\tguint32 want_cap; /* format the CAP REQ string based on previous capabilities being requested or not */\n\tguint32 want_sasl; /* CAP END shouldn't be sent when SASL is requested, it needs further responses */\n\tchar **extensions;\n\tint i;\n\n\tEMIT_SIGNAL_TIMESTAMP (XP_TE_CAPLIST, serv->server_session, nick,\n\t\t\t\t\t\t\t\t  extensions_str, NULL, NULL, 0, tags_data->timestamp);\n\twant_cap = 0;\n\twant_sasl = 0;\n\n\textensions = g_strsplit (extensions_str, \" \", 0);\n\n\tstrcpy (buffer, \"CAP REQ :\");\n\n\tfor (i=0; extensions[i]; i++)\n\t{\n\t\tconst char *extension = extensions[i];\n\n\t\tif (!strcmp (extension, \"identify-msg\"))\n\t\t{\n\t\t\tstrcat (buffer, \"identify-msg \");\n\t\t\twant_cap = 1;\n\t\t}\n\t\tif (!strcmp (extension, \"multi-prefix\"))\n\t\t{\n\t\t\tstrcat (buffer, \"multi-prefix \");\n\t\t\twant_cap = 1;\n\t\t}\n\t\tif (!strcmp (extension, \"away-notify\"))\n\t\t{\n\t\t\tstrcat (buffer, \"away-notify \");\n\t\t\twant_cap = 1;\n\t\t}\n\t\tif (!strcmp (extension, \"account-notify\"))\n\t\t{\n\t\t\tstrcat (buffer, \"account-notify \");\n\t\t\twant_cap = 1;\n\t\t}\n\t\tif (!strcmp (extension, \"extended-join\"))\n\t\t{\n\t\t\tstrcat (buffer, \"extended-join \");\n\t\t\twant_cap = 1;\n\t\t}\n\t\tif (!strcmp (extension, \"userhost-in-names\"))\n\t\t{\n\t\t\tstrcat (buffer, \"userhost-in-names \");\n\t\t\twant_cap = 1;\n\t\t}\n\n\t\t/* bouncers can prefix a name space to the extension so we should use.\n\t\t * znc <= 1.0 uses \"znc.in/server-time\" and newer use \"znc.in/server-time-iso\".\n\t\t */\n\t\tif (!strcmp (extension, \"znc.in/server-time-iso\"))\n\t\t{\n\t\t\tstrcat (buffer, \"znc.in/server-time-iso \");\n\t\t\twant_cap = 1;\n\t\t}\n\t\tif (!strcmp (extension, \"znc.in/server-time\"))\n\t\t{\n\t\t\tstrcat (buffer, \"znc.in/server-time \");\n\t\t\twant_cap = 1;\n\t\t}\n\t\tif (prefs.hex_irc_cap_server_time\n\t\t\t && !strcmp (extension, \"server-time\"))\n\t\t{\n\t\t\tstrcat (buffer, \"server-time \");\n\t\t\twant_cap = 1;\n\t\t}\n\t\t\n\t\t/* if the SASL password is set AND auth mode is set to SASL, request SASL auth */\n\t\tif (!strcmp (extension, \"sasl\")\n\t\t\t&& ((serv->loginmethod == LOGIN_SASL && strlen (serv->password) != 0)\n\t\t\t|| (serv->loginmethod == LOGIN_SASLEXTERNAL && serv->have_cert)))\n\t\t{\n\t\t\tstrcat (buffer, \"sasl \");\n\t\t\twant_cap = 1;\n\t\t\twant_sasl = 1;\n\t\t}\n\t}\n\n\tg_strfreev (extensions);\n\n\tif (want_cap)\n\t{\n\t\t/* buffer + 9 = emit buffer without \"CAP REQ :\" */\n\t\tEMIT_SIGNAL_TIMESTAMP (XP_TE_CAPREQ, serv->server_session,\n\t\t\t\t\t\t\t\t\t  buffer + 9, NULL, NULL, NULL, 0,\n\t\t\t\t\t\t\t\t\t  tags_data->timestamp);\n\t\ttcp_sendf (serv, \"%s\\r\\n\", g_strchomp (buffer));\n\t}\n\tif (!want_sasl)\n\t{\n\t\t/* if we use SASL, CAP END is dealt via raw numerics */\n\t\tserv->sent_capend = TRUE;\n\t\ttcp_send_len (serv, \"CAP END\\r\\n\", 9);\n\t}\n}", "func_hash": 289376674180826741553106169575003472652, "file_name": "inbound.c", "file_hash": 202497518967624726910452754426675896941, "cwe": ["CWE-22"], "cve": "CVE-2016-2087", "cve_desc": "Directory traversal vulnerability in the client in HexChat 2.11.0 allows remote IRC servers to read or modify arbitrary files via a .. (dot dot) in the server name.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-2087"}
{"idx": 292205, "project": "hexchat", "commit_id": "4e061a43b3453a9856d34250c3913175c45afe9d", "project_url": "https://github.com/hexchat/hexchat", "commit_url": "https://github.com/hexchat/hexchat/commit/4e061a43b3453a9856d34250c3913175c45afe9d", "commit_message": "Clean up handling CAP LS", "target": 0, "func": "inbound_cap_ls (server *serv, char *nick, char *extensions_str,\n\t\t\t\t\t const message_tags_data *tags_data)\n{\n\tchar buffer[256];\t/* buffer for requesting capabilities and emitting the signal */\n\tgboolean want_cap = FALSE; /* format the CAP REQ string based on previous capabilities being requested or not */\n\tgboolean want_sasl = FALSE; /* CAP END shouldn't be sent when SASL is requested, it needs further responses */\n\tchar **extensions;\n\tint i;\n\n\tEMIT_SIGNAL_TIMESTAMP (XP_TE_CAPLIST, serv->server_session, nick,\n\t\t\t\t\t\t\t\t  extensions_str, NULL, NULL, 0, tags_data->timestamp);\n\n\textensions = g_strsplit (extensions_str, \" \", 0);\n\n\tstrcpy (buffer, \"CAP REQ :\");\n\n\tfor (i=0; extensions[i]; i++)\n\t{\n\t\tconst char *extension = extensions[i];\n\t\tgsize x;\n\n\t\t/* if the SASL password is set AND auth mode is set to SASL, request SASL auth */\n\t\tif (!g_strcmp0 (extension, \"sasl\") &&\n\t\t\t((serv->loginmethod == LOGIN_SASL && strlen (serv->password) != 0)\n\t\t\t\t|| (serv->loginmethod == LOGIN_SASLEXTERNAL && serv->have_cert)))\n\t\t{\n\t\t\twant_cap = TRUE;\n\t\t\twant_sasl = TRUE;\n\t\t\tg_strlcat (buffer, \"sasl \", sizeof(buffer));\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor (x = 0; x < G_N_ELEMENTS(supported_caps); ++x)\n\t\t{\n\t\t\tif (!g_strcmp0 (extension, supported_caps[x]))\n\t\t\t{\n\t\t\t\tg_strlcat (buffer, extension, sizeof(buffer));\n\t\t\t\tg_strlcat (buffer, \" \", sizeof(buffer));\n\t\t\t\twant_cap = TRUE;\n\t\t\t}\n\t\t}\n\t}\n\n\tg_strfreev (extensions);\n\n\tif (want_cap)\n\t{\n\t\t/* buffer + 9 = emit buffer without \"CAP REQ :\" */\n\t\tEMIT_SIGNAL_TIMESTAMP (XP_TE_CAPREQ, serv->server_session,\n\t\t\t\t\t\t\t\t\t  buffer + 9, NULL, NULL, NULL, 0,\n\t\t\t\t\t\t\t\t\t  tags_data->timestamp);\n\t\ttcp_sendf (serv, \"%s\\r\\n\", g_strchomp (buffer));\n\t}\n\tif (!want_sasl)\n\t{\n\t\t/* if we use SASL, CAP END is dealt via raw numerics */\n\t\tserv->sent_capend = TRUE;\n\t\ttcp_send_len (serv, \"CAP END\\r\\n\", 9);\n\t}\n}", "func_hash": 298030143557811243277605801674004119778, "file_name": "inbound.c", "file_hash": 316287172279434102312310467592869221678, "cwe": ["CWE-22"], "cve": "CVE-2016-2087", "cve_desc": "Directory traversal vulnerability in the client in HexChat 2.11.0 allows remote IRC servers to read or modify arbitrary files via a .. (dot dot) in the server name.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-2087"}
{"idx": 199778, "project": "puma", "commit_id": "acdc3ae571dfae0e045cf09a295280127db65c7f", "project_url": "https://github.com/puma/puma", "commit_url": "https://github.com/puma/puma/commit/acdc3ae571dfae0e045cf09a295280127db65c7f", "commit_message": "Merge pull request from GHSA-48w2-rm65-62xx\n\n* Fix HTTP request smuggling vulnerability\n\nSee GHSA-48w2-rm65-62xx or CVE-2021-41136 for more info.\n\n* 4.3.9 release note\n\n* 5.5.1 release note\n\n* 5.5.1", "target": 1, "func": "size_t puma_parser_execute(puma_parser *parser, const char *buffer, size_t len, size_t off)  {\n  const char *p, *pe;\n  int cs = parser->cs;\n\n  assert(off <= len && \"offset past end of buffer\");\n\n  p = buffer+off;\n  pe = buffer+len;\n\n  /* assert(*pe == '\\0' && \"pointer does not end on NUL\"); */\n  assert((size_t) (pe - p) == len - off && \"pointers aren't same distance\");\n\n  \n#line 87 \"ext/puma_http11/http11_parser.c\"\n\t{\n\tif ( p == pe )\n\t\tgoto _test_eof;\n\tswitch ( cs )\n\t{\ncase 1:\n\tswitch( (*p) ) {\n\t\tcase 36: goto tr0;\n\t\tcase 95: goto tr0;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto tr0;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto tr0;\n\t} else\n\t\tgoto tr0;\n\tgoto st0;\nst0:\ncs = 0;\n\tgoto _out;\ntr0:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st2;\nst2:\n\tif ( ++p == pe )\n\t\tgoto _test_eof2;\ncase 2:\n#line 118 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st27;\n\t\tcase 95: goto st27;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st27;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st27;\n\t} else\n\t\tgoto st27;\n\tgoto st0;\ntr2:\n#line 50 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_method(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st3;\nst3:\n\tif ( ++p == pe )\n\t\tgoto _test_eof3;\ncase 3:\n#line 143 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 42: goto tr4;\n\t\tcase 43: goto tr5;\n\t\tcase 47: goto tr6;\n\t\tcase 58: goto tr7;\n\t}\n\tif ( (*p) < 65 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 57 )\n\t\t\tgoto tr5;\n\t} else if ( (*p) > 90 ) {\n\t\tif ( 97 <= (*p) && (*p) <= 122 )\n\t\t\tgoto tr5;\n\t} else\n\t\tgoto tr5;\n\tgoto st0;\ntr4:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st4;\nst4:\n\tif ( ++p == pe )\n\t\tgoto _test_eof4;\ncase 4:\n#line 167 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr8;\n\t\tcase 35: goto tr9;\n\t}\n\tgoto st0;\ntr8:\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st5;\ntr31:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n#line 56 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->fragment(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st5;\ntr33:\n#line 56 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->fragment(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st5;\ntr37:\n#line 69 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_path(parser, PTR_TO(mark), LEN(mark,p));\n  }\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st5;\ntr41:\n#line 60 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(query_start, p); }\n#line 61 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p));\n  }\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st5;\ntr44:\n#line 61 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p));\n  }\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st5;\nst5:\n\tif ( ++p == pe )\n\t\tgoto _test_eof5;\ncase 5:\n#line 229 \"ext/puma_http11/http11_parser.c\"\n\tif ( (*p) == 72 )\n\t\tgoto tr10;\n\tgoto st0;\ntr10:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st6;\nst6:\n\tif ( ++p == pe )\n\t\tgoto _test_eof6;\ncase 6:\n#line 241 \"ext/puma_http11/http11_parser.c\"\n\tif ( (*p) == 84 )\n\t\tgoto st7;\n\tgoto st0;\nst7:\n\tif ( ++p == pe )\n\t\tgoto _test_eof7;\ncase 7:\n\tif ( (*p) == 84 )\n\t\tgoto st8;\n\tgoto st0;\nst8:\n\tif ( ++p == pe )\n\t\tgoto _test_eof8;\ncase 8:\n\tif ( (*p) == 80 )\n\t\tgoto st9;\n\tgoto st0;\nst9:\n\tif ( ++p == pe )\n\t\tgoto _test_eof9;\ncase 9:\n\tif ( (*p) == 47 )\n\t\tgoto st10;\n\tgoto st0;\nst10:\n\tif ( ++p == pe )\n\t\tgoto _test_eof10;\ncase 10:\n\tif ( 48 <= (*p) && (*p) <= 57 )\n\t\tgoto st11;\n\tgoto st0;\nst11:\n\tif ( ++p == pe )\n\t\tgoto _test_eof11;\ncase 11:\n\tif ( (*p) == 46 )\n\t\tgoto st12;\n\tif ( 48 <= (*p) && (*p) <= 57 )\n\t\tgoto st11;\n\tgoto st0;\nst12:\n\tif ( ++p == pe )\n\t\tgoto _test_eof12;\ncase 12:\n\tif ( 48 <= (*p) && (*p) <= 57 )\n\t\tgoto st13;\n\tgoto st0;\nst13:\n\tif ( ++p == pe )\n\t\tgoto _test_eof13;\ncase 13:\n\tif ( (*p) == 13 )\n\t\tgoto tr18;\n\tif ( 48 <= (*p) && (*p) <= 57 )\n\t\tgoto st13;\n\tgoto st0;\ntr18:\n#line 65 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->http_version(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st14;\ntr26:\n#line 46 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n#line 47 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->http_field(parser, PTR_TO(field_start), parser->field_len, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st14;\ntr29:\n#line 47 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->http_field(parser, PTR_TO(field_start), parser->field_len, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st14;\nst14:\n\tif ( ++p == pe )\n\t\tgoto _test_eof14;\ncase 14:\n#line 322 \"ext/puma_http11/http11_parser.c\"\n\tif ( (*p) == 10 )\n\t\tgoto st15;\n\tgoto st0;\nst15:\n\tif ( ++p == pe )\n\t\tgoto _test_eof15;\ncase 15:\n\tswitch( (*p) ) {\n\t\tcase 13: goto st16;\n\t\tcase 33: goto tr21;\n\t\tcase 124: goto tr21;\n\t\tcase 126: goto tr21;\n\t}\n\tif ( (*p) < 45 ) {\n\t\tif ( (*p) > 39 ) {\n\t\t\tif ( 42 <= (*p) && (*p) <= 43 )\n\t\t\t\tgoto tr21;\n\t\t} else if ( (*p) >= 35 )\n\t\t\tgoto tr21;\n\t} else if ( (*p) > 46 ) {\n\t\tif ( (*p) < 65 ) {\n\t\t\tif ( 48 <= (*p) && (*p) <= 57 )\n\t\t\t\tgoto tr21;\n\t\t} else if ( (*p) > 90 ) {\n\t\t\tif ( 94 <= (*p) && (*p) <= 122 )\n\t\t\t\tgoto tr21;\n\t\t} else\n\t\t\tgoto tr21;\n\t} else\n\t\tgoto tr21;\n\tgoto st0;\nst16:\n\tif ( ++p == pe )\n\t\tgoto _test_eof16;\ncase 16:\n\tif ( (*p) == 10 )\n\t\tgoto tr22;\n\tgoto st0;\ntr22:\n#line 73 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->body_start = p - buffer + 1;\n    parser->header_done(parser, p + 1, pe - p - 1);\n    {p++; cs = 46; goto _out;}\n  }\n\tgoto st46;\nst46:\n\tif ( ++p == pe )\n\t\tgoto _test_eof46;\ncase 46:\n#line 373 \"ext/puma_http11/http11_parser.c\"\n\tgoto st0;\ntr21:\n#line 40 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(field_start, p); }\n#line 41 \"ext/puma_http11/http11_parser.rl\"\n\t{ snake_upcase_char((char *)p); }\n\tgoto st17;\ntr23:\n#line 41 \"ext/puma_http11/http11_parser.rl\"\n\t{ snake_upcase_char((char *)p); }\n\tgoto st17;\nst17:\n\tif ( ++p == pe )\n\t\tgoto _test_eof17;\ncase 17:\n#line 389 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 33: goto tr23;\n\t\tcase 58: goto tr24;\n\t\tcase 124: goto tr23;\n\t\tcase 126: goto tr23;\n\t}\n\tif ( (*p) < 45 ) {\n\t\tif ( (*p) > 39 ) {\n\t\t\tif ( 42 <= (*p) && (*p) <= 43 )\n\t\t\t\tgoto tr23;\n\t\t} else if ( (*p) >= 35 )\n\t\t\tgoto tr23;\n\t} else if ( (*p) > 46 ) {\n\t\tif ( (*p) < 65 ) {\n\t\t\tif ( 48 <= (*p) && (*p) <= 57 )\n\t\t\t\tgoto tr23;\n\t\t} else if ( (*p) > 90 ) {\n\t\t\tif ( 94 <= (*p) && (*p) <= 122 )\n\t\t\t\tgoto tr23;\n\t\t} else\n\t\t\tgoto tr23;\n\t} else\n\t\tgoto tr23;\n\tgoto st0;\ntr24:\n#line 42 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->field_len = LEN(field_start, p);\n  }\n\tgoto st18;\ntr27:\n#line 46 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st18;\nst18:\n\tif ( ++p == pe )\n\t\tgoto _test_eof18;\ncase 18:\n#line 428 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 13: goto tr26;\n\t\tcase 32: goto tr27;\n\t}\n\tgoto tr25;\ntr25:\n#line 46 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st19;\nst19:\n\tif ( ++p == pe )\n\t\tgoto _test_eof19;\ncase 19:\n#line 442 \"ext/puma_http11/http11_parser.c\"\n\tif ( (*p) == 13 )\n\t\tgoto tr29;\n\tgoto st19;\ntr9:\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st20;\ntr38:\n#line 69 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_path(parser, PTR_TO(mark), LEN(mark,p));\n  }\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st20;\ntr42:\n#line 60 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(query_start, p); }\n#line 61 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p));\n  }\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st20;\ntr45:\n#line 61 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p));\n  }\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st20;\nst20:\n\tif ( ++p == pe )\n\t\tgoto _test_eof20;\ncase 20:\n#line 488 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr31;\n\t\tcase 60: goto st0;\n\t\tcase 62: goto st0;\n\t\tcase 127: goto st0;\n\t}\n\tif ( (*p) > 31 ) {\n\t\tif ( 34 <= (*p) && (*p) <= 35 )\n\t\t\tgoto st0;\n\t} else if ( (*p) >= 0 )\n\t\tgoto st0;\n\tgoto tr30;\ntr30:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st21;\nst21:\n\tif ( ++p == pe )\n\t\tgoto _test_eof21;\ncase 21:\n#line 509 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr33;\n\t\tcase 60: goto st0;\n\t\tcase 62: goto st0;\n\t\tcase 127: goto st0;\n\t}\n\tif ( (*p) > 31 ) {\n\t\tif ( 34 <= (*p) && (*p) <= 35 )\n\t\t\tgoto st0;\n\t} else if ( (*p) >= 0 )\n\t\tgoto st0;\n\tgoto st21;\ntr5:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st22;\nst22:\n\tif ( ++p == pe )\n\t\tgoto _test_eof22;\ncase 22:\n#line 530 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 43: goto st22;\n\t\tcase 58: goto st23;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st22;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( (*p) > 90 ) {\n\t\t\tif ( 97 <= (*p) && (*p) <= 122 )\n\t\t\t\tgoto st22;\n\t\t} else if ( (*p) >= 65 )\n\t\t\tgoto st22;\n\t} else\n\t\tgoto st22;\n\tgoto st0;\ntr7:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st23;\nst23:\n\tif ( ++p == pe )\n\t\tgoto _test_eof23;\ncase 23:\n#line 555 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr8;\n\t\tcase 34: goto st0;\n\t\tcase 35: goto tr9;\n\t\tcase 60: goto st0;\n\t\tcase 62: goto st0;\n\t\tcase 127: goto st0;\n\t}\n\tif ( 0 <= (*p) && (*p) <= 31 )\n\t\tgoto st0;\n\tgoto st23;\ntr6:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st24;\nst24:\n\tif ( ++p == pe )\n\t\tgoto _test_eof24;\ncase 24:\n#line 575 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr37;\n\t\tcase 34: goto st0;\n\t\tcase 35: goto tr38;\n\t\tcase 60: goto st0;\n\t\tcase 62: goto st0;\n\t\tcase 63: goto tr39;\n\t\tcase 127: goto st0;\n\t}\n\tif ( 0 <= (*p) && (*p) <= 31 )\n\t\tgoto st0;\n\tgoto st24;\ntr39:\n#line 69 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_path(parser, PTR_TO(mark), LEN(mark,p));\n  }\n\tgoto st25;\nst25:\n\tif ( ++p == pe )\n\t\tgoto _test_eof25;\ncase 25:\n#line 598 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr41;\n\t\tcase 34: goto st0;\n\t\tcase 35: goto tr42;\n\t\tcase 60: goto st0;\n\t\tcase 62: goto st0;\n\t\tcase 127: goto st0;\n\t}\n\tif ( 0 <= (*p) && (*p) <= 31 )\n\t\tgoto st0;\n\tgoto tr40;\ntr40:\n#line 60 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(query_start, p); }\n\tgoto st26;\nst26:\n\tif ( ++p == pe )\n\t\tgoto _test_eof26;\ncase 26:\n#line 618 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr44;\n\t\tcase 34: goto st0;\n\t\tcase 35: goto tr45;\n\t\tcase 60: goto st0;\n\t\tcase 62: goto st0;\n\t\tcase 127: goto st0;\n\t}\n\tif ( 0 <= (*p) && (*p) <= 31 )\n\t\tgoto st0;\n\tgoto st26;\nst27:\n\tif ( ++p == pe )\n\t\tgoto _test_eof27;\ncase 27:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st28;\n\t\tcase 95: goto st28;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st28;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st28;\n\t} else\n\t\tgoto st28;\n\tgoto st0;\nst28:\n\tif ( ++p == pe )\n\t\tgoto _test_eof28;\ncase 28:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st29;\n\t\tcase 95: goto st29;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st29;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st29;\n\t} else\n\t\tgoto st29;\n\tgoto st0;\nst29:\n\tif ( ++p == pe )\n\t\tgoto _test_eof29;\ncase 29:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st30;\n\t\tcase 95: goto st30;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st30;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st30;\n\t} else\n\t\tgoto st30;\n\tgoto st0;\nst30:\n\tif ( ++p == pe )\n\t\tgoto _test_eof30;\ncase 30:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st31;\n\t\tcase 95: goto st31;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st31;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st31;\n\t} else\n\t\tgoto st31;\n\tgoto st0;\nst31:\n\tif ( ++p == pe )\n\t\tgoto _test_eof31;\ncase 31:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st32;\n\t\tcase 95: goto st32;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st32;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st32;\n\t} else\n\t\tgoto st32;\n\tgoto st0;\nst32:\n\tif ( ++p == pe )\n\t\tgoto _test_eof32;\ncase 32:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st33;\n\t\tcase 95: goto st33;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st33;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st33;\n\t} else\n\t\tgoto st33;\n\tgoto st0;\nst33:\n\tif ( ++p == pe )\n\t\tgoto _test_eof33;\ncase 33:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st34;\n\t\tcase 95: goto st34;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st34;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st34;\n\t} else\n\t\tgoto st34;\n\tgoto st0;\nst34:\n\tif ( ++p == pe )\n\t\tgoto _test_eof34;\ncase 34:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st35;\n\t\tcase 95: goto st35;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st35;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st35;\n\t} else\n\t\tgoto st35;\n\tgoto st0;\nst35:\n\tif ( ++p == pe )\n\t\tgoto _test_eof35;\ncase 35:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st36;\n\t\tcase 95: goto st36;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st36;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st36;\n\t} else\n\t\tgoto st36;\n\tgoto st0;\nst36:\n\tif ( ++p == pe )\n\t\tgoto _test_eof36;\ncase 36:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st37;\n\t\tcase 95: goto st37;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st37;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st37;\n\t} else\n\t\tgoto st37;\n\tgoto st0;\nst37:\n\tif ( ++p == pe )\n\t\tgoto _test_eof37;\ncase 37:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st38;\n\t\tcase 95: goto st38;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st38;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st38;\n\t} else\n\t\tgoto st38;\n\tgoto st0;\nst38:\n\tif ( ++p == pe )\n\t\tgoto _test_eof38;\ncase 38:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st39;\n\t\tcase 95: goto st39;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st39;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st39;\n\t} else\n\t\tgoto st39;\n\tgoto st0;\nst39:\n\tif ( ++p == pe )\n\t\tgoto _test_eof39;\ncase 39:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st40;\n\t\tcase 95: goto st40;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st40;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st40;\n\t} else\n\t\tgoto st40;\n\tgoto st0;\nst40:\n\tif ( ++p == pe )\n\t\tgoto _test_eof40;\ncase 40:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st41;\n\t\tcase 95: goto st41;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st41;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st41;\n\t} else\n\t\tgoto st41;\n\tgoto st0;\nst41:\n\tif ( ++p == pe )\n\t\tgoto _test_eof41;\ncase 41:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st42;\n\t\tcase 95: goto st42;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st42;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st42;\n\t} else\n\t\tgoto st42;\n\tgoto st0;\nst42:\n\tif ( ++p == pe )\n\t\tgoto _test_eof42;\ncase 42:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st43;\n\t\tcase 95: goto st43;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st43;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st43;\n\t} else\n\t\tgoto st43;\n\tgoto st0;\nst43:\n\tif ( ++p == pe )\n\t\tgoto _test_eof43;\ncase 43:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st44;\n\t\tcase 95: goto st44;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st44;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st44;\n\t} else\n\t\tgoto st44;\n\tgoto st0;\nst44:\n\tif ( ++p == pe )\n\t\tgoto _test_eof44;\ncase 44:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st45;\n\t\tcase 95: goto st45;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st45;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st45;\n\t} else\n\t\tgoto st45;\n\tgoto st0;\nst45:\n\tif ( ++p == pe )\n\t\tgoto _test_eof45;\ncase 45:\n\tif ( (*p) == 32 )\n\t\tgoto tr2;\n\tgoto st0;\n\t}\n\t_test_eof2: cs = 2; goto _test_eof; \n\t_test_eof3: cs = 3; goto _test_eof; \n\t_test_eof4: cs = 4; goto _test_eof; \n\t_test_eof5: cs = 5; goto _test_eof; \n\t_test_eof6: cs = 6; goto _test_eof; \n\t_test_eof7: cs = 7; goto _test_eof; \n\t_test_eof8: cs = 8; goto _test_eof; \n\t_test_eof9: cs = 9; goto _test_eof; \n\t_test_eof10: cs = 10; goto _test_eof; \n\t_test_eof11: cs = 11; goto _test_eof; \n\t_test_eof12: cs = 12; goto _test_eof; \n\t_test_eof13: cs = 13; goto _test_eof; \n\t_test_eof14: cs = 14; goto _test_eof; \n\t_test_eof15: cs = 15; goto _test_eof; \n\t_test_eof16: cs = 16; goto _test_eof; \n\t_test_eof46: cs = 46; goto _test_eof; \n\t_test_eof17: cs = 17; goto _test_eof; \n\t_test_eof18: cs = 18; goto _test_eof; \n\t_test_eof19: cs = 19; goto _test_eof; \n\t_test_eof20: cs = 20; goto _test_eof; \n\t_test_eof21: cs = 21; goto _test_eof; \n\t_test_eof22: cs = 22; goto _test_eof; \n\t_test_eof23: cs = 23; goto _test_eof; \n\t_test_eof24: cs = 24; goto _test_eof; \n\t_test_eof25: cs = 25; goto _test_eof; \n\t_test_eof26: cs = 26; goto _test_eof; \n\t_test_eof27: cs = 27; goto _test_eof; \n\t_test_eof28: cs = 28; goto _test_eof; \n\t_test_eof29: cs = 29; goto _test_eof; \n\t_test_eof30: cs = 30; goto _test_eof; \n\t_test_eof31: cs = 31; goto _test_eof; \n\t_test_eof32: cs = 32; goto _test_eof; \n\t_test_eof33: cs = 33; goto _test_eof; \n\t_test_eof34: cs = 34; goto _test_eof; \n\t_test_eof35: cs = 35; goto _test_eof; \n\t_test_eof36: cs = 36; goto _test_eof; \n\t_test_eof37: cs = 37; goto _test_eof; \n\t_test_eof38: cs = 38; goto _test_eof; \n\t_test_eof39: cs = 39; goto _test_eof; \n\t_test_eof40: cs = 40; goto _test_eof; \n\t_test_eof41: cs = 41; goto _test_eof; \n\t_test_eof42: cs = 42; goto _test_eof; \n\t_test_eof43: cs = 43; goto _test_eof; \n\t_test_eof44: cs = 44; goto _test_eof; \n\t_test_eof45: cs = 45; goto _test_eof; \n\n\t_test_eof: {}\n\t_out: {}\n\t}\n\n#line 117 \"ext/puma_http11/http11_parser.rl\"\n\n  if (!puma_parser_has_error(parser))\n    parser->cs = cs;\n  parser->nread += p - (buffer + off);\n\n  assert(p <= pe && \"buffer overflow after parsing execute\");\n  assert(parser->nread <= len && \"nread longer than length\");\n  assert(parser->body_start <= len && \"body starts after buffer end\");\n  assert(parser->mark < len && \"mark is after buffer end\");\n  assert(parser->field_len <= len && \"field has length longer than whole buffer\");\n  assert(parser->field_start < len && \"field starts after buffer end\");\n\n  return(parser->nread);\n}", "func_hash": 94439113710401505299900606066823977917, "file_name": "http11_parser.c", "file_hash": 59830834973701402944362779116096200943, "cwe": ["CWE-444"], "cve": "CVE-2021-41136", "cve_desc": "Puma is a HTTP 1.1 server for Ruby/Rack applications. Prior to versions 5.5.1 and 4.3.9, using `puma` with a proxy which forwards HTTP header values which contain the LF character could allow HTTP request smugggling. A client could smuggle a request through a proxy, causing the proxy to send a response back to another unknown client. The only proxy which has this behavior, as far as the Puma team is aware of, is Apache Traffic Server. If the proxy uses persistent connections and the client adds another request in via HTTP pipelining, the proxy may mistake it as the first request's body. Puma, however, would see it as two requests, and when processing the second request, send back a response that the proxy does not expect. If the proxy has reused the persistent connection to Puma to send another request for a different client, the second response from the first client will be sent to the second client. This vulnerability was patched in Puma 5.5.1 and 4.3.9. As a workaround, do not use Apache Traffic Server with `puma`.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41136"}
{"idx": 292609, "project": "puma", "commit_id": "acdc3ae571dfae0e045cf09a295280127db65c7f", "project_url": "https://github.com/puma/puma", "commit_url": "https://github.com/puma/puma/commit/acdc3ae571dfae0e045cf09a295280127db65c7f", "commit_message": "Merge pull request from GHSA-48w2-rm65-62xx\n\n* Fix HTTP request smuggling vulnerability\n\nSee GHSA-48w2-rm65-62xx or CVE-2021-41136 for more info.\n\n* 4.3.9 release note\n\n* 5.5.1 release note\n\n* 5.5.1", "target": 0, "func": "size_t puma_parser_execute(puma_parser *parser, const char *buffer, size_t len, size_t off)  {\n  const char *p, *pe;\n  int cs = parser->cs;\n\n  assert(off <= len && \"offset past end of buffer\");\n\n  p = buffer+off;\n  pe = buffer+len;\n\n  /* assert(*pe == '\\0' && \"pointer does not end on NUL\"); */\n  assert((size_t) (pe - p) == len - off && \"pointers aren't same distance\");\n\n  \n#line 87 \"ext/puma_http11/http11_parser.c\"\n\t{\n\tif ( p == pe )\n\t\tgoto _test_eof;\n\tswitch ( cs )\n\t{\ncase 1:\n\tswitch( (*p) ) {\n\t\tcase 36: goto tr0;\n\t\tcase 95: goto tr0;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto tr0;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto tr0;\n\t} else\n\t\tgoto tr0;\n\tgoto st0;\nst0:\ncs = 0;\n\tgoto _out;\ntr0:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st2;\nst2:\n\tif ( ++p == pe )\n\t\tgoto _test_eof2;\ncase 2:\n#line 118 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st27;\n\t\tcase 95: goto st27;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st27;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st27;\n\t} else\n\t\tgoto st27;\n\tgoto st0;\ntr2:\n#line 50 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_method(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st3;\nst3:\n\tif ( ++p == pe )\n\t\tgoto _test_eof3;\ncase 3:\n#line 143 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 42: goto tr4;\n\t\tcase 43: goto tr5;\n\t\tcase 47: goto tr6;\n\t\tcase 58: goto tr7;\n\t}\n\tif ( (*p) < 65 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 57 )\n\t\t\tgoto tr5;\n\t} else if ( (*p) > 90 ) {\n\t\tif ( 97 <= (*p) && (*p) <= 122 )\n\t\t\tgoto tr5;\n\t} else\n\t\tgoto tr5;\n\tgoto st0;\ntr4:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st4;\nst4:\n\tif ( ++p == pe )\n\t\tgoto _test_eof4;\ncase 4:\n#line 167 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr8;\n\t\tcase 35: goto tr9;\n\t}\n\tgoto st0;\ntr8:\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st5;\ntr31:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n#line 56 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->fragment(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st5;\ntr33:\n#line 56 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->fragment(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st5;\ntr37:\n#line 69 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_path(parser, PTR_TO(mark), LEN(mark,p));\n  }\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st5;\ntr41:\n#line 60 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(query_start, p); }\n#line 61 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p));\n  }\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st5;\ntr44:\n#line 61 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p));\n  }\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st5;\nst5:\n\tif ( ++p == pe )\n\t\tgoto _test_eof5;\ncase 5:\n#line 229 \"ext/puma_http11/http11_parser.c\"\n\tif ( (*p) == 72 )\n\t\tgoto tr10;\n\tgoto st0;\ntr10:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st6;\nst6:\n\tif ( ++p == pe )\n\t\tgoto _test_eof6;\ncase 6:\n#line 241 \"ext/puma_http11/http11_parser.c\"\n\tif ( (*p) == 84 )\n\t\tgoto st7;\n\tgoto st0;\nst7:\n\tif ( ++p == pe )\n\t\tgoto _test_eof7;\ncase 7:\n\tif ( (*p) == 84 )\n\t\tgoto st8;\n\tgoto st0;\nst8:\n\tif ( ++p == pe )\n\t\tgoto _test_eof8;\ncase 8:\n\tif ( (*p) == 80 )\n\t\tgoto st9;\n\tgoto st0;\nst9:\n\tif ( ++p == pe )\n\t\tgoto _test_eof9;\ncase 9:\n\tif ( (*p) == 47 )\n\t\tgoto st10;\n\tgoto st0;\nst10:\n\tif ( ++p == pe )\n\t\tgoto _test_eof10;\ncase 10:\n\tif ( 48 <= (*p) && (*p) <= 57 )\n\t\tgoto st11;\n\tgoto st0;\nst11:\n\tif ( ++p == pe )\n\t\tgoto _test_eof11;\ncase 11:\n\tif ( (*p) == 46 )\n\t\tgoto st12;\n\tif ( 48 <= (*p) && (*p) <= 57 )\n\t\tgoto st11;\n\tgoto st0;\nst12:\n\tif ( ++p == pe )\n\t\tgoto _test_eof12;\ncase 12:\n\tif ( 48 <= (*p) && (*p) <= 57 )\n\t\tgoto st13;\n\tgoto st0;\nst13:\n\tif ( ++p == pe )\n\t\tgoto _test_eof13;\ncase 13:\n\tif ( (*p) == 13 )\n\t\tgoto tr18;\n\tif ( 48 <= (*p) && (*p) <= 57 )\n\t\tgoto st13;\n\tgoto st0;\ntr18:\n#line 65 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->http_version(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st14;\ntr26:\n#line 46 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n#line 47 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->http_field(parser, PTR_TO(field_start), parser->field_len, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st14;\ntr29:\n#line 47 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->http_field(parser, PTR_TO(field_start), parser->field_len, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st14;\nst14:\n\tif ( ++p == pe )\n\t\tgoto _test_eof14;\ncase 14:\n#line 322 \"ext/puma_http11/http11_parser.c\"\n\tif ( (*p) == 10 )\n\t\tgoto st15;\n\tgoto st0;\nst15:\n\tif ( ++p == pe )\n\t\tgoto _test_eof15;\ncase 15:\n\tswitch( (*p) ) {\n\t\tcase 13: goto st16;\n\t\tcase 33: goto tr21;\n\t\tcase 124: goto tr21;\n\t\tcase 126: goto tr21;\n\t}\n\tif ( (*p) < 45 ) {\n\t\tif ( (*p) > 39 ) {\n\t\t\tif ( 42 <= (*p) && (*p) <= 43 )\n\t\t\t\tgoto tr21;\n\t\t} else if ( (*p) >= 35 )\n\t\t\tgoto tr21;\n\t} else if ( (*p) > 46 ) {\n\t\tif ( (*p) < 65 ) {\n\t\t\tif ( 48 <= (*p) && (*p) <= 57 )\n\t\t\t\tgoto tr21;\n\t\t} else if ( (*p) > 90 ) {\n\t\t\tif ( 94 <= (*p) && (*p) <= 122 )\n\t\t\t\tgoto tr21;\n\t\t} else\n\t\t\tgoto tr21;\n\t} else\n\t\tgoto tr21;\n\tgoto st0;\nst16:\n\tif ( ++p == pe )\n\t\tgoto _test_eof16;\ncase 16:\n\tif ( (*p) == 10 )\n\t\tgoto tr22;\n\tgoto st0;\ntr22:\n#line 73 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->body_start = p - buffer + 1;\n    parser->header_done(parser, p + 1, pe - p - 1);\n    {p++; cs = 46; goto _out;}\n  }\n\tgoto st46;\nst46:\n\tif ( ++p == pe )\n\t\tgoto _test_eof46;\ncase 46:\n#line 373 \"ext/puma_http11/http11_parser.c\"\n\tgoto st0;\ntr21:\n#line 40 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(field_start, p); }\n#line 41 \"ext/puma_http11/http11_parser.rl\"\n\t{ snake_upcase_char((char *)p); }\n\tgoto st17;\ntr23:\n#line 41 \"ext/puma_http11/http11_parser.rl\"\n\t{ snake_upcase_char((char *)p); }\n\tgoto st17;\nst17:\n\tif ( ++p == pe )\n\t\tgoto _test_eof17;\ncase 17:\n#line 389 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 33: goto tr23;\n\t\tcase 58: goto tr24;\n\t\tcase 124: goto tr23;\n\t\tcase 126: goto tr23;\n\t}\n\tif ( (*p) < 45 ) {\n\t\tif ( (*p) > 39 ) {\n\t\t\tif ( 42 <= (*p) && (*p) <= 43 )\n\t\t\t\tgoto tr23;\n\t\t} else if ( (*p) >= 35 )\n\t\t\tgoto tr23;\n\t} else if ( (*p) > 46 ) {\n\t\tif ( (*p) < 65 ) {\n\t\t\tif ( 48 <= (*p) && (*p) <= 57 )\n\t\t\t\tgoto tr23;\n\t\t} else if ( (*p) > 90 ) {\n\t\t\tif ( 94 <= (*p) && (*p) <= 122 )\n\t\t\t\tgoto tr23;\n\t\t} else\n\t\t\tgoto tr23;\n\t} else\n\t\tgoto tr23;\n\tgoto st0;\ntr24:\n#line 42 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->field_len = LEN(field_start, p);\n  }\n\tgoto st18;\ntr27:\n#line 46 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st18;\nst18:\n\tif ( ++p == pe )\n\t\tgoto _test_eof18;\ncase 18:\n#line 428 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 9: goto tr25;\n\t\tcase 13: goto tr26;\n\t\tcase 32: goto tr27;\n\t}\n\tif ( 33 <= (*p) && (*p) <= 126 )\n\t\tgoto tr25;\n\tgoto st0;\ntr25:\n#line 46 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st19;\nst19:\n\tif ( ++p == pe )\n\t\tgoto _test_eof19;\ncase 19:\n#line 445 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 9: goto st19;\n\t\tcase 13: goto tr29;\n\t}\n\tif ( 32 <= (*p) && (*p) <= 126 )\n\t\tgoto st19;\n\tgoto st0;\ntr9:\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st20;\ntr38:\n#line 69 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_path(parser, PTR_TO(mark), LEN(mark,p));\n  }\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st20;\ntr42:\n#line 60 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(query_start, p); }\n#line 61 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p));\n  }\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st20;\ntr45:\n#line 61 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p));\n  }\n#line 53 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));\n  }\n\tgoto st20;\nst20:\n\tif ( ++p == pe )\n\t\tgoto _test_eof20;\ncase 20:\n#line 495 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr31;\n\t\tcase 60: goto st0;\n\t\tcase 62: goto st0;\n\t\tcase 127: goto st0;\n\t}\n\tif ( (*p) > 31 ) {\n\t\tif ( 34 <= (*p) && (*p) <= 35 )\n\t\t\tgoto st0;\n\t} else if ( (*p) >= 0 )\n\t\tgoto st0;\n\tgoto tr30;\ntr30:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st21;\nst21:\n\tif ( ++p == pe )\n\t\tgoto _test_eof21;\ncase 21:\n#line 516 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr33;\n\t\tcase 60: goto st0;\n\t\tcase 62: goto st0;\n\t\tcase 127: goto st0;\n\t}\n\tif ( (*p) > 31 ) {\n\t\tif ( 34 <= (*p) && (*p) <= 35 )\n\t\t\tgoto st0;\n\t} else if ( (*p) >= 0 )\n\t\tgoto st0;\n\tgoto st21;\ntr5:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st22;\nst22:\n\tif ( ++p == pe )\n\t\tgoto _test_eof22;\ncase 22:\n#line 537 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 43: goto st22;\n\t\tcase 58: goto st23;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st22;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( (*p) > 90 ) {\n\t\t\tif ( 97 <= (*p) && (*p) <= 122 )\n\t\t\t\tgoto st22;\n\t\t} else if ( (*p) >= 65 )\n\t\t\tgoto st22;\n\t} else\n\t\tgoto st22;\n\tgoto st0;\ntr7:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st23;\nst23:\n\tif ( ++p == pe )\n\t\tgoto _test_eof23;\ncase 23:\n#line 562 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr8;\n\t\tcase 34: goto st0;\n\t\tcase 35: goto tr9;\n\t\tcase 60: goto st0;\n\t\tcase 62: goto st0;\n\t\tcase 127: goto st0;\n\t}\n\tif ( 0 <= (*p) && (*p) <= 31 )\n\t\tgoto st0;\n\tgoto st23;\ntr6:\n#line 37 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(mark, p); }\n\tgoto st24;\nst24:\n\tif ( ++p == pe )\n\t\tgoto _test_eof24;\ncase 24:\n#line 582 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr37;\n\t\tcase 34: goto st0;\n\t\tcase 35: goto tr38;\n\t\tcase 60: goto st0;\n\t\tcase 62: goto st0;\n\t\tcase 63: goto tr39;\n\t\tcase 127: goto st0;\n\t}\n\tif ( 0 <= (*p) && (*p) <= 31 )\n\t\tgoto st0;\n\tgoto st24;\ntr39:\n#line 69 \"ext/puma_http11/http11_parser.rl\"\n\t{\n    parser->request_path(parser, PTR_TO(mark), LEN(mark,p));\n  }\n\tgoto st25;\nst25:\n\tif ( ++p == pe )\n\t\tgoto _test_eof25;\ncase 25:\n#line 605 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr41;\n\t\tcase 34: goto st0;\n\t\tcase 35: goto tr42;\n\t\tcase 60: goto st0;\n\t\tcase 62: goto st0;\n\t\tcase 127: goto st0;\n\t}\n\tif ( 0 <= (*p) && (*p) <= 31 )\n\t\tgoto st0;\n\tgoto tr40;\ntr40:\n#line 60 \"ext/puma_http11/http11_parser.rl\"\n\t{ MARK(query_start, p); }\n\tgoto st26;\nst26:\n\tif ( ++p == pe )\n\t\tgoto _test_eof26;\ncase 26:\n#line 625 \"ext/puma_http11/http11_parser.c\"\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr44;\n\t\tcase 34: goto st0;\n\t\tcase 35: goto tr45;\n\t\tcase 60: goto st0;\n\t\tcase 62: goto st0;\n\t\tcase 127: goto st0;\n\t}\n\tif ( 0 <= (*p) && (*p) <= 31 )\n\t\tgoto st0;\n\tgoto st26;\nst27:\n\tif ( ++p == pe )\n\t\tgoto _test_eof27;\ncase 27:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st28;\n\t\tcase 95: goto st28;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st28;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st28;\n\t} else\n\t\tgoto st28;\n\tgoto st0;\nst28:\n\tif ( ++p == pe )\n\t\tgoto _test_eof28;\ncase 28:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st29;\n\t\tcase 95: goto st29;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st29;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st29;\n\t} else\n\t\tgoto st29;\n\tgoto st0;\nst29:\n\tif ( ++p == pe )\n\t\tgoto _test_eof29;\ncase 29:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st30;\n\t\tcase 95: goto st30;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st30;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st30;\n\t} else\n\t\tgoto st30;\n\tgoto st0;\nst30:\n\tif ( ++p == pe )\n\t\tgoto _test_eof30;\ncase 30:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st31;\n\t\tcase 95: goto st31;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st31;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st31;\n\t} else\n\t\tgoto st31;\n\tgoto st0;\nst31:\n\tif ( ++p == pe )\n\t\tgoto _test_eof31;\ncase 31:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st32;\n\t\tcase 95: goto st32;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st32;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st32;\n\t} else\n\t\tgoto st32;\n\tgoto st0;\nst32:\n\tif ( ++p == pe )\n\t\tgoto _test_eof32;\ncase 32:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st33;\n\t\tcase 95: goto st33;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st33;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st33;\n\t} else\n\t\tgoto st33;\n\tgoto st0;\nst33:\n\tif ( ++p == pe )\n\t\tgoto _test_eof33;\ncase 33:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st34;\n\t\tcase 95: goto st34;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st34;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st34;\n\t} else\n\t\tgoto st34;\n\tgoto st0;\nst34:\n\tif ( ++p == pe )\n\t\tgoto _test_eof34;\ncase 34:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st35;\n\t\tcase 95: goto st35;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st35;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st35;\n\t} else\n\t\tgoto st35;\n\tgoto st0;\nst35:\n\tif ( ++p == pe )\n\t\tgoto _test_eof35;\ncase 35:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st36;\n\t\tcase 95: goto st36;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st36;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st36;\n\t} else\n\t\tgoto st36;\n\tgoto st0;\nst36:\n\tif ( ++p == pe )\n\t\tgoto _test_eof36;\ncase 36:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st37;\n\t\tcase 95: goto st37;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st37;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st37;\n\t} else\n\t\tgoto st37;\n\tgoto st0;\nst37:\n\tif ( ++p == pe )\n\t\tgoto _test_eof37;\ncase 37:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st38;\n\t\tcase 95: goto st38;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st38;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st38;\n\t} else\n\t\tgoto st38;\n\tgoto st0;\nst38:\n\tif ( ++p == pe )\n\t\tgoto _test_eof38;\ncase 38:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st39;\n\t\tcase 95: goto st39;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st39;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st39;\n\t} else\n\t\tgoto st39;\n\tgoto st0;\nst39:\n\tif ( ++p == pe )\n\t\tgoto _test_eof39;\ncase 39:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st40;\n\t\tcase 95: goto st40;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st40;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st40;\n\t} else\n\t\tgoto st40;\n\tgoto st0;\nst40:\n\tif ( ++p == pe )\n\t\tgoto _test_eof40;\ncase 40:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st41;\n\t\tcase 95: goto st41;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st41;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st41;\n\t} else\n\t\tgoto st41;\n\tgoto st0;\nst41:\n\tif ( ++p == pe )\n\t\tgoto _test_eof41;\ncase 41:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st42;\n\t\tcase 95: goto st42;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st42;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st42;\n\t} else\n\t\tgoto st42;\n\tgoto st0;\nst42:\n\tif ( ++p == pe )\n\t\tgoto _test_eof42;\ncase 42:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st43;\n\t\tcase 95: goto st43;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st43;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st43;\n\t} else\n\t\tgoto st43;\n\tgoto st0;\nst43:\n\tif ( ++p == pe )\n\t\tgoto _test_eof43;\ncase 43:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st44;\n\t\tcase 95: goto st44;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st44;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st44;\n\t} else\n\t\tgoto st44;\n\tgoto st0;\nst44:\n\tif ( ++p == pe )\n\t\tgoto _test_eof44;\ncase 44:\n\tswitch( (*p) ) {\n\t\tcase 32: goto tr2;\n\t\tcase 36: goto st45;\n\t\tcase 95: goto st45;\n\t}\n\tif ( (*p) < 48 ) {\n\t\tif ( 45 <= (*p) && (*p) <= 46 )\n\t\t\tgoto st45;\n\t} else if ( (*p) > 57 ) {\n\t\tif ( 65 <= (*p) && (*p) <= 90 )\n\t\t\tgoto st45;\n\t} else\n\t\tgoto st45;\n\tgoto st0;\nst45:\n\tif ( ++p == pe )\n\t\tgoto _test_eof45;\ncase 45:\n\tif ( (*p) == 32 )\n\t\tgoto tr2;\n\tgoto st0;\n\t}\n\t_test_eof2: cs = 2; goto _test_eof; \n\t_test_eof3: cs = 3; goto _test_eof; \n\t_test_eof4: cs = 4; goto _test_eof; \n\t_test_eof5: cs = 5; goto _test_eof; \n\t_test_eof6: cs = 6; goto _test_eof; \n\t_test_eof7: cs = 7; goto _test_eof; \n\t_test_eof8: cs = 8; goto _test_eof; \n\t_test_eof9: cs = 9; goto _test_eof; \n\t_test_eof10: cs = 10; goto _test_eof; \n\t_test_eof11: cs = 11; goto _test_eof; \n\t_test_eof12: cs = 12; goto _test_eof; \n\t_test_eof13: cs = 13; goto _test_eof; \n\t_test_eof14: cs = 14; goto _test_eof; \n\t_test_eof15: cs = 15; goto _test_eof; \n\t_test_eof16: cs = 16; goto _test_eof; \n\t_test_eof46: cs = 46; goto _test_eof; \n\t_test_eof17: cs = 17; goto _test_eof; \n\t_test_eof18: cs = 18; goto _test_eof; \n\t_test_eof19: cs = 19; goto _test_eof; \n\t_test_eof20: cs = 20; goto _test_eof; \n\t_test_eof21: cs = 21; goto _test_eof; \n\t_test_eof22: cs = 22; goto _test_eof; \n\t_test_eof23: cs = 23; goto _test_eof; \n\t_test_eof24: cs = 24; goto _test_eof; \n\t_test_eof25: cs = 25; goto _test_eof; \n\t_test_eof26: cs = 26; goto _test_eof; \n\t_test_eof27: cs = 27; goto _test_eof; \n\t_test_eof28: cs = 28; goto _test_eof; \n\t_test_eof29: cs = 29; goto _test_eof; \n\t_test_eof30: cs = 30; goto _test_eof; \n\t_test_eof31: cs = 31; goto _test_eof; \n\t_test_eof32: cs = 32; goto _test_eof; \n\t_test_eof33: cs = 33; goto _test_eof; \n\t_test_eof34: cs = 34; goto _test_eof; \n\t_test_eof35: cs = 35; goto _test_eof; \n\t_test_eof36: cs = 36; goto _test_eof; \n\t_test_eof37: cs = 37; goto _test_eof; \n\t_test_eof38: cs = 38; goto _test_eof; \n\t_test_eof39: cs = 39; goto _test_eof; \n\t_test_eof40: cs = 40; goto _test_eof; \n\t_test_eof41: cs = 41; goto _test_eof; \n\t_test_eof42: cs = 42; goto _test_eof; \n\t_test_eof43: cs = 43; goto _test_eof; \n\t_test_eof44: cs = 44; goto _test_eof; \n\t_test_eof45: cs = 45; goto _test_eof; \n\n\t_test_eof: {}\n\t_out: {}\n\t}\n\n#line 117 \"ext/puma_http11/http11_parser.rl\"\n\n  if (!puma_parser_has_error(parser))\n    parser->cs = cs;\n  parser->nread += p - (buffer + off);\n\n  assert(p <= pe && \"buffer overflow after parsing execute\");\n  assert(parser->nread <= len && \"nread longer than length\");\n  assert(parser->body_start <= len && \"body starts after buffer end\");\n  assert(parser->mark < len && \"mark is after buffer end\");\n  assert(parser->field_len <= len && \"field has length longer than whole buffer\");\n  assert(parser->field_start < len && \"field starts after buffer end\");\n\n  return(parser->nread);\n}", "func_hash": 5609299839918997212046312730863248259, "file_name": "http11_parser.c", "file_hash": 310028467856200472681435734448209650249, "cwe": ["CWE-444"], "cve": "CVE-2021-41136", "cve_desc": "Puma is a HTTP 1.1 server for Ruby/Rack applications. Prior to versions 5.5.1 and 4.3.9, using `puma` with a proxy which forwards HTTP header values which contain the LF character could allow HTTP request smugggling. A client could smuggle a request through a proxy, causing the proxy to send a response back to another unknown client. The only proxy which has this behavior, as far as the Puma team is aware of, is Apache Traffic Server. If the proxy uses persistent connections and the client adds another request in via HTTP pipelining, the proxy may mistake it as the first request's body. Puma, however, would see it as two requests, and when processing the second request, send back a response that the proxy does not expect. If the proxy has reused the persistent connection to Puma to send another request for a different client, the second response from the first client will be sent to the second client. This vulnerability was patched in Puma 5.5.1 and 4.3.9. As a workaround, do not use Apache Traffic Server with `puma`.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41136"}
{"idx": 199833, "project": "chafa", "commit_id": "e4b777c7b7c144cd16a0ea96108267b1004fe6c9", "project_url": "https://github.com/hpjansson/chafa", "commit_url": "https://github.com/hpjansson/chafa/commit/e4b777c7b7c144cd16a0ea96108267b1004fe6c9", "commit_message": "libnsgif: Fix null pointer deref on frameless GIF input\n\nA crafted GIF file with no frame data could cause a null pointer\ndereference leading to denial of service (crash). Reported by\n@JieyongMa via huntr.dev.", "target": 1, "func": "gif_internal_decode_frame(gif_animation *gif,\n                          unsigned int frame,\n                          bool clear_image)\n{\n        unsigned int index = 0;\n        const unsigned char *gif_data, *gif_end;\n        ssize_t gif_bytes;\n        unsigned int width, height, offset_x, offset_y;\n        unsigned int flags, colour_table_size, interlace;\n        unsigned int *colour_table;\n        unsigned int *frame_data = 0;\t// Set to 0 for no warnings\n        unsigned int *frame_scanline;\n        ssize_t save_buffer_position;\n        unsigned int return_value = 0;\n        unsigned int x, y, decode_y, burst_bytes;\n        register unsigned char colour;\n\n        /* Ensure this frame is supposed to be decoded */\n        if (gif->frames[frame].display == false) {\n                return GIF_OK;\n        }\n\n        /* Ensure the frame is in range to decode */\n        if (frame > gif->frame_count_partial) {\n                return GIF_INSUFFICIENT_DATA;\n        }\n\n        /* done if frame is already decoded */\n        if ((!clear_image) &&\n            ((int)frame == gif->decoded_frame)) {\n                return GIF_OK;\n        }\n\n        /* Get the start of our frame data and the end of the GIF data */\n        gif_data = gif->gif_data + gif->frames[frame].frame_pointer;\n        gif_end = gif->gif_data + gif->buffer_size;\n        gif_bytes = (gif_end - gif_data);\n\n        /*\n         * Ensure there is a minimal amount of data to proceed.  The shortest\n         * block of data is a 10-byte image descriptor + 1-byte gif trailer\n         */\n        if (gif_bytes < 12) {\n                return GIF_INSUFFICIENT_FRAME_DATA;\n        }\n\n        /* Save the buffer position */\n        save_buffer_position = gif->buffer_position;\n        gif->buffer_position = gif_data - gif->gif_data;\n\n        /* Skip any extensions because they have allready been processed */\n        if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK) {\n                goto gif_decode_frame_exit;\n        }\n        gif_data = (gif->gif_data + gif->buffer_position);\n        gif_bytes = (gif_end - gif_data);\n\n        /* Ensure we have enough data for the 10-byte image descriptor + 1-byte\n         * gif trailer\n         */\n        if (gif_bytes < 12) {\n                return_value = GIF_INSUFFICIENT_FRAME_DATA;\n                goto gif_decode_frame_exit;\n        }\n\n        /* 10-byte Image Descriptor is:\n         *\n         *\t+0\tCHAR\tImage Separator (0x2c)\n         *\t+1\tSHORT\tImage Left Position\n         *\t+3\tSHORT\tImage Top Position\n         *\t+5\tSHORT\tWidth\n         *\t+7\tSHORT\tHeight\n         *\t+9\tCHAR\t__Packed Fields__\n         *\t\t\t1BIT\tLocal Colour Table Flag\n         *\t\t\t1BIT\tInterlace Flag\n         *\t\t\t1BIT\tSort Flag\n         *\t\t\t2BITS\tReserved\n         *\t\t\t3BITS\tSize of Local Colour Table\n         */\n        if (gif_data[0] != GIF_IMAGE_SEPARATOR) {\n                return_value = GIF_DATA_ERROR;\n                goto gif_decode_frame_exit;\n        }\n        offset_x = gif_data[1] | (gif_data[2] << 8);\n        offset_y = gif_data[3] | (gif_data[4] << 8);\n        width = gif_data[5] | (gif_data[6] << 8);\n        height = gif_data[7] | (gif_data[8] << 8);\n\n        /* Boundary checking - shouldn't ever happen except unless the data has\n         * been modified since initialisation.\n         */\n        if ((offset_x + width > gif->width) ||\n            (offset_y + height > gif->height)) {\n                return_value = GIF_DATA_ERROR;\n                goto gif_decode_frame_exit;\n        }\n\n        /* Decode the flags */\n        flags = gif_data[9];\n        colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK);\n        interlace = flags & GIF_INTERLACE_MASK;\n\n        /* Advance data pointer to next block either colour table or image\n         * data.\n         */\n        gif_data += 10;\n        gif_bytes = (gif_end - gif_data);\n\n        /* Set up the colour table */\n        if (flags & GIF_COLOUR_TABLE_MASK) {\n                if (gif_bytes < (int)(3 * colour_table_size)) {\n                        return_value = GIF_INSUFFICIENT_FRAME_DATA;\n                        goto gif_decode_frame_exit;\n                }\n                colour_table = gif->local_colour_table;\n                if (!clear_image) {\n                        for (index = 0; index < colour_table_size; index++) {\n                                /* Gif colour map contents are r,g,b.\n                                 *\n                                 * We want to pack them bytewise into the\n                                 * colour table, such that the red component\n                                 * is in byte 0 and the alpha component is in\n                                 * byte 3.\n                                 */\n                                unsigned char *entry =\n                                        (unsigned char *) &colour_table[index];\n\n                                entry[0] = gif_data[0];\t/* r */\n                                entry[1] = gif_data[1];\t/* g */\n                                entry[2] = gif_data[2];\t/* b */\n                                entry[3] = 0xff;\t/* a */\n\n                                gif_data += 3;\n                        }\n                } else {\n                        gif_data += 3 * colour_table_size;\n                }\n                gif_bytes = (gif_end - gif_data);\n        } else {\n                colour_table = gif->global_colour_table;\n        }\n\n        /* Ensure sufficient data remains */\n        if (gif_bytes < 1) {\n                return_value = GIF_INSUFFICIENT_FRAME_DATA;\n                goto gif_decode_frame_exit;\n        }\n\n        /* check for an end marker */\n        if (gif_data[0] == GIF_TRAILER) {\n                return_value = GIF_OK;\n                goto gif_decode_frame_exit;\n        }\n\n        /* Get the frame data */\n        assert(gif->bitmap_callbacks.bitmap_get_buffer);\n        frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);\n        if (!frame_data) {\n                return GIF_INSUFFICIENT_MEMORY;\n        }\n\n        /* If we are clearing the image we just clear, if not decode */\n        if (!clear_image) {\n                lzw_result res;\n                const uint8_t *stack_base;\n                const uint8_t *stack_pos;\n\n                /* Ensure we have enough data for a 1-byte LZW code size +\n                 * 1-byte gif trailer\n                 */\n                if (gif_bytes < 2) {\n                        return_value = GIF_INSUFFICIENT_FRAME_DATA;\n                        goto gif_decode_frame_exit;\n                }\n\n                /* If we only have a 1-byte LZW code size + 1-byte gif trailer,\n                 * we're finished\n                 */\n                if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) {\n                        return_value = GIF_OK;\n                        goto gif_decode_frame_exit;\n                }\n\n                /* If the previous frame's disposal method requires we restore\n                 * the background colour or this is the first frame, clear\n                 * the frame data\n                 */\n                if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) {\n                        memset((char*)frame_data,\n                               GIF_TRANSPARENT_COLOUR,\n                               gif->width * gif->height * sizeof(int));\n                        gif->decoded_frame = frame;\n                        /* The line below would fill the image with its\n                         * background color, but because GIFs support\n                         * transparency we likely wouldn't want to do that. */\n                        /* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */\n                } else if ((frame != 0) &&\n                           (gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) {\n                        return_value = gif_internal_decode_frame(gif,\n                                                                 (frame - 1),\n                                                                 true);\n                        if (return_value != GIF_OK) {\n                                goto gif_decode_frame_exit;\n                        }\n\n                } else if ((frame != 0) &&\n                           (gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) {\n                        /*\n                         * If the previous frame's disposal method requires we\n                         * restore the previous image, find the last image set\n                         * to \"do not dispose\" and get that frame data\n                         */\n                        int last_undisposed_frame = frame - 2;\n                        while ((last_undisposed_frame >= 0) &&\n                               (gif->frames[last_undisposed_frame].disposal_method == GIF_FRAME_RESTORE)) {\n                                last_undisposed_frame--;\n                        }\n\n                        /* If we don't find one, clear the frame data */\n                        if (last_undisposed_frame == -1) {\n                                /* see notes above on transparency\n                                 * vs. background color\n                                 */\n                                memset((char*)frame_data,\n                                       GIF_TRANSPARENT_COLOUR,\n                                       gif->width * gif->height * sizeof(int));\n                        } else {\n                                return_value = gif_internal_decode_frame(gif, last_undisposed_frame, false);\n                                if (return_value != GIF_OK) {\n                                        goto gif_decode_frame_exit;\n                                }\n                                /* Get this frame's data */\n                                assert(gif->bitmap_callbacks.bitmap_get_buffer);\n                                frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);\n                                if (!frame_data) {\n                                        return GIF_INSUFFICIENT_MEMORY;\n                                }\n                        }\n                }\n                gif->decoded_frame = frame;\n                gif->buffer_position = (gif_data - gif->gif_data) + 1;\n\n                /* Initialise the LZW decoding */\n                res = lzw_decode_init(gif->lzw_ctx, gif->gif_data,\n                                gif->buffer_size, gif->buffer_position,\n                                gif_data[0], &stack_base, &stack_pos);\n                if (res != LZW_OK) {\n                        return gif_error_from_lzw(res);\n                }\n\n                /* Decompress the data */\n                for (y = 0; y < height; y++) {\n                        if (interlace) {\n                                decode_y = gif_interlaced_line(height, y) + offset_y;\n                        } else {\n                                decode_y = y + offset_y;\n                        }\n                        frame_scanline = frame_data + offset_x + (decode_y * gif->width);\n\n                        /* Rather than decoding pixel by pixel, we try to burst\n                         * out streams of data to remove the need for end-of\n                         * data checks every pixel.\n                         */\n                        x = width;\n                        while (x > 0) {\n                                burst_bytes = (stack_pos - stack_base);\n                                if (burst_bytes > 0) {\n                                        if (burst_bytes > x) {\n                                                burst_bytes = x;\n                                        }\n                                        x -= burst_bytes;\n                                        while (burst_bytes-- > 0) {\n                                                colour = *--stack_pos;\n                                                if (((gif->frames[frame].transparency) &&\n                                                     (colour != gif->frames[frame].transparency_index)) ||\n                                                    (!gif->frames[frame].transparency)) {\n                                                        *frame_scanline = colour_table[colour];\n                                                }\n                                                frame_scanline++;\n                                        }\n                                } else {\n                                        res = lzw_decode(gif->lzw_ctx, &stack_pos);\n                                        if (res != LZW_OK) {\n                                                /* Unexpected end of frame, try to recover */\n                                                if (res == LZW_OK_EOD) {\n                                                        return_value = GIF_OK;\n                                                } else {\n                                                        return_value = gif_error_from_lzw(res);\n                                                }\n                                                goto gif_decode_frame_exit;\n                                        }\n                                }\n                        }\n                }\n        } else {\n                /* Clear our frame */\n                if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) {\n                        for (y = 0; y < height; y++) {\n                                frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width);\n                                if (gif->frames[frame].transparency) {\n                                        memset(frame_scanline,\n                                               GIF_TRANSPARENT_COLOUR,\n                                               width * 4);\n                                } else {\n                                        memset(frame_scanline,\n                                               colour_table[gif->background_index],\n                                               width * 4);\n                                }\n                        }\n                }\n        }\ngif_decode_frame_exit:\n\n        /* Check if we should test for optimisation */\n        if (gif->frames[frame].virgin) {\n                if (gif->bitmap_callbacks.bitmap_test_opaque) {\n                        gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image);\n                } else {\n                        gif->frames[frame].opaque = false;\n                }\n                gif->frames[frame].virgin = false;\n        }\n\n        if (gif->bitmap_callbacks.bitmap_set_opaque) {\n                gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque);\n        }\n\n        if (gif->bitmap_callbacks.bitmap_modified) {\n                gif->bitmap_callbacks.bitmap_modified(gif->frame_image);\n        }\n\n        /* Restore the buffer position */\n        gif->buffer_position = save_buffer_position;\n\n        return return_value;\n}", "func_hash": 44351140165833891890072470559672892000, "file_name": "libnsgif.c", "file_hash": 198094748346353506643883012228634204471, "cwe": ["CWE-476"], "cve": "CVE-2022-1507", "cve_desc": "chafa: NULL Pointer Dereference in function gif_internal_decode_frame at libnsgif.c:599 allows attackers to cause a denial of service (crash) via a crafted input file. in GitHub repository hpjansson/chafa prior to 1.10.2. chafa: NULL Pointer Dereference in function gif_internal_decode_frame at libnsgif.c:599 allows attackers to cause a denial of service (crash) via a crafted input file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1507"}
{"idx": 293496, "project": "chafa", "commit_id": "e4b777c7b7c144cd16a0ea96108267b1004fe6c9", "project_url": "https://github.com/hpjansson/chafa", "commit_url": "https://github.com/hpjansson/chafa/commit/e4b777c7b7c144cd16a0ea96108267b1004fe6c9", "commit_message": "libnsgif: Fix null pointer deref on frameless GIF input\n\nA crafted GIF file with no frame data could cause a null pointer\ndereference leading to denial of service (crash). Reported by\n@JieyongMa via huntr.dev.", "target": 0, "func": "gif_internal_decode_frame(gif_animation *gif,\n                          unsigned int frame,\n                          bool clear_image)\n{\n        unsigned int index = 0;\n        const unsigned char *gif_data, *gif_end;\n        ssize_t gif_bytes;\n        unsigned int width, height, offset_x, offset_y;\n        unsigned int flags, colour_table_size, interlace;\n        unsigned int *colour_table;\n        unsigned int *frame_data = 0;\t// Set to 0 for no warnings\n        unsigned int *frame_scanline;\n        ssize_t save_buffer_position;\n        unsigned int return_value = 0;\n        unsigned int x, y, decode_y, burst_bytes;\n        register unsigned char colour;\n\n        /* If the GIF has no frame data, frame holders will not be allocated in\n         * gif_initialise() */\n        if (gif->frames == NULL) {\n                return GIF_INSUFFICIENT_DATA;\n        }\n\n        /* Ensure this frame is supposed to be decoded */\n        if (gif->frames[frame].display == false) {\n                return GIF_OK;\n        }\n\n        /* Ensure the frame is in range to decode */\n        if (frame > gif->frame_count_partial) {\n                return GIF_INSUFFICIENT_DATA;\n        }\n\n        /* done if frame is already decoded */\n        if ((!clear_image) &&\n            ((int)frame == gif->decoded_frame)) {\n                return GIF_OK;\n        }\n\n        /* Get the start of our frame data and the end of the GIF data */\n        gif_data = gif->gif_data + gif->frames[frame].frame_pointer;\n        gif_end = gif->gif_data + gif->buffer_size;\n        gif_bytes = (gif_end - gif_data);\n\n        /*\n         * Ensure there is a minimal amount of data to proceed.  The shortest\n         * block of data is a 10-byte image descriptor + 1-byte gif trailer\n         */\n        if (gif_bytes < 12) {\n                return GIF_INSUFFICIENT_FRAME_DATA;\n        }\n\n        /* Save the buffer position */\n        save_buffer_position = gif->buffer_position;\n        gif->buffer_position = gif_data - gif->gif_data;\n\n        /* Skip any extensions because they have allready been processed */\n        if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK) {\n                goto gif_decode_frame_exit;\n        }\n        gif_data = (gif->gif_data + gif->buffer_position);\n        gif_bytes = (gif_end - gif_data);\n\n        /* Ensure we have enough data for the 10-byte image descriptor + 1-byte\n         * gif trailer\n         */\n        if (gif_bytes < 12) {\n                return_value = GIF_INSUFFICIENT_FRAME_DATA;\n                goto gif_decode_frame_exit;\n        }\n\n        /* 10-byte Image Descriptor is:\n         *\n         *\t+0\tCHAR\tImage Separator (0x2c)\n         *\t+1\tSHORT\tImage Left Position\n         *\t+3\tSHORT\tImage Top Position\n         *\t+5\tSHORT\tWidth\n         *\t+7\tSHORT\tHeight\n         *\t+9\tCHAR\t__Packed Fields__\n         *\t\t\t1BIT\tLocal Colour Table Flag\n         *\t\t\t1BIT\tInterlace Flag\n         *\t\t\t1BIT\tSort Flag\n         *\t\t\t2BITS\tReserved\n         *\t\t\t3BITS\tSize of Local Colour Table\n         */\n        if (gif_data[0] != GIF_IMAGE_SEPARATOR) {\n                return_value = GIF_DATA_ERROR;\n                goto gif_decode_frame_exit;\n        }\n        offset_x = gif_data[1] | (gif_data[2] << 8);\n        offset_y = gif_data[3] | (gif_data[4] << 8);\n        width = gif_data[5] | (gif_data[6] << 8);\n        height = gif_data[7] | (gif_data[8] << 8);\n\n        /* Boundary checking - shouldn't ever happen except unless the data has\n         * been modified since initialisation.\n         */\n        if ((offset_x + width > gif->width) ||\n            (offset_y + height > gif->height)) {\n                return_value = GIF_DATA_ERROR;\n                goto gif_decode_frame_exit;\n        }\n\n        /* Decode the flags */\n        flags = gif_data[9];\n        colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK);\n        interlace = flags & GIF_INTERLACE_MASK;\n\n        /* Advance data pointer to next block either colour table or image\n         * data.\n         */\n        gif_data += 10;\n        gif_bytes = (gif_end - gif_data);\n\n        /* Set up the colour table */\n        if (flags & GIF_COLOUR_TABLE_MASK) {\n                if (gif_bytes < (int)(3 * colour_table_size)) {\n                        return_value = GIF_INSUFFICIENT_FRAME_DATA;\n                        goto gif_decode_frame_exit;\n                }\n                colour_table = gif->local_colour_table;\n                if (!clear_image) {\n                        for (index = 0; index < colour_table_size; index++) {\n                                /* Gif colour map contents are r,g,b.\n                                 *\n                                 * We want to pack them bytewise into the\n                                 * colour table, such that the red component\n                                 * is in byte 0 and the alpha component is in\n                                 * byte 3.\n                                 */\n                                unsigned char *entry =\n                                        (unsigned char *) &colour_table[index];\n\n                                entry[0] = gif_data[0];\t/* r */\n                                entry[1] = gif_data[1];\t/* g */\n                                entry[2] = gif_data[2];\t/* b */\n                                entry[3] = 0xff;\t/* a */\n\n                                gif_data += 3;\n                        }\n                } else {\n                        gif_data += 3 * colour_table_size;\n                }\n                gif_bytes = (gif_end - gif_data);\n        } else {\n                colour_table = gif->global_colour_table;\n        }\n\n        /* Ensure sufficient data remains */\n        if (gif_bytes < 1) {\n                return_value = GIF_INSUFFICIENT_FRAME_DATA;\n                goto gif_decode_frame_exit;\n        }\n\n        /* check for an end marker */\n        if (gif_data[0] == GIF_TRAILER) {\n                return_value = GIF_OK;\n                goto gif_decode_frame_exit;\n        }\n\n        /* Get the frame data */\n        assert(gif->bitmap_callbacks.bitmap_get_buffer);\n        frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);\n        if (!frame_data) {\n                return GIF_INSUFFICIENT_MEMORY;\n        }\n\n        /* If we are clearing the image we just clear, if not decode */\n        if (!clear_image) {\n                lzw_result res;\n                const uint8_t *stack_base;\n                const uint8_t *stack_pos;\n\n                /* Ensure we have enough data for a 1-byte LZW code size +\n                 * 1-byte gif trailer\n                 */\n                if (gif_bytes < 2) {\n                        return_value = GIF_INSUFFICIENT_FRAME_DATA;\n                        goto gif_decode_frame_exit;\n                }\n\n                /* If we only have a 1-byte LZW code size + 1-byte gif trailer,\n                 * we're finished\n                 */\n                if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) {\n                        return_value = GIF_OK;\n                        goto gif_decode_frame_exit;\n                }\n\n                /* If the previous frame's disposal method requires we restore\n                 * the background colour or this is the first frame, clear\n                 * the frame data\n                 */\n                if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) {\n                        memset((char*)frame_data,\n                               GIF_TRANSPARENT_COLOUR,\n                               gif->width * gif->height * sizeof(int));\n                        gif->decoded_frame = frame;\n                        /* The line below would fill the image with its\n                         * background color, but because GIFs support\n                         * transparency we likely wouldn't want to do that. */\n                        /* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */\n                } else if ((frame != 0) &&\n                           (gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) {\n                        return_value = gif_internal_decode_frame(gif,\n                                                                 (frame - 1),\n                                                                 true);\n                        if (return_value != GIF_OK) {\n                                goto gif_decode_frame_exit;\n                        }\n\n                } else if ((frame != 0) &&\n                           (gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) {\n                        /*\n                         * If the previous frame's disposal method requires we\n                         * restore the previous image, find the last image set\n                         * to \"do not dispose\" and get that frame data\n                         */\n                        int last_undisposed_frame = frame - 2;\n                        while ((last_undisposed_frame >= 0) &&\n                               (gif->frames[last_undisposed_frame].disposal_method == GIF_FRAME_RESTORE)) {\n                                last_undisposed_frame--;\n                        }\n\n                        /* If we don't find one, clear the frame data */\n                        if (last_undisposed_frame == -1) {\n                                /* see notes above on transparency\n                                 * vs. background color\n                                 */\n                                memset((char*)frame_data,\n                                       GIF_TRANSPARENT_COLOUR,\n                                       gif->width * gif->height * sizeof(int));\n                        } else {\n                                return_value = gif_internal_decode_frame(gif, last_undisposed_frame, false);\n                                if (return_value != GIF_OK) {\n                                        goto gif_decode_frame_exit;\n                                }\n                                /* Get this frame's data */\n                                assert(gif->bitmap_callbacks.bitmap_get_buffer);\n                                frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);\n                                if (!frame_data) {\n                                        return GIF_INSUFFICIENT_MEMORY;\n                                }\n                        }\n                }\n                gif->decoded_frame = frame;\n                gif->buffer_position = (gif_data - gif->gif_data) + 1;\n\n                /* Initialise the LZW decoding */\n                res = lzw_decode_init(gif->lzw_ctx, gif->gif_data,\n                                gif->buffer_size, gif->buffer_position,\n                                gif_data[0], &stack_base, &stack_pos);\n                if (res != LZW_OK) {\n                        return gif_error_from_lzw(res);\n                }\n\n                /* Decompress the data */\n                for (y = 0; y < height; y++) {\n                        if (interlace) {\n                                decode_y = gif_interlaced_line(height, y) + offset_y;\n                        } else {\n                                decode_y = y + offset_y;\n                        }\n                        frame_scanline = frame_data + offset_x + (decode_y * gif->width);\n\n                        /* Rather than decoding pixel by pixel, we try to burst\n                         * out streams of data to remove the need for end-of\n                         * data checks every pixel.\n                         */\n                        x = width;\n                        while (x > 0) {\n                                burst_bytes = (stack_pos - stack_base);\n                                if (burst_bytes > 0) {\n                                        if (burst_bytes > x) {\n                                                burst_bytes = x;\n                                        }\n                                        x -= burst_bytes;\n                                        while (burst_bytes-- > 0) {\n                                                colour = *--stack_pos;\n                                                if (((gif->frames[frame].transparency) &&\n                                                     (colour != gif->frames[frame].transparency_index)) ||\n                                                    (!gif->frames[frame].transparency)) {\n                                                        *frame_scanline = colour_table[colour];\n                                                }\n                                                frame_scanline++;\n                                        }\n                                } else {\n                                        res = lzw_decode(gif->lzw_ctx, &stack_pos);\n                                        if (res != LZW_OK) {\n                                                /* Unexpected end of frame, try to recover */\n                                                if (res == LZW_OK_EOD) {\n                                                        return_value = GIF_OK;\n                                                } else {\n                                                        return_value = gif_error_from_lzw(res);\n                                                }\n                                                goto gif_decode_frame_exit;\n                                        }\n                                }\n                        }\n                }\n        } else {\n                /* Clear our frame */\n                if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) {\n                        for (y = 0; y < height; y++) {\n                                frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width);\n                                if (gif->frames[frame].transparency) {\n                                        memset(frame_scanline,\n                                               GIF_TRANSPARENT_COLOUR,\n                                               width * 4);\n                                } else {\n                                        memset(frame_scanline,\n                                               colour_table[gif->background_index],\n                                               width * 4);\n                                }\n                        }\n                }\n        }\ngif_decode_frame_exit:\n\n        /* Check if we should test for optimisation */\n        if (gif->frames[frame].virgin) {\n                if (gif->bitmap_callbacks.bitmap_test_opaque) {\n                        gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image);\n                } else {\n                        gif->frames[frame].opaque = false;\n                }\n                gif->frames[frame].virgin = false;\n        }\n\n        if (gif->bitmap_callbacks.bitmap_set_opaque) {\n                gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque);\n        }\n\n        if (gif->bitmap_callbacks.bitmap_modified) {\n                gif->bitmap_callbacks.bitmap_modified(gif->frame_image);\n        }\n\n        /* Restore the buffer position */\n        gif->buffer_position = save_buffer_position;\n\n        return return_value;\n}", "func_hash": 289353344148943948893339832130354113499, "file_name": "libnsgif.c", "file_hash": 172226271399464040769871629514764443605, "cwe": ["CWE-476"], "cve": "CVE-2022-1507", "cve_desc": "chafa: NULL Pointer Dereference in function gif_internal_decode_frame at libnsgif.c:599 allows attackers to cause a denial of service (crash) via a crafted input file. in GitHub repository hpjansson/chafa prior to 1.10.2. chafa: NULL Pointer Dereference in function gif_internal_decode_frame at libnsgif.c:599 allows attackers to cause a denial of service (crash) via a crafted input file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1507"}
{"idx": 199836, "project": "pjproject", "commit_id": "077b465c33f0aec05a49cd2ca456f9a1b112e896", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/077b465c33f0aec05a49cd2ca456f9a1b112e896", "commit_message": "Merge pull request from GHSA-7fw8-54cv-r7pm", "target": 1, "func": "PJ_DEF(int) pj_scan_get_char( pj_scanner *scanner )\n{\n    int chr = *scanner->curptr;\n\n    if (!chr) {\n\tpj_scan_syntax_err(scanner);\n\treturn 0;\n    }\n\n    ++scanner->curptr;\n\n    if (PJ_SCAN_IS_PROBABLY_SPACE(*scanner->curptr) && scanner->skip_ws) {\n\tpj_scan_skip_whitespace(scanner);\n    }\n    return chr;\n}", "func_hash": 113292852369107945981597354542276439074, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2022-21723", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In versions 2.11.1 and prior, parsing an incoming SIP message that contains a malformed multipart can potentially cause out-of-bound read access. This issue affects all PJSIP users that accept SIP multipart. The patch is available as commit in the `master` branch. There are no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21723"}
{"idx": 293522, "project": "pjproject", "commit_id": "077b465c33f0aec05a49cd2ca456f9a1b112e896", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/077b465c33f0aec05a49cd2ca456f9a1b112e896", "commit_message": "Merge pull request from GHSA-7fw8-54cv-r7pm", "target": 0, "func": "PJ_DEF(int) pj_scan_get_char( pj_scanner *scanner )\n{\n    register char *s = scanner->curptr;\n    int chr;\n\n    if (s >= scanner->end || !*s) {\n\tpj_scan_syntax_err(scanner);\n\treturn 0;\n    }\n\n    chr = *s;\n\n    ++s;\n    scanner->curptr = s;\n    if (PJ_SCAN_CHECK_EOF(s) && PJ_SCAN_IS_PROBABLY_SPACE(*s) &&\n    \tscanner->skip_ws)\n    {\n\tpj_scan_skip_whitespace(scanner);\n    }\n    return chr;\n}", "func_hash": 311538047427415366173114134774711443657, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2022-21723", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In versions 2.11.1 and prior, parsing an incoming SIP message that contains a malformed multipart can potentially cause out-of-bound read access. This issue affects all PJSIP users that accept SIP multipart. The patch is available as commit in the `master` branch. There are no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21723"}
{"idx": 199841, "project": "radare2", "commit_id": "feaa4e7f7399c51ee6f52deb84dc3f795b4035d6", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/feaa4e7f7399c51ee6f52deb84dc3f795b4035d6", "commit_message": "Fix null deref in xnu.kernelcache ##crash\n\n* Reported by @xshad3 via huntr.dev", "target": 1, "func": "static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadaddr, Sdb *sdb) {\n\tRBuffer *fbuf = r_buf_ref (buf);\n\tstruct MACH0_(opts_t) opts;\n\tMACH0_(opts_set_default) (&opts, bf);\n\tstruct MACH0_(obj_t) *main_mach0 = MACH0_(new_buf) (fbuf, &opts);\n\tif (!main_mach0) {\n\t\treturn false;\n\t}\n\n\tRRebaseInfo *rebase_info = r_rebase_info_new_from_mach0 (fbuf, main_mach0);\n\tRKernelCacheObj *obj = NULL;\n\n\tRPrelinkRange *prelink_range = get_prelink_info_range_from_mach0 (main_mach0);\n\tif (!prelink_range) {\n\t\tgoto beach;\n\t}\n\n\tobj = R_NEW0 (RKernelCacheObj);\n\tif (!obj) {\n\t\tR_FREE (prelink_range);\n\t\tgoto beach;\n\t}\n\n\tRCFValueDict *prelink_info = NULL;\n\tif (main_mach0->hdr.filetype != MH_FILESET && prelink_range->range.size) {\n\t\tprelink_info = r_cf_value_dict_parse (fbuf, prelink_range->range.offset,\n\t\t\t\tprelink_range->range.size, R_CF_OPTION_SKIP_NSDATA);\n\t\tif (!prelink_info) {\n\t\t\tR_FREE (prelink_range);\n\t\t\tR_FREE (obj);\n\t\t\tgoto beach;\n\t\t}\n\t}\n\n\tif (!pending_bin_files) {\n\t\tpending_bin_files = r_list_new ();\n\t\tif (!pending_bin_files) {\n\t\t\tR_FREE (prelink_range);\n\t\t\tR_FREE (obj);\n\t\t\tR_FREE (prelink_info);\n\t\t\tgoto beach;\n\t\t}\n\t}\n\n\tobj->mach0 = main_mach0;\n\tobj->rebase_info = rebase_info;\n\tobj->prelink_info = prelink_info;\n\tobj->cache_buf = fbuf;\n\tobj->pa2va_exec = prelink_range->pa2va_exec;\n\tobj->pa2va_data = prelink_range->pa2va_data;\n\n\tR_FREE (prelink_range);\n\n\t*bin_obj = obj;\n\n\tr_list_push (pending_bin_files, bf);\n\n\tif (rebase_info || main_mach0->chained_starts) {\n\t\tRIO *io = bf->rbin->iob.io;\n\t\tswizzle_io_read (obj, io);\n\t}\n\n\treturn true;\n\nbeach:\n\tr_buf_free (fbuf);\n\tobj->cache_buf = NULL;\n\tMACH0_(mach0_free) (main_mach0);\n\treturn false;\n}", "func_hash": 233224811640274540394040555084759924603, "file_name": "bin_xnu_kernelcache.c", "file_hash": 125322815790464606650182134413161579767, "cwe": ["CWE-476"], "cve": "CVE-2022-0419", "cve_desc": "NULL Pointer Dereference in GitHub repository radareorg/radare2 prior to 5.6.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0419"}
{"idx": 293750, "project": "radare2", "commit_id": "feaa4e7f7399c51ee6f52deb84dc3f795b4035d6", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/feaa4e7f7399c51ee6f52deb84dc3f795b4035d6", "commit_message": "Fix null deref in xnu.kernelcache ##crash\n\n* Reported by @xshad3 via huntr.dev", "target": 0, "func": "static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadaddr, Sdb *sdb) {\n\tRBuffer *fbuf = r_buf_ref (buf);\n\tstruct MACH0_(opts_t) opts;\n\tMACH0_(opts_set_default) (&opts, bf);\n\tstruct MACH0_(obj_t) *main_mach0 = MACH0_(new_buf) (fbuf, &opts);\n\tif (!main_mach0) {\n\t\treturn false;\n\t}\n\n\tRRebaseInfo *rebase_info = r_rebase_info_new_from_mach0 (fbuf, main_mach0);\n\tRKernelCacheObj *obj = NULL;\n\n\tRPrelinkRange *prelink_range = get_prelink_info_range_from_mach0 (main_mach0);\n\tif (!prelink_range) {\n\t\tgoto beach;\n\t}\n\n\tobj = R_NEW0 (RKernelCacheObj);\n\tif (!obj) {\n\t\tR_FREE (prelink_range);\n\t\tgoto beach;\n\t}\n\n\tRCFValueDict *prelink_info = NULL;\n\tif (main_mach0->hdr.filetype != MH_FILESET && prelink_range->range.size) {\n\t\tprelink_info = r_cf_value_dict_parse (fbuf, prelink_range->range.offset,\n\t\t\t\tprelink_range->range.size, R_CF_OPTION_SKIP_NSDATA);\n\t\tif (!prelink_info) {\n\t\t\tR_FREE (prelink_range);\n\t\t\tR_FREE (obj);\n\t\t\tgoto beach;\n\t\t}\n\t}\n\n\tif (!pending_bin_files) {\n\t\tpending_bin_files = r_list_new ();\n\t\tif (!pending_bin_files) {\n\t\t\tR_FREE (prelink_range);\n\t\t\tR_FREE (obj);\n\t\t\tR_FREE (prelink_info);\n\t\t\tgoto beach;\n\t\t}\n\t}\n\n\tobj->mach0 = main_mach0;\n\tobj->rebase_info = rebase_info;\n\tobj->prelink_info = prelink_info;\n\tobj->cache_buf = fbuf;\n\tobj->pa2va_exec = prelink_range->pa2va_exec;\n\tobj->pa2va_data = prelink_range->pa2va_data;\n\n\tR_FREE (prelink_range);\n\n\t*bin_obj = obj;\n\n\tr_list_push (pending_bin_files, bf);\n\n\tif (rebase_info || main_mach0->chained_starts) {\n\t\tRIO *io = bf->rbin->iob.io;\n\t\tswizzle_io_read (obj, io);\n\t}\n\n\treturn true;\n\nbeach:\n\tr_buf_free (fbuf);\n\tif (obj) {\n\t\tobj->cache_buf = NULL;\n\t}\n\tMACH0_(mach0_free) (main_mach0);\n\treturn false;\n}", "func_hash": 89284562812027856469144613822814889366, "file_name": "bin_xnu_kernelcache.c", "file_hash": 321377781677570580244771377920228203962, "cwe": ["CWE-476"], "cve": "CVE-2022-0419", "cve_desc": "NULL Pointer Dereference in GitHub repository radareorg/radare2 prior to 5.6.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0419"}
{"idx": 199851, "project": "vim", "commit_id": "6e28703a8e41f775f64e442c5d11ce1ff599aa3f", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/6e28703a8e41f775f64e442c5d11ce1ff599aa3f", "commit_message": "patch 8.2.4359: crash when repeatedly using :retab\n\nProblem:    crash when repeatedly using :retab.\nSolution:   Bail out when the line is getting too long.", "target": 1, "func": "ex_retab(exarg_T *eap)\n{\n    linenr_T\tlnum;\n    int\t\tgot_tab = FALSE;\n    long\tnum_spaces = 0;\n    long\tnum_tabs;\n    long\tlen;\n    long\tcol;\n    long\tvcol;\n    long\tstart_col = 0;\t\t// For start of white-space string\n    long\tstart_vcol = 0;\t\t// For start of white-space string\n    long\told_len;\n    char_u\t*ptr;\n    char_u\t*new_line = (char_u *)1; // init to non-NULL\n    int\t\tdid_undo;\t\t// called u_save for current line\n#ifdef FEAT_VARTABS\n    int\t\t*new_vts_array = NULL;\n    char_u\t*new_ts_str;\t\t// string value of tab argument\n#else\n    int\t\ttemp;\n    int\t\tnew_ts;\n#endif\n    int\t\tsave_list;\n    linenr_T\tfirst_line = 0;\t\t// first changed line\n    linenr_T\tlast_line = 0;\t\t// last changed line\n\n    save_list = curwin->w_p_list;\n    curwin->w_p_list = 0;\t    // don't want list mode here\n\n#ifdef FEAT_VARTABS\n    new_ts_str = eap->arg;\n    if (tabstop_set(eap->arg, &new_vts_array) == FAIL)\n\treturn;\n    while (vim_isdigit(*(eap->arg)) || *(eap->arg) == ',')\n\t++(eap->arg);\n\n    // This ensures that either new_vts_array and new_ts_str are freshly\n    // allocated, or new_vts_array points to an existing array and new_ts_str\n    // is null.\n    if (new_vts_array == NULL)\n    {\n\tnew_vts_array = curbuf->b_p_vts_array;\n\tnew_ts_str = NULL;\n    }\n    else\n\tnew_ts_str = vim_strnsave(new_ts_str, eap->arg - new_ts_str);\n#else\n    ptr = eap->arg;\n    new_ts = getdigits(&ptr);\n    if (new_ts < 0 && *eap->arg == '-')\n    {\n\temsg(_(e_argument_must_be_positive));\n\treturn;\n    }\n    if (new_ts < 0 || new_ts > TABSTOP_MAX)\n    {\n\tsemsg(_(e_invalid_argument_str), eap->arg);\n\treturn;\n    }\n    if (new_ts == 0)\n\tnew_ts = curbuf->b_p_ts;\n#endif\n    for (lnum = eap->line1; !got_int && lnum <= eap->line2; ++lnum)\n    {\n\tptr = ml_get(lnum);\n\tcol = 0;\n\tvcol = 0;\n\tdid_undo = FALSE;\n\tfor (;;)\n\t{\n\t    if (VIM_ISWHITE(ptr[col]))\n\t    {\n\t\tif (!got_tab && num_spaces == 0)\n\t\t{\n\t\t    // First consecutive white-space\n\t\t    start_vcol = vcol;\n\t\t    start_col = col;\n\t\t}\n\t\tif (ptr[col] == ' ')\n\t\t    num_spaces++;\n\t\telse\n\t\t    got_tab = TRUE;\n\t    }\n\t    else\n\t    {\n\t\tif (got_tab || (eap->forceit && num_spaces > 1))\n\t\t{\n\t\t    // Retabulate this string of white-space\n\n\t\t    // len is virtual length of white string\n\t\t    len = num_spaces = vcol - start_vcol;\n\t\t    num_tabs = 0;\n\t\t    if (!curbuf->b_p_et)\n\t\t    {\n#ifdef FEAT_VARTABS\n\t\t\tint t, s;\n\n\t\t\ttabstop_fromto(start_vcol, vcol,\n\t\t\t\t\tcurbuf->b_p_ts, new_vts_array, &t, &s);\n\t\t\tnum_tabs = t;\n\t\t\tnum_spaces = s;\n#else\n\t\t\ttemp = new_ts - (start_vcol % new_ts);\n\t\t\tif (num_spaces >= temp)\n\t\t\t{\n\t\t\t    num_spaces -= temp;\n\t\t\t    num_tabs++;\n\t\t\t}\n\t\t\tnum_tabs += num_spaces / new_ts;\n\t\t\tnum_spaces -= (num_spaces / new_ts) * new_ts;\n#endif\n\t\t    }\n\t\t    if (curbuf->b_p_et || got_tab ||\n\t\t\t\t\t(num_spaces + num_tabs < len))\n\t\t    {\n\t\t\tif (did_undo == FALSE)\n\t\t\t{\n\t\t\t    did_undo = TRUE;\n\t\t\t    if (u_save((linenr_T)(lnum - 1),\n\t\t\t\t\t\t(linenr_T)(lnum + 1)) == FAIL)\n\t\t\t    {\n\t\t\t\tnew_line = NULL;\t// flag out-of-memory\n\t\t\t\tbreak;\n\t\t\t    }\n\t\t\t}\n\n\t\t\t// len is actual number of white characters used\n\t\t\tlen = num_spaces + num_tabs;\n\t\t\told_len = (long)STRLEN(ptr);\n\t\t\tnew_line = alloc(old_len - col + start_col + len + 1);\n\t\t\tif (new_line == NULL)\n\t\t\t    break;\n\t\t\tif (start_col > 0)\n\t\t\t    mch_memmove(new_line, ptr, (size_t)start_col);\n\t\t\tmch_memmove(new_line + start_col + len,\n\t\t\t\t      ptr + col, (size_t)(old_len - col + 1));\n\t\t\tptr = new_line + start_col;\n\t\t\tfor (col = 0; col < len; col++)\n\t\t\t    ptr[col] = (col < num_tabs) ? '\\t' : ' ';\n\t\t\tif (ml_replace(lnum, new_line, FALSE) == OK)\n\t\t\t    // \"new_line\" may have been copied\n\t\t\t    new_line = curbuf->b_ml.ml_line_ptr;\n\t\t\tif (first_line == 0)\n\t\t\t    first_line = lnum;\n\t\t\tlast_line = lnum;\n\t\t\tptr = new_line;\n\t\t\tcol = start_col + len;\n\t\t    }\n\t\t}\n\t\tgot_tab = FALSE;\n\t\tnum_spaces = 0;\n\t    }\n\t    if (ptr[col] == NUL)\n\t\tbreak;\n\t    vcol += chartabsize(ptr + col, (colnr_T)vcol);\n\t    if (has_mbyte)\n\t\tcol += (*mb_ptr2len)(ptr + col);\n\t    else\n\t\t++col;\n\t}\n\tif (new_line == NULL)\t\t    // out of memory\n\t    break;\n\tline_breakcheck();\n    }\n    if (got_int)\n\temsg(_(e_interrupted));\n\n#ifdef FEAT_VARTABS\n    // If a single value was given then it can be considered equal to\n    // either the value of 'tabstop' or the value of 'vartabstop'.\n    if (tabstop_count(curbuf->b_p_vts_array) == 0\n\t&& tabstop_count(new_vts_array) == 1\n\t&& curbuf->b_p_ts == tabstop_first(new_vts_array))\n\t; // not changed\n    else if (tabstop_count(curbuf->b_p_vts_array) > 0\n        && tabstop_eq(curbuf->b_p_vts_array, new_vts_array))\n\t; // not changed\n    else\n\tredraw_curbuf_later(NOT_VALID);\n#else\n    if (curbuf->b_p_ts != new_ts)\n\tredraw_curbuf_later(NOT_VALID);\n#endif\n    if (first_line != 0)\n\tchanged_lines(first_line, 0, last_line + 1, 0L);\n\n    curwin->w_p_list = save_list;\t// restore 'list'\n\n#ifdef FEAT_VARTABS\n    if (new_ts_str != NULL)\t\t// set the new tabstop\n    {\n\t// If 'vartabstop' is in use or if the value given to retab has more\n\t// than one tabstop then update 'vartabstop'.\n\tint *old_vts_ary = curbuf->b_p_vts_array;\n\n\tif (tabstop_count(old_vts_ary) > 0 || tabstop_count(new_vts_array) > 1)\n\t{\n\t    set_string_option_direct((char_u *)\"vts\", -1, new_ts_str,\n\t\t\t\t\t\t\tOPT_FREE|OPT_LOCAL, 0);\n\t    curbuf->b_p_vts_array = new_vts_array;\n\t    vim_free(old_vts_ary);\n\t}\n\telse\n\t{\n\t    // 'vartabstop' wasn't in use and a single value was given to\n\t    // retab then update 'tabstop'.\n\t    curbuf->b_p_ts = tabstop_first(new_vts_array);\n\t    vim_free(new_vts_array);\n\t}\n\tvim_free(new_ts_str);\n    }\n#else\n    curbuf->b_p_ts = new_ts;\n#endif\n    coladvance(curwin->w_curswant);\n\n    u_clearline();\n}", "func_hash": 55704685563391152697895881333081984969, "file_name": "indent.c", "file_hash": 264017227782989622614587099376842569247, "cwe": ["CWE-787"], "cve": "CVE-2022-0572", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0572"}
{"idx": 293939, "project": "vim", "commit_id": "6e28703a8e41f775f64e442c5d11ce1ff599aa3f", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/6e28703a8e41f775f64e442c5d11ce1ff599aa3f", "commit_message": "patch 8.2.4359: crash when repeatedly using :retab\n\nProblem:    crash when repeatedly using :retab.\nSolution:   Bail out when the line is getting too long.", "target": 0, "func": "ex_retab(exarg_T *eap)\n{\n    linenr_T\tlnum;\n    int\t\tgot_tab = FALSE;\n    long\tnum_spaces = 0;\n    long\tnum_tabs;\n    long\tlen;\n    long\tcol;\n    long\tvcol;\n    long\tstart_col = 0;\t\t// For start of white-space string\n    long\tstart_vcol = 0;\t\t// For start of white-space string\n    long\told_len;\n    char_u\t*ptr;\n    char_u\t*new_line = (char_u *)1; // init to non-NULL\n    int\t\tdid_undo;\t\t// called u_save for current line\n#ifdef FEAT_VARTABS\n    int\t\t*new_vts_array = NULL;\n    char_u\t*new_ts_str;\t\t// string value of tab argument\n#else\n    int\t\ttemp;\n    int\t\tnew_ts;\n#endif\n    int\t\tsave_list;\n    linenr_T\tfirst_line = 0;\t\t// first changed line\n    linenr_T\tlast_line = 0;\t\t// last changed line\n\n    save_list = curwin->w_p_list;\n    curwin->w_p_list = 0;\t    // don't want list mode here\n\n#ifdef FEAT_VARTABS\n    new_ts_str = eap->arg;\n    if (tabstop_set(eap->arg, &new_vts_array) == FAIL)\n\treturn;\n    while (vim_isdigit(*(eap->arg)) || *(eap->arg) == ',')\n\t++(eap->arg);\n\n    // This ensures that either new_vts_array and new_ts_str are freshly\n    // allocated, or new_vts_array points to an existing array and new_ts_str\n    // is null.\n    if (new_vts_array == NULL)\n    {\n\tnew_vts_array = curbuf->b_p_vts_array;\n\tnew_ts_str = NULL;\n    }\n    else\n\tnew_ts_str = vim_strnsave(new_ts_str, eap->arg - new_ts_str);\n#else\n    ptr = eap->arg;\n    new_ts = getdigits(&ptr);\n    if (new_ts < 0 && *eap->arg == '-')\n    {\n\temsg(_(e_argument_must_be_positive));\n\treturn;\n    }\n    if (new_ts < 0 || new_ts > TABSTOP_MAX)\n    {\n\tsemsg(_(e_invalid_argument_str), eap->arg);\n\treturn;\n    }\n    if (new_ts == 0)\n\tnew_ts = curbuf->b_p_ts;\n#endif\n    for (lnum = eap->line1; !got_int && lnum <= eap->line2; ++lnum)\n    {\n\tptr = ml_get(lnum);\n\tcol = 0;\n\tvcol = 0;\n\tdid_undo = FALSE;\n\tfor (;;)\n\t{\n\t    if (VIM_ISWHITE(ptr[col]))\n\t    {\n\t\tif (!got_tab && num_spaces == 0)\n\t\t{\n\t\t    // First consecutive white-space\n\t\t    start_vcol = vcol;\n\t\t    start_col = col;\n\t\t}\n\t\tif (ptr[col] == ' ')\n\t\t    num_spaces++;\n\t\telse\n\t\t    got_tab = TRUE;\n\t    }\n\t    else\n\t    {\n\t\tif (got_tab || (eap->forceit && num_spaces > 1))\n\t\t{\n\t\t    // Retabulate this string of white-space\n\n\t\t    // len is virtual length of white string\n\t\t    len = num_spaces = vcol - start_vcol;\n\t\t    num_tabs = 0;\n\t\t    if (!curbuf->b_p_et)\n\t\t    {\n#ifdef FEAT_VARTABS\n\t\t\tint t, s;\n\n\t\t\ttabstop_fromto(start_vcol, vcol,\n\t\t\t\t\tcurbuf->b_p_ts, new_vts_array, &t, &s);\n\t\t\tnum_tabs = t;\n\t\t\tnum_spaces = s;\n#else\n\t\t\ttemp = new_ts - (start_vcol % new_ts);\n\t\t\tif (num_spaces >= temp)\n\t\t\t{\n\t\t\t    num_spaces -= temp;\n\t\t\t    num_tabs++;\n\t\t\t}\n\t\t\tnum_tabs += num_spaces / new_ts;\n\t\t\tnum_spaces -= (num_spaces / new_ts) * new_ts;\n#endif\n\t\t    }\n\t\t    if (curbuf->b_p_et || got_tab ||\n\t\t\t\t\t(num_spaces + num_tabs < len))\n\t\t    {\n\t\t\tif (did_undo == FALSE)\n\t\t\t{\n\t\t\t    did_undo = TRUE;\n\t\t\t    if (u_save((linenr_T)(lnum - 1),\n\t\t\t\t\t\t(linenr_T)(lnum + 1)) == FAIL)\n\t\t\t    {\n\t\t\t\tnew_line = NULL;\t// flag out-of-memory\n\t\t\t\tbreak;\n\t\t\t    }\n\t\t\t}\n\n\t\t\t// len is actual number of white characters used\n\t\t\tlen = num_spaces + num_tabs;\n\t\t\told_len = (long)STRLEN(ptr);\n\t\t\tnew_line = alloc(old_len - col + start_col + len + 1);\n\t\t\tif (new_line == NULL)\n\t\t\t    break;\n\t\t\tif (start_col > 0)\n\t\t\t    mch_memmove(new_line, ptr, (size_t)start_col);\n\t\t\tmch_memmove(new_line + start_col + len,\n\t\t\t\t      ptr + col, (size_t)(old_len - col + 1));\n\t\t\tptr = new_line + start_col;\n\t\t\tfor (col = 0; col < len; col++)\n\t\t\t    ptr[col] = (col < num_tabs) ? '\\t' : ' ';\n\t\t\tif (ml_replace(lnum, new_line, FALSE) == OK)\n\t\t\t    // \"new_line\" may have been copied\n\t\t\t    new_line = curbuf->b_ml.ml_line_ptr;\n\t\t\tif (first_line == 0)\n\t\t\t    first_line = lnum;\n\t\t\tlast_line = lnum;\n\t\t\tptr = new_line;\n\t\t\tcol = start_col + len;\n\t\t    }\n\t\t}\n\t\tgot_tab = FALSE;\n\t\tnum_spaces = 0;\n\t    }\n\t    if (ptr[col] == NUL)\n\t\tbreak;\n\t    vcol += chartabsize(ptr + col, (colnr_T)vcol);\n\t    if (vcol >= MAXCOL)\n\t    {\n\t\temsg(_(e_resulting_text_too_long));\n\t\tbreak;\n\t    }\n\t    if (has_mbyte)\n\t\tcol += (*mb_ptr2len)(ptr + col);\n\t    else\n\t\t++col;\n\t}\n\tif (new_line == NULL)\t\t    // out of memory\n\t    break;\n\tline_breakcheck();\n    }\n    if (got_int)\n\temsg(_(e_interrupted));\n\n#ifdef FEAT_VARTABS\n    // If a single value was given then it can be considered equal to\n    // either the value of 'tabstop' or the value of 'vartabstop'.\n    if (tabstop_count(curbuf->b_p_vts_array) == 0\n\t&& tabstop_count(new_vts_array) == 1\n\t&& curbuf->b_p_ts == tabstop_first(new_vts_array))\n\t; // not changed\n    else if (tabstop_count(curbuf->b_p_vts_array) > 0\n        && tabstop_eq(curbuf->b_p_vts_array, new_vts_array))\n\t; // not changed\n    else\n\tredraw_curbuf_later(NOT_VALID);\n#else\n    if (curbuf->b_p_ts != new_ts)\n\tredraw_curbuf_later(NOT_VALID);\n#endif\n    if (first_line != 0)\n\tchanged_lines(first_line, 0, last_line + 1, 0L);\n\n    curwin->w_p_list = save_list;\t// restore 'list'\n\n#ifdef FEAT_VARTABS\n    if (new_ts_str != NULL)\t\t// set the new tabstop\n    {\n\t// If 'vartabstop' is in use or if the value given to retab has more\n\t// than one tabstop then update 'vartabstop'.\n\tint *old_vts_ary = curbuf->b_p_vts_array;\n\n\tif (tabstop_count(old_vts_ary) > 0 || tabstop_count(new_vts_array) > 1)\n\t{\n\t    set_string_option_direct((char_u *)\"vts\", -1, new_ts_str,\n\t\t\t\t\t\t\tOPT_FREE|OPT_LOCAL, 0);\n\t    curbuf->b_p_vts_array = new_vts_array;\n\t    vim_free(old_vts_ary);\n\t}\n\telse\n\t{\n\t    // 'vartabstop' wasn't in use and a single value was given to\n\t    // retab then update 'tabstop'.\n\t    curbuf->b_p_ts = tabstop_first(new_vts_array);\n\t    vim_free(new_vts_array);\n\t}\n\tvim_free(new_ts_str);\n    }\n#else\n    curbuf->b_p_ts = new_ts;\n#endif\n    coladvance(curwin->w_curswant);\n\n    u_clearline();\n}", "func_hash": 256003981723363048355423518421227047339, "file_name": "indent.c", "file_hash": 225104819640164774379021828754456921804, "cwe": ["CWE-787"], "cve": "CVE-2022-0572", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0572"}
{"idx": 199952, "project": "MilkyTracker", "commit_id": "3a5474f9102cbdc10fbd9e7b1b2c8d3f3f45d91b", "project_url": "https://github.com/milkytracker/MilkyTracker", "commit_url": "https://github.com/milkytracker/MilkyTracker/commit/3a5474f9102cbdc10fbd9e7b1b2c8d3f3f45d91b", "commit_message": "Fix possible stack corruption with XM instrument headers claiming a size of less than 4\n\nCloses #275", "target": 1, "func": "mp_sint32 LoaderXM::load(XMFileBase& f, XModule* module)\n{\n\tmp_ubyte insData[230];\t\t\n\tmp_sint32 smpReloc[MP_MAXINSSAMPS];\n\tmp_ubyte nbu[MP_MAXINSSAMPS];\n\tmp_uint32 fileSize = 0;\n\t\t\t\n\tmodule->cleanUp();\n\n\t// this will make code much easier to read\n\tTXMHeader*\t\theader = &module->header;\n\tTXMInstrument*\tinstr  = module->instr;\n\tTXMSample*\t\tsmp\t   = module->smp;\n\tTXMPattern*\t\tphead  = module->phead;\t\n\n\t// we're already out of memory here\n\tif (!phead || !instr || !smp)\n\t\treturn MP_OUT_OF_MEMORY;\n\t\n\tfileSize = f.sizeWithBaseOffset();\n\t\n\tf.read(&header->sig,1,17);\n\tf.read(&header->name,1,20);\n\tf.read(&header->whythis1a,1,1);\n\theader->whythis1a=0;\n\tf.read(&header->tracker,1,20);\n\tf.readWords(&header->ver,1);\n\t\n\tif (header->ver != 0x102 && \n\t\theader->ver != 0x103 && // untested\n\t\theader->ver != 0x104)\n\t\treturn MP_LOADER_FAILED;\n\t\n\tf.readDwords(&header->hdrsize,1);\n\t\n\theader->hdrsize-=4;\n\t\n\tmp_uint32 hdrSize = 0x110;\n\tif (header->hdrsize > hdrSize)\n\t\thdrSize = header->hdrsize;\n\t\t\t\t\n\tmp_ubyte* hdrBuff = new mp_ubyte[hdrSize];\n\tmemset(hdrBuff, 0, hdrSize);\n\t\n\tf.read(hdrBuff, 1, header->hdrsize);\n\t\n\theader->ordnum = LittleEndian::GET_WORD(hdrBuff);\n\theader->restart = LittleEndian::GET_WORD(hdrBuff+2);\n\theader->channum = LittleEndian::GET_WORD(hdrBuff+4);\n\theader->patnum = LittleEndian::GET_WORD(hdrBuff+6);\n\theader->insnum = LittleEndian::GET_WORD(hdrBuff+8);\n\theader->freqtab = LittleEndian::GET_WORD(hdrBuff+10);\n\theader->tempo = LittleEndian::GET_WORD(hdrBuff+12);\n\theader->speed = LittleEndian::GET_WORD(hdrBuff+14);\n\tmemcpy(header->ord, hdrBuff+16, 256);\n\tif(header->ordnum > MP_MAXORDERS)\n\t\theader->ordnum = MP_MAXORDERS;\n\tif(header->insnum > MP_MAXINS)\n\t\treturn MP_LOADER_FAILED;\n\n\tdelete[] hdrBuff;\n\t\n\theader->mainvol=255;\n\theader->flags = XModule::MODULE_XMNOTECLIPPING | \n\t\tXModule::MODULE_XMARPEGGIO | \n\t\tXModule::MODULE_XMPORTANOTEBUFFER | \n\t\tXModule::MODULE_XMVOLCOLUMNVIBRATO;\n\n\theader->uppernotebound = 119;\n\t\n\tmp_sint32 i,y,sc;\n\tfor (i=0;i<32;i++) header->pan[i]=0x80;\n\t\n\t// old version?\n\tif (header->ver == 0x102 || header->ver == 0x103)\n\t{\n\t\tmp_sint32 s = 0;\n\t\tmp_sint32 e = 0;\n\t\tfor (y=0;yinsnum;y++) {\n\t\t\t\n\t\t\tf.readDwords(&instr[y].size,1);\n\t\t\tf.read(&instr[y].name,1,22);\t\t\n\t\t\tf.read(&instr[y].type,1,1);\n\t\t\tmp_uword numSamples = 0;\n\t\t\tf.readWords(&numSamples,1);\n\t\t\tif(numSamples > MP_MAXINSSAMPS)\n\t\t\t\treturn MP_LOADER_FAILED;\n\t\t\tinstr[y].samp = numSamples;\n\n\t\t\tif (instr[y].size == 29)\n\t\t\t{\n#ifdef MILKYTRACKER\n\t\t\t\ts+=16;\n#endif\n\t\t\t\tfor (mp_sint32 i = 0; i < 120; i++)\n\t\t\t\t\tinstr[y].snum[i] = -1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tf.readDwords(&instr[y].shsize,1);\n\n\t\t\tmemset(insData, 0, 230);\n\t\t\t\n\t\t\tif (instr[y].size - 33 > 230)\n\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\n\t\t\tf.read(insData, 1, instr[y].size - 33);\n\t\t\t\t\t\t\n\t\t\tif (instr[y].samp) {\n\t\t\t\tmp_ubyte* insDataPtr = insData;\n\t\t\t\t\n\t\t\t\tmemcpy(nbu, insDataPtr, MP_MAXINSSAMPS);\n\t\t\t\tinsDataPtr+=MP_MAXINSSAMPS;\n\t\t\t\t\n\t\t\t\tTEnvelope venv;\n\t\t\t\tTEnvelope penv;\n\t\t\t\tmemset(&venv,0,sizeof(venv));\n\t\t\t\tmemset(&penv,0,sizeof(penv));\n\t\t\t\t\n\t\t\t\tmp_sint32 k;\n\t\t\t\tfor (k = 0; k < XM_ENVELOPENUMPOINTS; k++)\n\t\t\t\t{\n\t\t\t\t\tvenv.env[k][0] = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\t\tvenv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2);\n\t\t\t\t\tinsDataPtr+=4;\n\t\t\t\t}\n\t\t\t\tfor (k = 0; k < XM_ENVELOPENUMPOINTS; k++)\n\t\t\t\t{\n\t\t\t\t\tpenv.env[k][0] = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\t\tpenv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2);\n\t\t\t\t\tinsDataPtr+=4;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvenv.num = *insDataPtr++;\t\n\t\t\t\tif (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS;\n\t\t\t\tpenv.num = *insDataPtr++;\t\n\t\t\t\tif (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS;\n\t\t\t\tvenv.sustain = *insDataPtr++;\n\t\t\t\tvenv.loops = *insDataPtr++;\n\t\t\t\tvenv.loope = *insDataPtr++;\n\t\t\t\tpenv.sustain = *insDataPtr++;\n\t\t\t\tpenv.loops = *insDataPtr++;\n\t\t\t\tpenv.loope = *insDataPtr++;\n\t\t\t\tvenv.type = *insDataPtr++;\n\t\t\t\tpenv.type = *insDataPtr++;\t\t\t\t\n\t\t\t\t\n\t\t\t\tmp_ubyte vibtype, vibsweep, vibdepth, vibrate;\n\t\t\t\tmp_uword volfade;\n\t\t\t\t\n\t\t\t\tvibtype = *insDataPtr++;\n\t\t\t\tvibsweep = *insDataPtr++;\n\t\t\t\tvibdepth = *insDataPtr++;\n\t\t\t\tvibrate = *insDataPtr++;\n\t\t\t\t\n\t\t\t\tvibdepth<<=1;\n\t\t\t\t\n\t\t\t\tvolfade = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\tinsDataPtr+=2;\n\t\t\t\tvolfade<<=1;\n\t\t\t\t\n\t\t\t\t//instr[y].res = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\tinsDataPtr+=2;\n\t\t\t\t\n\t\t\t\tfor (mp_sint32 l=0;laddVolumeEnvelope(venv)) \n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\tif (!module->addPanningEnvelope(penv)) \n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\t\n\t\t\t\tmp_sint32 g=0, sc;\n\t\t\t\tfor (sc=0;scaddSongMessageLine(line);\n\t\t\t\t\t\n\t\t\t\t\t// ignore empty samples\n#ifndef MILKYTRACKER\n\t\t\t\t\t// ignore empty samples when not being a tracker\n\t\t\t\t\tif (smp[g+s].samplen) {\n\t\t\t\t\t\tsmpReloc[sc] = g;\n\t\t\t\t\t\tg++;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tsmpReloc[sc] = -1;\n#else\n\t\t\t\t\tsmpReloc[sc] = g;\n\t\t\t\t\tg++;\n#endif\n\t\t\t\t}\n\n\t\t\t\tinstr[y].samp = g;\n\n\t\t\t\tfor (sc = 0; sc < MP_MAXINSSAMPS; sc++) {\n\t\t\t\t\tif (smpReloc[nbu[sc]] == -1)\n\t\t\t\t\t\tinstr[y].snum[sc] = -1;\n\t\t\t\t\telse\n\t\t\t\t\t\tinstr[y].snum[sc] = smpReloc[nbu[sc]]+s;\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\te++;\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor (mp_sint32 i = 0; i < 120; i++)\n\t\t\t\t\tinstr[y].snum[i] = -1;\n\t\t\t}\n\n#ifdef MILKYTRACKER\n\t\t\ts+=16;\n#else\n\t\t\ts+=instr[y].samp;\n#endif\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t}\n\t\t\n\t\theader->smpnum=s;\n\t\theader->volenvnum=e;\n\t\theader->panenvnum=e;\n\t}\n\t\n\tfor (y=0;ypatnum;y++) {\n\t\t\n\t\tif (header->ver == 0x104 || header->ver == 0x103)\n\t\t{\n\t\t\tf.readDwords(&phead[y].len,1);\n\t\t\tf.read(&phead[y].ptype,1,1);\n\t\t\tf.readWords(&phead[y].rows,1);\n\t\t\tf.readWords(&phead[y].patdata,1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tf.readDwords(&phead[y].len,1);\n\t\t\tf.read(&phead[y].ptype,1,1);\n\t\t\tphead[y].rows = (mp_uword)f.readByte()+1;\n\t\t\tf.readWords(&phead[y].patdata,1);\t\t\t\n\t\t}\n\t\t\n\t\tphead[y].effnum=2;\n\t\tphead[y].channum=(mp_ubyte)header->channum;\n\t\t\n\t\tphead[y].patternData = new mp_ubyte[phead[y].rows*header->channum*6];\n\t\t\n\t\t// out of memory?\n\t\tif (phead[y].patternData == NULL)\n\t\t{\n\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t}\n\t\t\n\t\tmemset(phead[y].patternData,0,phead[y].rows*header->channum*6);\n\t\t\n\t\tif (phead[y].patdata) {\n\t\t\tmp_ubyte *buffer = new mp_ubyte[phead[y].patdata];\n\t\t\t\n\t\t\t// out of memory?\n\t\t\tif (buffer == NULL)\n\t\t\t{\n\t\t\t\treturn MP_OUT_OF_MEMORY;\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tf.read(buffer,1,phead[y].patdata);\n\t\t\t\n\t\t\t//printf(\"%i\\n\", phead[y].patdata);\n\t\t\t\n\t\t\tmp_sint32 pc = 0, bc = 0;\n\t\t\tfor (mp_sint32 r=0;rchannum;c++) {\n\t\t\t\t\t\n\t\t\t\t\tmp_ubyte slot[5];\n\t\t\t\t\tmemset(slot,0,5);\n\t\t\t\t\t\n\t\t\t\t\tif ((buffer[pc]&128)) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tmp_ubyte pb = buffer[pc];\n\t\t\t\t\t\tpc++;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ((pb&1)) {\n\t\t\t\t\t\t\t//phead[y].patternData[bc]=buffer[pc];\n\t\t\t\t\t\t\tslot[0]=buffer[pc];\n\t\t\t\t\t\t\tpc++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((pb&2)) {\n\t\t\t\t\t\t\t//phead[y].patternData[bc+1]=buffer[pc];\n\t\t\t\t\t\t\tslot[1]=buffer[pc];\n\t\t\t\t\t\t\tpc++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((pb&4)) {\n\t\t\t\t\t\t\t//phead[y].patternData[bc+2]=buffer[pc];\n\t\t\t\t\t\t\tslot[2]=buffer[pc];\n\t\t\t\t\t\t\tpc++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((pb&8)) {\n\t\t\t\t\t\t\t//phead[y].patternData[bc+3]=buffer[pc];\n\t\t\t\t\t\t\tslot[3]=buffer[pc];\n\t\t\t\t\t\t\tpc++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((pb&16)) {\n\t\t\t\t\t\t\t//phead[y].patternData[bc+4]=buffer[pc];\n\t\t\t\t\t\t\tslot[4]=buffer[pc];\n\t\t\t\t\t\t\tpc++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t//memcpy(phead[y].patternData+bc,buffer+pc,5);\n\t\t\t\t\t\tmemcpy(slot,buffer+pc,5);\n\t\t\t\t\t\tpc+=5;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tchar gl=0;\n\t\t\t\t\tfor (mp_sint32 i=0;i64) bl=64;\n\t\t\t\t\t\tslot[4]=(bl*261120)>>16;*/\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif ((!slot[3])&&(slot[4])) slot[3]=0x20;\n\t\t\t\t\t\n\t\t\t\t\tif (slot[3]==0xE) {\n\t\t\t\t\t\tslot[3]=(slot[4]>>4)+0x30;\n\t\t\t\t\t\tslot[4]=slot[4]&0xf;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (slot[3]==0x21) {\n\t\t\t\t\t\tslot[3]=(slot[4]>>4)+0x40;\n\t\t\t\t\t\tslot[4]=slot[4]&0xf;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (slot[0]==97) slot[0]=XModule::NOTE_OFF;\n\t\t\t\t\t\n\t\t\t\t\tphead[y].patternData[bc]=slot[0];\n\t\t\t\t\tphead[y].patternData[bc+1]=slot[1];\n\t\t\t\t\t\n\t\t\t\t\tXModule::convertXMVolumeEffects(slot[2], phead[y].patternData[bc+2], phead[y].patternData[bc+3]);\n\n\t\t\t\t\tphead[y].patternData[bc+4]=slot[3];\n\t\t\t\t\tphead[y].patternData[bc+5]=slot[4];\n\t\t\t\t\t\n\t\t\t\t\t/*if ((y==3)&&(c==2)) {\n\t\t\t\t\t\tfor (mp_sint32 bl=0;bl<6;bl++) cprintf(\"%x \",phead[y].patternData[bc+bl]);\n\t\t\t\t\tcprintf(\"\\r\\n\");\n\t\t\t\t\tgetch();\n\t\t\t\t\t};*/\n\t\t\t\t\t\n\t\t\t\t\t/*printf(\"Note : %i\\r\\n\",phead[y].patternData[bc]);\n\t\t\t\t\tprintf(\"Ins  : %i\\r\\n\",phead[y].patternData[bc+1]);\n\t\t\t\t\tprintf(\"Vol  : %i\\r\\n\",phead[y].patternData[bc+2]);\n\t\t\t\t\tprintf(\"Eff  : %i\\r\\n\",phead[y].patternData[bc+3]);\n\t\t\t\t\tprintf(\"Effop: %i\\r\\n\",phead[y].patternData[bc+4]);\n\t\t\t\t\tgetch();*/\n\t\t\t\t\t\n\t\t\t\t\tbc+=6;\n\t\t\t\t} // for c\n\t\t\t\t\t\n\t\t\t} // for r\n\t\t\t\t\n\t\t\tdelete[] buffer;\n\t\t}\n\t\t\t\n\t}\n\t\t\n\tif (header->ver == 0x104)\n\t{\n\t\tmp_sint32 s = 0;\n\t\tmp_sint32 e = 0;\n\t\tfor (y=0;yinsnum;y++) {\n\n\t\t\t// fixes MOOH.XM loading problems\n\t\t\t// seems to store more instruments in the header than in the actual file\n\t\t\tif (f.posWithBaseOffset() >= fileSize)\n\t\t\t\tbreak;\n\t\t\n\t\t\t//TXMInstrument* ins = &instr[y];\n\t\t\n\t\t\tf.readDwords(&instr[y].size,1);\n\t\t\t\n\t\t\tif (instr[y].size < 29)\n\t\t\t{\n\t\t\t\tmp_ubyte buffer[29];\n\t\t\t\tmemset(buffer, 0, sizeof(buffer));\n\t\t\t\tf.read(buffer, 1, instr[y].size - 4);\n\t\t\t\tmemcpy(instr[y].name, buffer, 22);\n\t\t\t\tinstr[y].type = buffer[22];\n\t\t\t\tinstr[y].samp = LittleEndian::GET_WORD(buffer + 23);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tf.read(&instr[y].name,1,22);\t\t\n\t\t\t\tf.read(&instr[y].type,1,1);\n\t\t\t\tf.readWords(&instr[y].samp,1);\n\t\t\t}\n\t\t\tif (instr[y].samp > MP_MAXINSSAMPS)\n\t\t\t\treturn MP_LOADER_FAILED;\n\n\t\t\t//printf(\"%i, %i\\n\", instr[y].size, instr[y].samp);\n\n\t\t\tif (instr[y].size <= 29)\n\t\t\t{\n#ifdef MILKYTRACKER\n\t\t\t\ts+=16;\n#endif\n\t\t\t\tfor (mp_sint32 i = 0; i < 120; i++)\n\t\t\t\t\tinstr[y].snum[i] = -1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tf.readDwords(&instr[y].shsize,1);\n#ifdef VERBOSE\n\t\t\tprintf(\"%i/%i: %i, %i, %i, %s\\n\",y,header->insnum-1,instr[y].size,instr[y].shsize,instr[y].samp,instr[y].name);\t\t\t\n#endif\n\t\t\tmemset(insData, 0, 230);\n\t\t\t\n\t\t\tif (instr[y].size - 33 > 230)\n\t\t\t{\n\t\t\t\t//return -7;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tf.read(insData, 1, instr[y].size - 33);\n\t\t\t\n\t\t\t/*printf(\"%i\\r\\n\",instr[y].size);\n\t\t\tprintf(\"%s\\r\\n\",instr[y].name);\n\t\t\tprintf(\"%i\\r\\n\",instr[y].type);\n\t\t\tprintf(\"%i\\r\\n\",instr[y].samp);\n\t\t\tprintf(\"%i\\r\\n\",instr[y].shsize);*/\n\t\t\t//getch();\n\t\t\t\t\t\n\t\t\tmemset(smpReloc, 0, sizeof(smpReloc));\n\t\t\t\n\t\t\tif (instr[y].samp) {\n\t\t\t\tmp_ubyte* insDataPtr = insData;\n\t\t\t\t\n\t\t\t\t//f.read(&nbu,1,96);\n\t\t\t\t\n\t\t\t\tmemcpy(nbu, insDataPtr, MP_MAXINSSAMPS);\n\t\t\t\tinsDataPtr+=MP_MAXINSSAMPS;\n\t\t\t\t\n\t\t\t\tTEnvelope venv;\n\t\t\t\tTEnvelope penv;\n\t\t\t\tmemset(&venv,0,sizeof(venv));\n\t\t\t\tmemset(&penv,0,sizeof(penv));\n\t\t\t\t\n\t\t\t\tmp_sint32 k;\n\t\t\t\tfor (k = 0; k < XM_ENVELOPENUMPOINTS; k++)\n\t\t\t\t{\n\t\t\t\t\tvenv.env[k][0] = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\t\tvenv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2);\n\t\t\t\t\tinsDataPtr+=4;\n\t\t\t\t}\n\t\t\t\tfor (k = 0; k < XM_ENVELOPENUMPOINTS; k++)\n\t\t\t\t{\n\t\t\t\t\tpenv.env[k][0] = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\t\tpenv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2);\n\t\t\t\t\tinsDataPtr+=4;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvenv.num = *insDataPtr++;\t\n\t\t\t\tif (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS;\n\t\t\t\tpenv.num = *insDataPtr++;\t\t\t\t\t\n\t\t\t\tif (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS;\n\t\t\t\tvenv.sustain = *insDataPtr++;\n\t\t\t\tvenv.loops = *insDataPtr++;\n\t\t\t\tvenv.loope = *insDataPtr++;\n\t\t\t\tpenv.sustain = *insDataPtr++;\n\t\t\t\tpenv.loops = *insDataPtr++;\n\t\t\t\tpenv.loope = *insDataPtr++;\n\t\t\t\tvenv.type = *insDataPtr++;\n\t\t\t\tpenv.type = *insDataPtr++;\t\t\t\t\n\t\t\t\t\n\t\t\t\tmp_ubyte vibtype, vibsweep, vibdepth, vibrate;\n\t\t\t\tmp_uword volfade;\n\t\t\t\t\n\t\t\t\tvibtype = *insDataPtr++;\n\t\t\t\tvibsweep = *insDataPtr++;\n\t\t\t\tvibdepth = *insDataPtr++;\n\t\t\t\tvibrate = *insDataPtr++;\n\t\t\t\t\n\t\t\t\tvibdepth<<=1;\n\t\t\t\t\n\t\t\t\t//f.readWords(&volfade,1);\n\t\t\t\tvolfade = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\tinsDataPtr+=2;\n\t\t\t\tvolfade<<=1;\n\t\t\t\t\n\t\t\t\t//instr[y].res = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\tinsDataPtr+=2;\n\t\t\t\t\n\t\t\t\tfor (mp_sint32 l=0;laddVolumeEnvelope(venv)) \n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\tif (!module->addPanningEnvelope(penv)) \n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\t\n\t\t\t\tmp_sint32 g=0, sc;\n\t\t\t\tfor (sc=0;scaddSongMessageLine(line);\n\t\t\t\t\t\n#ifndef MILKYTRACKER\n\t\t\t\t\t// ignore empty samples when not being a tracker\n\t\t\t\t\tif (smp[g+s].samplen) {\n\t\t\t\t\t\tsmpReloc[sc] = g;\n\t\t\t\t\t\tg++;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tsmpReloc[sc] = -1;\n#else\n\t\t\t\t\tsmpReloc[sc] = g;\n\t\t\t\t\tg++;\n#endif\n\t\t\t\t}\n\n\t\t\t\tinstr[y].samp = g;\n\n\t\t\t\tfor (sc = 0; sc < MP_MAXINSSAMPS; sc++) {\t\t\t\t\t\n\t\t\t\t\tif (smpReloc[nbu[sc]] == -1)\n\t\t\t\t\t\tinstr[y].snum[sc] = -1;\n\t\t\t\t\telse\n\t\t\t\t\t\tinstr[y].snum[sc] = smpReloc[nbu[sc]]+s;\n\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\tfor (sc=0;sc>=1;\n\t\t\t\t\t\t\tsmp[s].loopstart>>=1;\n\t\t\t\t\t\t\tsmp[s].looplen>>=1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmp_sint32 result = module->loadModuleSample(f, s, \n\t\t\t\t\t\t\t\t\t\t\t\t\t adpcm ? XModule::ST_PACKING_ADPCM : XModule::ST_DELTA, \n\t\t\t\t\t\t\t\t\t\t\t\t\t adpcm ? (XModule::ST_PACKING_ADPCM | XModule::ST_16BIT) : (XModule::ST_DELTA | XModule::ST_16BIT), \n\t\t\t\t\t\t\t\t\t\t\t\t\t oldSize);\n\t\t\t\t\t\tif (result != MP_OK)\n\t\t\t\t\t\t\treturn result;\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (adpcm)\n\t\t\t\t\t\t\tsmp[s].res = 0;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\ts++;\n\t\t\t\t\t\n\t\t\t\t\tif (s>=MP_MAXSAMPLES)\n\t\t\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\te++;\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor (mp_sint32 i = 0; i < 120; i++)\n\t\t\t\t\tinstr[y].snum[i] = -1;\n\t\t\t}\n\n#ifdef MILKYTRACKER\n\t\t\ts+=16 - instr[y].samp;\n#endif\t\t\t\t\n\t\t\t\n\t\t}\n\t\t\n\t\theader->smpnum=s;\n\t\theader->volenvnum=e;\n\t\theader->panenvnum=e;\t\t\n\t\t\n\t}\n\telse\n\t{\n\t\tmp_sint32 s = 0;\n\t\tfor (y=0;yinsnum;y++) {\n\t\t\tfor (sc=0;sc>=1;\n\t\t\t\t\t\tsmp[s].loopstart>>=1;\n\t\t\t\t\t\tsmp[s].looplen>>=1;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tmp_sint32 result = module->loadModuleSample(f, s, XModule::ST_DELTA, XModule::ST_DELTA | XModule::ST_16BIT, oldSize);\n\t\t\t\t\tif (result != MP_OK)\n\t\t\t\t\t\treturn result;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ts++;\n\t\t\t\t\n\t\t\t\tif (s>=MP_MAXSAMPLES)\n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\t\t\t\t\n\t\t\t}\n\t\t\t\n#ifdef MILKYTRACKER\n\t\t\ts+=16 - instr[y].samp;\n#endif\n\t\t\t\n\t\t}\t\t\n\t}\n\t\n\t// convert modplug stereo samples\n\tfor (mp_sint32 s = 0; s < header->smpnum; s++)\n\t{\n\t\tif (smp[s].type & 32)\n\t\t{\t\t\n\t\t\t// that's what's allowed, stupid modplug tracker\n\t\t\tsmp[s].type &= 3+16;\t\t\t\t\t\n\n\t\t\tif (smp[s].sample == NULL)\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tif (!(smp[s].type&16)) {\t\t\t\n\t\t\t\tsmp[s].samplen>>=1;\n\t\t\t\tsmp[s].loopstart>>=1;\n\t\t\t\tsmp[s].looplen>>=1;\n\t\t\t\t\n\t\t\t\tmp_sbyte* sample = (mp_sbyte*)smp[s].sample;\n\t\t\t\tmp_sint32 samplen = smp[s].samplen;\n\t\t\t\tfor (mp_sint32 i = 0; i < samplen; i++)\n\t\t\t\t{\n\t\t\t\t\tmp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1;\n\t\t\t\t\tif (s < -128) s = -128;\n\t\t\t\t\tif (s > 127) s = 127;\n\t\t\t\t\tsample[i] = (mp_sbyte)s;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsmp[s].samplen>>=1;\n\t\t\t\tsmp[s].loopstart>>=1;\n\t\t\t\tsmp[s].looplen>>=1;\n\t\t\t\t\n\t\t\t\tmp_sword* sample = (mp_sword*)smp[s].sample;\n\t\t\t\tmp_sint32 samplen = smp[s].samplen;\n\t\t\t\tfor (mp_sint32 i = 0; i < samplen; i++)\n\t\t\t\t{\n\t\t\t\t\tmp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1;\n\t\t\t\t\tif (s < -32768) s = -32768;\n\t\t\t\t\tif (s > 32767) s = 32767;\n\t\t\t\t\tsample[i] = (mp_sword)s;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// correct loop type 0x03 (undefined)\n\t\t// will become ping pong loop\n\t\t// note that FT2 will refuse to load XM files with such a loop type\n\t\tif ((smp[s].type & 0x3) == 0x3)\n\t\t\tsmp[s].type&=~1;\t\t\n\t}\n\n\t// correct number of patterns if necessary, otherwise the post processing will remove\n\t// the \"invalid\" patterns from the order list\n\tbool addPatterns = false;\n\tfor (i = 0; i < header->ordnum; i++)\n\t\tif (header->ord[i]+1 > header->patnum)\n\t\t{\n\t\t\theader->patnum = header->ord[i]+1;\t\n\t\t\taddPatterns = true;\n\t\t}\n\t\n\t// if the pattern number has been adjusted, add some empty patterns\n\tif (addPatterns)\n\t{\n\t\tfor (i = 0; i < header->patnum; i++)\n\t\t\tif (phead[i].patternData == NULL)\n\t\t\t{\n\t\t\t\tphead[i].rows = 64;\n\t\t\t\tphead[i].effnum = 2;\n\t\t\t\tphead[i].channum = (mp_ubyte)header->channum;\n\n\t\t\t\tphead[i].patternData = new mp_ubyte[phead[i].rows*header->channum*6];\n\t\t\t\n\t\t\t\t// out of memory?\n\t\t\t\tif (phead[i].patternData == NULL)\n\t\t\t\t{\n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\t}\n\t\t\n\t\t\t\tmemset(phead[i].patternData,0,phead[i].rows*header->channum*6);\n\t\t\t}\n\t}\n\t\n\t// check for MODPLUG extensions\n\tif (f.posWithBaseOffset() + 8 <= fileSize)\n\t{\n\t\tchar buffer[4];\n\t\tf.read(buffer, 1, 4);\n\t\tif (memcmp(buffer, \"text\", 4) == 0)\n\t\t{\n\t\t\tmp_uint32 len = f.readDword();\n\t\t\tmodule->allocateSongMessage(len+1);\n\t\t\t\n\t\t\tmemset(module->message, 0, len+1);\n\t\t\t\n\t\t\tf.read(module->message, 1, len);\n\t\t}\n\t}\n\t\n\tmodule->postProcessSamples();\n\t\n\treturn MP_OK;\n}", "func_hash": 297622282182467898464562664481031169978, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-34927", "cve_desc": "MilkyTracker v1.03.00 was discovered to contain a stack overflow via the component LoaderXM::load. This vulnerability is triggered when the program is supplied a crafted XM module file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-34927"}
{"idx": 295887, "project": "MilkyTracker", "commit_id": "3a5474f9102cbdc10fbd9e7b1b2c8d3f3f45d91b", "project_url": "https://github.com/milkytracker/MilkyTracker", "commit_url": "https://github.com/milkytracker/MilkyTracker/commit/3a5474f9102cbdc10fbd9e7b1b2c8d3f3f45d91b", "commit_message": "Fix possible stack corruption with XM instrument headers claiming a size of less than 4\n\nCloses #275", "target": 0, "func": "mp_sint32 LoaderXM::load(XMFileBase& f, XModule* module)\n{\n\tmp_ubyte insData[230];\t\t\n\tmp_sint32 smpReloc[MP_MAXINSSAMPS];\n\tmp_ubyte nbu[MP_MAXINSSAMPS];\n\tmp_uint32 fileSize = 0;\n\t\t\t\n\tmodule->cleanUp();\n\n\t// this will make code much easier to read\n\tTXMHeader*\t\theader = &module->header;\n\tTXMInstrument*\tinstr  = module->instr;\n\tTXMSample*\t\tsmp\t   = module->smp;\n\tTXMPattern*\t\tphead  = module->phead;\t\n\n\t// we're already out of memory here\n\tif (!phead || !instr || !smp)\n\t\treturn MP_OUT_OF_MEMORY;\n\t\n\tfileSize = f.sizeWithBaseOffset();\n\t\n\tf.read(&header->sig,1,17);\n\tf.read(&header->name,1,20);\n\tf.read(&header->whythis1a,1,1);\n\theader->whythis1a=0;\n\tf.read(&header->tracker,1,20);\n\tf.readWords(&header->ver,1);\n\t\n\tif (header->ver != 0x102 && \n\t\theader->ver != 0x103 && // untested\n\t\theader->ver != 0x104)\n\t\treturn MP_LOADER_FAILED;\n\t\n\tf.readDwords(&header->hdrsize,1);\n\t\n\theader->hdrsize-=4;\n\t\n\tmp_uint32 hdrSize = 0x110;\n\tif (header->hdrsize > hdrSize)\n\t\thdrSize = header->hdrsize;\n\t\t\t\t\n\tmp_ubyte* hdrBuff = new mp_ubyte[hdrSize];\n\tmemset(hdrBuff, 0, hdrSize);\n\t\n\tf.read(hdrBuff, 1, header->hdrsize);\n\t\n\theader->ordnum = LittleEndian::GET_WORD(hdrBuff);\n\theader->restart = LittleEndian::GET_WORD(hdrBuff+2);\n\theader->channum = LittleEndian::GET_WORD(hdrBuff+4);\n\theader->patnum = LittleEndian::GET_WORD(hdrBuff+6);\n\theader->insnum = LittleEndian::GET_WORD(hdrBuff+8);\n\theader->freqtab = LittleEndian::GET_WORD(hdrBuff+10);\n\theader->tempo = LittleEndian::GET_WORD(hdrBuff+12);\n\theader->speed = LittleEndian::GET_WORD(hdrBuff+14);\n\tmemcpy(header->ord, hdrBuff+16, 256);\n\tif(header->ordnum > MP_MAXORDERS)\n\t\theader->ordnum = MP_MAXORDERS;\n\tif(header->insnum > MP_MAXINS)\n\t\treturn MP_LOADER_FAILED;\n\n\tdelete[] hdrBuff;\n\t\n\theader->mainvol=255;\n\theader->flags = XModule::MODULE_XMNOTECLIPPING | \n\t\tXModule::MODULE_XMARPEGGIO | \n\t\tXModule::MODULE_XMPORTANOTEBUFFER | \n\t\tXModule::MODULE_XMVOLCOLUMNVIBRATO;\n\n\theader->uppernotebound = 119;\n\t\n\tmp_sint32 i,y,sc;\n\tfor (i=0;i<32;i++) header->pan[i]=0x80;\n\t\n\t// old version?\n\tif (header->ver == 0x102 || header->ver == 0x103)\n\t{\n\t\tmp_sint32 s = 0;\n\t\tmp_sint32 e = 0;\n\t\tfor (y=0;yinsnum;y++) {\n\t\t\t\n\t\t\tf.readDwords(&instr[y].size,1);\n\t\t\tf.read(&instr[y].name,1,22);\t\t\n\t\t\tf.read(&instr[y].type,1,1);\n\t\t\tmp_uword numSamples = 0;\n\t\t\tf.readWords(&numSamples,1);\n\t\t\tif(numSamples > MP_MAXINSSAMPS)\n\t\t\t\treturn MP_LOADER_FAILED;\n\t\t\tinstr[y].samp = numSamples;\n\n\t\t\tif (instr[y].size == 29)\n\t\t\t{\n#ifdef MILKYTRACKER\n\t\t\t\ts+=16;\n#endif\n\t\t\t\tfor (mp_sint32 i = 0; i < 120; i++)\n\t\t\t\t\tinstr[y].snum[i] = -1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tf.readDwords(&instr[y].shsize,1);\n\n\t\t\tmemset(insData, 0, 230);\n\t\t\t\n\t\t\tif (instr[y].size - 33 > 230)\n\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\n\t\t\tf.read(insData, 1, instr[y].size - 33);\n\t\t\t\t\t\t\n\t\t\tif (instr[y].samp) {\n\t\t\t\tmp_ubyte* insDataPtr = insData;\n\t\t\t\t\n\t\t\t\tmemcpy(nbu, insDataPtr, MP_MAXINSSAMPS);\n\t\t\t\tinsDataPtr+=MP_MAXINSSAMPS;\n\t\t\t\t\n\t\t\t\tTEnvelope venv;\n\t\t\t\tTEnvelope penv;\n\t\t\t\tmemset(&venv,0,sizeof(venv));\n\t\t\t\tmemset(&penv,0,sizeof(penv));\n\t\t\t\t\n\t\t\t\tmp_sint32 k;\n\t\t\t\tfor (k = 0; k < XM_ENVELOPENUMPOINTS; k++)\n\t\t\t\t{\n\t\t\t\t\tvenv.env[k][0] = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\t\tvenv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2);\n\t\t\t\t\tinsDataPtr+=4;\n\t\t\t\t}\n\t\t\t\tfor (k = 0; k < XM_ENVELOPENUMPOINTS; k++)\n\t\t\t\t{\n\t\t\t\t\tpenv.env[k][0] = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\t\tpenv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2);\n\t\t\t\t\tinsDataPtr+=4;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvenv.num = *insDataPtr++;\t\n\t\t\t\tif (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS;\n\t\t\t\tpenv.num = *insDataPtr++;\t\n\t\t\t\tif (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS;\n\t\t\t\tvenv.sustain = *insDataPtr++;\n\t\t\t\tvenv.loops = *insDataPtr++;\n\t\t\t\tvenv.loope = *insDataPtr++;\n\t\t\t\tpenv.sustain = *insDataPtr++;\n\t\t\t\tpenv.loops = *insDataPtr++;\n\t\t\t\tpenv.loope = *insDataPtr++;\n\t\t\t\tvenv.type = *insDataPtr++;\n\t\t\t\tpenv.type = *insDataPtr++;\t\t\t\t\n\t\t\t\t\n\t\t\t\tmp_ubyte vibtype, vibsweep, vibdepth, vibrate;\n\t\t\t\tmp_uword volfade;\n\t\t\t\t\n\t\t\t\tvibtype = *insDataPtr++;\n\t\t\t\tvibsweep = *insDataPtr++;\n\t\t\t\tvibdepth = *insDataPtr++;\n\t\t\t\tvibrate = *insDataPtr++;\n\t\t\t\t\n\t\t\t\tvibdepth<<=1;\n\t\t\t\t\n\t\t\t\tvolfade = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\tinsDataPtr+=2;\n\t\t\t\tvolfade<<=1;\n\t\t\t\t\n\t\t\t\t//instr[y].res = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\tinsDataPtr+=2;\n\t\t\t\t\n\t\t\t\tfor (mp_sint32 l=0;laddVolumeEnvelope(venv)) \n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\tif (!module->addPanningEnvelope(penv)) \n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\t\n\t\t\t\tmp_sint32 g=0, sc;\n\t\t\t\tfor (sc=0;scaddSongMessageLine(line);\n\t\t\t\t\t\n\t\t\t\t\t// ignore empty samples\n#ifndef MILKYTRACKER\n\t\t\t\t\t// ignore empty samples when not being a tracker\n\t\t\t\t\tif (smp[g+s].samplen) {\n\t\t\t\t\t\tsmpReloc[sc] = g;\n\t\t\t\t\t\tg++;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tsmpReloc[sc] = -1;\n#else\n\t\t\t\t\tsmpReloc[sc] = g;\n\t\t\t\t\tg++;\n#endif\n\t\t\t\t}\n\n\t\t\t\tinstr[y].samp = g;\n\n\t\t\t\tfor (sc = 0; sc < MP_MAXINSSAMPS; sc++) {\n\t\t\t\t\tif (smpReloc[nbu[sc]] == -1)\n\t\t\t\t\t\tinstr[y].snum[sc] = -1;\n\t\t\t\t\telse\n\t\t\t\t\t\tinstr[y].snum[sc] = smpReloc[nbu[sc]]+s;\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\te++;\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor (mp_sint32 i = 0; i < 120; i++)\n\t\t\t\t\tinstr[y].snum[i] = -1;\n\t\t\t}\n\n#ifdef MILKYTRACKER\n\t\t\ts+=16;\n#else\n\t\t\ts+=instr[y].samp;\n#endif\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t}\n\t\t\n\t\theader->smpnum=s;\n\t\theader->volenvnum=e;\n\t\theader->panenvnum=e;\n\t}\n\t\n\tfor (y=0;ypatnum;y++) {\n\t\t\n\t\tif (header->ver == 0x104 || header->ver == 0x103)\n\t\t{\n\t\t\tf.readDwords(&phead[y].len,1);\n\t\t\tf.read(&phead[y].ptype,1,1);\n\t\t\tf.readWords(&phead[y].rows,1);\n\t\t\tf.readWords(&phead[y].patdata,1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tf.readDwords(&phead[y].len,1);\n\t\t\tf.read(&phead[y].ptype,1,1);\n\t\t\tphead[y].rows = (mp_uword)f.readByte()+1;\n\t\t\tf.readWords(&phead[y].patdata,1);\t\t\t\n\t\t}\n\t\t\n\t\tphead[y].effnum=2;\n\t\tphead[y].channum=(mp_ubyte)header->channum;\n\t\t\n\t\tphead[y].patternData = new mp_ubyte[phead[y].rows*header->channum*6];\n\t\t\n\t\t// out of memory?\n\t\tif (phead[y].patternData == NULL)\n\t\t{\n\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t}\n\t\t\n\t\tmemset(phead[y].patternData,0,phead[y].rows*header->channum*6);\n\t\t\n\t\tif (phead[y].patdata) {\n\t\t\tmp_ubyte *buffer = new mp_ubyte[phead[y].patdata];\n\t\t\t\n\t\t\t// out of memory?\n\t\t\tif (buffer == NULL)\n\t\t\t{\n\t\t\t\treturn MP_OUT_OF_MEMORY;\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tf.read(buffer,1,phead[y].patdata);\n\t\t\t\n\t\t\t//printf(\"%i\\n\", phead[y].patdata);\n\t\t\t\n\t\t\tmp_sint32 pc = 0, bc = 0;\n\t\t\tfor (mp_sint32 r=0;rchannum;c++) {\n\t\t\t\t\t\n\t\t\t\t\tmp_ubyte slot[5];\n\t\t\t\t\tmemset(slot,0,5);\n\t\t\t\t\t\n\t\t\t\t\tif ((buffer[pc]&128)) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tmp_ubyte pb = buffer[pc];\n\t\t\t\t\t\tpc++;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ((pb&1)) {\n\t\t\t\t\t\t\t//phead[y].patternData[bc]=buffer[pc];\n\t\t\t\t\t\t\tslot[0]=buffer[pc];\n\t\t\t\t\t\t\tpc++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((pb&2)) {\n\t\t\t\t\t\t\t//phead[y].patternData[bc+1]=buffer[pc];\n\t\t\t\t\t\t\tslot[1]=buffer[pc];\n\t\t\t\t\t\t\tpc++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((pb&4)) {\n\t\t\t\t\t\t\t//phead[y].patternData[bc+2]=buffer[pc];\n\t\t\t\t\t\t\tslot[2]=buffer[pc];\n\t\t\t\t\t\t\tpc++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((pb&8)) {\n\t\t\t\t\t\t\t//phead[y].patternData[bc+3]=buffer[pc];\n\t\t\t\t\t\t\tslot[3]=buffer[pc];\n\t\t\t\t\t\t\tpc++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((pb&16)) {\n\t\t\t\t\t\t\t//phead[y].patternData[bc+4]=buffer[pc];\n\t\t\t\t\t\t\tslot[4]=buffer[pc];\n\t\t\t\t\t\t\tpc++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t//memcpy(phead[y].patternData+bc,buffer+pc,5);\n\t\t\t\t\t\tmemcpy(slot,buffer+pc,5);\n\t\t\t\t\t\tpc+=5;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tchar gl=0;\n\t\t\t\t\tfor (mp_sint32 i=0;i64) bl=64;\n\t\t\t\t\t\tslot[4]=(bl*261120)>>16;*/\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif ((!slot[3])&&(slot[4])) slot[3]=0x20;\n\t\t\t\t\t\n\t\t\t\t\tif (slot[3]==0xE) {\n\t\t\t\t\t\tslot[3]=(slot[4]>>4)+0x30;\n\t\t\t\t\t\tslot[4]=slot[4]&0xf;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (slot[3]==0x21) {\n\t\t\t\t\t\tslot[3]=(slot[4]>>4)+0x40;\n\t\t\t\t\t\tslot[4]=slot[4]&0xf;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (slot[0]==97) slot[0]=XModule::NOTE_OFF;\n\t\t\t\t\t\n\t\t\t\t\tphead[y].patternData[bc]=slot[0];\n\t\t\t\t\tphead[y].patternData[bc+1]=slot[1];\n\t\t\t\t\t\n\t\t\t\t\tXModule::convertXMVolumeEffects(slot[2], phead[y].patternData[bc+2], phead[y].patternData[bc+3]);\n\n\t\t\t\t\tphead[y].patternData[bc+4]=slot[3];\n\t\t\t\t\tphead[y].patternData[bc+5]=slot[4];\n\t\t\t\t\t\n\t\t\t\t\t/*if ((y==3)&&(c==2)) {\n\t\t\t\t\t\tfor (mp_sint32 bl=0;bl<6;bl++) cprintf(\"%x \",phead[y].patternData[bc+bl]);\n\t\t\t\t\tcprintf(\"\\r\\n\");\n\t\t\t\t\tgetch();\n\t\t\t\t\t};*/\n\t\t\t\t\t\n\t\t\t\t\t/*printf(\"Note : %i\\r\\n\",phead[y].patternData[bc]);\n\t\t\t\t\tprintf(\"Ins  : %i\\r\\n\",phead[y].patternData[bc+1]);\n\t\t\t\t\tprintf(\"Vol  : %i\\r\\n\",phead[y].patternData[bc+2]);\n\t\t\t\t\tprintf(\"Eff  : %i\\r\\n\",phead[y].patternData[bc+3]);\n\t\t\t\t\tprintf(\"Effop: %i\\r\\n\",phead[y].patternData[bc+4]);\n\t\t\t\t\tgetch();*/\n\t\t\t\t\t\n\t\t\t\t\tbc+=6;\n\t\t\t\t} // for c\n\t\t\t\t\t\n\t\t\t} // for r\n\t\t\t\t\n\t\t\tdelete[] buffer;\n\t\t}\n\t\t\t\n\t}\n\t\t\n\tif (header->ver == 0x104)\n\t{\n\t\tmp_sint32 s = 0;\n\t\tmp_sint32 e = 0;\n\t\tfor (y=0;yinsnum;y++) {\n\n\t\t\t// fixes MOOH.XM loading problems\n\t\t\t// seems to store more instruments in the header than in the actual file\n\t\t\tif (f.posWithBaseOffset() >= fileSize)\n\t\t\t\tbreak;\n\t\t\n\t\t\t//TXMInstrument* ins = &instr[y];\n\t\t\n\t\t\tf.readDwords(&instr[y].size,1);\n\t\t\t\n\t\t\tif (instr[y].size >= 4 && instr[y].size < 29)\n\t\t\t{\n\t\t\t\tmp_ubyte buffer[29];\n\t\t\t\tmemset(buffer, 0, sizeof(buffer));\n\t\t\t\tf.read(buffer, 1, instr[y].size - 4);\n\t\t\t\tmemcpy(instr[y].name, buffer, 22);\n\t\t\t\tinstr[y].type = buffer[22];\n\t\t\t\tinstr[y].samp = LittleEndian::GET_WORD(buffer + 23);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tf.read(&instr[y].name,1,22);\t\t\n\t\t\t\tf.read(&instr[y].type,1,1);\n\t\t\t\tf.readWords(&instr[y].samp,1);\n\t\t\t}\n\t\t\tif (instr[y].samp > MP_MAXINSSAMPS)\n\t\t\t\treturn MP_LOADER_FAILED;\n\n\t\t\t//printf(\"%i, %i\\n\", instr[y].size, instr[y].samp);\n\n\t\t\tif (instr[y].size <= 29)\n\t\t\t{\n#ifdef MILKYTRACKER\n\t\t\t\ts+=16;\n#endif\n\t\t\t\tfor (mp_sint32 i = 0; i < 120; i++)\n\t\t\t\t\tinstr[y].snum[i] = -1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tf.readDwords(&instr[y].shsize,1);\n#ifdef VERBOSE\n\t\t\tprintf(\"%i/%i: %i, %i, %i, %s\\n\",y,header->insnum-1,instr[y].size,instr[y].shsize,instr[y].samp,instr[y].name);\t\t\t\n#endif\n\t\t\tmemset(insData, 0, 230);\n\t\t\t\n\t\t\tif (instr[y].size - 33 > 230)\n\t\t\t{\n\t\t\t\t//return -7;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tf.read(insData, 1, instr[y].size - 33);\n\t\t\t\n\t\t\t/*printf(\"%i\\r\\n\",instr[y].size);\n\t\t\tprintf(\"%s\\r\\n\",instr[y].name);\n\t\t\tprintf(\"%i\\r\\n\",instr[y].type);\n\t\t\tprintf(\"%i\\r\\n\",instr[y].samp);\n\t\t\tprintf(\"%i\\r\\n\",instr[y].shsize);*/\n\t\t\t//getch();\n\t\t\t\t\t\n\t\t\tmemset(smpReloc, 0, sizeof(smpReloc));\n\t\t\t\n\t\t\tif (instr[y].samp) {\n\t\t\t\tmp_ubyte* insDataPtr = insData;\n\t\t\t\t\n\t\t\t\t//f.read(&nbu,1,96);\n\t\t\t\t\n\t\t\t\tmemcpy(nbu, insDataPtr, MP_MAXINSSAMPS);\n\t\t\t\tinsDataPtr+=MP_MAXINSSAMPS;\n\t\t\t\t\n\t\t\t\tTEnvelope venv;\n\t\t\t\tTEnvelope penv;\n\t\t\t\tmemset(&venv,0,sizeof(venv));\n\t\t\t\tmemset(&penv,0,sizeof(penv));\n\t\t\t\t\n\t\t\t\tmp_sint32 k;\n\t\t\t\tfor (k = 0; k < XM_ENVELOPENUMPOINTS; k++)\n\t\t\t\t{\n\t\t\t\t\tvenv.env[k][0] = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\t\tvenv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2);\n\t\t\t\t\tinsDataPtr+=4;\n\t\t\t\t}\n\t\t\t\tfor (k = 0; k < XM_ENVELOPENUMPOINTS; k++)\n\t\t\t\t{\n\t\t\t\t\tpenv.env[k][0] = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\t\tpenv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2);\n\t\t\t\t\tinsDataPtr+=4;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvenv.num = *insDataPtr++;\t\n\t\t\t\tif (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS;\n\t\t\t\tpenv.num = *insDataPtr++;\t\t\t\t\t\n\t\t\t\tif (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS;\n\t\t\t\tvenv.sustain = *insDataPtr++;\n\t\t\t\tvenv.loops = *insDataPtr++;\n\t\t\t\tvenv.loope = *insDataPtr++;\n\t\t\t\tpenv.sustain = *insDataPtr++;\n\t\t\t\tpenv.loops = *insDataPtr++;\n\t\t\t\tpenv.loope = *insDataPtr++;\n\t\t\t\tvenv.type = *insDataPtr++;\n\t\t\t\tpenv.type = *insDataPtr++;\t\t\t\t\n\t\t\t\t\n\t\t\t\tmp_ubyte vibtype, vibsweep, vibdepth, vibrate;\n\t\t\t\tmp_uword volfade;\n\t\t\t\t\n\t\t\t\tvibtype = *insDataPtr++;\n\t\t\t\tvibsweep = *insDataPtr++;\n\t\t\t\tvibdepth = *insDataPtr++;\n\t\t\t\tvibrate = *insDataPtr++;\n\t\t\t\t\n\t\t\t\tvibdepth<<=1;\n\t\t\t\t\n\t\t\t\t//f.readWords(&volfade,1);\n\t\t\t\tvolfade = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\tinsDataPtr+=2;\n\t\t\t\tvolfade<<=1;\n\t\t\t\t\n\t\t\t\t//instr[y].res = LittleEndian::GET_WORD(insDataPtr);\n\t\t\t\tinsDataPtr+=2;\n\t\t\t\t\n\t\t\t\tfor (mp_sint32 l=0;laddVolumeEnvelope(venv)) \n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\tif (!module->addPanningEnvelope(penv)) \n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\t\n\t\t\t\tmp_sint32 g=0, sc;\n\t\t\t\tfor (sc=0;scaddSongMessageLine(line);\n\t\t\t\t\t\n#ifndef MILKYTRACKER\n\t\t\t\t\t// ignore empty samples when not being a tracker\n\t\t\t\t\tif (smp[g+s].samplen) {\n\t\t\t\t\t\tsmpReloc[sc] = g;\n\t\t\t\t\t\tg++;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tsmpReloc[sc] = -1;\n#else\n\t\t\t\t\tsmpReloc[sc] = g;\n\t\t\t\t\tg++;\n#endif\n\t\t\t\t}\n\n\t\t\t\tinstr[y].samp = g;\n\n\t\t\t\tfor (sc = 0; sc < MP_MAXINSSAMPS; sc++) {\t\t\t\t\t\n\t\t\t\t\tif (smpReloc[nbu[sc]] == -1)\n\t\t\t\t\t\tinstr[y].snum[sc] = -1;\n\t\t\t\t\telse\n\t\t\t\t\t\tinstr[y].snum[sc] = smpReloc[nbu[sc]]+s;\n\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\tfor (sc=0;sc>=1;\n\t\t\t\t\t\t\tsmp[s].loopstart>>=1;\n\t\t\t\t\t\t\tsmp[s].looplen>>=1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmp_sint32 result = module->loadModuleSample(f, s, \n\t\t\t\t\t\t\t\t\t\t\t\t\t adpcm ? XModule::ST_PACKING_ADPCM : XModule::ST_DELTA, \n\t\t\t\t\t\t\t\t\t\t\t\t\t adpcm ? (XModule::ST_PACKING_ADPCM | XModule::ST_16BIT) : (XModule::ST_DELTA | XModule::ST_16BIT), \n\t\t\t\t\t\t\t\t\t\t\t\t\t oldSize);\n\t\t\t\t\t\tif (result != MP_OK)\n\t\t\t\t\t\t\treturn result;\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (adpcm)\n\t\t\t\t\t\t\tsmp[s].res = 0;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\ts++;\n\t\t\t\t\t\n\t\t\t\t\tif (s>=MP_MAXSAMPLES)\n\t\t\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\te++;\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor (mp_sint32 i = 0; i < 120; i++)\n\t\t\t\t\tinstr[y].snum[i] = -1;\n\t\t\t}\n\n#ifdef MILKYTRACKER\n\t\t\ts+=16 - instr[y].samp;\n#endif\t\t\t\t\n\t\t\t\n\t\t}\n\t\t\n\t\theader->smpnum=s;\n\t\theader->volenvnum=e;\n\t\theader->panenvnum=e;\t\t\n\t\t\n\t}\n\telse\n\t{\n\t\tmp_sint32 s = 0;\n\t\tfor (y=0;yinsnum;y++) {\n\t\t\tfor (sc=0;sc>=1;\n\t\t\t\t\t\tsmp[s].loopstart>>=1;\n\t\t\t\t\t\tsmp[s].looplen>>=1;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tmp_sint32 result = module->loadModuleSample(f, s, XModule::ST_DELTA, XModule::ST_DELTA | XModule::ST_16BIT, oldSize);\n\t\t\t\t\tif (result != MP_OK)\n\t\t\t\t\t\treturn result;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ts++;\n\t\t\t\t\n\t\t\t\tif (s>=MP_MAXSAMPLES)\n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\t\t\t\t\n\t\t\t}\n\t\t\t\n#ifdef MILKYTRACKER\n\t\t\ts+=16 - instr[y].samp;\n#endif\n\t\t\t\n\t\t}\t\t\n\t}\n\t\n\t// convert modplug stereo samples\n\tfor (mp_sint32 s = 0; s < header->smpnum; s++)\n\t{\n\t\tif (smp[s].type & 32)\n\t\t{\t\t\n\t\t\t// that's what's allowed, stupid modplug tracker\n\t\t\tsmp[s].type &= 3+16;\t\t\t\t\t\n\n\t\t\tif (smp[s].sample == NULL)\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tif (!(smp[s].type&16)) {\t\t\t\n\t\t\t\tsmp[s].samplen>>=1;\n\t\t\t\tsmp[s].loopstart>>=1;\n\t\t\t\tsmp[s].looplen>>=1;\n\t\t\t\t\n\t\t\t\tmp_sbyte* sample = (mp_sbyte*)smp[s].sample;\n\t\t\t\tmp_sint32 samplen = smp[s].samplen;\n\t\t\t\tfor (mp_sint32 i = 0; i < samplen; i++)\n\t\t\t\t{\n\t\t\t\t\tmp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1;\n\t\t\t\t\tif (s < -128) s = -128;\n\t\t\t\t\tif (s > 127) s = 127;\n\t\t\t\t\tsample[i] = (mp_sbyte)s;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsmp[s].samplen>>=1;\n\t\t\t\tsmp[s].loopstart>>=1;\n\t\t\t\tsmp[s].looplen>>=1;\n\t\t\t\t\n\t\t\t\tmp_sword* sample = (mp_sword*)smp[s].sample;\n\t\t\t\tmp_sint32 samplen = smp[s].samplen;\n\t\t\t\tfor (mp_sint32 i = 0; i < samplen; i++)\n\t\t\t\t{\n\t\t\t\t\tmp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1;\n\t\t\t\t\tif (s < -32768) s = -32768;\n\t\t\t\t\tif (s > 32767) s = 32767;\n\t\t\t\t\tsample[i] = (mp_sword)s;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// correct loop type 0x03 (undefined)\n\t\t// will become ping pong loop\n\t\t// note that FT2 will refuse to load XM files with such a loop type\n\t\tif ((smp[s].type & 0x3) == 0x3)\n\t\t\tsmp[s].type&=~1;\t\t\n\t}\n\n\t// correct number of patterns if necessary, otherwise the post processing will remove\n\t// the \"invalid\" patterns from the order list\n\tbool addPatterns = false;\n\tfor (i = 0; i < header->ordnum; i++)\n\t\tif (header->ord[i]+1 > header->patnum)\n\t\t{\n\t\t\theader->patnum = header->ord[i]+1;\t\n\t\t\taddPatterns = true;\n\t\t}\n\t\n\t// if the pattern number has been adjusted, add some empty patterns\n\tif (addPatterns)\n\t{\n\t\tfor (i = 0; i < header->patnum; i++)\n\t\t\tif (phead[i].patternData == NULL)\n\t\t\t{\n\t\t\t\tphead[i].rows = 64;\n\t\t\t\tphead[i].effnum = 2;\n\t\t\t\tphead[i].channum = (mp_ubyte)header->channum;\n\n\t\t\t\tphead[i].patternData = new mp_ubyte[phead[i].rows*header->channum*6];\n\t\t\t\n\t\t\t\t// out of memory?\n\t\t\t\tif (phead[i].patternData == NULL)\n\t\t\t\t{\n\t\t\t\t\treturn MP_OUT_OF_MEMORY;\n\t\t\t\t}\n\t\t\n\t\t\t\tmemset(phead[i].patternData,0,phead[i].rows*header->channum*6);\n\t\t\t}\n\t}\n\t\n\t// check for MODPLUG extensions\n\tif (f.posWithBaseOffset() + 8 <= fileSize)\n\t{\n\t\tchar buffer[4];\n\t\tf.read(buffer, 1, 4);\n\t\tif (memcmp(buffer, \"text\", 4) == 0)\n\t\t{\n\t\t\tmp_uint32 len = f.readDword();\n\t\t\tmodule->allocateSongMessage(len+1);\n\t\t\t\n\t\t\tmemset(module->message, 0, len+1);\n\t\t\t\n\t\t\tf.read(module->message, 1, len);\n\t\t}\n\t}\n\t\n\tmodule->postProcessSamples();\n\t\n\treturn MP_OK;\n}", "func_hash": 77426307026803583568821855740200554303, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-34927", "cve_desc": "MilkyTracker v1.03.00 was discovered to contain a stack overflow via the component LoaderXM::load. This vulnerability is triggered when the program is supplied a crafted XM module file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-34927"}
{"idx": 199984, "project": "vim", "commit_id": "37f47958b8a2a44abc60614271d9537e7f14e51a", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/37f47958b8a2a44abc60614271d9537e7f14e51a", "commit_message": "patch 8.2.4253: using freed memory when substitute with function call\n\nProblem:    Using freed memory when substitute uses a recursive function call.\nSolution:   Make a copy of the substitute text.", "target": 1, "func": "ex_substitute(exarg_T *eap)\n{\n    linenr_T\tlnum;\n    long\ti = 0;\n    regmmatch_T regmatch;\n    static subflags_T subflags = {FALSE, FALSE, FALSE, TRUE, FALSE,\n\t\t\t\t\t\t\t      FALSE, FALSE, 0};\n#ifdef FEAT_EVAL\n    subflags_T\tsubflags_save;\n#endif\n    int\t\tsave_do_all;\t\t// remember user specified 'g' flag\n    int\t\tsave_do_ask;\t\t// remember user specified 'c' flag\n    char_u\t*pat = NULL, *sub = NULL;\t// init for GCC\n    int\t\tdelimiter;\n    int\t\tsublen;\n    int\t\tgot_quit = FALSE;\n    int\t\tgot_match = FALSE;\n    int\t\ttemp;\n    int\t\twhich_pat;\n    char_u\t*cmd;\n    int\t\tsave_State;\n    linenr_T\tfirst_line = 0;\t\t// first changed line\n    linenr_T\tlast_line= 0;\t\t// below last changed line AFTER the\n\t\t\t\t\t// change\n    linenr_T\told_line_count = curbuf->b_ml.ml_line_count;\n    linenr_T\tline2;\n    long\tnmatch;\t\t\t// number of lines in match\n    char_u\t*sub_firstline;\t\t// allocated copy of first sub line\n    int\t\tendcolumn = FALSE;\t// cursor in last column when done\n    pos_T\told_cursor = curwin->w_cursor;\n    int\t\tstart_nsubs;\n#ifdef FEAT_EVAL\n    int\t\tsave_ma = 0;\n#endif\n\n    cmd = eap->arg;\n    if (!global_busy)\n    {\n\tsub_nsubs = 0;\n\tsub_nlines = 0;\n    }\n    start_nsubs = sub_nsubs;\n\n    if (eap->cmdidx == CMD_tilde)\n\twhich_pat = RE_LAST;\t// use last used regexp\n    else\n\twhich_pat = RE_SUBST;\t// use last substitute regexp\n\n\t\t\t\t// new pattern and substitution\n    if (eap->cmd[0] == 's' && *cmd != NUL && !VIM_ISWHITE(*cmd)\n\t\t&& vim_strchr((char_u *)\"0123456789cegriIp|\\\"\", *cmd) == NULL)\n    {\n\t\t\t\t// don't accept alphanumeric for separator\n\tif (check_regexp_delim(*cmd) == FAIL)\n\t    return;\n#ifdef FEAT_EVAL\n\tif (in_vim9script() && check_global_and_subst(eap->cmd, eap->arg)\n\t\t\t\t\t\t\t\t      == FAIL)\n\t    return;\n#endif\n\n\t/*\n\t * undocumented vi feature:\n\t *  \"\\/sub/\" and \"\\?sub?\" use last used search pattern (almost like\n\t *  //sub/r).  \"\\&sub&\" use last substitute pattern (like //sub/).\n\t */\n\tif (*cmd == '\\\\')\n\t{\n\t    ++cmd;\n\t    if (vim_strchr((char_u *)\"/?&\", *cmd) == NULL)\n\t    {\n\t\temsg(_(e_backslash_should_be_followed_by));\n\t\treturn;\n\t    }\n\t    if (*cmd != '&')\n\t\twhich_pat = RE_SEARCH;\t    // use last '/' pattern\n\t    pat = (char_u *)\"\";\t\t    // empty search pattern\n\t    delimiter = *cmd++;\t\t    // remember delimiter character\n\t}\n\telse\t\t// find the end of the regexp\n\t{\n\t    which_pat = RE_LAST;\t    // use last used regexp\n\t    delimiter = *cmd++;\t\t    // remember delimiter character\n\t    pat = cmd;\t\t\t    // remember start of search pat\n\t    cmd = skip_regexp_ex(cmd, delimiter, magic_isset(),\n\t\t\t\t\t\t\t&eap->arg, NULL, NULL);\n\t    if (cmd[0] == delimiter)\t    // end delimiter found\n\t\t*cmd++ = NUL;\t\t    // replace it with a NUL\n\t}\n\n\t/*\n\t * Small incompatibility: vi sees '\\n' as end of the command, but in\n\t * Vim we want to use '\\n' to find/substitute a NUL.\n\t */\n\tsub = cmd;\t    // remember the start of the substitution\n\tcmd = skip_substitute(cmd, delimiter);\n\n\tif (!eap->skip)\n\t{\n\t    // In POSIX vi \":s/pat/%/\" uses the previous subst. string.\n\t    if (STRCMP(sub, \"%\") == 0\n\t\t\t\t && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)\n\t    {\n\t\tif (old_sub == NULL)\t// there is no previous command\n\t\t{\n\t\t    emsg(_(e_no_previous_substitute_regular_expression));\n\t\t    return;\n\t\t}\n\t\tsub = old_sub;\n\t    }\n\t    else\n\t    {\n\t\tvim_free(old_sub);\n\t\told_sub = vim_strsave(sub);\n\t    }\n\t}\n    }\n    else if (!eap->skip)\t// use previous pattern and substitution\n    {\n\tif (old_sub == NULL)\t// there is no previous command\n\t{\n\t    emsg(_(e_no_previous_substitute_regular_expression));\n\t    return;\n\t}\n\tpat = NULL;\t\t// search_regcomp() will use previous pattern\n\tsub = old_sub;\n\n\t// Vi compatibility quirk: repeating with \":s\" keeps the cursor in the\n\t// last column after using \"$\".\n\tendcolumn = (curwin->w_curswant == MAXCOL);\n    }\n\n    // Recognize \":%s/\\n//\" and turn it into a join command, which is much\n    // more efficient.\n    // TODO: find a generic solution to make line-joining operations more\n    // efficient, avoid allocating a string that grows in size.\n    if (pat != NULL && STRCMP(pat, \"\\\\n\") == 0\n\t    && *sub == NUL\n\t    && (*cmd == NUL || (cmd[1] == NUL && (*cmd == 'g' || *cmd == 'l'\n\t\t\t\t\t     || *cmd == 'p' || *cmd == '#'))))\n    {\n\tlinenr_T    joined_lines_count;\n\n\tif (eap->skip)\n\t    return;\n\tcurwin->w_cursor.lnum = eap->line1;\n\tif (*cmd == 'l')\n\t    eap->flags = EXFLAG_LIST;\n\telse if (*cmd == '#')\n\t    eap->flags = EXFLAG_NR;\n\telse if (*cmd == 'p')\n\t    eap->flags = EXFLAG_PRINT;\n\n\t// The number of lines joined is the number of lines in the range plus\n\t// one.  One less when the last line is included.\n\tjoined_lines_count = eap->line2 - eap->line1 + 1;\n\tif (eap->line2 < curbuf->b_ml.ml_line_count)\n\t    ++joined_lines_count;\n\tif (joined_lines_count > 1)\n\t{\n\t    (void)do_join(joined_lines_count, FALSE, TRUE, FALSE, TRUE);\n\t    sub_nsubs = joined_lines_count - 1;\n\t    sub_nlines = 1;\n\t    (void)do_sub_msg(FALSE);\n\t    ex_may_print(eap);\n\t}\n\n\tif ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0)\n\t    save_re_pat(RE_SUBST, pat, magic_isset());\n\t// put pattern in history\n\tadd_to_history(HIST_SEARCH, pat, TRUE, NUL);\n\n\treturn;\n    }\n\n    /*\n     * Find trailing options.  When '&' is used, keep old options.\n     */\n    if (*cmd == '&')\n\t++cmd;\n    else\n    {\n#ifdef FEAT_EVAL\n\tif (in_vim9script())\n\t{\n\t    // ignore 'gdefault' and 'edcompatible'\n\t    subflags.do_all = FALSE;\n\t    subflags.do_ask = FALSE;\n\t}\n\telse\n#endif\n\tif (!p_ed)\n\t{\n\t    if (p_gd)\t\t// default is global on\n\t\tsubflags.do_all = TRUE;\n\t    else\n\t\tsubflags.do_all = FALSE;\n\t    subflags.do_ask = FALSE;\n\t}\n\tsubflags.do_error = TRUE;\n\tsubflags.do_print = FALSE;\n\tsubflags.do_list = FALSE;\n\tsubflags.do_count = FALSE;\n\tsubflags.do_number = FALSE;\n\tsubflags.do_ic = 0;\n    }\n    while (*cmd)\n    {\n\t/*\n\t * Note that 'g' and 'c' are always inverted, also when p_ed is off.\n\t * 'r' is never inverted.\n\t */\n\tif (*cmd == 'g')\n\t    subflags.do_all = !subflags.do_all;\n\telse if (*cmd == 'c')\n\t    subflags.do_ask = !subflags.do_ask;\n\telse if (*cmd == 'n')\n\t    subflags.do_count = TRUE;\n\telse if (*cmd == 'e')\n\t    subflags.do_error = !subflags.do_error;\n\telse if (*cmd == 'r')\t    // use last used regexp\n\t    which_pat = RE_LAST;\n\telse if (*cmd == 'p')\n\t    subflags.do_print = TRUE;\n\telse if (*cmd == '#')\n\t{\n\t    subflags.do_print = TRUE;\n\t    subflags.do_number = TRUE;\n\t}\n\telse if (*cmd == 'l')\n\t{\n\t    subflags.do_print = TRUE;\n\t    subflags.do_list = TRUE;\n\t}\n\telse if (*cmd == 'i')\t    // ignore case\n\t    subflags.do_ic = 'i';\n\telse if (*cmd == 'I')\t    // don't ignore case\n\t    subflags.do_ic = 'I';\n\telse\n\t    break;\n\t++cmd;\n    }\n    if (subflags.do_count)\n\tsubflags.do_ask = FALSE;\n\n    save_do_all = subflags.do_all;\n    save_do_ask = subflags.do_ask;\n\n    /*\n     * check for a trailing count\n     */\n    cmd = skipwhite(cmd);\n    if (VIM_ISDIGIT(*cmd))\n    {\n\ti = getdigits(&cmd);\n\tif (i <= 0 && !eap->skip && subflags.do_error)\n\t{\n\t    emsg(_(e_positive_count_required));\n\t    return;\n\t}\n\teap->line1 = eap->line2;\n\teap->line2 += i - 1;\n\tif (eap->line2 > curbuf->b_ml.ml_line_count)\n\t    eap->line2 = curbuf->b_ml.ml_line_count;\n    }\n\n    /*\n     * check for trailing command or garbage\n     */\n    cmd = skipwhite(cmd);\n    if (*cmd && *cmd != '\"')\t    // if not end-of-line or comment\n    {\n\tset_nextcmd(eap, cmd);\n\tif (eap->nextcmd == NULL)\n\t{\n\t    semsg(_(e_trailing_characters_str), cmd);\n\t    return;\n\t}\n    }\n\n    if (eap->skip)\t    // not executing commands, only parsing\n\treturn;\n\n    if (!subflags.do_count && !curbuf->b_p_ma)\n    {\n\t// Substitution is not allowed in non-'modifiable' buffer\n\temsg(_(e_cannot_make_changes_modifiable_is_off));\n\treturn;\n    }\n\n    if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, ®match) == FAIL)\n    {\n\tif (subflags.do_error)\n\t    emsg(_(e_invalid_command));\n\treturn;\n    }\n\n    // the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase'\n    if (subflags.do_ic == 'i')\n\tregmatch.rmm_ic = TRUE;\n    else if (subflags.do_ic == 'I')\n\tregmatch.rmm_ic = FALSE;\n\n    sub_firstline = NULL;\n\n    /*\n     * ~ in the substitute pattern is replaced with the old pattern.\n     * We do it here once to avoid it to be replaced over and over again.\n     * But don't do it when it starts with \"\\=\", then it's an expression.\n     */\n    if (!(sub[0] == '\\\\' && sub[1] == '='))\n\tsub = regtilde(sub, magic_isset());\n\n    /*\n     * Check for a match on each line.\n     */\n    line2 = eap->line2;\n    for (lnum = eap->line1; lnum <= line2 && !(got_quit\n#if defined(FEAT_EVAL)\n\t\t|| aborting()\n#endif\n\t\t); ++lnum)\n    {\n\tnmatch = vim_regexec_multi(®match, curwin, curbuf, lnum,\n\t\t\t\t\t\t       (colnr_T)0, NULL, NULL);\n\tif (nmatch)\n\t{\n\t    colnr_T\tcopycol;\n\t    colnr_T\tmatchcol;\n\t    colnr_T\tprev_matchcol = MAXCOL;\n\t    char_u\t*new_end, *new_start = NULL;\n\t    unsigned\tnew_start_len = 0;\n\t    char_u\t*p1;\n\t    int\t\tdid_sub = FALSE;\n\t    int\t\tlastone;\n\t    int\t\tlen, copy_len, needed_len;\n\t    long\tnmatch_tl = 0;\t// nr of lines matched below lnum\n\t    int\t\tdo_again;\t// do it again after joining lines\n\t    int\t\tskip_match = FALSE;\n\t    linenr_T\tsub_firstlnum;\t// nr of first sub line\n#ifdef FEAT_PROP_POPUP\n\t    int\t\tapc_flags = APC_SAVE_FOR_UNDO | APC_SUBSTITUTE;\n\t    colnr_T\ttotal_added =  0;\n#endif\n\n\t    /*\n\t     * The new text is build up step by step, to avoid too much\n\t     * copying.  There are these pieces:\n\t     * sub_firstline\tThe old text, unmodified.\n\t     * copycol\t\tColumn in the old text where we started\n\t     *\t\t\tlooking for a match; from here old text still\n\t     *\t\t\tneeds to be copied to the new text.\n\t     * matchcol\t\tColumn number of the old text where to look\n\t     *\t\t\tfor the next match.  It's just after the\n\t     *\t\t\tprevious match or one further.\n\t     * prev_matchcol\tColumn just after the previous match (if any).\n\t     *\t\t\tMostly equal to matchcol, except for the first\n\t     *\t\t\tmatch and after skipping an empty match.\n\t     * regmatch.*pos\tWhere the pattern matched in the old text.\n\t     * new_start\tThe new text, all that has been produced so\n\t     *\t\t\tfar.\n\t     * new_end\t\tThe new text, where to append new text.\n\t     *\n\t     * lnum\t\tThe line number where we found the start of\n\t     *\t\t\tthe match.  Can be below the line we searched\n\t     *\t\t\twhen there is a \\n before a \\zs in the\n\t     *\t\t\tpattern.\n\t     * sub_firstlnum\tThe line number in the buffer where to look\n\t     *\t\t\tfor a match.  Can be different from \"lnum\"\n\t     *\t\t\twhen the pattern or substitute string contains\n\t     *\t\t\tline breaks.\n\t     *\n\t     * Special situations:\n\t     * - When the substitute string contains a line break, the part up\n\t     *   to the line break is inserted in the text, but the copy of\n\t     *   the original line is kept.  \"sub_firstlnum\" is adjusted for\n\t     *   the inserted lines.\n\t     * - When the matched pattern contains a line break, the old line\n\t     *   is taken from the line at the end of the pattern.  The lines\n\t     *   in the match are deleted later, \"sub_firstlnum\" is adjusted\n\t     *   accordingly.\n\t     *\n\t     * The new text is built up in new_start[].  It has some extra\n\t     * room to avoid using alloc()/free() too often.  new_start_len is\n\t     * the length of the allocated memory at new_start.\n\t     *\n\t     * Make a copy of the old line, so it won't be taken away when\n\t     * updating the screen or handling a multi-line match.  The \"old_\"\n\t     * pointers point into this copy.\n\t     */\n\t    sub_firstlnum = lnum;\n\t    copycol = 0;\n\t    matchcol = 0;\n\n\t    // At first match, remember current cursor position.\n\t    if (!got_match)\n\t    {\n\t\tsetpcmark();\n\t\tgot_match = TRUE;\n\t    }\n\n\t    /*\n\t     * Loop until nothing more to replace in this line.\n\t     * 1. Handle match with empty string.\n\t     * 2. If do_ask is set, ask for confirmation.\n\t     * 3. substitute the string.\n\t     * 4. if do_all is set, find next match\n\t     * 5. break if there isn't another match in this line\n\t     */\n\t    for (;;)\n\t    {\n\t\t// Advance \"lnum\" to the line where the match starts.  The\n\t\t// match does not start in the first line when there is a line\n\t\t// break before \\zs.\n\t\tif (regmatch.startpos[0].lnum > 0)\n\t\t{\n\t\t    lnum += regmatch.startpos[0].lnum;\n\t\t    sub_firstlnum += regmatch.startpos[0].lnum;\n\t\t    nmatch -= regmatch.startpos[0].lnum;\n\t\t    VIM_CLEAR(sub_firstline);\n\t\t}\n\n\t\t// Match might be after the last line for \"\\n\\zs\" matching at\n\t\t// the end of the last line.\n\t\tif (lnum > curbuf->b_ml.ml_line_count)\n\t\t    break;\n\n\t\tif (sub_firstline == NULL)\n\t\t{\n\t\t    sub_firstline = vim_strsave(ml_get(sub_firstlnum));\n\t\t    if (sub_firstline == NULL)\n\t\t    {\n\t\t\tvim_free(new_start);\n\t\t\tgoto outofmem;\n\t\t    }\n\t\t}\n\n\t\t// Save the line number of the last change for the final\n\t\t// cursor position (just like Vi).\n\t\tcurwin->w_cursor.lnum = lnum;\n\t\tdo_again = FALSE;\n\n\t\t/*\n\t\t * 1. Match empty string does not count, except for first\n\t\t * match.  This reproduces the strange vi behaviour.\n\t\t * This also catches endless loops.\n\t\t */\n\t\tif (matchcol == prev_matchcol\n\t\t\t&& regmatch.endpos[0].lnum == 0\n\t\t\t&& matchcol == regmatch.endpos[0].col)\n\t\t{\n\t\t    if (sub_firstline[matchcol] == NUL)\n\t\t\t// We already were at the end of the line.  Don't look\n\t\t\t// for a match in this line again.\n\t\t\tskip_match = TRUE;\n\t\t    else\n\t\t    {\n\t\t\t // search for a match at next column\n\t\t\tif (has_mbyte)\n\t\t\t    matchcol += mb_ptr2len(sub_firstline + matchcol);\n\t\t\telse\n\t\t\t    ++matchcol;\n\t\t    }\n\t\t    goto skip;\n\t\t}\n\n\t\t// Normally we continue searching for a match just after the\n\t\t// previous match.\n\t\tmatchcol = regmatch.endpos[0].col;\n\t\tprev_matchcol = matchcol;\n\n\t\t/*\n\t\t * 2. If do_count is set only increase the counter.\n\t\t *    If do_ask is set, ask for confirmation.\n\t\t */\n\t\tif (subflags.do_count)\n\t\t{\n\t\t    // For a multi-line match, put matchcol at the NUL at\n\t\t    // the end of the line and set nmatch to one, so that\n\t\t    // we continue looking for a match on the next line.\n\t\t    // Avoids that \":s/\\nB\\@=//gc\" get stuck.\n\t\t    if (nmatch > 1)\n\t\t    {\n\t\t\tmatchcol = (colnr_T)STRLEN(sub_firstline);\n\t\t\tnmatch = 1;\n\t\t\tskip_match = TRUE;\n\t\t    }\n\t\t    sub_nsubs++;\n\t\t    did_sub = TRUE;\n#ifdef FEAT_EVAL\n\t\t    // Skip the substitution, unless an expression is used,\n\t\t    // then it is evaluated in the sandbox.\n\t\t    if (!(sub[0] == '\\\\' && sub[1] == '='))\n#endif\n\t\t\tgoto skip;\n\t\t}\n\n\t\tif (subflags.do_ask)\n\t\t{\n\t\t    int typed = 0;\n\n\t\t    // change State to CONFIRM, so that the mouse works\n\t\t    // properly\n\t\t    save_State = State;\n\t\t    State = CONFIRM;\n\t\t    setmouse();\t\t// disable mouse in xterm\n\t\t    curwin->w_cursor.col = regmatch.startpos[0].col;\n\t\t    if (curwin->w_p_crb)\n\t\t\tdo_check_cursorbind();\n\n\t\t    // When 'cpoptions' contains \"u\" don't sync undo when\n\t\t    // asking for confirmation.\n\t\t    if (vim_strchr(p_cpo, CPO_UNDO) != NULL)\n\t\t\t++no_u_sync;\n\n\t\t    /*\n\t\t     * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.\n\t\t     */\n\t\t    while (subflags.do_ask)\n\t\t    {\n\t\t\tif (exmode_active)\n\t\t\t{\n\t\t\t    char_u\t*resp;\n\t\t\t    colnr_T\tsc, ec;\n\n\t\t\t    print_line_no_prefix(lnum,\n\t\t\t\t\t subflags.do_number, subflags.do_list);\n\n\t\t\t    getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL);\n\t\t\t    curwin->w_cursor.col = regmatch.endpos[0].col - 1;\n\t\t\t    if (curwin->w_cursor.col < 0)\n\t\t\t\tcurwin->w_cursor.col = 0;\n\t\t\t    getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec);\n\t\t\t    curwin->w_cursor.col = regmatch.startpos[0].col;\n\t\t\t    if (subflags.do_number || curwin->w_p_nu)\n\t\t\t    {\n\t\t\t\tint numw = number_width(curwin) + 1;\n\t\t\t\tsc += numw;\n\t\t\t\tec += numw;\n\t\t\t    }\n\t\t\t    msg_start();\n\t\t\t    for (i = 0; i < (long)sc; ++i)\n\t\t\t\tmsg_putchar(' ');\n\t\t\t    for ( ; i <= (long)ec; ++i)\n\t\t\t\tmsg_putchar('^');\n\n\t\t\t    resp = getexmodeline('?', NULL, 0, TRUE);\n\t\t\t    if (resp != NULL)\n\t\t\t    {\n\t\t\t\ttyped = *resp;\n\t\t\t\tvim_free(resp);\n\t\t\t    }\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t    char_u *orig_line = NULL;\n\t\t\t    int    len_change = 0;\n\t\t\t    int\t   save_p_lz = p_lz;\n#ifdef FEAT_FOLDING\n\t\t\t    int save_p_fen = curwin->w_p_fen;\n\n\t\t\t    curwin->w_p_fen = FALSE;\n#endif\n\t\t\t    // Invert the matched string.\n\t\t\t    // Remove the inversion afterwards.\n\t\t\t    temp = RedrawingDisabled;\n\t\t\t    RedrawingDisabled = 0;\n\n\t\t\t    // avoid calling update_screen() in vgetorpeek()\n\t\t\t    p_lz = FALSE;\n\n\t\t\t    if (new_start != NULL)\n\t\t\t    {\n\t\t\t\t// There already was a substitution, we would\n\t\t\t\t// like to show this to the user.  We cannot\n\t\t\t\t// really update the line, it would change\n\t\t\t\t// what matches.  Temporarily replace the line\n\t\t\t\t// and change it back afterwards.\n\t\t\t\torig_line = vim_strsave(ml_get(lnum));\n\t\t\t\tif (orig_line != NULL)\n\t\t\t\t{\n\t\t\t\t    char_u *new_line = concat_str(new_start,\n\t\t\t\t\t\t     sub_firstline + copycol);\n\n\t\t\t\t    if (new_line == NULL)\n\t\t\t\t\tVIM_CLEAR(orig_line);\n\t\t\t\t    else\n\t\t\t\t    {\n\t\t\t\t\t// Position the cursor relative to the\n\t\t\t\t\t// end of the line, the previous\n\t\t\t\t\t// substitute may have inserted or\n\t\t\t\t\t// deleted characters before the\n\t\t\t\t\t// cursor.\n\t\t\t\t\tlen_change = (int)STRLEN(new_line)\n\t\t\t\t\t\t     - (int)STRLEN(orig_line);\n\t\t\t\t\tcurwin->w_cursor.col += len_change;\n\t\t\t\t\tml_replace(lnum, new_line, FALSE);\n\t\t\t\t    }\n\t\t\t\t}\n\t\t\t    }\n\n\t\t\t    search_match_lines = regmatch.endpos[0].lnum\n\t\t\t\t\t\t  - regmatch.startpos[0].lnum;\n\t\t\t    search_match_endcol = regmatch.endpos[0].col\n\t\t\t\t\t\t\t\t + len_change;\n\t\t\t    highlight_match = TRUE;\n\n\t\t\t    update_topline();\n\t\t\t    validate_cursor();\n\t\t\t    update_screen(SOME_VALID);\n\t\t\t    highlight_match = FALSE;\n\t\t\t    redraw_later(SOME_VALID);\n\n#ifdef FEAT_FOLDING\n\t\t\t    curwin->w_p_fen = save_p_fen;\n#endif\n\t\t\t    if (msg_row == Rows - 1)\n\t\t\t\tmsg_didout = FALSE;\t// avoid a scroll-up\n\t\t\t    msg_starthere();\n\t\t\t    i = msg_scroll;\n\t\t\t    msg_scroll = 0;\t\t// truncate msg when\n\t\t\t\t\t\t\t// needed\n\t\t\t    msg_no_more = TRUE;\n\t\t\t    // write message same highlighting as for\n\t\t\t    // wait_return\n\t\t\t    smsg_attr(HL_ATTR(HLF_R),\n\t\t\t\t_(\"replace with %s (y/n/a/q/l/^E/^Y)?\"), sub);\n\t\t\t    msg_no_more = FALSE;\n\t\t\t    msg_scroll = i;\n\t\t\t    showruler(TRUE);\n\t\t\t    windgoto(msg_row, msg_col);\n\t\t\t    RedrawingDisabled = temp;\n\n#ifdef USE_ON_FLY_SCROLL\n\t\t\t    dont_scroll = FALSE; // allow scrolling here\n#endif\n\t\t\t    ++no_mapping;\t// don't map this key\n\t\t\t    ++allow_keys;\t// allow special keys\n\t\t\t    typed = plain_vgetc();\n\t\t\t    --allow_keys;\n\t\t\t    --no_mapping;\n\n\t\t\t    // clear the question\n\t\t\t    msg_didout = FALSE;\t// don't scroll up\n\t\t\t    msg_col = 0;\n\t\t\t    gotocmdline(TRUE);\n\t\t\t    p_lz = save_p_lz;\n\n\t\t\t    // restore the line\n\t\t\t    if (orig_line != NULL)\n\t\t\t\tml_replace(lnum, orig_line, FALSE);\n\t\t\t}\n\n\t\t\tneed_wait_return = FALSE; // no hit-return prompt\n\t\t\tif (typed == 'q' || typed == ESC || typed == Ctrl_C\n#ifdef UNIX\n\t\t\t\t|| typed == intr_char\n#endif\n\t\t\t\t)\n\t\t\t{\n\t\t\t    got_quit = TRUE;\n\t\t\t    break;\n\t\t\t}\n\t\t\tif (typed == 'n')\n\t\t\t    break;\n\t\t\tif (typed == 'y')\n\t\t\t    break;\n\t\t\tif (typed == 'l')\n\t\t\t{\n\t\t\t    // last: replace and then stop\n\t\t\t    subflags.do_all = FALSE;\n\t\t\t    line2 = lnum;\n\t\t\t    break;\n\t\t\t}\n\t\t\tif (typed == 'a')\n\t\t\t{\n\t\t\t    subflags.do_ask = FALSE;\n\t\t\t    break;\n\t\t\t}\n\t\t\tif (typed == Ctrl_E)\n\t\t\t    scrollup_clamp();\n\t\t\telse if (typed == Ctrl_Y)\n\t\t\t    scrolldown_clamp();\n\t\t    }\n\t\t    State = save_State;\n\t\t    setmouse();\n\t\t    if (vim_strchr(p_cpo, CPO_UNDO) != NULL)\n\t\t\t--no_u_sync;\n\n\t\t    if (typed == 'n')\n\t\t    {\n\t\t\t// For a multi-line match, put matchcol at the NUL at\n\t\t\t// the end of the line and set nmatch to one, so that\n\t\t\t// we continue looking for a match on the next line.\n\t\t\t// Avoids that \":%s/\\nB\\@=//gc\" and \":%s/\\n/,\\r/gc\"\n\t\t\t// get stuck when pressing 'n'.\n\t\t\tif (nmatch > 1)\n\t\t\t{\n\t\t\t    matchcol = (colnr_T)STRLEN(sub_firstline);\n\t\t\t    skip_match = TRUE;\n\t\t\t}\n\t\t\tgoto skip;\n\t\t    }\n\t\t    if (got_quit)\n\t\t\tgoto skip;\n\t\t}\n\n\t\t// Move the cursor to the start of the match, so that we can\n\t\t// use \"\\=col(\".\").\n\t\tcurwin->w_cursor.col = regmatch.startpos[0].col;\n\n\t\t/*\n\t\t * 3. substitute the string.\n\t\t */\n#ifdef FEAT_EVAL\n\t\tsave_ma = curbuf->b_p_ma;\n\t\tif (subflags.do_count)\n\t\t{\n\t\t    // prevent accidentally changing the buffer by a function\n\t\t    curbuf->b_p_ma = FALSE;\n\t\t    sandbox++;\n\t\t}\n\t\t// Save flags for recursion.  They can change for e.g.\n\t\t// :s/^/\\=execute(\"s#^##gn\")\n\t\tsubflags_save = subflags;\n#endif\n\t\t// get length of substitution part\n\t\tsublen = vim_regsub_multi(®match,\n\t\t\t\t    sub_firstlnum - regmatch.startpos[0].lnum,\n\t\t\t       sub, sub_firstline, FALSE, magic_isset(), TRUE);\n#ifdef FEAT_EVAL\n\t\t// If getting the substitute string caused an error, don't do\n\t\t// the replacement.\n\t\t// Don't keep flags set by a recursive call.\n\t\tsubflags = subflags_save;\n\t\tif (aborting() || subflags.do_count)\n\t\t{\n\t\t    curbuf->b_p_ma = save_ma;\n\t\t    if (sandbox > 0)\n\t\t\tsandbox--;\n\t\t    goto skip;\n\t\t}\n#endif\n\n\t\t// When the match included the \"$\" of the last line it may\n\t\t// go beyond the last line of the buffer.\n\t\tif (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1)\n\t\t{\n\t\t    nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1;\n\t\t    skip_match = TRUE;\n\t\t}\n\n\t\t// Need room for:\n\t\t// - result so far in new_start (not for first sub in line)\n\t\t// - original text up to match\n\t\t// - length of substituted part\n\t\t// - original text after match\n\t\t// Adjust text properties here, since we have all information\n\t\t// needed.\n\t\tif (nmatch == 1)\n\t\t{\n\t\t    p1 = sub_firstline;\n#ifdef FEAT_PROP_POPUP\n\t\t    if (curbuf->b_has_textprop)\n\t\t    {\n\t\t\tint bytes_added = sublen - 1 - (regmatch.endpos[0].col\n\t\t\t\t\t\t   - regmatch.startpos[0].col);\n\n\t\t\t// When text properties are changed, need to save for\n\t\t\t// undo first, unless done already.\n\t\t\tif (adjust_prop_columns(lnum,\n\t\t\t\t\ttotal_added + regmatch.startpos[0].col,\n\t\t\t\t\t\t       bytes_added, apc_flags))\n\t\t\t    apc_flags &= ~APC_SAVE_FOR_UNDO;\n\t\t\t// Offset for column byte number of the text property\n\t\t\t// in the resulting buffer afterwards.\n\t\t\ttotal_added += bytes_added;\n\t\t    }\n#endif\n\t\t}\n\t\telse\n\t\t{\n\t\t    p1 = ml_get(sub_firstlnum + nmatch - 1);\n\t\t    nmatch_tl += nmatch - 1;\n\t\t}\n\t\tcopy_len = regmatch.startpos[0].col - copycol;\n\t\tneeded_len = copy_len + ((unsigned)STRLEN(p1)\n\t\t\t\t       - regmatch.endpos[0].col) + sublen + 1;\n\t\tif (new_start == NULL)\n\t\t{\n\t\t    /*\n\t\t     * Get some space for a temporary buffer to do the\n\t\t     * substitution into (and some extra space to avoid\n\t\t     * too many calls to alloc()/free()).\n\t\t     */\n\t\t    new_start_len = needed_len + 50;\n\t\t    if ((new_start = alloc(new_start_len)) == NULL)\n\t\t\tgoto outofmem;\n\t\t    *new_start = NUL;\n\t\t    new_end = new_start;\n\t\t}\n\t\telse\n\t\t{\n\t\t    /*\n\t\t     * Check if the temporary buffer is long enough to do the\n\t\t     * substitution into.  If not, make it larger (with a bit\n\t\t     * extra to avoid too many calls to alloc()/free()).\n\t\t     */\n\t\t    len = (unsigned)STRLEN(new_start);\n\t\t    needed_len += len;\n\t\t    if (needed_len > (int)new_start_len)\n\t\t    {\n\t\t\tnew_start_len = needed_len + 50;\n\t\t\tif ((p1 = alloc(new_start_len)) == NULL)\n\t\t\t{\n\t\t\t    vim_free(new_start);\n\t\t\t    goto outofmem;\n\t\t\t}\n\t\t\tmch_memmove(p1, new_start, (size_t)(len + 1));\n\t\t\tvim_free(new_start);\n\t\t\tnew_start = p1;\n\t\t    }\n\t\t    new_end = new_start + len;\n\t\t}\n\n\t\t/*\n\t\t * copy the text up to the part that matched\n\t\t */\n\t\tmch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len);\n\t\tnew_end += copy_len;\n\n\t\t(void)vim_regsub_multi(®match,\n\t\t\t\t    sub_firstlnum - regmatch.startpos[0].lnum,\n\t\t\t\t      sub, new_end, TRUE, magic_isset(), TRUE);\n\t\tsub_nsubs++;\n\t\tdid_sub = TRUE;\n\n\t\t// Move the cursor to the start of the line, to avoid that it\n\t\t// is beyond the end of the line after the substitution.\n\t\tcurwin->w_cursor.col = 0;\n\n\t\t// For a multi-line match, make a copy of the last matched\n\t\t// line and continue in that one.\n\t\tif (nmatch > 1)\n\t\t{\n\t\t    sub_firstlnum += nmatch - 1;\n\t\t    vim_free(sub_firstline);\n\t\t    sub_firstline = vim_strsave(ml_get(sub_firstlnum));\n\t\t    // When going beyond the last line, stop substituting.\n\t\t    if (sub_firstlnum <= line2)\n\t\t\tdo_again = TRUE;\n\t\t    else\n\t\t\tsubflags.do_all = FALSE;\n\t\t}\n\n\t\t// Remember next character to be copied.\n\t\tcopycol = regmatch.endpos[0].col;\n\n\t\tif (skip_match)\n\t\t{\n\t\t    // Already hit end of the buffer, sub_firstlnum is one\n\t\t    // less than what it ought to be.\n\t\t    vim_free(sub_firstline);\n\t\t    sub_firstline = vim_strsave((char_u *)\"\");\n\t\t    copycol = 0;\n\t\t}\n\n\t\t/*\n\t\t * Now the trick is to replace CTRL-M chars with a real line\n\t\t * break.  This would make it impossible to insert a CTRL-M in\n\t\t * the text.  The line break can be avoided by preceding the\n\t\t * CTRL-M with a backslash.  To be able to insert a backslash,\n\t\t * they must be doubled in the string and are halved here.\n\t\t * That is Vi compatible.\n\t\t */\n\t\tfor (p1 = new_end; *p1; ++p1)\n\t\t{\n\t\t    if (p1[0] == '\\\\' && p1[1] != NUL)  // remove backslash\n\t\t    {\n\t\t\tSTRMOVE(p1, p1 + 1);\n#ifdef FEAT_PROP_POPUP\n\t\t\tif (curbuf->b_has_textprop)\n\t\t\t{\n\t\t\t    // When text properties are changed, need to save\n\t\t\t    // for undo first, unless done already.\n\t\t\t    if (adjust_prop_columns(lnum,\n\t\t\t\t\t(colnr_T)(p1 - new_start), -1,\n\t\t\t\t\tapc_flags))\n\t\t\t\tapc_flags &= ~APC_SAVE_FOR_UNDO;\n\t\t\t}\n#endif\n\t\t    }\n\t\t    else if (*p1 == CAR)\n\t\t    {\n\t\t\tif (u_inssub(lnum) == OK)   // prepare for undo\n\t\t\t{\n\t\t\t    colnr_T\tplen = (colnr_T)(p1 - new_start + 1);\n\n\t\t\t    *p1 = NUL;\t\t    // truncate up to the CR\n\t\t\t    ml_append(lnum - 1, new_start, plen, FALSE);\n\t\t\t    mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);\n\t\t\t    if (subflags.do_ask)\n\t\t\t\tappended_lines(lnum - 1, 1L);\n\t\t\t    else\n\t\t\t    {\n\t\t\t\tif (first_line == 0)\n\t\t\t\t    first_line = lnum;\n\t\t\t\tlast_line = lnum + 1;\n\t\t\t    }\n#ifdef FEAT_PROP_POPUP\n\t\t\t    adjust_props_for_split(lnum + 1, lnum, plen, 1);\n#endif\n\t\t\t    // all line numbers increase\n\t\t\t    ++sub_firstlnum;\n\t\t\t    ++lnum;\n\t\t\t    ++line2;\n\t\t\t    // move the cursor to the new line, like Vi\n\t\t\t    ++curwin->w_cursor.lnum;\n\t\t\t    // copy the rest\n\t\t\t    STRMOVE(new_start, p1 + 1);\n\t\t\t    p1 = new_start - 1;\n\t\t\t}\n\t\t    }\n\t\t    else if (has_mbyte)\n\t\t\tp1 += (*mb_ptr2len)(p1) - 1;\n\t\t}\n\n\t\t/*\n\t\t * 4. If do_all is set, find next match.\n\t\t * Prevent endless loop with patterns that match empty\n\t\t * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.\n\t\t * But \":s/\\n/#/\" is OK.\n\t\t */\nskip:\n\t\t// We already know that we did the last subst when we are at\n\t\t// the end of the line, except that a pattern like\n\t\t// \"bar\\|\\nfoo\" may match at the NUL.  \"lnum\" can be below\n\t\t// \"line2\" when there is a \\zs in the pattern after a line\n\t\t// break.\n\t\tlastone = (skip_match\n\t\t\t|| got_int\n\t\t\t|| got_quit\n\t\t\t|| lnum > line2\n\t\t\t|| !(subflags.do_all || do_again)\n\t\t\t|| (sub_firstline[matchcol] == NUL && nmatch <= 1\n\t\t\t\t\t && !re_multiline(regmatch.regprog)));\n\t\tnmatch = -1;\n\n\t\t/*\n\t\t * Replace the line in the buffer when needed.  This is\n\t\t * skipped when there are more matches.\n\t\t * The check for nmatch_tl is needed for when multi-line\n\t\t * matching must replace the lines before trying to do another\n\t\t * match, otherwise \"\\@<=\" won't work.\n\t\t * When the match starts below where we start searching also\n\t\t * need to replace the line first (using \\zs after \\n).\n\t\t */\n\t\tif (lastone\n\t\t\t|| nmatch_tl > 0\n\t\t\t|| (nmatch = vim_regexec_multi(®match, curwin,\n\t\t\t\t\t\t\tcurbuf, sub_firstlnum,\n\t\t\t\t\t\t    matchcol, NULL, NULL)) == 0\n\t\t\t|| regmatch.startpos[0].lnum > 0)\n\t\t{\n\t\t    if (new_start != NULL)\n\t\t    {\n\t\t\t/*\n\t\t\t * Copy the rest of the line, that didn't match.\n\t\t\t * \"matchcol\" has to be adjusted, we use the end of\n\t\t\t * the line as reference, because the substitute may\n\t\t\t * have changed the number of characters.  Same for\n\t\t\t * \"prev_matchcol\".\n\t\t\t */\n\t\t\tSTRCAT(new_start, sub_firstline + copycol);\n\t\t\tmatchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;\n\t\t\tprev_matchcol = (colnr_T)STRLEN(sub_firstline)\n\t\t\t\t\t\t\t      - prev_matchcol;\n\n\t\t\tif (u_savesub(lnum) != OK)\n\t\t\t    break;\n\t\t\tml_replace(lnum, new_start, TRUE);\n\n\t\t\tif (nmatch_tl > 0)\n\t\t\t{\n\t\t\t    /*\n\t\t\t     * Matched lines have now been substituted and are\n\t\t\t     * useless, delete them.  The part after the match\n\t\t\t     * has been appended to new_start, we don't need\n\t\t\t     * it in the buffer.\n\t\t\t     */\n\t\t\t    ++lnum;\n\t\t\t    if (u_savedel(lnum, nmatch_tl) != OK)\n\t\t\t\tbreak;\n\t\t\t    for (i = 0; i < nmatch_tl; ++i)\n\t\t\t\tml_delete(lnum);\n\t\t\t    mark_adjust(lnum, lnum + nmatch_tl - 1,\n\t\t\t\t\t\t   (long)MAXLNUM, -nmatch_tl);\n\t\t\t    if (subflags.do_ask)\n\t\t\t\tdeleted_lines(lnum, nmatch_tl);\n\t\t\t    --lnum;\n\t\t\t    line2 -= nmatch_tl; // nr of lines decreases\n\t\t\t    nmatch_tl = 0;\n\t\t\t}\n\n\t\t\t// When asking, undo is saved each time, must also set\n\t\t\t// changed flag each time.\n\t\t\tif (subflags.do_ask)\n\t\t\t    changed_bytes(lnum, 0);\n\t\t\telse\n\t\t\t{\n\t\t\t    if (first_line == 0)\n\t\t\t\tfirst_line = lnum;\n\t\t\t    last_line = lnum + 1;\n\t\t\t}\n\n\t\t\tsub_firstlnum = lnum;\n\t\t\tvim_free(sub_firstline);    // free the temp buffer\n\t\t\tsub_firstline = new_start;\n\t\t\tnew_start = NULL;\n\t\t\tmatchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;\n\t\t\tprev_matchcol = (colnr_T)STRLEN(sub_firstline)\n\t\t\t\t\t\t\t      - prev_matchcol;\n\t\t\tcopycol = 0;\n\t\t    }\n\t\t    if (nmatch == -1 && !lastone)\n\t\t\tnmatch = vim_regexec_multi(®match, curwin, curbuf,\n\t\t\t\t\t  sub_firstlnum, matchcol, NULL, NULL);\n\n\t\t    /*\n\t\t     * 5. break if there isn't another match in this line\n\t\t     */\n\t\t    if (nmatch <= 0)\n\t\t    {\n\t\t\t// If the match found didn't start where we were\n\t\t\t// searching, do the next search in the line where we\n\t\t\t// found the match.\n\t\t\tif (nmatch == -1)\n\t\t\t    lnum -= regmatch.startpos[0].lnum;\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\n\t\tline_breakcheck();\n\t    }\n\n\t    if (did_sub)\n\t\t++sub_nlines;\n\t    vim_free(new_start);\t// for when substitute was cancelled\n\t    VIM_CLEAR(sub_firstline);\t// free the copy of the original line\n\t}\n\n\tline_breakcheck();\n    }\n\n    if (first_line != 0)\n    {\n\t// Need to subtract the number of added lines from \"last_line\" to get\n\t// the line number before the change (same as adding the number of\n\t// deleted lines).\n\ti = curbuf->b_ml.ml_line_count - old_line_count;\n\tchanged_lines(first_line, 0, last_line - i, i);\n    }\n\noutofmem:\n    vim_free(sub_firstline); // may have to free allocated copy of the line\n\n    // \":s/pat//n\" doesn't move the cursor\n    if (subflags.do_count)\n\tcurwin->w_cursor = old_cursor;\n\n    if (sub_nsubs > start_nsubs)\n    {\n\tif ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)\n\t{\n\t    // Set the '[ and '] marks.\n\t    curbuf->b_op_start.lnum = eap->line1;\n\t    curbuf->b_op_end.lnum = line2;\n\t    curbuf->b_op_start.col = curbuf->b_op_end.col = 0;\n\t}\n\n\tif (!global_busy)\n\t{\n\t    // when interactive leave cursor on the match\n\t    if (!subflags.do_ask)\n\t    {\n\t\tif (endcolumn)\n\t\t    coladvance((colnr_T)MAXCOL);\n\t\telse\n\t\t    beginline(BL_WHITE | BL_FIX);\n\t    }\n\t    if (!do_sub_msg(subflags.do_count) && subflags.do_ask)\n\t\tmsg(\"\");\n\t}\n\telse\n\t    global_need_beginline = TRUE;\n\tif (subflags.do_print)\n\t    print_line(curwin->w_cursor.lnum,\n\t\t\t\t\t subflags.do_number, subflags.do_list);\n    }\n    else if (!global_busy)\n    {\n\tif (got_int)\t\t// interrupted\n\t    emsg(_(e_interrupted));\n\telse if (got_match)\t// did find something but nothing substituted\n\t    msg(\"\");\n\telse if (subflags.do_error)\t// nothing found\n\t    semsg(_(e_pattern_not_found_str), get_search_pat());\n    }\n\n#ifdef FEAT_FOLDING\n    if (subflags.do_ask && hasAnyFolding(curwin))\n\t// Cursor position may require updating\n\tchanged_window_setting();\n#endif\n\n    vim_regfree(regmatch.regprog);\n\n    // Restore the flag values, they can be used for \":&&\".\n    subflags.do_all = save_do_all;\n    subflags.do_ask = save_do_ask;\n}", "func_hash": 259196751787508005925510441148614080583, "file_name": "ex_cmds.c", "file_hash": 59965875084146466287270368497703800580, "cwe": ["CWE-416"], "cve": "CVE-2022-0413", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0413"}
{"idx": 296226, "project": "vim", "commit_id": "37f47958b8a2a44abc60614271d9537e7f14e51a", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/37f47958b8a2a44abc60614271d9537e7f14e51a", "commit_message": "patch 8.2.4253: using freed memory when substitute with function call\n\nProblem:    Using freed memory when substitute uses a recursive function call.\nSolution:   Make a copy of the substitute text.", "target": 0, "func": "ex_substitute(exarg_T *eap)\n{\n    linenr_T\tlnum;\n    long\ti = 0;\n    regmmatch_T regmatch;\n    static subflags_T subflags = {FALSE, FALSE, FALSE, TRUE, FALSE,\n\t\t\t\t\t\t\t      FALSE, FALSE, 0};\n#ifdef FEAT_EVAL\n    subflags_T\tsubflags_save;\n#endif\n    int\t\tsave_do_all;\t\t// remember user specified 'g' flag\n    int\t\tsave_do_ask;\t\t// remember user specified 'c' flag\n    char_u\t*pat = NULL, *sub = NULL;\t// init for GCC\n    char_u\t*sub_copy = NULL;\n    int\t\tdelimiter;\n    int\t\tsublen;\n    int\t\tgot_quit = FALSE;\n    int\t\tgot_match = FALSE;\n    int\t\ttemp;\n    int\t\twhich_pat;\n    char_u\t*cmd;\n    int\t\tsave_State;\n    linenr_T\tfirst_line = 0;\t\t// first changed line\n    linenr_T\tlast_line= 0;\t\t// below last changed line AFTER the\n\t\t\t\t\t// change\n    linenr_T\told_line_count = curbuf->b_ml.ml_line_count;\n    linenr_T\tline2;\n    long\tnmatch;\t\t\t// number of lines in match\n    char_u\t*sub_firstline;\t\t// allocated copy of first sub line\n    int\t\tendcolumn = FALSE;\t// cursor in last column when done\n    pos_T\told_cursor = curwin->w_cursor;\n    int\t\tstart_nsubs;\n#ifdef FEAT_EVAL\n    int\t\tsave_ma = 0;\n#endif\n\n    cmd = eap->arg;\n    if (!global_busy)\n    {\n\tsub_nsubs = 0;\n\tsub_nlines = 0;\n    }\n    start_nsubs = sub_nsubs;\n\n    if (eap->cmdidx == CMD_tilde)\n\twhich_pat = RE_LAST;\t// use last used regexp\n    else\n\twhich_pat = RE_SUBST;\t// use last substitute regexp\n\n\t\t\t\t// new pattern and substitution\n    if (eap->cmd[0] == 's' && *cmd != NUL && !VIM_ISWHITE(*cmd)\n\t\t&& vim_strchr((char_u *)\"0123456789cegriIp|\\\"\", *cmd) == NULL)\n    {\n\t\t\t\t// don't accept alphanumeric for separator\n\tif (check_regexp_delim(*cmd) == FAIL)\n\t    return;\n#ifdef FEAT_EVAL\n\tif (in_vim9script() && check_global_and_subst(eap->cmd, eap->arg)\n\t\t\t\t\t\t\t\t      == FAIL)\n\t    return;\n#endif\n\n\t/*\n\t * undocumented vi feature:\n\t *  \"\\/sub/\" and \"\\?sub?\" use last used search pattern (almost like\n\t *  //sub/r).  \"\\&sub&\" use last substitute pattern (like //sub/).\n\t */\n\tif (*cmd == '\\\\')\n\t{\n\t    ++cmd;\n\t    if (vim_strchr((char_u *)\"/?&\", *cmd) == NULL)\n\t    {\n\t\temsg(_(e_backslash_should_be_followed_by));\n\t\treturn;\n\t    }\n\t    if (*cmd != '&')\n\t\twhich_pat = RE_SEARCH;\t    // use last '/' pattern\n\t    pat = (char_u *)\"\";\t\t    // empty search pattern\n\t    delimiter = *cmd++;\t\t    // remember delimiter character\n\t}\n\telse\t\t// find the end of the regexp\n\t{\n\t    which_pat = RE_LAST;\t    // use last used regexp\n\t    delimiter = *cmd++;\t\t    // remember delimiter character\n\t    pat = cmd;\t\t\t    // remember start of search pat\n\t    cmd = skip_regexp_ex(cmd, delimiter, magic_isset(),\n\t\t\t\t\t\t\t&eap->arg, NULL, NULL);\n\t    if (cmd[0] == delimiter)\t    // end delimiter found\n\t\t*cmd++ = NUL;\t\t    // replace it with a NUL\n\t}\n\n\t/*\n\t * Small incompatibility: vi sees '\\n' as end of the command, but in\n\t * Vim we want to use '\\n' to find/substitute a NUL.\n\t */\n\tsub = cmd;\t    // remember the start of the substitution\n\tcmd = skip_substitute(cmd, delimiter);\n\n\tif (!eap->skip)\n\t{\n\t    // In POSIX vi \":s/pat/%/\" uses the previous subst. string.\n\t    if (STRCMP(sub, \"%\") == 0\n\t\t\t\t && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)\n\t    {\n\t\tif (old_sub == NULL)\t// there is no previous command\n\t\t{\n\t\t    emsg(_(e_no_previous_substitute_regular_expression));\n\t\t    return;\n\t\t}\n\t\tsub = old_sub;\n\t    }\n\t    else\n\t    {\n\t\tvim_free(old_sub);\n\t\told_sub = vim_strsave(sub);\n\t    }\n\t}\n    }\n    else if (!eap->skip)\t// use previous pattern and substitution\n    {\n\tif (old_sub == NULL)\t// there is no previous command\n\t{\n\t    emsg(_(e_no_previous_substitute_regular_expression));\n\t    return;\n\t}\n\tpat = NULL;\t\t// search_regcomp() will use previous pattern\n\tsub = old_sub;\n\n\t// Vi compatibility quirk: repeating with \":s\" keeps the cursor in the\n\t// last column after using \"$\".\n\tendcolumn = (curwin->w_curswant == MAXCOL);\n    }\n\n    // Recognize \":%s/\\n//\" and turn it into a join command, which is much\n    // more efficient.\n    // TODO: find a generic solution to make line-joining operations more\n    // efficient, avoid allocating a string that grows in size.\n    if (pat != NULL && STRCMP(pat, \"\\\\n\") == 0\n\t    && *sub == NUL\n\t    && (*cmd == NUL || (cmd[1] == NUL && (*cmd == 'g' || *cmd == 'l'\n\t\t\t\t\t     || *cmd == 'p' || *cmd == '#'))))\n    {\n\tlinenr_T    joined_lines_count;\n\n\tif (eap->skip)\n\t    return;\n\tcurwin->w_cursor.lnum = eap->line1;\n\tif (*cmd == 'l')\n\t    eap->flags = EXFLAG_LIST;\n\telse if (*cmd == '#')\n\t    eap->flags = EXFLAG_NR;\n\telse if (*cmd == 'p')\n\t    eap->flags = EXFLAG_PRINT;\n\n\t// The number of lines joined is the number of lines in the range plus\n\t// one.  One less when the last line is included.\n\tjoined_lines_count = eap->line2 - eap->line1 + 1;\n\tif (eap->line2 < curbuf->b_ml.ml_line_count)\n\t    ++joined_lines_count;\n\tif (joined_lines_count > 1)\n\t{\n\t    (void)do_join(joined_lines_count, FALSE, TRUE, FALSE, TRUE);\n\t    sub_nsubs = joined_lines_count - 1;\n\t    sub_nlines = 1;\n\t    (void)do_sub_msg(FALSE);\n\t    ex_may_print(eap);\n\t}\n\n\tif ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0)\n\t    save_re_pat(RE_SUBST, pat, magic_isset());\n\t// put pattern in history\n\tadd_to_history(HIST_SEARCH, pat, TRUE, NUL);\n\n\treturn;\n    }\n\n    /*\n     * Find trailing options.  When '&' is used, keep old options.\n     */\n    if (*cmd == '&')\n\t++cmd;\n    else\n    {\n#ifdef FEAT_EVAL\n\tif (in_vim9script())\n\t{\n\t    // ignore 'gdefault' and 'edcompatible'\n\t    subflags.do_all = FALSE;\n\t    subflags.do_ask = FALSE;\n\t}\n\telse\n#endif\n\tif (!p_ed)\n\t{\n\t    if (p_gd)\t\t// default is global on\n\t\tsubflags.do_all = TRUE;\n\t    else\n\t\tsubflags.do_all = FALSE;\n\t    subflags.do_ask = FALSE;\n\t}\n\tsubflags.do_error = TRUE;\n\tsubflags.do_print = FALSE;\n\tsubflags.do_list = FALSE;\n\tsubflags.do_count = FALSE;\n\tsubflags.do_number = FALSE;\n\tsubflags.do_ic = 0;\n    }\n    while (*cmd)\n    {\n\t/*\n\t * Note that 'g' and 'c' are always inverted, also when p_ed is off.\n\t * 'r' is never inverted.\n\t */\n\tif (*cmd == 'g')\n\t    subflags.do_all = !subflags.do_all;\n\telse if (*cmd == 'c')\n\t    subflags.do_ask = !subflags.do_ask;\n\telse if (*cmd == 'n')\n\t    subflags.do_count = TRUE;\n\telse if (*cmd == 'e')\n\t    subflags.do_error = !subflags.do_error;\n\telse if (*cmd == 'r')\t    // use last used regexp\n\t    which_pat = RE_LAST;\n\telse if (*cmd == 'p')\n\t    subflags.do_print = TRUE;\n\telse if (*cmd == '#')\n\t{\n\t    subflags.do_print = TRUE;\n\t    subflags.do_number = TRUE;\n\t}\n\telse if (*cmd == 'l')\n\t{\n\t    subflags.do_print = TRUE;\n\t    subflags.do_list = TRUE;\n\t}\n\telse if (*cmd == 'i')\t    // ignore case\n\t    subflags.do_ic = 'i';\n\telse if (*cmd == 'I')\t    // don't ignore case\n\t    subflags.do_ic = 'I';\n\telse\n\t    break;\n\t++cmd;\n    }\n    if (subflags.do_count)\n\tsubflags.do_ask = FALSE;\n\n    save_do_all = subflags.do_all;\n    save_do_ask = subflags.do_ask;\n\n    /*\n     * check for a trailing count\n     */\n    cmd = skipwhite(cmd);\n    if (VIM_ISDIGIT(*cmd))\n    {\n\ti = getdigits(&cmd);\n\tif (i <= 0 && !eap->skip && subflags.do_error)\n\t{\n\t    emsg(_(e_positive_count_required));\n\t    return;\n\t}\n\teap->line1 = eap->line2;\n\teap->line2 += i - 1;\n\tif (eap->line2 > curbuf->b_ml.ml_line_count)\n\t    eap->line2 = curbuf->b_ml.ml_line_count;\n    }\n\n    /*\n     * check for trailing command or garbage\n     */\n    cmd = skipwhite(cmd);\n    if (*cmd && *cmd != '\"')\t    // if not end-of-line or comment\n    {\n\tset_nextcmd(eap, cmd);\n\tif (eap->nextcmd == NULL)\n\t{\n\t    semsg(_(e_trailing_characters_str), cmd);\n\t    return;\n\t}\n    }\n\n    if (eap->skip)\t    // not executing commands, only parsing\n\treturn;\n\n    if (!subflags.do_count && !curbuf->b_p_ma)\n    {\n\t// Substitution is not allowed in non-'modifiable' buffer\n\temsg(_(e_cannot_make_changes_modifiable_is_off));\n\treturn;\n    }\n\n    if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, ®match) == FAIL)\n    {\n\tif (subflags.do_error)\n\t    emsg(_(e_invalid_command));\n\treturn;\n    }\n\n    // the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase'\n    if (subflags.do_ic == 'i')\n\tregmatch.rmm_ic = TRUE;\n    else if (subflags.do_ic == 'I')\n\tregmatch.rmm_ic = FALSE;\n\n    sub_firstline = NULL;\n\n    /*\n     * If the substitute pattern starts with \"\\=\" then it's an expression.\n     * Make a copy, a recursive function may free it.\n     * Otherwise, '~' in the substitute pattern is replaced with the old\n     * pattern.  We do it here once to avoid it to be replaced over and over\n     * again.\n     */\n    if (sub[0] == '\\\\' && sub[1] == '=')\n    {\n\tsub = vim_strsave(sub);\n\tif (sub == NULL)\n\t    return;\n\tsub_copy = sub;\n    }\n    else\n\tsub = regtilde(sub, magic_isset());\n\n    /*\n     * Check for a match on each line.\n     */\n    line2 = eap->line2;\n    for (lnum = eap->line1; lnum <= line2 && !(got_quit\n#if defined(FEAT_EVAL)\n\t\t|| aborting()\n#endif\n\t\t); ++lnum)\n    {\n\tnmatch = vim_regexec_multi(®match, curwin, curbuf, lnum,\n\t\t\t\t\t\t       (colnr_T)0, NULL, NULL);\n\tif (nmatch)\n\t{\n\t    colnr_T\tcopycol;\n\t    colnr_T\tmatchcol;\n\t    colnr_T\tprev_matchcol = MAXCOL;\n\t    char_u\t*new_end, *new_start = NULL;\n\t    unsigned\tnew_start_len = 0;\n\t    char_u\t*p1;\n\t    int\t\tdid_sub = FALSE;\n\t    int\t\tlastone;\n\t    int\t\tlen, copy_len, needed_len;\n\t    long\tnmatch_tl = 0;\t// nr of lines matched below lnum\n\t    int\t\tdo_again;\t// do it again after joining lines\n\t    int\t\tskip_match = FALSE;\n\t    linenr_T\tsub_firstlnum;\t// nr of first sub line\n#ifdef FEAT_PROP_POPUP\n\t    int\t\tapc_flags = APC_SAVE_FOR_UNDO | APC_SUBSTITUTE;\n\t    colnr_T\ttotal_added =  0;\n#endif\n\n\t    /*\n\t     * The new text is build up step by step, to avoid too much\n\t     * copying.  There are these pieces:\n\t     * sub_firstline\tThe old text, unmodified.\n\t     * copycol\t\tColumn in the old text where we started\n\t     *\t\t\tlooking for a match; from here old text still\n\t     *\t\t\tneeds to be copied to the new text.\n\t     * matchcol\t\tColumn number of the old text where to look\n\t     *\t\t\tfor the next match.  It's just after the\n\t     *\t\t\tprevious match or one further.\n\t     * prev_matchcol\tColumn just after the previous match (if any).\n\t     *\t\t\tMostly equal to matchcol, except for the first\n\t     *\t\t\tmatch and after skipping an empty match.\n\t     * regmatch.*pos\tWhere the pattern matched in the old text.\n\t     * new_start\tThe new text, all that has been produced so\n\t     *\t\t\tfar.\n\t     * new_end\t\tThe new text, where to append new text.\n\t     *\n\t     * lnum\t\tThe line number where we found the start of\n\t     *\t\t\tthe match.  Can be below the line we searched\n\t     *\t\t\twhen there is a \\n before a \\zs in the\n\t     *\t\t\tpattern.\n\t     * sub_firstlnum\tThe line number in the buffer where to look\n\t     *\t\t\tfor a match.  Can be different from \"lnum\"\n\t     *\t\t\twhen the pattern or substitute string contains\n\t     *\t\t\tline breaks.\n\t     *\n\t     * Special situations:\n\t     * - When the substitute string contains a line break, the part up\n\t     *   to the line break is inserted in the text, but the copy of\n\t     *   the original line is kept.  \"sub_firstlnum\" is adjusted for\n\t     *   the inserted lines.\n\t     * - When the matched pattern contains a line break, the old line\n\t     *   is taken from the line at the end of the pattern.  The lines\n\t     *   in the match are deleted later, \"sub_firstlnum\" is adjusted\n\t     *   accordingly.\n\t     *\n\t     * The new text is built up in new_start[].  It has some extra\n\t     * room to avoid using alloc()/free() too often.  new_start_len is\n\t     * the length of the allocated memory at new_start.\n\t     *\n\t     * Make a copy of the old line, so it won't be taken away when\n\t     * updating the screen or handling a multi-line match.  The \"old_\"\n\t     * pointers point into this copy.\n\t     */\n\t    sub_firstlnum = lnum;\n\t    copycol = 0;\n\t    matchcol = 0;\n\n\t    // At first match, remember current cursor position.\n\t    if (!got_match)\n\t    {\n\t\tsetpcmark();\n\t\tgot_match = TRUE;\n\t    }\n\n\t    /*\n\t     * Loop until nothing more to replace in this line.\n\t     * 1. Handle match with empty string.\n\t     * 2. If do_ask is set, ask for confirmation.\n\t     * 3. substitute the string.\n\t     * 4. if do_all is set, find next match\n\t     * 5. break if there isn't another match in this line\n\t     */\n\t    for (;;)\n\t    {\n\t\t// Advance \"lnum\" to the line where the match starts.  The\n\t\t// match does not start in the first line when there is a line\n\t\t// break before \\zs.\n\t\tif (regmatch.startpos[0].lnum > 0)\n\t\t{\n\t\t    lnum += regmatch.startpos[0].lnum;\n\t\t    sub_firstlnum += regmatch.startpos[0].lnum;\n\t\t    nmatch -= regmatch.startpos[0].lnum;\n\t\t    VIM_CLEAR(sub_firstline);\n\t\t}\n\n\t\t// Match might be after the last line for \"\\n\\zs\" matching at\n\t\t// the end of the last line.\n\t\tif (lnum > curbuf->b_ml.ml_line_count)\n\t\t    break;\n\n\t\tif (sub_firstline == NULL)\n\t\t{\n\t\t    sub_firstline = vim_strsave(ml_get(sub_firstlnum));\n\t\t    if (sub_firstline == NULL)\n\t\t    {\n\t\t\tvim_free(new_start);\n\t\t\tgoto outofmem;\n\t\t    }\n\t\t}\n\n\t\t// Save the line number of the last change for the final\n\t\t// cursor position (just like Vi).\n\t\tcurwin->w_cursor.lnum = lnum;\n\t\tdo_again = FALSE;\n\n\t\t/*\n\t\t * 1. Match empty string does not count, except for first\n\t\t * match.  This reproduces the strange vi behaviour.\n\t\t * This also catches endless loops.\n\t\t */\n\t\tif (matchcol == prev_matchcol\n\t\t\t&& regmatch.endpos[0].lnum == 0\n\t\t\t&& matchcol == regmatch.endpos[0].col)\n\t\t{\n\t\t    if (sub_firstline[matchcol] == NUL)\n\t\t\t// We already were at the end of the line.  Don't look\n\t\t\t// for a match in this line again.\n\t\t\tskip_match = TRUE;\n\t\t    else\n\t\t    {\n\t\t\t // search for a match at next column\n\t\t\tif (has_mbyte)\n\t\t\t    matchcol += mb_ptr2len(sub_firstline + matchcol);\n\t\t\telse\n\t\t\t    ++matchcol;\n\t\t    }\n\t\t    goto skip;\n\t\t}\n\n\t\t// Normally we continue searching for a match just after the\n\t\t// previous match.\n\t\tmatchcol = regmatch.endpos[0].col;\n\t\tprev_matchcol = matchcol;\n\n\t\t/*\n\t\t * 2. If do_count is set only increase the counter.\n\t\t *    If do_ask is set, ask for confirmation.\n\t\t */\n\t\tif (subflags.do_count)\n\t\t{\n\t\t    // For a multi-line match, put matchcol at the NUL at\n\t\t    // the end of the line and set nmatch to one, so that\n\t\t    // we continue looking for a match on the next line.\n\t\t    // Avoids that \":s/\\nB\\@=//gc\" get stuck.\n\t\t    if (nmatch > 1)\n\t\t    {\n\t\t\tmatchcol = (colnr_T)STRLEN(sub_firstline);\n\t\t\tnmatch = 1;\n\t\t\tskip_match = TRUE;\n\t\t    }\n\t\t    sub_nsubs++;\n\t\t    did_sub = TRUE;\n#ifdef FEAT_EVAL\n\t\t    // Skip the substitution, unless an expression is used,\n\t\t    // then it is evaluated in the sandbox.\n\t\t    if (!(sub[0] == '\\\\' && sub[1] == '='))\n#endif\n\t\t\tgoto skip;\n\t\t}\n\n\t\tif (subflags.do_ask)\n\t\t{\n\t\t    int typed = 0;\n\n\t\t    // change State to CONFIRM, so that the mouse works\n\t\t    // properly\n\t\t    save_State = State;\n\t\t    State = CONFIRM;\n\t\t    setmouse();\t\t// disable mouse in xterm\n\t\t    curwin->w_cursor.col = regmatch.startpos[0].col;\n\t\t    if (curwin->w_p_crb)\n\t\t\tdo_check_cursorbind();\n\n\t\t    // When 'cpoptions' contains \"u\" don't sync undo when\n\t\t    // asking for confirmation.\n\t\t    if (vim_strchr(p_cpo, CPO_UNDO) != NULL)\n\t\t\t++no_u_sync;\n\n\t\t    /*\n\t\t     * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.\n\t\t     */\n\t\t    while (subflags.do_ask)\n\t\t    {\n\t\t\tif (exmode_active)\n\t\t\t{\n\t\t\t    char_u\t*resp;\n\t\t\t    colnr_T\tsc, ec;\n\n\t\t\t    print_line_no_prefix(lnum,\n\t\t\t\t\t subflags.do_number, subflags.do_list);\n\n\t\t\t    getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL);\n\t\t\t    curwin->w_cursor.col = regmatch.endpos[0].col - 1;\n\t\t\t    if (curwin->w_cursor.col < 0)\n\t\t\t\tcurwin->w_cursor.col = 0;\n\t\t\t    getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec);\n\t\t\t    curwin->w_cursor.col = regmatch.startpos[0].col;\n\t\t\t    if (subflags.do_number || curwin->w_p_nu)\n\t\t\t    {\n\t\t\t\tint numw = number_width(curwin) + 1;\n\t\t\t\tsc += numw;\n\t\t\t\tec += numw;\n\t\t\t    }\n\t\t\t    msg_start();\n\t\t\t    for (i = 0; i < (long)sc; ++i)\n\t\t\t\tmsg_putchar(' ');\n\t\t\t    for ( ; i <= (long)ec; ++i)\n\t\t\t\tmsg_putchar('^');\n\n\t\t\t    resp = getexmodeline('?', NULL, 0, TRUE);\n\t\t\t    if (resp != NULL)\n\t\t\t    {\n\t\t\t\ttyped = *resp;\n\t\t\t\tvim_free(resp);\n\t\t\t    }\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t    char_u *orig_line = NULL;\n\t\t\t    int    len_change = 0;\n\t\t\t    int\t   save_p_lz = p_lz;\n#ifdef FEAT_FOLDING\n\t\t\t    int save_p_fen = curwin->w_p_fen;\n\n\t\t\t    curwin->w_p_fen = FALSE;\n#endif\n\t\t\t    // Invert the matched string.\n\t\t\t    // Remove the inversion afterwards.\n\t\t\t    temp = RedrawingDisabled;\n\t\t\t    RedrawingDisabled = 0;\n\n\t\t\t    // avoid calling update_screen() in vgetorpeek()\n\t\t\t    p_lz = FALSE;\n\n\t\t\t    if (new_start != NULL)\n\t\t\t    {\n\t\t\t\t// There already was a substitution, we would\n\t\t\t\t// like to show this to the user.  We cannot\n\t\t\t\t// really update the line, it would change\n\t\t\t\t// what matches.  Temporarily replace the line\n\t\t\t\t// and change it back afterwards.\n\t\t\t\torig_line = vim_strsave(ml_get(lnum));\n\t\t\t\tif (orig_line != NULL)\n\t\t\t\t{\n\t\t\t\t    char_u *new_line = concat_str(new_start,\n\t\t\t\t\t\t     sub_firstline + copycol);\n\n\t\t\t\t    if (new_line == NULL)\n\t\t\t\t\tVIM_CLEAR(orig_line);\n\t\t\t\t    else\n\t\t\t\t    {\n\t\t\t\t\t// Position the cursor relative to the\n\t\t\t\t\t// end of the line, the previous\n\t\t\t\t\t// substitute may have inserted or\n\t\t\t\t\t// deleted characters before the\n\t\t\t\t\t// cursor.\n\t\t\t\t\tlen_change = (int)STRLEN(new_line)\n\t\t\t\t\t\t     - (int)STRLEN(orig_line);\n\t\t\t\t\tcurwin->w_cursor.col += len_change;\n\t\t\t\t\tml_replace(lnum, new_line, FALSE);\n\t\t\t\t    }\n\t\t\t\t}\n\t\t\t    }\n\n\t\t\t    search_match_lines = regmatch.endpos[0].lnum\n\t\t\t\t\t\t  - regmatch.startpos[0].lnum;\n\t\t\t    search_match_endcol = regmatch.endpos[0].col\n\t\t\t\t\t\t\t\t + len_change;\n\t\t\t    highlight_match = TRUE;\n\n\t\t\t    update_topline();\n\t\t\t    validate_cursor();\n\t\t\t    update_screen(SOME_VALID);\n\t\t\t    highlight_match = FALSE;\n\t\t\t    redraw_later(SOME_VALID);\n\n#ifdef FEAT_FOLDING\n\t\t\t    curwin->w_p_fen = save_p_fen;\n#endif\n\t\t\t    if (msg_row == Rows - 1)\n\t\t\t\tmsg_didout = FALSE;\t// avoid a scroll-up\n\t\t\t    msg_starthere();\n\t\t\t    i = msg_scroll;\n\t\t\t    msg_scroll = 0;\t\t// truncate msg when\n\t\t\t\t\t\t\t// needed\n\t\t\t    msg_no_more = TRUE;\n\t\t\t    // write message same highlighting as for\n\t\t\t    // wait_return\n\t\t\t    smsg_attr(HL_ATTR(HLF_R),\n\t\t\t\t_(\"replace with %s (y/n/a/q/l/^E/^Y)?\"), sub);\n\t\t\t    msg_no_more = FALSE;\n\t\t\t    msg_scroll = i;\n\t\t\t    showruler(TRUE);\n\t\t\t    windgoto(msg_row, msg_col);\n\t\t\t    RedrawingDisabled = temp;\n\n#ifdef USE_ON_FLY_SCROLL\n\t\t\t    dont_scroll = FALSE; // allow scrolling here\n#endif\n\t\t\t    ++no_mapping;\t// don't map this key\n\t\t\t    ++allow_keys;\t// allow special keys\n\t\t\t    typed = plain_vgetc();\n\t\t\t    --allow_keys;\n\t\t\t    --no_mapping;\n\n\t\t\t    // clear the question\n\t\t\t    msg_didout = FALSE;\t// don't scroll up\n\t\t\t    msg_col = 0;\n\t\t\t    gotocmdline(TRUE);\n\t\t\t    p_lz = save_p_lz;\n\n\t\t\t    // restore the line\n\t\t\t    if (orig_line != NULL)\n\t\t\t\tml_replace(lnum, orig_line, FALSE);\n\t\t\t}\n\n\t\t\tneed_wait_return = FALSE; // no hit-return prompt\n\t\t\tif (typed == 'q' || typed == ESC || typed == Ctrl_C\n#ifdef UNIX\n\t\t\t\t|| typed == intr_char\n#endif\n\t\t\t\t)\n\t\t\t{\n\t\t\t    got_quit = TRUE;\n\t\t\t    break;\n\t\t\t}\n\t\t\tif (typed == 'n')\n\t\t\t    break;\n\t\t\tif (typed == 'y')\n\t\t\t    break;\n\t\t\tif (typed == 'l')\n\t\t\t{\n\t\t\t    // last: replace and then stop\n\t\t\t    subflags.do_all = FALSE;\n\t\t\t    line2 = lnum;\n\t\t\t    break;\n\t\t\t}\n\t\t\tif (typed == 'a')\n\t\t\t{\n\t\t\t    subflags.do_ask = FALSE;\n\t\t\t    break;\n\t\t\t}\n\t\t\tif (typed == Ctrl_E)\n\t\t\t    scrollup_clamp();\n\t\t\telse if (typed == Ctrl_Y)\n\t\t\t    scrolldown_clamp();\n\t\t    }\n\t\t    State = save_State;\n\t\t    setmouse();\n\t\t    if (vim_strchr(p_cpo, CPO_UNDO) != NULL)\n\t\t\t--no_u_sync;\n\n\t\t    if (typed == 'n')\n\t\t    {\n\t\t\t// For a multi-line match, put matchcol at the NUL at\n\t\t\t// the end of the line and set nmatch to one, so that\n\t\t\t// we continue looking for a match on the next line.\n\t\t\t// Avoids that \":%s/\\nB\\@=//gc\" and \":%s/\\n/,\\r/gc\"\n\t\t\t// get stuck when pressing 'n'.\n\t\t\tif (nmatch > 1)\n\t\t\t{\n\t\t\t    matchcol = (colnr_T)STRLEN(sub_firstline);\n\t\t\t    skip_match = TRUE;\n\t\t\t}\n\t\t\tgoto skip;\n\t\t    }\n\t\t    if (got_quit)\n\t\t\tgoto skip;\n\t\t}\n\n\t\t// Move the cursor to the start of the match, so that we can\n\t\t// use \"\\=col(\".\").\n\t\tcurwin->w_cursor.col = regmatch.startpos[0].col;\n\n\t\t/*\n\t\t * 3. substitute the string.\n\t\t */\n#ifdef FEAT_EVAL\n\t\tsave_ma = curbuf->b_p_ma;\n\t\tif (subflags.do_count)\n\t\t{\n\t\t    // prevent accidentally changing the buffer by a function\n\t\t    curbuf->b_p_ma = FALSE;\n\t\t    sandbox++;\n\t\t}\n\t\t// Save flags for recursion.  They can change for e.g.\n\t\t// :s/^/\\=execute(\"s#^##gn\")\n\t\tsubflags_save = subflags;\n#endif\n\t\t// get length of substitution part\n\t\tsublen = vim_regsub_multi(®match,\n\t\t\t\t    sub_firstlnum - regmatch.startpos[0].lnum,\n\t\t\t       sub, sub_firstline, FALSE, magic_isset(), TRUE);\n#ifdef FEAT_EVAL\n\t\t// If getting the substitute string caused an error, don't do\n\t\t// the replacement.\n\t\t// Don't keep flags set by a recursive call.\n\t\tsubflags = subflags_save;\n\t\tif (aborting() || subflags.do_count)\n\t\t{\n\t\t    curbuf->b_p_ma = save_ma;\n\t\t    if (sandbox > 0)\n\t\t\tsandbox--;\n\t\t    goto skip;\n\t\t}\n#endif\n\n\t\t// When the match included the \"$\" of the last line it may\n\t\t// go beyond the last line of the buffer.\n\t\tif (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1)\n\t\t{\n\t\t    nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1;\n\t\t    skip_match = TRUE;\n\t\t}\n\n\t\t// Need room for:\n\t\t// - result so far in new_start (not for first sub in line)\n\t\t// - original text up to match\n\t\t// - length of substituted part\n\t\t// - original text after match\n\t\t// Adjust text properties here, since we have all information\n\t\t// needed.\n\t\tif (nmatch == 1)\n\t\t{\n\t\t    p1 = sub_firstline;\n#ifdef FEAT_PROP_POPUP\n\t\t    if (curbuf->b_has_textprop)\n\t\t    {\n\t\t\tint bytes_added = sublen - 1 - (regmatch.endpos[0].col\n\t\t\t\t\t\t   - regmatch.startpos[0].col);\n\n\t\t\t// When text properties are changed, need to save for\n\t\t\t// undo first, unless done already.\n\t\t\tif (adjust_prop_columns(lnum,\n\t\t\t\t\ttotal_added + regmatch.startpos[0].col,\n\t\t\t\t\t\t       bytes_added, apc_flags))\n\t\t\t    apc_flags &= ~APC_SAVE_FOR_UNDO;\n\t\t\t// Offset for column byte number of the text property\n\t\t\t// in the resulting buffer afterwards.\n\t\t\ttotal_added += bytes_added;\n\t\t    }\n#endif\n\t\t}\n\t\telse\n\t\t{\n\t\t    p1 = ml_get(sub_firstlnum + nmatch - 1);\n\t\t    nmatch_tl += nmatch - 1;\n\t\t}\n\t\tcopy_len = regmatch.startpos[0].col - copycol;\n\t\tneeded_len = copy_len + ((unsigned)STRLEN(p1)\n\t\t\t\t       - regmatch.endpos[0].col) + sublen + 1;\n\t\tif (new_start == NULL)\n\t\t{\n\t\t    /*\n\t\t     * Get some space for a temporary buffer to do the\n\t\t     * substitution into (and some extra space to avoid\n\t\t     * too many calls to alloc()/free()).\n\t\t     */\n\t\t    new_start_len = needed_len + 50;\n\t\t    if ((new_start = alloc(new_start_len)) == NULL)\n\t\t\tgoto outofmem;\n\t\t    *new_start = NUL;\n\t\t    new_end = new_start;\n\t\t}\n\t\telse\n\t\t{\n\t\t    /*\n\t\t     * Check if the temporary buffer is long enough to do the\n\t\t     * substitution into.  If not, make it larger (with a bit\n\t\t     * extra to avoid too many calls to alloc()/free()).\n\t\t     */\n\t\t    len = (unsigned)STRLEN(new_start);\n\t\t    needed_len += len;\n\t\t    if (needed_len > (int)new_start_len)\n\t\t    {\n\t\t\tnew_start_len = needed_len + 50;\n\t\t\tif ((p1 = alloc(new_start_len)) == NULL)\n\t\t\t{\n\t\t\t    vim_free(new_start);\n\t\t\t    goto outofmem;\n\t\t\t}\n\t\t\tmch_memmove(p1, new_start, (size_t)(len + 1));\n\t\t\tvim_free(new_start);\n\t\t\tnew_start = p1;\n\t\t    }\n\t\t    new_end = new_start + len;\n\t\t}\n\n\t\t/*\n\t\t * copy the text up to the part that matched\n\t\t */\n\t\tmch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len);\n\t\tnew_end += copy_len;\n\n\t\t(void)vim_regsub_multi(®match,\n\t\t\t\t    sub_firstlnum - regmatch.startpos[0].lnum,\n\t\t\t\t      sub, new_end, TRUE, magic_isset(), TRUE);\n\t\tsub_nsubs++;\n\t\tdid_sub = TRUE;\n\n\t\t// Move the cursor to the start of the line, to avoid that it\n\t\t// is beyond the end of the line after the substitution.\n\t\tcurwin->w_cursor.col = 0;\n\n\t\t// For a multi-line match, make a copy of the last matched\n\t\t// line and continue in that one.\n\t\tif (nmatch > 1)\n\t\t{\n\t\t    sub_firstlnum += nmatch - 1;\n\t\t    vim_free(sub_firstline);\n\t\t    sub_firstline = vim_strsave(ml_get(sub_firstlnum));\n\t\t    // When going beyond the last line, stop substituting.\n\t\t    if (sub_firstlnum <= line2)\n\t\t\tdo_again = TRUE;\n\t\t    else\n\t\t\tsubflags.do_all = FALSE;\n\t\t}\n\n\t\t// Remember next character to be copied.\n\t\tcopycol = regmatch.endpos[0].col;\n\n\t\tif (skip_match)\n\t\t{\n\t\t    // Already hit end of the buffer, sub_firstlnum is one\n\t\t    // less than what it ought to be.\n\t\t    vim_free(sub_firstline);\n\t\t    sub_firstline = vim_strsave((char_u *)\"\");\n\t\t    copycol = 0;\n\t\t}\n\n\t\t/*\n\t\t * Now the trick is to replace CTRL-M chars with a real line\n\t\t * break.  This would make it impossible to insert a CTRL-M in\n\t\t * the text.  The line break can be avoided by preceding the\n\t\t * CTRL-M with a backslash.  To be able to insert a backslash,\n\t\t * they must be doubled in the string and are halved here.\n\t\t * That is Vi compatible.\n\t\t */\n\t\tfor (p1 = new_end; *p1; ++p1)\n\t\t{\n\t\t    if (p1[0] == '\\\\' && p1[1] != NUL)  // remove backslash\n\t\t    {\n\t\t\tSTRMOVE(p1, p1 + 1);\n#ifdef FEAT_PROP_POPUP\n\t\t\tif (curbuf->b_has_textprop)\n\t\t\t{\n\t\t\t    // When text properties are changed, need to save\n\t\t\t    // for undo first, unless done already.\n\t\t\t    if (adjust_prop_columns(lnum,\n\t\t\t\t\t(colnr_T)(p1 - new_start), -1,\n\t\t\t\t\tapc_flags))\n\t\t\t\tapc_flags &= ~APC_SAVE_FOR_UNDO;\n\t\t\t}\n#endif\n\t\t    }\n\t\t    else if (*p1 == CAR)\n\t\t    {\n\t\t\tif (u_inssub(lnum) == OK)   // prepare for undo\n\t\t\t{\n\t\t\t    colnr_T\tplen = (colnr_T)(p1 - new_start + 1);\n\n\t\t\t    *p1 = NUL;\t\t    // truncate up to the CR\n\t\t\t    ml_append(lnum - 1, new_start, plen, FALSE);\n\t\t\t    mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);\n\t\t\t    if (subflags.do_ask)\n\t\t\t\tappended_lines(lnum - 1, 1L);\n\t\t\t    else\n\t\t\t    {\n\t\t\t\tif (first_line == 0)\n\t\t\t\t    first_line = lnum;\n\t\t\t\tlast_line = lnum + 1;\n\t\t\t    }\n#ifdef FEAT_PROP_POPUP\n\t\t\t    adjust_props_for_split(lnum + 1, lnum, plen, 1);\n#endif\n\t\t\t    // all line numbers increase\n\t\t\t    ++sub_firstlnum;\n\t\t\t    ++lnum;\n\t\t\t    ++line2;\n\t\t\t    // move the cursor to the new line, like Vi\n\t\t\t    ++curwin->w_cursor.lnum;\n\t\t\t    // copy the rest\n\t\t\t    STRMOVE(new_start, p1 + 1);\n\t\t\t    p1 = new_start - 1;\n\t\t\t}\n\t\t    }\n\t\t    else if (has_mbyte)\n\t\t\tp1 += (*mb_ptr2len)(p1) - 1;\n\t\t}\n\n\t\t/*\n\t\t * 4. If do_all is set, find next match.\n\t\t * Prevent endless loop with patterns that match empty\n\t\t * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.\n\t\t * But \":s/\\n/#/\" is OK.\n\t\t */\nskip:\n\t\t// We already know that we did the last subst when we are at\n\t\t// the end of the line, except that a pattern like\n\t\t// \"bar\\|\\nfoo\" may match at the NUL.  \"lnum\" can be below\n\t\t// \"line2\" when there is a \\zs in the pattern after a line\n\t\t// break.\n\t\tlastone = (skip_match\n\t\t\t|| got_int\n\t\t\t|| got_quit\n\t\t\t|| lnum > line2\n\t\t\t|| !(subflags.do_all || do_again)\n\t\t\t|| (sub_firstline[matchcol] == NUL && nmatch <= 1\n\t\t\t\t\t && !re_multiline(regmatch.regprog)));\n\t\tnmatch = -1;\n\n\t\t/*\n\t\t * Replace the line in the buffer when needed.  This is\n\t\t * skipped when there are more matches.\n\t\t * The check for nmatch_tl is needed for when multi-line\n\t\t * matching must replace the lines before trying to do another\n\t\t * match, otherwise \"\\@<=\" won't work.\n\t\t * When the match starts below where we start searching also\n\t\t * need to replace the line first (using \\zs after \\n).\n\t\t */\n\t\tif (lastone\n\t\t\t|| nmatch_tl > 0\n\t\t\t|| (nmatch = vim_regexec_multi(®match, curwin,\n\t\t\t\t\t\t\tcurbuf, sub_firstlnum,\n\t\t\t\t\t\t    matchcol, NULL, NULL)) == 0\n\t\t\t|| regmatch.startpos[0].lnum > 0)\n\t\t{\n\t\t    if (new_start != NULL)\n\t\t    {\n\t\t\t/*\n\t\t\t * Copy the rest of the line, that didn't match.\n\t\t\t * \"matchcol\" has to be adjusted, we use the end of\n\t\t\t * the line as reference, because the substitute may\n\t\t\t * have changed the number of characters.  Same for\n\t\t\t * \"prev_matchcol\".\n\t\t\t */\n\t\t\tSTRCAT(new_start, sub_firstline + copycol);\n\t\t\tmatchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;\n\t\t\tprev_matchcol = (colnr_T)STRLEN(sub_firstline)\n\t\t\t\t\t\t\t      - prev_matchcol;\n\n\t\t\tif (u_savesub(lnum) != OK)\n\t\t\t    break;\n\t\t\tml_replace(lnum, new_start, TRUE);\n\n\t\t\tif (nmatch_tl > 0)\n\t\t\t{\n\t\t\t    /*\n\t\t\t     * Matched lines have now been substituted and are\n\t\t\t     * useless, delete them.  The part after the match\n\t\t\t     * has been appended to new_start, we don't need\n\t\t\t     * it in the buffer.\n\t\t\t     */\n\t\t\t    ++lnum;\n\t\t\t    if (u_savedel(lnum, nmatch_tl) != OK)\n\t\t\t\tbreak;\n\t\t\t    for (i = 0; i < nmatch_tl; ++i)\n\t\t\t\tml_delete(lnum);\n\t\t\t    mark_adjust(lnum, lnum + nmatch_tl - 1,\n\t\t\t\t\t\t   (long)MAXLNUM, -nmatch_tl);\n\t\t\t    if (subflags.do_ask)\n\t\t\t\tdeleted_lines(lnum, nmatch_tl);\n\t\t\t    --lnum;\n\t\t\t    line2 -= nmatch_tl; // nr of lines decreases\n\t\t\t    nmatch_tl = 0;\n\t\t\t}\n\n\t\t\t// When asking, undo is saved each time, must also set\n\t\t\t// changed flag each time.\n\t\t\tif (subflags.do_ask)\n\t\t\t    changed_bytes(lnum, 0);\n\t\t\telse\n\t\t\t{\n\t\t\t    if (first_line == 0)\n\t\t\t\tfirst_line = lnum;\n\t\t\t    last_line = lnum + 1;\n\t\t\t}\n\n\t\t\tsub_firstlnum = lnum;\n\t\t\tvim_free(sub_firstline);    // free the temp buffer\n\t\t\tsub_firstline = new_start;\n\t\t\tnew_start = NULL;\n\t\t\tmatchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;\n\t\t\tprev_matchcol = (colnr_T)STRLEN(sub_firstline)\n\t\t\t\t\t\t\t      - prev_matchcol;\n\t\t\tcopycol = 0;\n\t\t    }\n\t\t    if (nmatch == -1 && !lastone)\n\t\t\tnmatch = vim_regexec_multi(®match, curwin, curbuf,\n\t\t\t\t\t  sub_firstlnum, matchcol, NULL, NULL);\n\n\t\t    /*\n\t\t     * 5. break if there isn't another match in this line\n\t\t     */\n\t\t    if (nmatch <= 0)\n\t\t    {\n\t\t\t// If the match found didn't start where we were\n\t\t\t// searching, do the next search in the line where we\n\t\t\t// found the match.\n\t\t\tif (nmatch == -1)\n\t\t\t    lnum -= regmatch.startpos[0].lnum;\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\n\t\tline_breakcheck();\n\t    }\n\n\t    if (did_sub)\n\t\t++sub_nlines;\n\t    vim_free(new_start);\t// for when substitute was cancelled\n\t    VIM_CLEAR(sub_firstline);\t// free the copy of the original line\n\t}\n\n\tline_breakcheck();\n    }\n\n    if (first_line != 0)\n    {\n\t// Need to subtract the number of added lines from \"last_line\" to get\n\t// the line number before the change (same as adding the number of\n\t// deleted lines).\n\ti = curbuf->b_ml.ml_line_count - old_line_count;\n\tchanged_lines(first_line, 0, last_line - i, i);\n    }\n\noutofmem:\n    vim_free(sub_firstline); // may have to free allocated copy of the line\n\n    // \":s/pat//n\" doesn't move the cursor\n    if (subflags.do_count)\n\tcurwin->w_cursor = old_cursor;\n\n    if (sub_nsubs > start_nsubs)\n    {\n\tif ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)\n\t{\n\t    // Set the '[ and '] marks.\n\t    curbuf->b_op_start.lnum = eap->line1;\n\t    curbuf->b_op_end.lnum = line2;\n\t    curbuf->b_op_start.col = curbuf->b_op_end.col = 0;\n\t}\n\n\tif (!global_busy)\n\t{\n\t    // when interactive leave cursor on the match\n\t    if (!subflags.do_ask)\n\t    {\n\t\tif (endcolumn)\n\t\t    coladvance((colnr_T)MAXCOL);\n\t\telse\n\t\t    beginline(BL_WHITE | BL_FIX);\n\t    }\n\t    if (!do_sub_msg(subflags.do_count) && subflags.do_ask)\n\t\tmsg(\"\");\n\t}\n\telse\n\t    global_need_beginline = TRUE;\n\tif (subflags.do_print)\n\t    print_line(curwin->w_cursor.lnum,\n\t\t\t\t\t subflags.do_number, subflags.do_list);\n    }\n    else if (!global_busy)\n    {\n\tif (got_int)\t\t// interrupted\n\t    emsg(_(e_interrupted));\n\telse if (got_match)\t// did find something but nothing substituted\n\t    msg(\"\");\n\telse if (subflags.do_error)\t// nothing found\n\t    semsg(_(e_pattern_not_found_str), get_search_pat());\n    }\n\n#ifdef FEAT_FOLDING\n    if (subflags.do_ask && hasAnyFolding(curwin))\n\t// Cursor position may require updating\n\tchanged_window_setting();\n#endif\n\n    vim_regfree(regmatch.regprog);\n    vim_free(sub_copy);\n\n    // Restore the flag values, they can be used for \":&&\".\n    subflags.do_all = save_do_all;\n    subflags.do_ask = save_do_ask;\n}", "func_hash": 291806400828750764975961626021835315123, "file_name": "ex_cmds.c", "file_hash": 316790051330868655972553819181856040285, "cwe": ["CWE-416"], "cve": "CVE-2022-0413", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0413"}
{"idx": 200113, "project": "ImageMagick", "commit_id": "389ecc365a7c61404ba078a72c3fa5a3cf1b4101", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/389ecc365a7c61404ba078a72c3fa5a3cf1b4101", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1221", "target": 1, "func": "static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image,\n  ExceptionInfo *exception)\n{\n  typedef struct {\n    unsigned char Type[4];\n    unsigned int nRows;\n    unsigned int nCols;\n    unsigned int imagf;\n    unsigned int nameLen;\n  } MAT4_HDR;\n\n  long\n    ldblk;\n\n  EndianType\n    endian;\n\n  Image\n    *rotated_image;\n\n  MagickBooleanType\n    status;\n\n  MAT4_HDR\n    HDR;\n\n  QuantumInfo\n    *quantum_info;\n\n  QuantumFormatType\n    format_type;\n\n  register ssize_t\n    i;\n\n  ssize_t\n    count,\n    y;\n\n  unsigned char\n    *pixels;\n\n  unsigned int\n    depth;\n\n\n  quantum_info=(QuantumInfo *) NULL;\n  (void) SeekBlob(image,0,SEEK_SET);\n  while (EOFBlob(image) == MagickFalse)\n  {\n    /*\n     Object parser loop.\n    */\n    ldblk=ReadBlobLSBLong(image);\n    if ((ldblk > 9999) || (ldblk < 0))\n      break;\n    HDR.Type[3]=ldblk % 10; ldblk /= 10;  /* T digit */\n    HDR.Type[2]=ldblk % 10; ldblk /= 10;  /* P digit */\n    HDR.Type[1]=ldblk % 10; ldblk /= 10;  /* O digit */\n    HDR.Type[0]=ldblk;        /* M digit */\n    if (HDR.Type[3] != 0)\n      break;  /* Data format */\n    if (HDR.Type[2] != 0)\n      break;  /* Always 0 */\n    if (HDR.Type[0] == 0)\n      {\n        HDR.nRows=ReadBlobLSBLong(image);\n        HDR.nCols=ReadBlobLSBLong(image);\n        HDR.imagf=ReadBlobLSBLong(image);\n        HDR.nameLen=ReadBlobLSBLong(image);\n        endian=LSBEndian;\n      }\n    else\n      {\n        HDR.nRows=ReadBlobMSBLong(image);\n        HDR.nCols=ReadBlobMSBLong(image);\n        HDR.imagf=ReadBlobMSBLong(image);\n        HDR.nameLen=ReadBlobMSBLong(image);\n        endian=MSBEndian;\n      }\n    if ((HDR.imagf != 0) && (HDR.imagf != 1))\n      break;\n    if (HDR.nameLen > 0xFFFF)\n      return(DestroyImageList(image));\n    for (i=0; i < (ssize_t) HDR.nameLen; i++)\n    {\n      int\n        byte;\n\n      /*\n        Skip matrix name.\n      */\n      byte=ReadBlobByte(image);\n      if (byte == EOF)\n        {\n          ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n            image->filename);\n          break;\n        }\n    }\n    image->columns=(size_t) HDR.nRows;\n    image->rows=(size_t) HDR.nCols;\n    if ((image->columns == 0) || (image->rows == 0))\n      return(DestroyImageList(image));\n    if (image_info->ping != MagickFalse)\n      {\n        Swap(image->columns,image->rows);\n        if(HDR.imagf==1) ldblk *= 2;\n        SeekBlob(image, HDR.nCols*ldblk, SEEK_CUR);\n        if ((image->columns == 0) || (image->rows == 0))\n          return(image->previous == (Image *) NULL ? DestroyImageList(image)\n            : image);\n        goto skip_reading_current;\n      }\n    status=SetImageExtent(image,image->columns,image->rows,exception);\n    if (status == MagickFalse)\n      return(DestroyImageList(image));\n    (void) SetImageBackgroundColor(image,exception);\n    (void) SetImageColorspace(image,GRAYColorspace,exception);\n    quantum_info=AcquireQuantumInfo(image_info,image);\n    if (quantum_info == (QuantumInfo *) NULL)\n      return(DestroyImageList(image));\n    switch(HDR.Type[1])\n    {\n      case 0:\n        format_type=FloatingPointQuantumFormat;\n        depth=64;\n        break;\n      case 1:\n        format_type=FloatingPointQuantumFormat;\n        depth=32;\n        break;\n      case 2:\n        format_type=UnsignedQuantumFormat;\n        depth=16;\n        break;\n      case 3:\n        format_type=SignedQuantumFormat;\n        depth=16;\n        break;\n      case 4:\n        format_type=UnsignedQuantumFormat;\n        depth=8;\n        break;\n      default:\n        format_type=UnsignedQuantumFormat;\n        depth=8;\n        break;\n    }\n    image->depth=depth;\n    if (HDR.Type[0] != 0)\n      SetQuantumEndian(image,quantum_info,MSBEndian);\n    status=SetQuantumFormat(image,quantum_info,format_type);\n    status=SetQuantumDepth(image,quantum_info,depth);\n    status=SetQuantumEndian(image,quantum_info,endian);\n    SetQuantumScale(quantum_info,1.0);\n    pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n    for (y=0; y < (ssize_t) image->rows; y++)\n    {\n      register Quantum\n        *magick_restrict q;\n\n      count=ReadBlob(image,depth/8*image->columns,(char *) pixels);\n      if (count == -1)\n        break;\n      q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,\n        exception);\n      if (q == (Quantum *) NULL)\n        break;\n      (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n        GrayQuantum,pixels,exception);\n      if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3))\n        FixSignedValues(image,q,(int) image->columns);\n      if (SyncAuthenticPixels(image,exception) == MagickFalse)\n        break;\n      if (image->previous == (Image *) NULL)\n        {\n          status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n            image->rows);\n          if (status == MagickFalse)\n            break;\n        }\n    }\n    if (HDR.imagf == 1)\n      for (y=0; y < (ssize_t) image->rows; y++)\n      {\n        /*\n          Read complex pixels.\n        */\n        count=ReadBlob(image,depth/8*image->columns,(char *) pixels);\n        if (count == -1)\n          break;\n        if (HDR.Type[1] == 0)\n          InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception);\n        else\n          InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception);\n      }\n    if (quantum_info != (QuantumInfo *) NULL)\n      quantum_info=DestroyQuantumInfo(quantum_info);\n    if (EOFBlob(image) != MagickFalse)\n      {\n        ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n          image->filename);\n        break;\n      }\n    rotated_image=RotateImage(image,90.0,exception);\n    if (rotated_image != (Image *) NULL)\n      {\n        rotated_image->page.x=0;\n        rotated_image->page.y=0;\n        rotated_image->colors = image->colors;\n        DestroyBlob(rotated_image);\n        rotated_image->blob=ReferenceBlob(image->blob);\n        AppendImageToList(&image,rotated_image);\n        DeleteImageFromList(&image);\n      }\n    /*\n      Proceed to next image.\n    */\n    if (image_info->number_scenes != 0)\n      if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n        break;\n    /*\n      Allocate next image structure.\n    */\nskip_reading_current:\n    AcquireNextImage(image_info,image,exception);\n    if (GetNextImageInList(image) == (Image *) NULL)\n      {\n        status=MagickFalse;\n        break;\n      }\n    image=SyncNextImageInList(image);\n    status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n      GetBlobSize(image));\n    if (status == MagickFalse)\n      break;\n  }\n  (void) CloseBlob(image);\n  if (status == MagickFalse)\n    return(DestroyImageList(image));\n  return(GetFirstImageInList(image));\n}", "func_hash": 285338942932126464684406061663699404409, "file_name": "mat.c", "file_hash": 152895055268444149031499537279657208937, "cwe": ["CWE-787"], "cve": "CVE-2018-14551", "cve_desc": "The ReadMATImageV4 function in coders/mat.c in ImageMagick 7.0.8-7 uses an uninitialized variable, leading to memory corruption.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-14551"}
{"idx": 299319, "project": "ImageMagick", "commit_id": "389ecc365a7c61404ba078a72c3fa5a3cf1b4101", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/389ecc365a7c61404ba078a72c3fa5a3cf1b4101", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1221", "target": 0, "func": "static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image,\n  ExceptionInfo *exception)\n{\n  typedef struct {\n    unsigned char Type[4];\n    unsigned int nRows;\n    unsigned int nCols;\n    unsigned int imagf;\n    unsigned int nameLen;\n  } MAT4_HDR;\n\n  long\n    ldblk;\n\n  EndianType\n    endian;\n\n  Image\n    *rotated_image;\n\n  MagickBooleanType\n    status;\n\n  MAT4_HDR\n    HDR;\n\n  QuantumInfo\n    *quantum_info;\n\n  QuantumFormatType\n    format_type;\n\n  register ssize_t\n    i;\n\n  ssize_t\n    count,\n    y;\n\n  unsigned char\n    *pixels;\n\n  unsigned int\n    depth;\n\n  quantum_info=(QuantumInfo *) NULL;\n  (void) SeekBlob(image,0,SEEK_SET);\n  status=MagickTrue;\n  while (EOFBlob(image) == MagickFalse)\n  {\n    /*\n     Object parser loop.\n    */\n    ldblk=ReadBlobLSBLong(image);\n    if ((ldblk > 9999) || (ldblk < 0))\n      break;\n    HDR.Type[3]=ldblk % 10; ldblk /= 10;  /* T digit */\n    HDR.Type[2]=ldblk % 10; ldblk /= 10;  /* P digit */\n    HDR.Type[1]=ldblk % 10; ldblk /= 10;  /* O digit */\n    HDR.Type[0]=ldblk;        /* M digit */\n    if (HDR.Type[3] != 0)\n      break;  /* Data format */\n    if (HDR.Type[2] != 0)\n      break;  /* Always 0 */\n    if (HDR.Type[0] == 0)\n      {\n        HDR.nRows=ReadBlobLSBLong(image);\n        HDR.nCols=ReadBlobLSBLong(image);\n        HDR.imagf=ReadBlobLSBLong(image);\n        HDR.nameLen=ReadBlobLSBLong(image);\n        endian=LSBEndian;\n      }\n    else\n      {\n        HDR.nRows=ReadBlobMSBLong(image);\n        HDR.nCols=ReadBlobMSBLong(image);\n        HDR.imagf=ReadBlobMSBLong(image);\n        HDR.nameLen=ReadBlobMSBLong(image);\n        endian=MSBEndian;\n      }\n    if ((HDR.imagf != 0) && (HDR.imagf != 1))\n      break;\n    if (HDR.nameLen > 0xFFFF)\n      return(DestroyImageList(image));\n    for (i=0; i < (ssize_t) HDR.nameLen; i++)\n    {\n      int\n        byte;\n\n      /*\n        Skip matrix name.\n      */\n      byte=ReadBlobByte(image);\n      if (byte == EOF)\n        {\n          ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n            image->filename);\n          break;\n        }\n    }\n    image->columns=(size_t) HDR.nRows;\n    image->rows=(size_t) HDR.nCols;\n    if ((image->columns == 0) || (image->rows == 0))\n      return(DestroyImageList(image));\n    if (image_info->ping != MagickFalse)\n      {\n        Swap(image->columns,image->rows);\n        if(HDR.imagf==1) ldblk *= 2;\n        SeekBlob(image, HDR.nCols*ldblk, SEEK_CUR);\n        if ((image->columns == 0) || (image->rows == 0))\n          return(image->previous == (Image *) NULL ? DestroyImageList(image)\n            : image);\n        goto skip_reading_current;\n      }\n    status=SetImageExtent(image,image->columns,image->rows,exception);\n    if (status == MagickFalse)\n      return(DestroyImageList(image));\n    (void) SetImageBackgroundColor(image,exception);\n    (void) SetImageColorspace(image,GRAYColorspace,exception);\n    quantum_info=AcquireQuantumInfo(image_info,image);\n    if (quantum_info == (QuantumInfo *) NULL)\n      return(DestroyImageList(image));\n    switch(HDR.Type[1])\n    {\n      case 0:\n        format_type=FloatingPointQuantumFormat;\n        depth=64;\n        break;\n      case 1:\n        format_type=FloatingPointQuantumFormat;\n        depth=32;\n        break;\n      case 2:\n        format_type=UnsignedQuantumFormat;\n        depth=16;\n        break;\n      case 3:\n        format_type=SignedQuantumFormat;\n        depth=16;\n        break;\n      case 4:\n        format_type=UnsignedQuantumFormat;\n        depth=8;\n        break;\n      default:\n        format_type=UnsignedQuantumFormat;\n        depth=8;\n        break;\n    }\n    image->depth=depth;\n    if (HDR.Type[0] != 0)\n      SetQuantumEndian(image,quantum_info,MSBEndian);\n    status=SetQuantumFormat(image,quantum_info,format_type);\n    status=SetQuantumDepth(image,quantum_info,depth);\n    status=SetQuantumEndian(image,quantum_info,endian);\n    SetQuantumScale(quantum_info,1.0);\n    pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n    for (y=0; y < (ssize_t) image->rows; y++)\n    {\n      register Quantum\n        *magick_restrict q;\n\n      count=ReadBlob(image,depth/8*image->columns,(char *) pixels);\n      if (count == -1)\n        break;\n      q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,\n        exception);\n      if (q == (Quantum *) NULL)\n        break;\n      (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n        GrayQuantum,pixels,exception);\n      if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3))\n        FixSignedValues(image,q,(int) image->columns);\n      if (SyncAuthenticPixels(image,exception) == MagickFalse)\n        break;\n      if (image->previous == (Image *) NULL)\n        {\n          status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n            image->rows);\n          if (status == MagickFalse)\n            break;\n        }\n    }\n    if (HDR.imagf == 1)\n      for (y=0; y < (ssize_t) image->rows; y++)\n      {\n        /*\n          Read complex pixels.\n        */\n        count=ReadBlob(image,depth/8*image->columns,(char *) pixels);\n        if (count == -1)\n          break;\n        if (HDR.Type[1] == 0)\n          InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception);\n        else\n          InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception);\n      }\n    if (quantum_info != (QuantumInfo *) NULL)\n      quantum_info=DestroyQuantumInfo(quantum_info);\n    if (EOFBlob(image) != MagickFalse)\n      {\n        ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n          image->filename);\n        break;\n      }\n    rotated_image=RotateImage(image,90.0,exception);\n    if (rotated_image != (Image *) NULL)\n      {\n        rotated_image->page.x=0;\n        rotated_image->page.y=0;\n        rotated_image->colors = image->colors;\n        DestroyBlob(rotated_image);\n        rotated_image->blob=ReferenceBlob(image->blob);\n        AppendImageToList(&image,rotated_image);\n        DeleteImageFromList(&image);\n      }\n    /*\n      Proceed to next image.\n    */\n    if (image_info->number_scenes != 0)\n      if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n        break;\n    /*\n      Allocate next image structure.\n    */\nskip_reading_current:\n    AcquireNextImage(image_info,image,exception);\n    if (GetNextImageInList(image) == (Image *) NULL)\n      {\n        status=MagickFalse;\n        break;\n      }\n    image=SyncNextImageInList(image);\n    status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n      GetBlobSize(image));\n    if (status == MagickFalse)\n      break;\n  }\n  (void) CloseBlob(image);\n  if (status == MagickFalse)\n    return(DestroyImageList(image));\n  return(GetFirstImageInList(image));\n}", "func_hash": 27945736353263207032658277682673712117, "file_name": "mat.c", "file_hash": 197422043282011428208750932279920042610, "cwe": ["CWE-787"], "cve": "CVE-2018-14551", "cve_desc": "The ReadMATImageV4 function in coders/mat.c in ImageMagick 7.0.8-7 uses an uninitialized variable, leading to memory corruption.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-14551"}
{"idx": 200157, "project": "exim", "commit_id": "e2f5dc151e2e79058e93924e6d35510557f0535d", "project_url": "https://github.com/Exim/exim", "commit_url": "http://git.exim.org/exim.git/commit/e2f5dc151e2e79058e93924e6d35510557f0535d", "commit_message": "Check configure file permissions even for non-default files if still privileged\n\n(Bug 1044, CVE-2010-4345)", "target": 1, "func": "readconf_main(void)\n{\nint sep = 0;\nstruct stat statbuf;\nuschar *s, *filename;\nuschar *list = config_main_filelist;\n\n/* Loop through the possible file names */\n\nwhile((filename = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))\n       != NULL)\n  {\n  /* Cut out all the fancy processing unless specifically wanted */\n\n  #if defined(CONFIGURE_FILE_USE_NODE) || defined(CONFIGURE_FILE_USE_EUID)\n  uschar *suffix = filename + Ustrlen(filename);\n\n  /* Try for the node-specific file if a node name exists */\n\n  #ifdef CONFIGURE_FILE_USE_NODE\n  struct utsname uts;\n  if (uname(&uts) >= 0)\n    {\n    #ifdef CONFIGURE_FILE_USE_EUID\n    sprintf(CS suffix, \".%ld.%.256s\", (long int)original_euid, uts.nodename);\n    config_file = Ufopen(filename, \"rb\");\n    if (config_file == NULL)\n    #endif  /* CONFIGURE_FILE_USE_EUID */\n      {\n      sprintf(CS suffix, \".%.256s\", uts.nodename);\n      config_file = Ufopen(filename, \"rb\");\n      }\n    }\n  #endif  /* CONFIGURE_FILE_USE_NODE */\n\n  /* Otherwise, try the generic name, possibly with the euid added */\n\n  #ifdef CONFIGURE_FILE_USE_EUID\n  if (config_file == NULL)\n    {\n    sprintf(CS suffix, \".%ld\", (long int)original_euid);\n    config_file = Ufopen(filename, \"rb\");\n    }\n  #endif  /* CONFIGURE_FILE_USE_EUID */\n\n  /* Finally, try the unadorned name */\n\n  if (config_file == NULL)\n    {\n    *suffix = 0;\n    config_file = Ufopen(filename, \"rb\");\n    }\n  #else  /* if neither defined */\n\n  /* This is the common case when the fancy processing is not included. */\n\n  config_file = Ufopen(filename, \"rb\");\n  #endif\n\n  /* If the file does not exist, continue to try any others. For any other\n  error, break out (and die). */\n\n  if (config_file != NULL || errno != ENOENT) break;\n  }\n\n/* On success, save the name for verification; config_filename is used when\nlogging configuration errors (it changes for .included files) whereas\nconfig_main_filename is the name shown by -bP. Failure to open a configuration\nfile is a serious disaster. */\n\nif (config_file != NULL)\n  {\n  config_filename = config_main_filename = string_copy(filename);\n  }\nelse\n  {\n  if (filename == NULL)\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"non-existent configuration file(s): \"\n      \"%s\", config_main_filelist);\n  else\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"%s\", string_open_failed(errno,\n      \"configuration file %s\", filename));\n  }\n\n/* Check the status of the file we have opened, unless it was specified on\nthe command line, in which case privilege was given away at the start. */\n\nif (!config_changed)\n  {\n  if (fstat(fileno(config_file), &statbuf) != 0)\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to stat configuration file %s\",\n      big_buffer);\n\n  if ((statbuf.st_uid != root_uid                /* owner not root */\n       #ifdef CONFIGURE_OWNER\n       && statbuf.st_uid != config_uid           /* owner not the special one */\n       #endif\n         ) ||                                    /* or */\n      (statbuf.st_gid != root_gid                /* group not root & */\n       #ifdef CONFIGURE_GROUP\n       && statbuf.st_gid != config_gid           /* group not the special one */\n       #endif\n       && (statbuf.st_mode & 020) != 0) ||       /* group writeable  */\n                                                 /* or */\n      ((statbuf.st_mode & 2) != 0))              /* world writeable  */\n\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Exim configuration file %s has the \"\n      \"wrong owner, group, or mode\", big_buffer);\n  }\n\n/* Process the main configuration settings. They all begin with a lower case\nletter. If we see something starting with an upper case letter, it is taken as\na macro definition. */\n\nwhile ((s = get_config_line()) != NULL)\n  {\n  if (isupper(s[0])) read_macro_assignment(s);\n\n  else if (Ustrncmp(s, \"domainlist\", 10) == 0)\n    read_named_list(&domainlist_anchor, &domainlist_count,\n      MAX_NAMED_LIST, s+10, US\"domain list\");\n\n  else if (Ustrncmp(s, \"hostlist\", 8) == 0)\n    read_named_list(&hostlist_anchor, &hostlist_count,\n      MAX_NAMED_LIST, s+8, US\"host list\");\n\n  else if (Ustrncmp(s, US\"addresslist\", 11) == 0)\n    read_named_list(&addresslist_anchor, &addresslist_count,\n      MAX_NAMED_LIST, s+11, US\"address list\");\n\n  else if (Ustrncmp(s, US\"localpartlist\", 13) == 0)\n    read_named_list(&localpartlist_anchor, &localpartlist_count,\n      MAX_NAMED_LIST, s+13, US\"local part list\");\n\n  else\n    (void) readconf_handle_option(s, optionlist_config, optionlist_config_size,\n      NULL, US\"main option \\\"%s\\\" unknown\");\n  }\n\n\n/* If local_sender_retain is set, local_from_check must be unset. */\n\nif (local_sender_retain && local_from_check)\n  log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"both local_from_check and \"\n    \"local_sender_retain are set; this combination is not allowed\");\n\n/* If the timezone string is empty, set it to NULL, implying no TZ variable\nwanted. */\n\nif (timezone_string != NULL && *timezone_string == 0) timezone_string = NULL;\n\n/* The max retry interval must not be greater than 24 hours. */\n\nif (retry_interval_max > 24*60*60) retry_interval_max = 24*60*60;\n\n/* remote_max_parallel must be > 0 */\n\nif (remote_max_parallel <= 0) remote_max_parallel = 1;\n\n/* Save the configured setting of freeze_tell, so we can re-instate it at the\nstart of a new SMTP message. */\n\nfreeze_tell_config = freeze_tell;\n\n/* The primary host name may be required for expansion of spool_directory\nand log_file_path, so make sure it is set asap. It is obtained from uname(),\nbut if that yields an unqualified value, make a FQDN by using gethostbyname to\ncanonize it. Some people like upper case letters in their host names, so we\ndon't force the case. */\n\nif (primary_hostname == NULL)\n  {\n  uschar *hostname;\n  struct utsname uts;\n  if (uname(&uts) < 0)\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"uname() failed to yield host name\");\n  hostname = US uts.nodename;\n\n  if (Ustrchr(hostname, '.') == NULL)\n    {\n    int af = AF_INET;\n    struct hostent *hostdata;\n\n    #if HAVE_IPV6\n    if (!disable_ipv6 && (dns_ipv4_lookup == NULL ||\n         match_isinlist(hostname, &dns_ipv4_lookup, 0, NULL, NULL, MCL_DOMAIN,\n           TRUE, NULL) != OK))\n      af = AF_INET6;\n    #else\n    af = AF_INET;\n    #endif\n\n    for (;;)\n      {\n      #if HAVE_IPV6\n        #if HAVE_GETIPNODEBYNAME\n        int error_num;\n        hostdata = getipnodebyname(CS hostname, af, 0, &error_num);\n        #else\n        hostdata = gethostbyname2(CS hostname, af);\n        #endif\n      #else\n      hostdata = gethostbyname(CS hostname);\n      #endif\n\n      if (hostdata != NULL)\n        {\n        hostname = US hostdata->h_name;\n        break;\n        }\n\n      if (af == AF_INET) break;\n      af = AF_INET;\n      }\n    }\n\n  primary_hostname = string_copy(hostname);\n  }\n\n/* Set up default value for smtp_active_hostname */\n\nsmtp_active_hostname = primary_hostname;\n\n/* If spool_directory wasn't set in the build-time configuration, it must have\ngot set above. Of course, writing to the log may not work if log_file_path is\nnot set, but it will at least get to syslog or somewhere, with any luck. */\n\nif (*spool_directory == 0)\n  log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"spool_directory undefined: cannot \"\n    \"proceed\");\n\n/* Expand the spool directory name; it may, for example, contain the primary\nhost name. Same comment about failure. */\n\ns = expand_string(spool_directory);\nif (s == NULL)\n  log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand spool_directory \"\n    \"\\\"%s\\\": %s\", spool_directory, expand_string_message);\nspool_directory = s;\n\n/* Expand log_file_path, which must contain \"%s\" in any component that isn't\nthe null string or \"syslog\". It is also allowed to contain one instance of %D.\nHowever, it must NOT contain % followed by anything else. */\n\nif (*log_file_path != 0)\n  {\n  uschar *ss, *sss;\n  int sep = ':';                       /* Fixed for log file path */\n  s = expand_string(log_file_path);\n  if (s == NULL)\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand log_file_path \"\n      \"\\\"%s\\\": %s\", log_file_path, expand_string_message);\n\n  ss = s;\n  while ((sss = string_nextinlist(&ss,&sep,big_buffer,big_buffer_size)) != NULL)\n    {\n    uschar *t;\n    if (sss[0] == 0 || Ustrcmp(sss, \"syslog\") == 0) continue;\n    t = Ustrstr(sss, \"%s\");\n    if (t == NULL)\n      log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"log_file_path \\\"%s\\\" does not \"\n        \"contain \\\"%%s\\\"\", sss);\n    *t = 'X';\n    t = Ustrchr(sss, '%');\n    if (t != NULL)\n      {\n      if (t[1] != 'D' || Ustrchr(t+2, '%') != NULL)\n        log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"log_file_path \\\"%s\\\" contains \"\n          \"unexpected \\\"%%\\\" character\", s);\n      }\n    }\n\n  log_file_path = s;\n  }\n\n/* Interpret syslog_facility into an integer argument for 'ident' param to\nopenlog(). Default is LOG_MAIL set in globals.c. Allow the user to omit the\nleading \"log_\". */\n\nif (syslog_facility_str != NULL)\n  {\n  int i;\n  uschar *s = syslog_facility_str;\n\n  if ((Ustrlen(syslog_facility_str) >= 4) &&\n        (strncmpic(syslog_facility_str, US\"log_\", 4) == 0))\n    s += 4;\n\n  for (i = 0; i < syslog_list_size; i++)\n    {\n    if (strcmpic(s, syslog_list[i].name) == 0)\n      {\n      syslog_facility = syslog_list[i].value;\n      break;\n      }\n    }\n\n  if (i >= syslog_list_size)\n    {\n    log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n      \"failed to interpret syslog_facility \\\"%s\\\"\", syslog_facility_str);\n    }\n  }\n\n/* Expand pid_file_path */\n\nif (*pid_file_path != 0)\n  {\n  s = expand_string(pid_file_path);\n  if (s == NULL)\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand pid_file_path \"\n      \"\\\"%s\\\": %s\", pid_file_path, expand_string_message);\n  pid_file_path = s;\n  }\n\n/* Compile the regex for matching a UUCP-style \"From_\" line in an incoming\nmessage. */\n\nregex_From = regex_must_compile(uucp_from_pattern, FALSE, TRUE);\n\n/* Unpick the SMTP rate limiting options, if set */\n\nif (smtp_ratelimit_mail != NULL)\n  {\n  unpick_ratelimit(smtp_ratelimit_mail, &smtp_rlm_threshold,\n    &smtp_rlm_base, &smtp_rlm_factor, &smtp_rlm_limit);\n  }\n\nif (smtp_ratelimit_rcpt != NULL)\n  {\n  unpick_ratelimit(smtp_ratelimit_rcpt, &smtp_rlr_threshold,\n    &smtp_rlr_base, &smtp_rlr_factor, &smtp_rlr_limit);\n  }\n\n/* The qualify domains default to the primary host name */\n\nif (qualify_domain_sender == NULL)\n  qualify_domain_sender = primary_hostname;\nif (qualify_domain_recipient == NULL)\n  qualify_domain_recipient = qualify_domain_sender;\n\n/* Setting system_filter_user in the configuration sets the gid as well if a\nname is given, but a numerical value does not. */\n\nif (system_filter_uid_set && !system_filter_gid_set)\n  {\n  struct passwd *pw = getpwuid(system_filter_uid);\n  if (pw == NULL)\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Failed to look up uid %ld\",\n      (long int)system_filter_uid);\n  system_filter_gid = pw->pw_gid;\n  system_filter_gid_set = TRUE;\n  }\n\n/* If the errors_reply_to field is set, check that it is syntactically valid\nand ensure it contains a domain. */\n\nif (errors_reply_to != NULL)\n  {\n  uschar *errmess;\n  int start, end, domain;\n  uschar *recipient = parse_extract_address(errors_reply_to, &errmess,\n    &start, &end, &domain, FALSE);\n\n  if (recipient == NULL)\n    log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n      \"error in errors_reply_to (%s): %s\", errors_reply_to, errmess);\n\n  if (domain == 0)\n    log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n      \"errors_reply_to (%s) does not contain a domain\", errors_reply_to);\n  }\n\n/* If smtp_accept_queue or smtp_accept_max_per_host is set, then\nsmtp_accept_max must also be set. */\n\nif (smtp_accept_max == 0 &&\n    (smtp_accept_queue > 0 || smtp_accept_max_per_host != NULL))\n  log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n    \"smtp_accept_max must be set if smtp_accept_queue or \"\n    \"smtp_accept_max_per_host is set\");\n\n/* Set up the host number if anything is specified. It is an expanded string\nso that it can be computed from the host name, for example. We do this last\nso as to ensure that everything else is set up before the expansion. */\n\nif (host_number_string != NULL)\n  {\n  uschar *end;\n  uschar *s = expand_string(host_number_string);\n  long int n = Ustrtol(s, &end, 0);\n  while (isspace(*end)) end++;\n  if (*end != 0)\n    log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n      \"localhost_number value is not a number: %s\", s);\n  if (n > LOCALHOST_MAX)\n    log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n      \"localhost_number is greater than the maximum allowed value (%d)\",\n        LOCALHOST_MAX);\n  host_number = n;\n  }\n\n#ifdef SUPPORT_TLS\n/* If tls_verify_hosts is set, tls_verify_certificates must also be set */\n\nif ((tls_verify_hosts != NULL || tls_try_verify_hosts != NULL) &&\n     tls_verify_certificates == NULL)\n  log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n    \"tls_%sverify_hosts is set, but tls_verify_certificates is not set\",\n    (tls_verify_hosts != NULL)? \"\" : \"try_\");\n\n/* If openssl_options is set, validate it */\nif (openssl_options != NULL)\n  {\n# ifdef USE_GNUTLS\n  log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n    \"openssl_options is set but we're using GnuTLS\");\n# else\n  long dummy;\n  if (!(tls_openssl_options_parse(openssl_options, &dummy)))\n    log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n      \"openssl_options parse error: %s\", openssl_options);\n# endif\n  }\n#endif\n}", "func_hash": 74987850300315727501245353003929658606, "file_name": "readconf.c", "file_hash": 217124537327695199621061480517955399637, "cwe": ["CWE-264"], "cve": "CVE-2010-4345", "cve_desc": "Exim 4.72 and earlier allows local users to gain privileges by leveraging the ability of the exim user account to specify an alternate configuration file with a directive that contains arbitrary commands, as demonstrated by the spool_directory directive.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2010-4345"}
{"idx": 299905, "project": "exim", "commit_id": "e2f5dc151e2e79058e93924e6d35510557f0535d", "project_url": "https://github.com/Exim/exim", "commit_url": "http://git.exim.org/exim.git/commit/e2f5dc151e2e79058e93924e6d35510557f0535d", "commit_message": "Check configure file permissions even for non-default files if still privileged\n\n(Bug 1044, CVE-2010-4345)", "target": 0, "func": "readconf_main(void)\n{\nint sep = 0;\nstruct stat statbuf;\nuschar *s, *filename;\nuschar *list = config_main_filelist;\n\n/* Loop through the possible file names */\n\nwhile((filename = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))\n       != NULL)\n  {\n  /* Cut out all the fancy processing unless specifically wanted */\n\n  #if defined(CONFIGURE_FILE_USE_NODE) || defined(CONFIGURE_FILE_USE_EUID)\n  uschar *suffix = filename + Ustrlen(filename);\n\n  /* Try for the node-specific file if a node name exists */\n\n  #ifdef CONFIGURE_FILE_USE_NODE\n  struct utsname uts;\n  if (uname(&uts) >= 0)\n    {\n    #ifdef CONFIGURE_FILE_USE_EUID\n    sprintf(CS suffix, \".%ld.%.256s\", (long int)original_euid, uts.nodename);\n    config_file = Ufopen(filename, \"rb\");\n    if (config_file == NULL)\n    #endif  /* CONFIGURE_FILE_USE_EUID */\n      {\n      sprintf(CS suffix, \".%.256s\", uts.nodename);\n      config_file = Ufopen(filename, \"rb\");\n      }\n    }\n  #endif  /* CONFIGURE_FILE_USE_NODE */\n\n  /* Otherwise, try the generic name, possibly with the euid added */\n\n  #ifdef CONFIGURE_FILE_USE_EUID\n  if (config_file == NULL)\n    {\n    sprintf(CS suffix, \".%ld\", (long int)original_euid);\n    config_file = Ufopen(filename, \"rb\");\n    }\n  #endif  /* CONFIGURE_FILE_USE_EUID */\n\n  /* Finally, try the unadorned name */\n\n  if (config_file == NULL)\n    {\n    *suffix = 0;\n    config_file = Ufopen(filename, \"rb\");\n    }\n  #else  /* if neither defined */\n\n  /* This is the common case when the fancy processing is not included. */\n\n  config_file = Ufopen(filename, \"rb\");\n  #endif\n\n  /* If the file does not exist, continue to try any others. For any other\n  error, break out (and die). */\n\n  if (config_file != NULL || errno != ENOENT) break;\n  }\n\n/* On success, save the name for verification; config_filename is used when\nlogging configuration errors (it changes for .included files) whereas\nconfig_main_filename is the name shown by -bP. Failure to open a configuration\nfile is a serious disaster. */\n\nif (config_file != NULL)\n  {\n  config_filename = config_main_filename = string_copy(filename);\n  }\nelse\n  {\n  if (filename == NULL)\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"non-existent configuration file(s): \"\n      \"%s\", config_main_filelist);\n  else\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"%s\", string_open_failed(errno,\n      \"configuration file %s\", filename));\n  }\n\n/* Check the status of the file we have opened, if we have retained root\nprivileges. */\n\nif (trusted_config)\n  {\n  if (fstat(fileno(config_file), &statbuf) != 0)\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to stat configuration file %s\",\n      big_buffer);\n\n  if ((statbuf.st_uid != root_uid                /* owner not root */\n       #ifdef CONFIGURE_OWNER\n       && statbuf.st_uid != config_uid           /* owner not the special one */\n       #endif\n         ) ||                                    /* or */\n      (statbuf.st_gid != root_gid                /* group not root & */\n       #ifdef CONFIGURE_GROUP\n       && statbuf.st_gid != config_gid           /* group not the special one */\n       #endif\n       && (statbuf.st_mode & 020) != 0) ||       /* group writeable  */\n                                                 /* or */\n      ((statbuf.st_mode & 2) != 0))              /* world writeable  */\n\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Exim configuration file %s has the \"\n      \"wrong owner, group, or mode\", big_buffer);\n  }\n\n/* Process the main configuration settings. They all begin with a lower case\nletter. If we see something starting with an upper case letter, it is taken as\na macro definition. */\n\nwhile ((s = get_config_line()) != NULL)\n  {\n  if (isupper(s[0])) read_macro_assignment(s);\n\n  else if (Ustrncmp(s, \"domainlist\", 10) == 0)\n    read_named_list(&domainlist_anchor, &domainlist_count,\n      MAX_NAMED_LIST, s+10, US\"domain list\");\n\n  else if (Ustrncmp(s, \"hostlist\", 8) == 0)\n    read_named_list(&hostlist_anchor, &hostlist_count,\n      MAX_NAMED_LIST, s+8, US\"host list\");\n\n  else if (Ustrncmp(s, US\"addresslist\", 11) == 0)\n    read_named_list(&addresslist_anchor, &addresslist_count,\n      MAX_NAMED_LIST, s+11, US\"address list\");\n\n  else if (Ustrncmp(s, US\"localpartlist\", 13) == 0)\n    read_named_list(&localpartlist_anchor, &localpartlist_count,\n      MAX_NAMED_LIST, s+13, US\"local part list\");\n\n  else\n    (void) readconf_handle_option(s, optionlist_config, optionlist_config_size,\n      NULL, US\"main option \\\"%s\\\" unknown\");\n  }\n\n\n/* If local_sender_retain is set, local_from_check must be unset. */\n\nif (local_sender_retain && local_from_check)\n  log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"both local_from_check and \"\n    \"local_sender_retain are set; this combination is not allowed\");\n\n/* If the timezone string is empty, set it to NULL, implying no TZ variable\nwanted. */\n\nif (timezone_string != NULL && *timezone_string == 0) timezone_string = NULL;\n\n/* The max retry interval must not be greater than 24 hours. */\n\nif (retry_interval_max > 24*60*60) retry_interval_max = 24*60*60;\n\n/* remote_max_parallel must be > 0 */\n\nif (remote_max_parallel <= 0) remote_max_parallel = 1;\n\n/* Save the configured setting of freeze_tell, so we can re-instate it at the\nstart of a new SMTP message. */\n\nfreeze_tell_config = freeze_tell;\n\n/* The primary host name may be required for expansion of spool_directory\nand log_file_path, so make sure it is set asap. It is obtained from uname(),\nbut if that yields an unqualified value, make a FQDN by using gethostbyname to\ncanonize it. Some people like upper case letters in their host names, so we\ndon't force the case. */\n\nif (primary_hostname == NULL)\n  {\n  uschar *hostname;\n  struct utsname uts;\n  if (uname(&uts) < 0)\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"uname() failed to yield host name\");\n  hostname = US uts.nodename;\n\n  if (Ustrchr(hostname, '.') == NULL)\n    {\n    int af = AF_INET;\n    struct hostent *hostdata;\n\n    #if HAVE_IPV6\n    if (!disable_ipv6 && (dns_ipv4_lookup == NULL ||\n         match_isinlist(hostname, &dns_ipv4_lookup, 0, NULL, NULL, MCL_DOMAIN,\n           TRUE, NULL) != OK))\n      af = AF_INET6;\n    #else\n    af = AF_INET;\n    #endif\n\n    for (;;)\n      {\n      #if HAVE_IPV6\n        #if HAVE_GETIPNODEBYNAME\n        int error_num;\n        hostdata = getipnodebyname(CS hostname, af, 0, &error_num);\n        #else\n        hostdata = gethostbyname2(CS hostname, af);\n        #endif\n      #else\n      hostdata = gethostbyname(CS hostname);\n      #endif\n\n      if (hostdata != NULL)\n        {\n        hostname = US hostdata->h_name;\n        break;\n        }\n\n      if (af == AF_INET) break;\n      af = AF_INET;\n      }\n    }\n\n  primary_hostname = string_copy(hostname);\n  }\n\n/* Set up default value for smtp_active_hostname */\n\nsmtp_active_hostname = primary_hostname;\n\n/* If spool_directory wasn't set in the build-time configuration, it must have\ngot set above. Of course, writing to the log may not work if log_file_path is\nnot set, but it will at least get to syslog or somewhere, with any luck. */\n\nif (*spool_directory == 0)\n  log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"spool_directory undefined: cannot \"\n    \"proceed\");\n\n/* Expand the spool directory name; it may, for example, contain the primary\nhost name. Same comment about failure. */\n\ns = expand_string(spool_directory);\nif (s == NULL)\n  log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand spool_directory \"\n    \"\\\"%s\\\": %s\", spool_directory, expand_string_message);\nspool_directory = s;\n\n/* Expand log_file_path, which must contain \"%s\" in any component that isn't\nthe null string or \"syslog\". It is also allowed to contain one instance of %D.\nHowever, it must NOT contain % followed by anything else. */\n\nif (*log_file_path != 0)\n  {\n  uschar *ss, *sss;\n  int sep = ':';                       /* Fixed for log file path */\n  s = expand_string(log_file_path);\n  if (s == NULL)\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand log_file_path \"\n      \"\\\"%s\\\": %s\", log_file_path, expand_string_message);\n\n  ss = s;\n  while ((sss = string_nextinlist(&ss,&sep,big_buffer,big_buffer_size)) != NULL)\n    {\n    uschar *t;\n    if (sss[0] == 0 || Ustrcmp(sss, \"syslog\") == 0) continue;\n    t = Ustrstr(sss, \"%s\");\n    if (t == NULL)\n      log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"log_file_path \\\"%s\\\" does not \"\n        \"contain \\\"%%s\\\"\", sss);\n    *t = 'X';\n    t = Ustrchr(sss, '%');\n    if (t != NULL)\n      {\n      if (t[1] != 'D' || Ustrchr(t+2, '%') != NULL)\n        log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"log_file_path \\\"%s\\\" contains \"\n          \"unexpected \\\"%%\\\" character\", s);\n      }\n    }\n\n  log_file_path = s;\n  }\n\n/* Interpret syslog_facility into an integer argument for 'ident' param to\nopenlog(). Default is LOG_MAIL set in globals.c. Allow the user to omit the\nleading \"log_\". */\n\nif (syslog_facility_str != NULL)\n  {\n  int i;\n  uschar *s = syslog_facility_str;\n\n  if ((Ustrlen(syslog_facility_str) >= 4) &&\n        (strncmpic(syslog_facility_str, US\"log_\", 4) == 0))\n    s += 4;\n\n  for (i = 0; i < syslog_list_size; i++)\n    {\n    if (strcmpic(s, syslog_list[i].name) == 0)\n      {\n      syslog_facility = syslog_list[i].value;\n      break;\n      }\n    }\n\n  if (i >= syslog_list_size)\n    {\n    log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n      \"failed to interpret syslog_facility \\\"%s\\\"\", syslog_facility_str);\n    }\n  }\n\n/* Expand pid_file_path */\n\nif (*pid_file_path != 0)\n  {\n  s = expand_string(pid_file_path);\n  if (s == NULL)\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand pid_file_path \"\n      \"\\\"%s\\\": %s\", pid_file_path, expand_string_message);\n  pid_file_path = s;\n  }\n\n/* Compile the regex for matching a UUCP-style \"From_\" line in an incoming\nmessage. */\n\nregex_From = regex_must_compile(uucp_from_pattern, FALSE, TRUE);\n\n/* Unpick the SMTP rate limiting options, if set */\n\nif (smtp_ratelimit_mail != NULL)\n  {\n  unpick_ratelimit(smtp_ratelimit_mail, &smtp_rlm_threshold,\n    &smtp_rlm_base, &smtp_rlm_factor, &smtp_rlm_limit);\n  }\n\nif (smtp_ratelimit_rcpt != NULL)\n  {\n  unpick_ratelimit(smtp_ratelimit_rcpt, &smtp_rlr_threshold,\n    &smtp_rlr_base, &smtp_rlr_factor, &smtp_rlr_limit);\n  }\n\n/* The qualify domains default to the primary host name */\n\nif (qualify_domain_sender == NULL)\n  qualify_domain_sender = primary_hostname;\nif (qualify_domain_recipient == NULL)\n  qualify_domain_recipient = qualify_domain_sender;\n\n/* Setting system_filter_user in the configuration sets the gid as well if a\nname is given, but a numerical value does not. */\n\nif (system_filter_uid_set && !system_filter_gid_set)\n  {\n  struct passwd *pw = getpwuid(system_filter_uid);\n  if (pw == NULL)\n    log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Failed to look up uid %ld\",\n      (long int)system_filter_uid);\n  system_filter_gid = pw->pw_gid;\n  system_filter_gid_set = TRUE;\n  }\n\n/* If the errors_reply_to field is set, check that it is syntactically valid\nand ensure it contains a domain. */\n\nif (errors_reply_to != NULL)\n  {\n  uschar *errmess;\n  int start, end, domain;\n  uschar *recipient = parse_extract_address(errors_reply_to, &errmess,\n    &start, &end, &domain, FALSE);\n\n  if (recipient == NULL)\n    log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n      \"error in errors_reply_to (%s): %s\", errors_reply_to, errmess);\n\n  if (domain == 0)\n    log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n      \"errors_reply_to (%s) does not contain a domain\", errors_reply_to);\n  }\n\n/* If smtp_accept_queue or smtp_accept_max_per_host is set, then\nsmtp_accept_max must also be set. */\n\nif (smtp_accept_max == 0 &&\n    (smtp_accept_queue > 0 || smtp_accept_max_per_host != NULL))\n  log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n    \"smtp_accept_max must be set if smtp_accept_queue or \"\n    \"smtp_accept_max_per_host is set\");\n\n/* Set up the host number if anything is specified. It is an expanded string\nso that it can be computed from the host name, for example. We do this last\nso as to ensure that everything else is set up before the expansion. */\n\nif (host_number_string != NULL)\n  {\n  uschar *end;\n  uschar *s = expand_string(host_number_string);\n  long int n = Ustrtol(s, &end, 0);\n  while (isspace(*end)) end++;\n  if (*end != 0)\n    log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n      \"localhost_number value is not a number: %s\", s);\n  if (n > LOCALHOST_MAX)\n    log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n      \"localhost_number is greater than the maximum allowed value (%d)\",\n        LOCALHOST_MAX);\n  host_number = n;\n  }\n\n#ifdef SUPPORT_TLS\n/* If tls_verify_hosts is set, tls_verify_certificates must also be set */\n\nif ((tls_verify_hosts != NULL || tls_try_verify_hosts != NULL) &&\n     tls_verify_certificates == NULL)\n  log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n    \"tls_%sverify_hosts is set, but tls_verify_certificates is not set\",\n    (tls_verify_hosts != NULL)? \"\" : \"try_\");\n\n/* If openssl_options is set, validate it */\nif (openssl_options != NULL)\n  {\n# ifdef USE_GNUTLS\n  log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n    \"openssl_options is set but we're using GnuTLS\");\n# else\n  long dummy;\n  if (!(tls_openssl_options_parse(openssl_options, &dummy)))\n    log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n      \"openssl_options parse error: %s\", openssl_options);\n# endif\n  }\n#endif\n}", "func_hash": 301428151374859174448691319049213421591, "file_name": "readconf.c", "file_hash": 241387030736703229400830956134687102289, "cwe": ["CWE-264"], "cve": "CVE-2010-4345", "cve_desc": "Exim 4.72 and earlier allows local users to gain privileges by leveraging the ability of the exim user account to specify an alternate configuration file with a directive that contains arbitrary commands, as demonstrated by the spool_directory directive.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2010-4345"}
{"idx": 200163, "project": "linux", "commit_id": "817b8b9c5396d2b2d92311b46719aad5d3339dbe", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/817b8b9c5396d2b2d92311b46719aad5d3339dbe", "commit_message": "HID: elo: fix memory leak in elo_probe\n\nWhen hid_parse() in elo_probe() fails, it forgets to call usb_put_dev to\ndecrease the refcount.\n\nFix this by adding usb_put_dev() in the error handling code of elo_probe().\n\nFixes: fbf42729d0e9 (\"HID: elo: update the reference count of the usb device structure\")\nReported-by: syzkaller \nSigned-off-by: Dongliang Mu \nSigned-off-by: Jiri Kosina ", "target": 1, "func": "static int elo_probe(struct hid_device *hdev, const struct hid_device_id *id)\n{\n\tstruct elo_priv *priv;\n\tint ret;\n\tstruct usb_device *udev;\n\n\tif (!hid_is_usb(hdev))\n\t\treturn -EINVAL;\n\n\tpriv = kzalloc(sizeof(*priv), GFP_KERNEL);\n\tif (!priv)\n\t\treturn -ENOMEM;\n\n\tINIT_DELAYED_WORK(&priv->work, elo_work);\n\tudev = interface_to_usbdev(to_usb_interface(hdev->dev.parent));\n\tpriv->usbdev = usb_get_dev(udev);\n\n\thid_set_drvdata(hdev, priv);\n\n\tret = hid_parse(hdev);\n\tif (ret) {\n\t\thid_err(hdev, \"parse failed\\n\");\n\t\tgoto err_free;\n\t}\n\n\tret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);\n\tif (ret) {\n\t\thid_err(hdev, \"hw start failed\\n\");\n\t\tgoto err_free;\n\t}\n\n\tif (elo_broken_firmware(priv->usbdev)) {\n\t\thid_info(hdev, \"broken firmware found, installing workaround\\n\");\n\t\tqueue_delayed_work(wq, &priv->work, ELO_PERIODIC_READ_INTERVAL);\n\t}\n\n\treturn 0;\nerr_free:\n\tkfree(priv);\n\treturn ret;\n}", "func_hash": 119771214080354607700352502150468808097, "file_name": "hid-elo.c", "file_hash": 34235452733984026251117954935462979934, "cwe": ["CWE-200"], "cve": "CVE-2022-27950", "cve_desc": "In drivers/hid/hid-elo.c in the Linux kernel before 5.16.11, a memory leak exists for a certain hid_parse error condition.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27950"}
{"idx": 299976, "project": "linux", "commit_id": "817b8b9c5396d2b2d92311b46719aad5d3339dbe", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/817b8b9c5396d2b2d92311b46719aad5d3339dbe", "commit_message": "HID: elo: fix memory leak in elo_probe\n\nWhen hid_parse() in elo_probe() fails, it forgets to call usb_put_dev to\ndecrease the refcount.\n\nFix this by adding usb_put_dev() in the error handling code of elo_probe().\n\nFixes: fbf42729d0e9 (\"HID: elo: update the reference count of the usb device structure\")\nReported-by: syzkaller \nSigned-off-by: Dongliang Mu \nSigned-off-by: Jiri Kosina ", "target": 0, "func": "static int elo_probe(struct hid_device *hdev, const struct hid_device_id *id)\n{\n\tstruct elo_priv *priv;\n\tint ret;\n\tstruct usb_device *udev;\n\n\tif (!hid_is_usb(hdev))\n\t\treturn -EINVAL;\n\n\tpriv = kzalloc(sizeof(*priv), GFP_KERNEL);\n\tif (!priv)\n\t\treturn -ENOMEM;\n\n\tINIT_DELAYED_WORK(&priv->work, elo_work);\n\tudev = interface_to_usbdev(to_usb_interface(hdev->dev.parent));\n\tpriv->usbdev = usb_get_dev(udev);\n\n\thid_set_drvdata(hdev, priv);\n\n\tret = hid_parse(hdev);\n\tif (ret) {\n\t\thid_err(hdev, \"parse failed\\n\");\n\t\tgoto err_free;\n\t}\n\n\tret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);\n\tif (ret) {\n\t\thid_err(hdev, \"hw start failed\\n\");\n\t\tgoto err_free;\n\t}\n\n\tif (elo_broken_firmware(priv->usbdev)) {\n\t\thid_info(hdev, \"broken firmware found, installing workaround\\n\");\n\t\tqueue_delayed_work(wq, &priv->work, ELO_PERIODIC_READ_INTERVAL);\n\t}\n\n\treturn 0;\nerr_free:\n\tusb_put_dev(udev);\n\tkfree(priv);\n\treturn ret;\n}", "func_hash": 135198268803525127724468857463616363456, "file_name": "hid-elo.c", "file_hash": 128667147531145854584279442153105575626, "cwe": ["CWE-200"], "cve": "CVE-2022-27950", "cve_desc": "In drivers/hid/hid-elo.c in the Linux kernel before 5.16.11, a memory leak exists for a certain hid_parse error condition.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27950"}
{"idx": 200287, "project": "linux", "commit_id": "d6d86830705f173fca6087a3e67ceaf68db80523", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/d6d86830705f173fca6087a3e67ceaf68db80523", "commit_message": "net ticp:fix a kernel-infoleak in __tipc_sendmsg()\n\nstruct tipc_socket_addr.ref has a 4-byte hole,and __tipc_getname() currently\ncopying it to user space,causing kernel-infoleak.\n\nBUG: KMSAN: kernel-infoleak in instrument_copy_to_user include/linux/instrumented.h:121 [inline]\nBUG: KMSAN: kernel-infoleak in instrument_copy_to_user include/linux/instrumented.h:121 [inline] lib/usercopy.c:33\nBUG: KMSAN: kernel-infoleak in _copy_to_user+0x1c9/0x270 lib/usercopy.c:33 lib/usercopy.c:33\n instrument_copy_to_user include/linux/instrumented.h:121 [inline]\n instrument_copy_to_user include/linux/instrumented.h:121 [inline] lib/usercopy.c:33\n _copy_to_user+0x1c9/0x270 lib/usercopy.c:33 lib/usercopy.c:33\n copy_to_user include/linux/uaccess.h:209 [inline]\n copy_to_user include/linux/uaccess.h:209 [inline] net/socket.c:287\n move_addr_to_user+0x3f6/0x600 net/socket.c:287 net/socket.c:287\n __sys_getpeername+0x470/0x6b0 net/socket.c:1987 net/socket.c:1987\n __do_sys_getpeername net/socket.c:1997 [inline]\n __se_sys_getpeername net/socket.c:1994 [inline]\n __do_sys_getpeername net/socket.c:1997 [inline] net/socket.c:1994\n __se_sys_getpeername net/socket.c:1994 [inline] net/socket.c:1994\n __x64_sys_getpeername+0xda/0x120 net/socket.c:1994 net/socket.c:1994\n do_syscall_x64 arch/x86/entry/common.c:51 [inline]\n do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82\n do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nUninit was stored to memory at:\n tipc_getname+0x575/0x5e0 net/tipc/socket.c:757 net/tipc/socket.c:757\n __sys_getpeername+0x3b3/0x6b0 net/socket.c:1984 net/socket.c:1984\n __do_sys_getpeername net/socket.c:1997 [inline]\n __se_sys_getpeername net/socket.c:1994 [inline]\n __do_sys_getpeername net/socket.c:1997 [inline] net/socket.c:1994\n __se_sys_getpeername net/socket.c:1994 [inline] net/socket.c:1994\n __x64_sys_getpeername+0xda/0x120 net/socket.c:1994 net/socket.c:1994\n do_syscall_x64 arch/x86/entry/common.c:51 [inline]\n do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82\n do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nUninit was stored to memory at:\n msg_set_word net/tipc/msg.h:212 [inline]\n msg_set_destport net/tipc/msg.h:619 [inline]\n msg_set_word net/tipc/msg.h:212 [inline] net/tipc/socket.c:1486\n msg_set_destport net/tipc/msg.h:619 [inline] net/tipc/socket.c:1486\n __tipc_sendmsg+0x44fa/0x5890 net/tipc/socket.c:1486 net/tipc/socket.c:1486\n tipc_sendmsg+0xeb/0x140 net/tipc/socket.c:1402 net/tipc/socket.c:1402\n sock_sendmsg_nosec net/socket.c:704 [inline]\n sock_sendmsg net/socket.c:724 [inline]\n sock_sendmsg_nosec net/socket.c:704 [inline] net/socket.c:2409\n sock_sendmsg net/socket.c:724 [inline] net/socket.c:2409\n ____sys_sendmsg+0xe11/0x12c0 net/socket.c:2409 net/socket.c:2409\n ___sys_sendmsg net/socket.c:2463 [inline]\n ___sys_sendmsg net/socket.c:2463 [inline] net/socket.c:2492\n __sys_sendmsg+0x704/0x840 net/socket.c:2492 net/socket.c:2492\n __do_sys_sendmsg net/socket.c:2501 [inline]\n __se_sys_sendmsg net/socket.c:2499 [inline]\n __do_sys_sendmsg net/socket.c:2501 [inline] net/socket.c:2499\n __se_sys_sendmsg net/socket.c:2499 [inline] net/socket.c:2499\n __x64_sys_sendmsg+0xe2/0x120 net/socket.c:2499 net/socket.c:2499\n do_syscall_x64 arch/x86/entry/common.c:51 [inline]\n do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82\n do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nLocal variable skaddr created at:\n __tipc_sendmsg+0x2d0/0x5890 net/tipc/socket.c:1419 net/tipc/socket.c:1419\n tipc_sendmsg+0xeb/0x140 net/tipc/socket.c:1402 net/tipc/socket.c:1402\n\nBytes 4-7 of 16 are uninitialized\nMemory access of size 16 starts at ffff888113753e00\nData copied to user address 0000000020000280\n\nReported-by: syzbot+cdbd40e0c3ca02cae3b7@syzkaller.appspotmail.com\nSigned-off-by: Haimin Zhang \nAcked-by: Jon Maloy \nLink: https://lore.kernel.org/r/1640918123-14547-1-git-send-email-tcs.kernel@gmail.com\nSigned-off-by: Jakub Kicinski ", "target": 1, "func": "static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dlen)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct net *net = sock_net(sk);\n\tstruct tipc_sock *tsk = tipc_sk(sk);\n\tstruct tipc_uaddr *ua = (struct tipc_uaddr *)m->msg_name;\n\tlong timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);\n\tstruct list_head *clinks = &tsk->cong_links;\n\tbool syn = !tipc_sk_type_connectionless(sk);\n\tstruct tipc_group *grp = tsk->group;\n\tstruct tipc_msg *hdr = &tsk->phdr;\n\tstruct tipc_socket_addr skaddr;\n\tstruct sk_buff_head pkts;\n\tint atype, mtu, rc;\n\n\tif (unlikely(dlen > TIPC_MAX_USER_MSG_SIZE))\n\t\treturn -EMSGSIZE;\n\n\tif (ua) {\n\t\tif (!tipc_uaddr_valid(ua, m->msg_namelen))\n\t\t\treturn -EINVAL;\n\t\tatype = ua->addrtype;\n\t}\n\n\t/* If socket belongs to a communication group follow other paths */\n\tif (grp) {\n\t\tif (!ua)\n\t\t\treturn tipc_send_group_bcast(sock, m, dlen, timeout);\n\t\tif (atype == TIPC_SERVICE_ADDR)\n\t\t\treturn tipc_send_group_anycast(sock, m, dlen, timeout);\n\t\tif (atype == TIPC_SOCKET_ADDR)\n\t\t\treturn tipc_send_group_unicast(sock, m, dlen, timeout);\n\t\tif (atype == TIPC_SERVICE_RANGE)\n\t\t\treturn tipc_send_group_mcast(sock, m, dlen, timeout);\n\t\treturn -EINVAL;\n\t}\n\n\tif (!ua) {\n\t\tua = (struct tipc_uaddr *)&tsk->peer;\n\t\tif (!syn && ua->family != AF_TIPC)\n\t\t\treturn -EDESTADDRREQ;\n\t\tatype = ua->addrtype;\n\t}\n\n\tif (unlikely(syn)) {\n\t\tif (sk->sk_state == TIPC_LISTEN)\n\t\t\treturn -EPIPE;\n\t\tif (sk->sk_state != TIPC_OPEN)\n\t\t\treturn -EISCONN;\n\t\tif (tsk->published)\n\t\t\treturn -EOPNOTSUPP;\n\t\tif (atype == TIPC_SERVICE_ADDR)\n\t\t\ttsk->conn_addrtype = atype;\n\t\tmsg_set_syn(hdr, 1);\n\t}\n\n\t/* Determine destination */\n\tif (atype == TIPC_SERVICE_RANGE) {\n\t\treturn tipc_sendmcast(sock, ua, m, dlen, timeout);\n\t} else if (atype == TIPC_SERVICE_ADDR) {\n\t\tskaddr.node = ua->lookup_node;\n\t\tua->scope = tipc_node2scope(skaddr.node);\n\t\tif (!tipc_nametbl_lookup_anycast(net, ua, &skaddr))\n\t\t\treturn -EHOSTUNREACH;\n\t} else if (atype == TIPC_SOCKET_ADDR) {\n\t\tskaddr = ua->sk;\n\t} else {\n\t\treturn -EINVAL;\n\t}\n\n\t/* Block or return if destination link is congested */\n\trc = tipc_wait_for_cond(sock, &timeout,\n\t\t\t\t!tipc_dest_find(clinks, skaddr.node, 0));\n\tif (unlikely(rc))\n\t\treturn rc;\n\n\t/* Finally build message header */\n\tmsg_set_destnode(hdr, skaddr.node);\n\tmsg_set_destport(hdr, skaddr.ref);\n\tif (atype == TIPC_SERVICE_ADDR) {\n\t\tmsg_set_type(hdr, TIPC_NAMED_MSG);\n\t\tmsg_set_hdr_sz(hdr, NAMED_H_SIZE);\n\t\tmsg_set_nametype(hdr, ua->sa.type);\n\t\tmsg_set_nameinst(hdr, ua->sa.instance);\n\t\tmsg_set_lookup_scope(hdr, ua->scope);\n\t} else { /* TIPC_SOCKET_ADDR */\n\t\tmsg_set_type(hdr, TIPC_DIRECT_MSG);\n\t\tmsg_set_lookup_scope(hdr, 0);\n\t\tmsg_set_hdr_sz(hdr, BASIC_H_SIZE);\n\t}\n\n\t/* Add message body */\n\t__skb_queue_head_init(&pkts);\n\tmtu = tipc_node_get_mtu(net, skaddr.node, tsk->portid, true);\n\trc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);\n\tif (unlikely(rc != dlen))\n\t\treturn rc;\n\tif (unlikely(syn && !tipc_msg_skb_clone(&pkts, &sk->sk_write_queue))) {\n\t\t__skb_queue_purge(&pkts);\n\t\treturn -ENOMEM;\n\t}\n\n\t/* Send message */\n\ttrace_tipc_sk_sendmsg(sk, skb_peek(&pkts), TIPC_DUMP_SK_SNDQ, \" \");\n\trc = tipc_node_xmit(net, &pkts, skaddr.node, tsk->portid);\n\tif (unlikely(rc == -ELINKCONG)) {\n\t\ttipc_dest_push(clinks, skaddr.node, 0);\n\t\ttsk->cong_link_cnt++;\n\t\trc = 0;\n\t}\n\n\tif (unlikely(syn && !rc)) {\n\t\ttipc_set_sk_state(sk, TIPC_CONNECTING);\n\t\tif (dlen && timeout) {\n\t\t\ttimeout = msecs_to_jiffies(timeout);\n\t\t\ttipc_wait_for_connect(sock, &timeout);\n\t\t}\n\t}\n\n\treturn rc ? rc : dlen;\n}", "func_hash": 187316583908925875095721276140565552990, "file_name": "socket.c", "file_hash": 211909288028562459580061336771266741769, "cwe": ["CWE-200"], "cve": "CVE-2022-0382", "cve_desc": "An information leak flaw was found due to uninitialized memory in the Linux kernel's TIPC protocol subsystem, in the way a user sends a TIPC datagram to one or more destinations. This flaw allows a local user to read some kernel memory. This issue is limited to no more than 7 bytes, and the user cannot control what is read. This flaw affects the Linux kernel versions prior to 5.17-rc1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0382"}
{"idx": 300731, "project": "linux", "commit_id": "d6d86830705f173fca6087a3e67ceaf68db80523", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/d6d86830705f173fca6087a3e67ceaf68db80523", "commit_message": "net ticp:fix a kernel-infoleak in __tipc_sendmsg()\n\nstruct tipc_socket_addr.ref has a 4-byte hole,and __tipc_getname() currently\ncopying it to user space,causing kernel-infoleak.\n\nBUG: KMSAN: kernel-infoleak in instrument_copy_to_user include/linux/instrumented.h:121 [inline]\nBUG: KMSAN: kernel-infoleak in instrument_copy_to_user include/linux/instrumented.h:121 [inline] lib/usercopy.c:33\nBUG: KMSAN: kernel-infoleak in _copy_to_user+0x1c9/0x270 lib/usercopy.c:33 lib/usercopy.c:33\n instrument_copy_to_user include/linux/instrumented.h:121 [inline]\n instrument_copy_to_user include/linux/instrumented.h:121 [inline] lib/usercopy.c:33\n _copy_to_user+0x1c9/0x270 lib/usercopy.c:33 lib/usercopy.c:33\n copy_to_user include/linux/uaccess.h:209 [inline]\n copy_to_user include/linux/uaccess.h:209 [inline] net/socket.c:287\n move_addr_to_user+0x3f6/0x600 net/socket.c:287 net/socket.c:287\n __sys_getpeername+0x470/0x6b0 net/socket.c:1987 net/socket.c:1987\n __do_sys_getpeername net/socket.c:1997 [inline]\n __se_sys_getpeername net/socket.c:1994 [inline]\n __do_sys_getpeername net/socket.c:1997 [inline] net/socket.c:1994\n __se_sys_getpeername net/socket.c:1994 [inline] net/socket.c:1994\n __x64_sys_getpeername+0xda/0x120 net/socket.c:1994 net/socket.c:1994\n do_syscall_x64 arch/x86/entry/common.c:51 [inline]\n do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82\n do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nUninit was stored to memory at:\n tipc_getname+0x575/0x5e0 net/tipc/socket.c:757 net/tipc/socket.c:757\n __sys_getpeername+0x3b3/0x6b0 net/socket.c:1984 net/socket.c:1984\n __do_sys_getpeername net/socket.c:1997 [inline]\n __se_sys_getpeername net/socket.c:1994 [inline]\n __do_sys_getpeername net/socket.c:1997 [inline] net/socket.c:1994\n __se_sys_getpeername net/socket.c:1994 [inline] net/socket.c:1994\n __x64_sys_getpeername+0xda/0x120 net/socket.c:1994 net/socket.c:1994\n do_syscall_x64 arch/x86/entry/common.c:51 [inline]\n do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82\n do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nUninit was stored to memory at:\n msg_set_word net/tipc/msg.h:212 [inline]\n msg_set_destport net/tipc/msg.h:619 [inline]\n msg_set_word net/tipc/msg.h:212 [inline] net/tipc/socket.c:1486\n msg_set_destport net/tipc/msg.h:619 [inline] net/tipc/socket.c:1486\n __tipc_sendmsg+0x44fa/0x5890 net/tipc/socket.c:1486 net/tipc/socket.c:1486\n tipc_sendmsg+0xeb/0x140 net/tipc/socket.c:1402 net/tipc/socket.c:1402\n sock_sendmsg_nosec net/socket.c:704 [inline]\n sock_sendmsg net/socket.c:724 [inline]\n sock_sendmsg_nosec net/socket.c:704 [inline] net/socket.c:2409\n sock_sendmsg net/socket.c:724 [inline] net/socket.c:2409\n ____sys_sendmsg+0xe11/0x12c0 net/socket.c:2409 net/socket.c:2409\n ___sys_sendmsg net/socket.c:2463 [inline]\n ___sys_sendmsg net/socket.c:2463 [inline] net/socket.c:2492\n __sys_sendmsg+0x704/0x840 net/socket.c:2492 net/socket.c:2492\n __do_sys_sendmsg net/socket.c:2501 [inline]\n __se_sys_sendmsg net/socket.c:2499 [inline]\n __do_sys_sendmsg net/socket.c:2501 [inline] net/socket.c:2499\n __se_sys_sendmsg net/socket.c:2499 [inline] net/socket.c:2499\n __x64_sys_sendmsg+0xe2/0x120 net/socket.c:2499 net/socket.c:2499\n do_syscall_x64 arch/x86/entry/common.c:51 [inline]\n do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82\n do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nLocal variable skaddr created at:\n __tipc_sendmsg+0x2d0/0x5890 net/tipc/socket.c:1419 net/tipc/socket.c:1419\n tipc_sendmsg+0xeb/0x140 net/tipc/socket.c:1402 net/tipc/socket.c:1402\n\nBytes 4-7 of 16 are uninitialized\nMemory access of size 16 starts at ffff888113753e00\nData copied to user address 0000000020000280\n\nReported-by: syzbot+cdbd40e0c3ca02cae3b7@syzkaller.appspotmail.com\nSigned-off-by: Haimin Zhang \nAcked-by: Jon Maloy \nLink: https://lore.kernel.org/r/1640918123-14547-1-git-send-email-tcs.kernel@gmail.com\nSigned-off-by: Jakub Kicinski ", "target": 0, "func": "static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dlen)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct net *net = sock_net(sk);\n\tstruct tipc_sock *tsk = tipc_sk(sk);\n\tstruct tipc_uaddr *ua = (struct tipc_uaddr *)m->msg_name;\n\tlong timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);\n\tstruct list_head *clinks = &tsk->cong_links;\n\tbool syn = !tipc_sk_type_connectionless(sk);\n\tstruct tipc_group *grp = tsk->group;\n\tstruct tipc_msg *hdr = &tsk->phdr;\n\tstruct tipc_socket_addr skaddr;\n\tstruct sk_buff_head pkts;\n\tint atype, mtu, rc;\n\n\tif (unlikely(dlen > TIPC_MAX_USER_MSG_SIZE))\n\t\treturn -EMSGSIZE;\n\n\tif (ua) {\n\t\tif (!tipc_uaddr_valid(ua, m->msg_namelen))\n\t\t\treturn -EINVAL;\n\t\tatype = ua->addrtype;\n\t}\n\n\t/* If socket belongs to a communication group follow other paths */\n\tif (grp) {\n\t\tif (!ua)\n\t\t\treturn tipc_send_group_bcast(sock, m, dlen, timeout);\n\t\tif (atype == TIPC_SERVICE_ADDR)\n\t\t\treturn tipc_send_group_anycast(sock, m, dlen, timeout);\n\t\tif (atype == TIPC_SOCKET_ADDR)\n\t\t\treturn tipc_send_group_unicast(sock, m, dlen, timeout);\n\t\tif (atype == TIPC_SERVICE_RANGE)\n\t\t\treturn tipc_send_group_mcast(sock, m, dlen, timeout);\n\t\treturn -EINVAL;\n\t}\n\n\tif (!ua) {\n\t\tua = (struct tipc_uaddr *)&tsk->peer;\n\t\tif (!syn && ua->family != AF_TIPC)\n\t\t\treturn -EDESTADDRREQ;\n\t\tatype = ua->addrtype;\n\t}\n\n\tif (unlikely(syn)) {\n\t\tif (sk->sk_state == TIPC_LISTEN)\n\t\t\treturn -EPIPE;\n\t\tif (sk->sk_state != TIPC_OPEN)\n\t\t\treturn -EISCONN;\n\t\tif (tsk->published)\n\t\t\treturn -EOPNOTSUPP;\n\t\tif (atype == TIPC_SERVICE_ADDR)\n\t\t\ttsk->conn_addrtype = atype;\n\t\tmsg_set_syn(hdr, 1);\n\t}\n\n\tmemset(&skaddr, 0, sizeof(skaddr));\n\n\t/* Determine destination */\n\tif (atype == TIPC_SERVICE_RANGE) {\n\t\treturn tipc_sendmcast(sock, ua, m, dlen, timeout);\n\t} else if (atype == TIPC_SERVICE_ADDR) {\n\t\tskaddr.node = ua->lookup_node;\n\t\tua->scope = tipc_node2scope(skaddr.node);\n\t\tif (!tipc_nametbl_lookup_anycast(net, ua, &skaddr))\n\t\t\treturn -EHOSTUNREACH;\n\t} else if (atype == TIPC_SOCKET_ADDR) {\n\t\tskaddr = ua->sk;\n\t} else {\n\t\treturn -EINVAL;\n\t}\n\n\t/* Block or return if destination link is congested */\n\trc = tipc_wait_for_cond(sock, &timeout,\n\t\t\t\t!tipc_dest_find(clinks, skaddr.node, 0));\n\tif (unlikely(rc))\n\t\treturn rc;\n\n\t/* Finally build message header */\n\tmsg_set_destnode(hdr, skaddr.node);\n\tmsg_set_destport(hdr, skaddr.ref);\n\tif (atype == TIPC_SERVICE_ADDR) {\n\t\tmsg_set_type(hdr, TIPC_NAMED_MSG);\n\t\tmsg_set_hdr_sz(hdr, NAMED_H_SIZE);\n\t\tmsg_set_nametype(hdr, ua->sa.type);\n\t\tmsg_set_nameinst(hdr, ua->sa.instance);\n\t\tmsg_set_lookup_scope(hdr, ua->scope);\n\t} else { /* TIPC_SOCKET_ADDR */\n\t\tmsg_set_type(hdr, TIPC_DIRECT_MSG);\n\t\tmsg_set_lookup_scope(hdr, 0);\n\t\tmsg_set_hdr_sz(hdr, BASIC_H_SIZE);\n\t}\n\n\t/* Add message body */\n\t__skb_queue_head_init(&pkts);\n\tmtu = tipc_node_get_mtu(net, skaddr.node, tsk->portid, true);\n\trc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);\n\tif (unlikely(rc != dlen))\n\t\treturn rc;\n\tif (unlikely(syn && !tipc_msg_skb_clone(&pkts, &sk->sk_write_queue))) {\n\t\t__skb_queue_purge(&pkts);\n\t\treturn -ENOMEM;\n\t}\n\n\t/* Send message */\n\ttrace_tipc_sk_sendmsg(sk, skb_peek(&pkts), TIPC_DUMP_SK_SNDQ, \" \");\n\trc = tipc_node_xmit(net, &pkts, skaddr.node, tsk->portid);\n\tif (unlikely(rc == -ELINKCONG)) {\n\t\ttipc_dest_push(clinks, skaddr.node, 0);\n\t\ttsk->cong_link_cnt++;\n\t\trc = 0;\n\t}\n\n\tif (unlikely(syn && !rc)) {\n\t\ttipc_set_sk_state(sk, TIPC_CONNECTING);\n\t\tif (dlen && timeout) {\n\t\t\ttimeout = msecs_to_jiffies(timeout);\n\t\t\ttipc_wait_for_connect(sock, &timeout);\n\t\t}\n\t}\n\n\treturn rc ? rc : dlen;\n}", "func_hash": 227702131307400151351141402297304867494, "file_name": "socket.c", "file_hash": 232810698779802669165593435483275736628, "cwe": ["CWE-200"], "cve": "CVE-2022-0382", "cve_desc": "An information leak flaw was found due to uninitialized memory in the Linux kernel's TIPC protocol subsystem, in the way a user sends a TIPC datagram to one or more destinations. This flaw allows a local user to read some kernel memory. This issue is limited to no more than 7 bytes, and the user cannot control what is read. This flaw affects the Linux kernel versions prior to 5.17-rc1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0382"}
{"idx": 200305, "project": "ghostpdl", "commit_id": "2793769ff107d8d22dadd30c6e68cd781b569550", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "https://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=2793769ff107d8d22dadd30c6e68cd781b569550", "commit_message": "Bug 701819: fixed ordering in if expression to avoid out-of-bounds access.\n\nFixes:\n    ./sanbin/gs -dBATCH -dNOPAUSE -r965 -sOutputFile=tmp -sDEVICE=pcx16 ../bug-701819.pdf", "target": 1, "func": "pcx_write_rle(const byte * from, const byte * end, int step, gp_file * file)\n{\t\t\t\t/*\n                                 * The PCX format theoretically allows encoding runs of 63\n                                 * identical bytes, but some readers can't handle repetition\n                                 * counts greater than 15.\n                                 */\n#define MAX_RUN_COUNT 15\n    int max_run = step * MAX_RUN_COUNT;\n\n    while (from < end) {\n        byte data = *from;\n\n        from += step;\n        if (data != *from || from == end) {\n            if (data >= 0xc0)\n                gp_fputc(0xc1, file);\n        } else {\n            const byte *start = from;\n\n            while ((from < end) && (*from == data))\n                from += step;\n            /* Now (from - start) / step + 1 is the run length. */\n            while (from - start >= max_run) {\n                gp_fputc(0xc0 + MAX_RUN_COUNT, file);\n                gp_fputc(data, file);\n                start += max_run;\n            }\n            if (from > start || data >= 0xc0)\n                gp_fputc((from - start) / step + 0xc1, file);\n        }\n        gp_fputc(data, file);\n    }\n#undef MAX_RUN_COUNT\n}", "func_hash": 302156343438902913796919673468889397004, "file_name": "gdevpcx.c", "file_hash": 193192744323180393354892924891696445092, "cwe": ["CWE-787"], "cve": "CVE-2020-16305", "cve_desc": "A buffer overflow vulnerability in pcx_write_rle() in contrib/japanese/gdev10v.c of Artifex Software GhostScript v9.50 allows a remote attacker to cause a denial of service via a crafted PDF file. This is fixed in v9.51.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16305"}
{"idx": 301016, "project": "ghostpdl", "commit_id": "2793769ff107d8d22dadd30c6e68cd781b569550", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "https://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=2793769ff107d8d22dadd30c6e68cd781b569550", "commit_message": "Bug 701819: fixed ordering in if expression to avoid out-of-bounds access.\n\nFixes:\n    ./sanbin/gs -dBATCH -dNOPAUSE -r965 -sOutputFile=tmp -sDEVICE=pcx16 ../bug-701819.pdf", "target": 0, "func": "pcx_write_rle(const byte * from, const byte * end, int step, gp_file * file)\n{\t\t\t\t/*\n                                 * The PCX format theoretically allows encoding runs of 63\n                                 * identical bytes, but some readers can't handle repetition\n                                 * counts greater than 15.\n                                 */\n#define MAX_RUN_COUNT 15\n    int max_run = step * MAX_RUN_COUNT;\n\n    while (from < end) {\n        byte data = *from;\n\n        from += step;\n        if (from >= end || data != *from) {\n            if (data >= 0xc0)\n                gp_fputc(0xc1, file);\n        } else {\n            const byte *start = from;\n\n            while ((from < end) && (*from == data))\n                from += step;\n            /* Now (from - start) / step + 1 is the run length. */\n            while (from - start >= max_run) {\n                gp_fputc(0xc0 + MAX_RUN_COUNT, file);\n                gp_fputc(data, file);\n                start += max_run;\n            }\n            if (from > start || data >= 0xc0)\n                gp_fputc((from - start) / step + 0xc1, file);\n        }\n        gp_fputc(data, file);\n    }\n#undef MAX_RUN_COUNT\n}", "func_hash": 242406925449442075366182864127739162962, "file_name": "gdevpcx.c", "file_hash": 146911482994709759285318949799638474400, "cwe": ["CWE-787"], "cve": "CVE-2020-16305", "cve_desc": "A buffer overflow vulnerability in pcx_write_rle() in contrib/japanese/gdev10v.c of Artifex Software GhostScript v9.50 allows a remote attacker to cause a denial of service via a crafted PDF file. This is fixed in v9.51.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16305"}
{"idx": 200320, "project": "samba", "commit_id": "eb50fb8f3bf670bd7d1cf8fd4368ef4a73083696", "project_url": "https://github.com/samba-team/samba", "commit_url": "http://git.samba.org/?p=samba.git;a=commitdiff;h=eb50fb8f3bf670bd7d1cf8fd4368ef4a73083696", "commit_message": "FSCTL_GET_SHADOW_COPY_DATA: Don't return 4 extra bytes at end\n\nlabels_data_count already accounts for the unicode null character at the\nend of the array. There is no need in adding space for it again.\n\nSigned-off-by: Christof Schmitt \nReviewed-by: Jeremy Allison \nReviewed-by: Simo Sorce \n\nAutobuild-User(master): Jeremy Allison \nAutobuild-Date(master): Tue Aug  6 04:03:17 CEST 2013 on sn-devel-104", "target": 1, "func": "static NTSTATUS vfswrap_fsctl(struct vfs_handle_struct *handle,\n\t\t\t      struct files_struct *fsp,\n\t\t\t      TALLOC_CTX *ctx,\n\t\t\t      uint32_t function,\n\t\t\t      uint16_t req_flags, /* Needed for UNICODE ... */\n\t\t\t      const uint8_t *_in_data,\n\t\t\t      uint32_t in_len,\n\t\t\t      uint8_t **_out_data,\n\t\t\t      uint32_t max_out_len,\n\t\t\t      uint32_t *out_len)\n{\n\tconst char *in_data = (const char *)_in_data;\n\tchar **out_data = (char **)_out_data;\n\n\tswitch (function) {\n\tcase FSCTL_SET_SPARSE:\n\t{\n\t\tbool set_sparse = true;\n\t\tNTSTATUS status;\n\n\t\tif (in_len >= 1 && in_data[0] == 0) {\n\t\t\tset_sparse = false;\n\t\t}\n\n\t\tstatus = file_set_sparse(handle->conn, fsp, set_sparse);\n\t\t\n\t\tDEBUG(NT_STATUS_IS_OK(status) ? 10 : 9,\n\t\t      (\"FSCTL_SET_SPARSE: fname[%s] set[%u] - %s\\n\",\n\t\t       smb_fname_str_dbg(fsp->fsp_name), set_sparse, \n\t\t       nt_errstr(status)));\n\n\t\treturn status;\n\t}\n\n\tcase FSCTL_CREATE_OR_GET_OBJECT_ID:\n\t{\n\t\tunsigned char objid[16];\n\t\tchar *return_data = NULL;\n\n\t\t/* This should return the object-id on this file.\n\t\t * I think I'll make this be the inode+dev. JRA.\n\t\t */\n\n\t\tDEBUG(10,(\"FSCTL_CREATE_OR_GET_OBJECT_ID: called on %s\\n\",\n\t\t\t  fsp_fnum_dbg(fsp)));\n\n\t\t*out_len = (max_out_len >= 64) ? 64 : max_out_len;\n\t\t/* Hmmm, will this cause problems if less data asked for? */\n\t\treturn_data = talloc_array(ctx, char, 64);\n\t\tif (return_data == NULL) {\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\n\t\t/* For backwards compatibility only store the dev/inode. */\n\t\tpush_file_id_16(return_data, &fsp->file_id);\n\t\tmemcpy(return_data+16,create_volume_objectid(fsp->conn,objid),16);\n\t\tpush_file_id_16(return_data+32, &fsp->file_id);\n\t\t*out_data = return_data;\n\t\treturn NT_STATUS_OK;\n\t}\n\n\tcase FSCTL_GET_REPARSE_POINT:\n\t{\n\t\t/* Fail it with STATUS_NOT_A_REPARSE_POINT */\n\t\tDEBUG(10, (\"FSCTL_GET_REPARSE_POINT: called on %s. \"\n\t\t\t   \"Status: NOT_IMPLEMENTED\\n\", fsp_fnum_dbg(fsp)));\n\t\treturn NT_STATUS_NOT_A_REPARSE_POINT;\n\t}\n\n\tcase FSCTL_SET_REPARSE_POINT:\n\t{\n\t\t/* Fail it with STATUS_NOT_A_REPARSE_POINT */\n\t\tDEBUG(10, (\"FSCTL_SET_REPARSE_POINT: called on %s. \"\n\t\t\t   \"Status: NOT_IMPLEMENTED\\n\", fsp_fnum_dbg(fsp)));\n\t\treturn NT_STATUS_NOT_A_REPARSE_POINT;\n\t}\n\n\tcase FSCTL_GET_SHADOW_COPY_DATA:\n\t{\n\t\t/*\n\t\t * This is called to retrieve the number of Shadow Copies (a.k.a. snapshots)\n\t\t * and return their volume names.  If max_data_count is 16, then it is just\n\t\t * asking for the number of volumes and length of the combined names.\n\t\t *\n\t\t * pdata is the data allocated by our caller, but that uses\n\t\t * total_data_count (which is 0 in our case) rather than max_data_count.\n\t\t * Allocate the correct amount and return the pointer to let\n\t\t * it be deallocated when we return.\n\t\t */\n\t\tstruct shadow_copy_data *shadow_data = NULL;\n\t\tbool labels = False;\n\t\tuint32 labels_data_count = 0;\n\t\tuint32 i;\n\t\tchar *cur_pdata = NULL;\n\n\t\tif (max_out_len < 16) {\n\t\t\tDEBUG(0,(\"FSCTL_GET_SHADOW_COPY_DATA: max_data_count(%u) < 16 is invalid!\\n\",\n\t\t\t\tmax_out_len));\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\n\t\tif (max_out_len > 16) {\n\t\t\tlabels = True;\n\t\t}\n\n\t\tshadow_data = talloc_zero(ctx, struct shadow_copy_data);\n\t\tif (shadow_data == NULL) {\n\t\t\tDEBUG(0,(\"TALLOC_ZERO() failed!\\n\"));\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\n\t\t/*\n\t\t * Call the VFS routine to actually do the work.\n\t\t */\n\t\tif (SMB_VFS_GET_SHADOW_COPY_DATA(fsp, shadow_data, labels)!=0) {\n\t\t\tTALLOC_FREE(shadow_data);\n\t\t\tif (errno == ENOSYS) {\n\t\t\t\tDEBUG(5,(\"FSCTL_GET_SHADOW_COPY_DATA: connectpath %s, not supported.\\n\", \n\t\t\t\t\tfsp->conn->connectpath));\n\t\t\t\treturn NT_STATUS_NOT_SUPPORTED;\n\t\t\t} else {\n\t\t\t\tDEBUG(0,(\"FSCTL_GET_SHADOW_COPY_DATA: connectpath %s, failed.\\n\", \n\t\t\t\t\tfsp->conn->connectpath));\n\t\t\t\treturn NT_STATUS_UNSUCCESSFUL;\n\t\t\t}\n\t\t}\n\n\t\tlabels_data_count = (shadow_data->num_volumes * 2 * \n\t\t\t\t\tsizeof(SHADOW_COPY_LABEL)) + 2;\n\n\t\tif (!labels) {\n\t\t\t*out_len = 16;\n\t\t} else {\n\t\t\t*out_len = 12 + labels_data_count + 4;\n\t\t}\n\n\t\tif (max_out_len < *out_len) {\n\t\t\tDEBUG(0,(\"FSCTL_GET_SHADOW_COPY_DATA: max_data_count(%u) too small (%u) bytes needed!\\n\",\n\t\t\t\tmax_out_len, *out_len));\n\t\t\tTALLOC_FREE(shadow_data);\n\t\t\treturn NT_STATUS_BUFFER_TOO_SMALL;\n\t\t}\n\n\t\tcur_pdata = talloc_zero_array(ctx, char, *out_len);\n\t\tif (cur_pdata == NULL) {\n\t\t\tTALLOC_FREE(shadow_data);\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\n\t\t*out_data = cur_pdata;\n\n\t\t/* num_volumes 4 bytes */\n\t\tSIVAL(cur_pdata, 0, shadow_data->num_volumes);\n\n\t\tif (labels) {\n\t\t\t/* num_labels 4 bytes */\n\t\t\tSIVAL(cur_pdata, 4, shadow_data->num_volumes);\n\t\t}\n\n\t\t/* needed_data_count 4 bytes */\n\t\tSIVAL(cur_pdata, 8, labels_data_count + 4);\n\n\t\tcur_pdata += 12;\n\n\t\tDEBUG(10,(\"FSCTL_GET_SHADOW_COPY_DATA: %u volumes for path[%s].\\n\",\n\t\t\t  shadow_data->num_volumes, fsp_str_dbg(fsp)));\n\t\tif (labels && shadow_data->labels) {\n\t\t\tfor (i=0; inum_volumes; i++) {\n\t\t\t\tsrvstr_push(cur_pdata, req_flags,\n\t\t\t\t\t    cur_pdata, shadow_data->labels[i],\n\t\t\t\t\t    2 * sizeof(SHADOW_COPY_LABEL),\n\t\t\t\t\t    STR_UNICODE|STR_TERMINATE);\n\t\t\t\tcur_pdata += 2 * sizeof(SHADOW_COPY_LABEL);\n\t\t\t\tDEBUGADD(10,(\"Label[%u]: '%s'\\n\",i,shadow_data->labels[i]));\n\t\t\t}\n\t\t}\n\n\t\tTALLOC_FREE(shadow_data);\n\n\t\treturn NT_STATUS_OK;\n\t}\n\n\tcase FSCTL_FIND_FILES_BY_SID:\n\t{\n\t\t/* pretend this succeeded -\n\t\t *\n\t\t * we have to send back a list with all files owned by this SID\n\t\t *\n\t\t * but I have to check that --metze\n\t\t */\n\t\tstruct dom_sid sid;\n\t\tuid_t uid;\n\t\tsize_t sid_len;\n\n\t\tDEBUG(10, (\"FSCTL_FIND_FILES_BY_SID: called on %s\\n\",\n\t\t\t   fsp_fnum_dbg(fsp)));\n\n\t\tif (in_len < 8) {\n\t\t\t/* NT_STATUS_BUFFER_TOO_SMALL maybe? */\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\n\t\tsid_len = MIN(in_len - 4,SID_MAX_SIZE);\n\n\t\t/* unknown 4 bytes: this is not the length of the sid :-(  */\n\t\t/*unknown = IVAL(pdata,0);*/\n\n\t\tif (!sid_parse(in_data + 4, sid_len, &sid)) {\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\t\tDEBUGADD(10, (\"for SID: %s\\n\", sid_string_dbg(&sid)));\n\n\t\tif (!sid_to_uid(&sid, &uid)) {\n\t\t\tDEBUG(0,(\"sid_to_uid: failed, sid[%s] sid_len[%lu]\\n\",\n\t\t\t\t sid_string_dbg(&sid),\n\t\t\t\t (unsigned long)sid_len));\n\t\t\tuid = (-1);\n\t\t}\n\n\t\t/* we can take a look at the find source :-)\n\t\t *\n\t\t * find ./ -uid $uid  -name '*'   is what we need here\n\t\t *\n\t\t *\n\t\t * and send 4bytes len and then NULL terminated unicode strings\n\t\t * for each file\n\t\t *\n\t\t * but I don't know how to deal with the paged results\n\t\t * (maybe we can hang the result anywhere in the fsp struct)\n\t\t *\n\t\t * but I don't know how to deal with the paged results\n\t\t * (maybe we can hang the result anywhere in the fsp struct)\n\t\t *\n\t\t * we don't send all files at once\n\t\t * and at the next we should *not* start from the beginning,\n\t\t * so we have to cache the result\n\t\t *\n\t\t * --metze\n\t\t */\n\n\t\t/* this works for now... */\n\t\treturn NT_STATUS_OK;\n\t}\n\n\tcase FSCTL_QUERY_ALLOCATED_RANGES:\n\t{\n\t\t/* FIXME: This is just a dummy reply, telling that all of the\n\t\t * file is allocated. MKS cp needs that.\n\t\t * Adding the real allocated ranges via FIEMAP on Linux\n\t\t * and SEEK_DATA/SEEK_HOLE on Solaris is needed to make\n\t\t * this FSCTL correct for sparse files.\n\t\t */\n\t\tNTSTATUS status;\n\t\tuint64_t offset, length;\n\t\tchar *out_data_tmp = NULL;\n\n\t\tif (in_len != 16) {\n\t\t\tDEBUG(0,(\"FSCTL_QUERY_ALLOCATED_RANGES: data_count(%u) != 16 is invalid!\\n\",\n\t\t\t\tin_len));\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\n\t\tif (max_out_len < 16) {\n\t\t\tDEBUG(0,(\"FSCTL_QUERY_ALLOCATED_RANGES: max_out_len (%u) < 16 is invalid!\\n\",\n\t\t\t\tmax_out_len));\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\n\t\toffset = BVAL(in_data,0);\n\t\tlength = BVAL(in_data,8);\n\n\t\tif (offset + length < offset) {\n\t\t\t/* No 64-bit integer wrap. */\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\n\t\t/* Shouldn't this be SMB_VFS_STAT ... ? */\n\t\tstatus = vfs_stat_fsp(fsp);\n\t\tif (!NT_STATUS_IS_OK(status)) {\n\t\t\treturn status;\n\t\t}\n\n\t\t*out_len = 16;\n\t\tout_data_tmp = talloc_array(ctx, char, *out_len);\n\t\tif (out_data_tmp == NULL) {\n\t\t\tDEBUG(10, (\"unable to allocate memory for response\\n\"));\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\n\t\tif (offset > fsp->fsp_name->st.st_ex_size ||\n\t\t\t\tfsp->fsp_name->st.st_ex_size == 0 ||\n\t\t\t\tlength == 0) {\n\t\t\tmemset(out_data_tmp, 0, *out_len);\n\t\t} else {\n\t\t\tuint64_t end = offset + length;\n\t\t\tend = MIN(end, fsp->fsp_name->st.st_ex_size);\n\t\t\tSBVAL(out_data_tmp, 0, 0);\n\t\t\tSBVAL(out_data_tmp, 8, end);\n\t\t}\n\n\t\t*out_data = out_data_tmp;\n\n\t\treturn NT_STATUS_OK;\n\t}\n\n\tcase FSCTL_IS_VOLUME_DIRTY:\n\t{\n\t\tDEBUG(10,(\"FSCTL_IS_VOLUME_DIRTY: called on %s \"\n\t\t\t  \"(but remotely not supported)\\n\", fsp_fnum_dbg(fsp)));\n\t\t/*\n\t\t * http://msdn.microsoft.com/en-us/library/cc232128%28PROT.10%29.aspx\n\t\t * says we have to respond with NT_STATUS_INVALID_PARAMETER\n\t\t */\n\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t}\n\n\tdefault:\n\t\t/* \n\t\t * Only print once ... unfortunately there could be lots of\n\t\t * different FSCTLs that are called.\n\t\t */\n\t\tif (!vfswrap_logged_ioctl_message) {\n\t\t\tvfswrap_logged_ioctl_message = true;\n\t\t\tDEBUG(2, (\"%s (0x%x): Currently not implemented.\\n\",\n\t\t\t__func__, function));\n\t\t}\n\t}\n\n\treturn NT_STATUS_NOT_SUPPORTED;\n}", "func_hash": 216855121268945563940656517843611340199, "file_name": "vfs_default.c", "file_hash": 120656139704674873497493645428059774528, "cwe": ["CWE-665"], "cve": "CVE-2014-0178", "cve_desc": "Samba 3.6.6 through 3.6.23, 4.0.x before 4.0.18, and 4.1.x before 4.1.8, when a certain vfs shadow copy configuration is enabled, does not properly initialize the SRV_SNAPSHOT_ARRAY response field, which allows remote authenticated users to obtain potentially sensitive information from process memory via a (1) FSCTL_GET_SHADOW_COPY_DATA or (2) FSCTL_SRV_ENUMERATE_SNAPSHOTS request.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-0178"}
{"idx": 301429, "project": "samba", "commit_id": "eb50fb8f3bf670bd7d1cf8fd4368ef4a73083696", "project_url": "https://github.com/samba-team/samba", "commit_url": "http://git.samba.org/?p=samba.git;a=commitdiff;h=eb50fb8f3bf670bd7d1cf8fd4368ef4a73083696", "commit_message": "FSCTL_GET_SHADOW_COPY_DATA: Don't return 4 extra bytes at end\n\nlabels_data_count already accounts for the unicode null character at the\nend of the array. There is no need in adding space for it again.\n\nSigned-off-by: Christof Schmitt \nReviewed-by: Jeremy Allison \nReviewed-by: Simo Sorce \n\nAutobuild-User(master): Jeremy Allison \nAutobuild-Date(master): Tue Aug  6 04:03:17 CEST 2013 on sn-devel-104", "target": 0, "func": "static NTSTATUS vfswrap_fsctl(struct vfs_handle_struct *handle,\n\t\t\t      struct files_struct *fsp,\n\t\t\t      TALLOC_CTX *ctx,\n\t\t\t      uint32_t function,\n\t\t\t      uint16_t req_flags, /* Needed for UNICODE ... */\n\t\t\t      const uint8_t *_in_data,\n\t\t\t      uint32_t in_len,\n\t\t\t      uint8_t **_out_data,\n\t\t\t      uint32_t max_out_len,\n\t\t\t      uint32_t *out_len)\n{\n\tconst char *in_data = (const char *)_in_data;\n\tchar **out_data = (char **)_out_data;\n\n\tswitch (function) {\n\tcase FSCTL_SET_SPARSE:\n\t{\n\t\tbool set_sparse = true;\n\t\tNTSTATUS status;\n\n\t\tif (in_len >= 1 && in_data[0] == 0) {\n\t\t\tset_sparse = false;\n\t\t}\n\n\t\tstatus = file_set_sparse(handle->conn, fsp, set_sparse);\n\t\t\n\t\tDEBUG(NT_STATUS_IS_OK(status) ? 10 : 9,\n\t\t      (\"FSCTL_SET_SPARSE: fname[%s] set[%u] - %s\\n\",\n\t\t       smb_fname_str_dbg(fsp->fsp_name), set_sparse, \n\t\t       nt_errstr(status)));\n\n\t\treturn status;\n\t}\n\n\tcase FSCTL_CREATE_OR_GET_OBJECT_ID:\n\t{\n\t\tunsigned char objid[16];\n\t\tchar *return_data = NULL;\n\n\t\t/* This should return the object-id on this file.\n\t\t * I think I'll make this be the inode+dev. JRA.\n\t\t */\n\n\t\tDEBUG(10,(\"FSCTL_CREATE_OR_GET_OBJECT_ID: called on %s\\n\",\n\t\t\t  fsp_fnum_dbg(fsp)));\n\n\t\t*out_len = (max_out_len >= 64) ? 64 : max_out_len;\n\t\t/* Hmmm, will this cause problems if less data asked for? */\n\t\treturn_data = talloc_array(ctx, char, 64);\n\t\tif (return_data == NULL) {\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\n\t\t/* For backwards compatibility only store the dev/inode. */\n\t\tpush_file_id_16(return_data, &fsp->file_id);\n\t\tmemcpy(return_data+16,create_volume_objectid(fsp->conn,objid),16);\n\t\tpush_file_id_16(return_data+32, &fsp->file_id);\n\t\t*out_data = return_data;\n\t\treturn NT_STATUS_OK;\n\t}\n\n\tcase FSCTL_GET_REPARSE_POINT:\n\t{\n\t\t/* Fail it with STATUS_NOT_A_REPARSE_POINT */\n\t\tDEBUG(10, (\"FSCTL_GET_REPARSE_POINT: called on %s. \"\n\t\t\t   \"Status: NOT_IMPLEMENTED\\n\", fsp_fnum_dbg(fsp)));\n\t\treturn NT_STATUS_NOT_A_REPARSE_POINT;\n\t}\n\n\tcase FSCTL_SET_REPARSE_POINT:\n\t{\n\t\t/* Fail it with STATUS_NOT_A_REPARSE_POINT */\n\t\tDEBUG(10, (\"FSCTL_SET_REPARSE_POINT: called on %s. \"\n\t\t\t   \"Status: NOT_IMPLEMENTED\\n\", fsp_fnum_dbg(fsp)));\n\t\treturn NT_STATUS_NOT_A_REPARSE_POINT;\n\t}\n\n\tcase FSCTL_GET_SHADOW_COPY_DATA:\n\t{\n\t\t/*\n\t\t * This is called to retrieve the number of Shadow Copies (a.k.a. snapshots)\n\t\t * and return their volume names.  If max_data_count is 16, then it is just\n\t\t * asking for the number of volumes and length of the combined names.\n\t\t *\n\t\t * pdata is the data allocated by our caller, but that uses\n\t\t * total_data_count (which is 0 in our case) rather than max_data_count.\n\t\t * Allocate the correct amount and return the pointer to let\n\t\t * it be deallocated when we return.\n\t\t */\n\t\tstruct shadow_copy_data *shadow_data = NULL;\n\t\tbool labels = False;\n\t\tuint32 labels_data_count = 0;\n\t\tuint32 i;\n\t\tchar *cur_pdata = NULL;\n\n\t\tif (max_out_len < 16) {\n\t\t\tDEBUG(0,(\"FSCTL_GET_SHADOW_COPY_DATA: max_data_count(%u) < 16 is invalid!\\n\",\n\t\t\t\tmax_out_len));\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\n\t\tif (max_out_len > 16) {\n\t\t\tlabels = True;\n\t\t}\n\n\t\tshadow_data = talloc_zero(ctx, struct shadow_copy_data);\n\t\tif (shadow_data == NULL) {\n\t\t\tDEBUG(0,(\"TALLOC_ZERO() failed!\\n\"));\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\n\t\t/*\n\t\t * Call the VFS routine to actually do the work.\n\t\t */\n\t\tif (SMB_VFS_GET_SHADOW_COPY_DATA(fsp, shadow_data, labels)!=0) {\n\t\t\tTALLOC_FREE(shadow_data);\n\t\t\tif (errno == ENOSYS) {\n\t\t\t\tDEBUG(5,(\"FSCTL_GET_SHADOW_COPY_DATA: connectpath %s, not supported.\\n\", \n\t\t\t\t\tfsp->conn->connectpath));\n\t\t\t\treturn NT_STATUS_NOT_SUPPORTED;\n\t\t\t} else {\n\t\t\t\tDEBUG(0,(\"FSCTL_GET_SHADOW_COPY_DATA: connectpath %s, failed.\\n\", \n\t\t\t\t\tfsp->conn->connectpath));\n\t\t\t\treturn NT_STATUS_UNSUCCESSFUL;\n\t\t\t}\n\t\t}\n\n\t\tlabels_data_count = (shadow_data->num_volumes * 2 * \n\t\t\t\t\tsizeof(SHADOW_COPY_LABEL)) + 2;\n\n\t\tif (!labels) {\n\t\t\t*out_len = 16;\n\t\t} else {\n\t\t\t*out_len = 12 + labels_data_count;\n\t\t}\n\n\t\tif (max_out_len < *out_len) {\n\t\t\tDEBUG(0,(\"FSCTL_GET_SHADOW_COPY_DATA: max_data_count(%u) too small (%u) bytes needed!\\n\",\n\t\t\t\tmax_out_len, *out_len));\n\t\t\tTALLOC_FREE(shadow_data);\n\t\t\treturn NT_STATUS_BUFFER_TOO_SMALL;\n\t\t}\n\n\t\tcur_pdata = talloc_zero_array(ctx, char, *out_len);\n\t\tif (cur_pdata == NULL) {\n\t\t\tTALLOC_FREE(shadow_data);\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\n\t\t*out_data = cur_pdata;\n\n\t\t/* num_volumes 4 bytes */\n\t\tSIVAL(cur_pdata, 0, shadow_data->num_volumes);\n\n\t\tif (labels) {\n\t\t\t/* num_labels 4 bytes */\n\t\t\tSIVAL(cur_pdata, 4, shadow_data->num_volumes);\n\t\t}\n\n\t\t/* needed_data_count 4 bytes */\n\t\tSIVAL(cur_pdata, 8, labels_data_count);\n\n\t\tcur_pdata += 12;\n\n\t\tDEBUG(10,(\"FSCTL_GET_SHADOW_COPY_DATA: %u volumes for path[%s].\\n\",\n\t\t\t  shadow_data->num_volumes, fsp_str_dbg(fsp)));\n\t\tif (labels && shadow_data->labels) {\n\t\t\tfor (i=0; inum_volumes; i++) {\n\t\t\t\tsrvstr_push(cur_pdata, req_flags,\n\t\t\t\t\t    cur_pdata, shadow_data->labels[i],\n\t\t\t\t\t    2 * sizeof(SHADOW_COPY_LABEL),\n\t\t\t\t\t    STR_UNICODE|STR_TERMINATE);\n\t\t\t\tcur_pdata += 2 * sizeof(SHADOW_COPY_LABEL);\n\t\t\t\tDEBUGADD(10,(\"Label[%u]: '%s'\\n\",i,shadow_data->labels[i]));\n\t\t\t}\n\t\t}\n\n\t\tTALLOC_FREE(shadow_data);\n\n\t\treturn NT_STATUS_OK;\n\t}\n\n\tcase FSCTL_FIND_FILES_BY_SID:\n\t{\n\t\t/* pretend this succeeded -\n\t\t *\n\t\t * we have to send back a list with all files owned by this SID\n\t\t *\n\t\t * but I have to check that --metze\n\t\t */\n\t\tstruct dom_sid sid;\n\t\tuid_t uid;\n\t\tsize_t sid_len;\n\n\t\tDEBUG(10, (\"FSCTL_FIND_FILES_BY_SID: called on %s\\n\",\n\t\t\t   fsp_fnum_dbg(fsp)));\n\n\t\tif (in_len < 8) {\n\t\t\t/* NT_STATUS_BUFFER_TOO_SMALL maybe? */\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\n\t\tsid_len = MIN(in_len - 4,SID_MAX_SIZE);\n\n\t\t/* unknown 4 bytes: this is not the length of the sid :-(  */\n\t\t/*unknown = IVAL(pdata,0);*/\n\n\t\tif (!sid_parse(in_data + 4, sid_len, &sid)) {\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\t\tDEBUGADD(10, (\"for SID: %s\\n\", sid_string_dbg(&sid)));\n\n\t\tif (!sid_to_uid(&sid, &uid)) {\n\t\t\tDEBUG(0,(\"sid_to_uid: failed, sid[%s] sid_len[%lu]\\n\",\n\t\t\t\t sid_string_dbg(&sid),\n\t\t\t\t (unsigned long)sid_len));\n\t\t\tuid = (-1);\n\t\t}\n\n\t\t/* we can take a look at the find source :-)\n\t\t *\n\t\t * find ./ -uid $uid  -name '*'   is what we need here\n\t\t *\n\t\t *\n\t\t * and send 4bytes len and then NULL terminated unicode strings\n\t\t * for each file\n\t\t *\n\t\t * but I don't know how to deal with the paged results\n\t\t * (maybe we can hang the result anywhere in the fsp struct)\n\t\t *\n\t\t * but I don't know how to deal with the paged results\n\t\t * (maybe we can hang the result anywhere in the fsp struct)\n\t\t *\n\t\t * we don't send all files at once\n\t\t * and at the next we should *not* start from the beginning,\n\t\t * so we have to cache the result\n\t\t *\n\t\t * --metze\n\t\t */\n\n\t\t/* this works for now... */\n\t\treturn NT_STATUS_OK;\n\t}\n\n\tcase FSCTL_QUERY_ALLOCATED_RANGES:\n\t{\n\t\t/* FIXME: This is just a dummy reply, telling that all of the\n\t\t * file is allocated. MKS cp needs that.\n\t\t * Adding the real allocated ranges via FIEMAP on Linux\n\t\t * and SEEK_DATA/SEEK_HOLE on Solaris is needed to make\n\t\t * this FSCTL correct for sparse files.\n\t\t */\n\t\tNTSTATUS status;\n\t\tuint64_t offset, length;\n\t\tchar *out_data_tmp = NULL;\n\n\t\tif (in_len != 16) {\n\t\t\tDEBUG(0,(\"FSCTL_QUERY_ALLOCATED_RANGES: data_count(%u) != 16 is invalid!\\n\",\n\t\t\t\tin_len));\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\n\t\tif (max_out_len < 16) {\n\t\t\tDEBUG(0,(\"FSCTL_QUERY_ALLOCATED_RANGES: max_out_len (%u) < 16 is invalid!\\n\",\n\t\t\t\tmax_out_len));\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\n\t\toffset = BVAL(in_data,0);\n\t\tlength = BVAL(in_data,8);\n\n\t\tif (offset + length < offset) {\n\t\t\t/* No 64-bit integer wrap. */\n\t\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t\t}\n\n\t\t/* Shouldn't this be SMB_VFS_STAT ... ? */\n\t\tstatus = vfs_stat_fsp(fsp);\n\t\tif (!NT_STATUS_IS_OK(status)) {\n\t\t\treturn status;\n\t\t}\n\n\t\t*out_len = 16;\n\t\tout_data_tmp = talloc_array(ctx, char, *out_len);\n\t\tif (out_data_tmp == NULL) {\n\t\t\tDEBUG(10, (\"unable to allocate memory for response\\n\"));\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\n\t\tif (offset > fsp->fsp_name->st.st_ex_size ||\n\t\t\t\tfsp->fsp_name->st.st_ex_size == 0 ||\n\t\t\t\tlength == 0) {\n\t\t\tmemset(out_data_tmp, 0, *out_len);\n\t\t} else {\n\t\t\tuint64_t end = offset + length;\n\t\t\tend = MIN(end, fsp->fsp_name->st.st_ex_size);\n\t\t\tSBVAL(out_data_tmp, 0, 0);\n\t\t\tSBVAL(out_data_tmp, 8, end);\n\t\t}\n\n\t\t*out_data = out_data_tmp;\n\n\t\treturn NT_STATUS_OK;\n\t}\n\n\tcase FSCTL_IS_VOLUME_DIRTY:\n\t{\n\t\tDEBUG(10,(\"FSCTL_IS_VOLUME_DIRTY: called on %s \"\n\t\t\t  \"(but remotely not supported)\\n\", fsp_fnum_dbg(fsp)));\n\t\t/*\n\t\t * http://msdn.microsoft.com/en-us/library/cc232128%28PROT.10%29.aspx\n\t\t * says we have to respond with NT_STATUS_INVALID_PARAMETER\n\t\t */\n\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t}\n\n\tdefault:\n\t\t/* \n\t\t * Only print once ... unfortunately there could be lots of\n\t\t * different FSCTLs that are called.\n\t\t */\n\t\tif (!vfswrap_logged_ioctl_message) {\n\t\t\tvfswrap_logged_ioctl_message = true;\n\t\t\tDEBUG(2, (\"%s (0x%x): Currently not implemented.\\n\",\n\t\t\t__func__, function));\n\t\t}\n\t}\n\n\treturn NT_STATUS_NOT_SUPPORTED;\n}", "func_hash": 132063817933322219914210218512719915905, "file_name": "None", "file_hash": null, "cwe": ["CWE-665"], "cve": "CVE-2014-0178", "cve_desc": "Samba 3.6.6 through 3.6.23, 4.0.x before 4.0.18, and 4.1.x before 4.1.8, when a certain vfs shadow copy configuration is enabled, does not properly initialize the SRV_SNAPSHOT_ARRAY response field, which allows remote authenticated users to obtain potentially sensitive information from process memory via a (1) FSCTL_GET_SHADOW_COPY_DATA or (2) FSCTL_SRV_ENUMERATE_SNAPSHOTS request.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-0178"}
{"idx": 200323, "project": "vim", "commit_id": "156d3911952d73b03d7420dc3540215247db0fe8", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/156d3911952d73b03d7420dc3540215247db0fe8", "commit_message": "patch 8.2.5123: using invalid index when looking for spell suggestions\n\nProblem:    Using invalid index when looking for spell suggestions.\nSolution:   Do not decrement the index when it is zero.", "target": 1, "func": "suggest_trie_walk(\n    suginfo_T\t*su,\n    langp_T\t*lp,\n    char_u\t*fword,\n    int\t\tsoundfold)\n{\n    char_u\ttword[MAXWLEN];\t    // good word collected so far\n    trystate_T\tstack[MAXWLEN];\n    char_u\tpreword[MAXWLEN * 3]; // word found with proper case;\n\t\t\t\t      // concatenation of prefix compound\n\t\t\t\t      // words and split word.  NUL terminated\n\t\t\t\t      // when going deeper but not when coming\n\t\t\t\t      // back.\n    char_u\tcompflags[MAXWLEN];\t// compound flags, one for each word\n    trystate_T\t*sp;\n    int\t\tnewscore;\n    int\t\tscore;\n    char_u\t*byts, *fbyts, *pbyts;\n    idx_T\t*idxs, *fidxs, *pidxs;\n    int\t\tdepth;\n    int\t\tc, c2, c3;\n    int\t\tn = 0;\n    int\t\tflags;\n    garray_T\t*gap;\n    idx_T\tarridx;\n    int\t\tlen;\n    char_u\t*p;\n    fromto_T\t*ftp;\n    int\t\tfl = 0, tl;\n    int\t\trepextra = 0;\t    // extra bytes in fword[] from REP item\n    slang_T\t*slang = lp->lp_slang;\n    int\t\tfword_ends;\n    int\t\tgoodword_ends;\n#ifdef DEBUG_TRIEWALK\n    // Stores the name of the change made at each level.\n    char_u\tchangename[MAXWLEN][80];\n#endif\n    int\t\tbreakcheckcount = 1000;\n#ifdef FEAT_RELTIME\n    proftime_T\ttime_limit;\n#endif\n    int\t\tcompound_ok;\n\n    // Go through the whole case-fold tree, try changes at each node.\n    // \"tword[]\" contains the word collected from nodes in the tree.\n    // \"fword[]\" the word we are trying to match with (initially the bad\n    // word).\n    depth = 0;\n    sp = &stack[0];\n    CLEAR_POINTER(sp);\n    sp->ts_curi = 1;\n\n    if (soundfold)\n    {\n\t// Going through the soundfold tree.\n\tbyts = fbyts = slang->sl_sbyts;\n\tidxs = fidxs = slang->sl_sidxs;\n\tpbyts = NULL;\n\tpidxs = NULL;\n\tsp->ts_prefixdepth = PFD_NOPREFIX;\n\tsp->ts_state = STATE_START;\n    }\n    else\n    {\n\t// When there are postponed prefixes we need to use these first.  At\n\t// the end of the prefix we continue in the case-fold tree.\n\tfbyts = slang->sl_fbyts;\n\tfidxs = slang->sl_fidxs;\n\tpbyts = slang->sl_pbyts;\n\tpidxs = slang->sl_pidxs;\n\tif (pbyts != NULL)\n\t{\n\t    byts = pbyts;\n\t    idxs = pidxs;\n\t    sp->ts_prefixdepth = PFD_PREFIXTREE;\n\t    sp->ts_state = STATE_NOPREFIX;\t// try without prefix first\n\t}\n\telse\n\t{\n\t    byts = fbyts;\n\t    idxs = fidxs;\n\t    sp->ts_prefixdepth = PFD_NOPREFIX;\n\t    sp->ts_state = STATE_START;\n\t}\n    }\n#ifdef FEAT_RELTIME\n    // The loop may take an indefinite amount of time. Break out after some\n    // time.\n    if (spell_suggest_timeout > 0)\n\tprofile_setlimit(spell_suggest_timeout, &time_limit);\n#endif\n\n    // Loop to find all suggestions.  At each round we either:\n    // - For the current state try one operation, advance \"ts_curi\",\n    //   increase \"depth\".\n    // - When a state is done go to the next, set \"ts_state\".\n    // - When all states are tried decrease \"depth\".\n    while (depth >= 0 && !got_int)\n    {\n\tsp = &stack[depth];\n\tswitch (sp->ts_state)\n\t{\n\tcase STATE_START:\n\tcase STATE_NOPREFIX:\n\t    // Start of node: Deal with NUL bytes, which means\n\t    // tword[] may end here.\n\t    arridx = sp->ts_arridx;\t    // current node in the tree\n\t    len = byts[arridx];\t\t    // bytes in this node\n\t    arridx += sp->ts_curi;\t    // index of current byte\n\n\t    if (sp->ts_prefixdepth == PFD_PREFIXTREE)\n\t    {\n\t\t// Skip over the NUL bytes, we use them later.\n\t\tfor (n = 0; n < len && byts[arridx + n] == 0; ++n)\n\t\t    ;\n\t\tsp->ts_curi += n;\n\n\t\t// Always past NUL bytes now.\n\t\tn = (int)sp->ts_state;\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_ENDNUL;\n\t\tsp->ts_save_badflags = su->su_badflags;\n\n\t\t// At end of a prefix or at start of prefixtree: check for\n\t\t// following word.\n\t\tif (depth < MAXWLEN - 1\n\t\t\t    && (byts[arridx] == 0 || n == (int)STATE_NOPREFIX))\n\t\t{\n\t\t    // Set su->su_badflags to the caps type at this position.\n\t\t    // Use the caps type until here for the prefix itself.\n\t\t    if (has_mbyte)\n\t\t\tn = nofold_len(fword, sp->ts_fidx, su->su_badptr);\n\t\t    else\n\t\t\tn = sp->ts_fidx;\n\t\t    flags = badword_captype(su->su_badptr, su->su_badptr + n);\n\t\t    su->su_badflags = badword_captype(su->su_badptr + n,\n\t\t\t\t\t       su->su_badptr + su->su_badlen);\n#ifdef DEBUG_TRIEWALK\n\t\t    sprintf(changename[depth], \"prefix\");\n#endif\n\t\t    go_deeper(stack, depth, 0);\n\t\t    ++depth;\n\t\t    sp = &stack[depth];\n\t\t    sp->ts_prefixdepth = depth - 1;\n\t\t    byts = fbyts;\n\t\t    idxs = fidxs;\n\t\t    sp->ts_arridx = 0;\n\n\t\t    // Move the prefix to preword[] with the right case\n\t\t    // and make find_keepcap_word() works.\n\t\t    tword[sp->ts_twordlen] = NUL;\n\t\t    make_case_word(tword + sp->ts_splitoff,\n\t\t\t\t\t  preword + sp->ts_prewordlen, flags);\n\t\t    sp->ts_prewordlen = (char_u)STRLEN(preword);\n\t\t    sp->ts_splitoff = sp->ts_twordlen;\n\t\t}\n\t\tbreak;\n\t    }\n\n\t    if (sp->ts_curi > len || byts[arridx] != 0)\n\t    {\n\t\t// Past bytes in node and/or past NUL bytes.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_ENDNUL;\n\t\tsp->ts_save_badflags = su->su_badflags;\n\t\tbreak;\n\t    }\n\n\t    // End of word in tree.\n\t    ++sp->ts_curi;\t\t// eat one NUL byte\n\n\t    flags = (int)idxs[arridx];\n\n\t    // Skip words with the NOSUGGEST flag.\n\t    if (flags & WF_NOSUGGEST)\n\t\tbreak;\n\n\t    fword_ends = (fword[sp->ts_fidx] == NUL\n\t\t\t   || (soundfold\n\t\t\t       ? VIM_ISWHITE(fword[sp->ts_fidx])\n\t\t\t       : !spell_iswordp(fword + sp->ts_fidx, curwin)));\n\t    tword[sp->ts_twordlen] = NUL;\n\n\t    if (sp->ts_prefixdepth <= PFD_NOTSPECIAL\n\t\t\t\t\t&& (sp->ts_flags & TSF_PREFIXOK) == 0\n\t\t\t\t\t&& pbyts != NULL)\n\t    {\n\t\t// There was a prefix before the word.  Check that the prefix\n\t\t// can be used with this word.\n\t\t// Count the length of the NULs in the prefix.  If there are\n\t\t// none this must be the first try without a prefix.\n\t\tn = stack[sp->ts_prefixdepth].ts_arridx;\n\t\tlen = pbyts[n++];\n\t\tfor (c = 0; c < len && pbyts[n + c] == 0; ++c)\n\t\t    ;\n\t\tif (c > 0)\n\t\t{\n\t\t    c = valid_word_prefix(c, n, flags,\n\t\t\t\t       tword + sp->ts_splitoff, slang, FALSE);\n\t\t    if (c == 0)\n\t\t\tbreak;\n\n\t\t    // Use the WF_RARE flag for a rare prefix.\n\t\t    if (c & WF_RAREPFX)\n\t\t\tflags |= WF_RARE;\n\n\t\t    // Tricky: when checking for both prefix and compounding\n\t\t    // we run into the prefix flag first.\n\t\t    // Remember that it's OK, so that we accept the prefix\n\t\t    // when arriving at a compound flag.\n\t\t    sp->ts_flags |= TSF_PREFIXOK;\n\t\t}\n\t    }\n\n\t    // Check NEEDCOMPOUND: can't use word without compounding.  Do try\n\t    // appending another compound word below.\n\t    if (sp->ts_complen == sp->ts_compsplit && fword_ends\n\t\t\t\t\t\t     && (flags & WF_NEEDCOMP))\n\t\tgoodword_ends = FALSE;\n\t    else\n\t\tgoodword_ends = TRUE;\n\n\t    p = NULL;\n\t    compound_ok = TRUE;\n\t    if (sp->ts_complen > sp->ts_compsplit)\n\t    {\n\t\tif (slang->sl_nobreak)\n\t\t{\n\t\t    // There was a word before this word.  When there was no\n\t\t    // change in this word (it was correct) add the first word\n\t\t    // as a suggestion.  If this word was corrected too, we\n\t\t    // need to check if a correct word follows.\n\t\t    if (sp->ts_fidx - sp->ts_splitfidx\n\t\t\t\t\t  == sp->ts_twordlen - sp->ts_splitoff\n\t\t\t    && STRNCMP(fword + sp->ts_splitfidx,\n\t\t\t\t\ttword + sp->ts_splitoff,\n\t\t\t\t\t sp->ts_fidx - sp->ts_splitfidx) == 0)\n\t\t    {\n\t\t\tpreword[sp->ts_prewordlen] = NUL;\n\t\t\tnewscore = score_wordcount_adj(slang, sp->ts_score,\n\t\t\t\t\t\t preword + sp->ts_prewordlen,\n\t\t\t\t\t\t sp->ts_prewordlen > 0);\n\t\t\t// Add the suggestion if the score isn't too bad.\n\t\t\tif (newscore <= su->su_maxscore)\n\t\t\t    add_suggestion(su, &su->su_ga, preword,\n\t\t\t\t    sp->ts_splitfidx - repextra,\n\t\t\t\t    newscore, 0, FALSE,\n\t\t\t\t    lp->lp_sallang, FALSE);\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    // There was a compound word before this word.  If this\n\t\t    // word does not support compounding then give up\n\t\t    // (splitting is tried for the word without compound\n\t\t    // flag).\n\t\t    if (((unsigned)flags >> 24) == 0\n\t\t\t    || sp->ts_twordlen - sp->ts_splitoff\n\t\t\t\t\t\t       < slang->sl_compminlen)\n\t\t\tbreak;\n\t\t    // For multi-byte chars check character length against\n\t\t    // COMPOUNDMIN.\n\t\t    if (has_mbyte\n\t\t\t    && slang->sl_compminlen > 0\n\t\t\t    && mb_charlen(tword + sp->ts_splitoff)\n\t\t\t\t\t\t       < slang->sl_compminlen)\n\t\t\tbreak;\n\n\t\t    compflags[sp->ts_complen] = ((unsigned)flags >> 24);\n\t\t    compflags[sp->ts_complen + 1] = NUL;\n\t\t    vim_strncpy(preword + sp->ts_prewordlen,\n\t\t\t    tword + sp->ts_splitoff,\n\t\t\t    sp->ts_twordlen - sp->ts_splitoff);\n\n\t\t    // Verify CHECKCOMPOUNDPATTERN  rules.\n\t\t    if (match_checkcompoundpattern(preword,  sp->ts_prewordlen,\n\t\t\t\t\t\t\t  &slang->sl_comppat))\n\t\t\tcompound_ok = FALSE;\n\n\t\t    if (compound_ok)\n\t\t    {\n\t\t\tp = preword;\n\t\t\twhile (*skiptowhite(p) != NUL)\n\t\t\t    p = skipwhite(skiptowhite(p));\n\t\t\tif (fword_ends && !can_compound(slang, p,\n\t\t\t\t\t\tcompflags + sp->ts_compsplit))\n\t\t\t    // Compound is not allowed.  But it may still be\n\t\t\t    // possible if we add another (short) word.\n\t\t\t    compound_ok = FALSE;\n\t\t    }\n\n\t\t    // Get pointer to last char of previous word.\n\t\t    p = preword + sp->ts_prewordlen;\n\t\t    MB_PTR_BACK(preword, p);\n\t\t}\n\t    }\n\n\t    // Form the word with proper case in preword.\n\t    // If there is a word from a previous split, append.\n\t    // For the soundfold tree don't change the case, simply append.\n\t    if (soundfold)\n\t\tSTRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff);\n\t    else if (flags & WF_KEEPCAP)\n\t\t// Must find the word in the keep-case tree.\n\t\tfind_keepcap_word(slang, tword + sp->ts_splitoff,\n\t\t\t\t\t\t preword + sp->ts_prewordlen);\n\t    else\n\t    {\n\t\t// Include badflags: If the badword is onecap or allcap\n\t\t// use that for the goodword too.  But if the badword is\n\t\t// allcap and it's only one char long use onecap.\n\t\tc = su->su_badflags;\n\t\tif ((c & WF_ALLCAP)\n\t\t\t&& su->su_badlen == (*mb_ptr2len)(su->su_badptr))\n\t\t    c = WF_ONECAP;\n\t\tc |= flags;\n\n\t\t// When appending a compound word after a word character don't\n\t\t// use Onecap.\n\t\tif (p != NULL && spell_iswordp_nmw(p, curwin))\n\t\t    c &= ~WF_ONECAP;\n\t\tmake_case_word(tword + sp->ts_splitoff,\n\t\t\t\t\t      preword + sp->ts_prewordlen, c);\n\t    }\n\n\t    if (!soundfold)\n\t    {\n\t\t// Don't use a banned word.  It may appear again as a good\n\t\t// word, thus remember it.\n\t\tif (flags & WF_BANNED)\n\t\t{\n\t\t    add_banned(su, preword + sp->ts_prewordlen);\n\t\t    break;\n\t\t}\n\t\tif ((sp->ts_complen == sp->ts_compsplit\n\t\t\t    && WAS_BANNED(su, preword + sp->ts_prewordlen))\n\t\t\t\t\t\t   || WAS_BANNED(su, preword))\n\t\t{\n\t\t    if (slang->sl_compprog == NULL)\n\t\t\tbreak;\n\t\t    // the word so far was banned but we may try compounding\n\t\t    goodword_ends = FALSE;\n\t\t}\n\t    }\n\n\t    newscore = 0;\n\t    if (!soundfold)\t// soundfold words don't have flags\n\t    {\n\t\tif ((flags & WF_REGION)\n\t\t\t    && (((unsigned)flags >> 16) & lp->lp_region) == 0)\n\t\t    newscore += SCORE_REGION;\n\t\tif (flags & WF_RARE)\n\t\t    newscore += SCORE_RARE;\n\n\t\tif (!spell_valid_case(su->su_badflags,\n\t\t\t\t  captype(preword + sp->ts_prewordlen, NULL)))\n\t\t    newscore += SCORE_ICASE;\n\t    }\n\n\t    // TODO: how about splitting in the soundfold tree?\n\t    if (fword_ends\n\t\t    && goodword_ends\n\t\t    && sp->ts_fidx >= sp->ts_fidxtry\n\t\t    && compound_ok)\n\t    {\n\t\t// The badword also ends: add suggestions.\n#ifdef DEBUG_TRIEWALK\n\t\tif (soundfold && STRCMP(preword, \"smwrd\") == 0)\n\t\t{\n\t\t    int\t    j;\n\n\t\t    // print the stack of changes that brought us here\n\t\t    smsg(\"------ %s -------\", fword);\n\t\t    for (j = 0; j < depth; ++j)\n\t\t\tsmsg(\"%s\", changename[j]);\n\t\t}\n#endif\n\t\tif (soundfold)\n\t\t{\n\t\t    // For soundfolded words we need to find the original\n\t\t    // words, the edit distance and then add them.\n\t\t    add_sound_suggest(su, preword, sp->ts_score, lp);\n\t\t}\n\t\telse if (sp->ts_fidx > 0)\n\t\t{\n\t\t    // Give a penalty when changing non-word char to word\n\t\t    // char, e.g., \"thes,\" -> \"these\".\n\t\t    p = fword + sp->ts_fidx;\n\t\t    MB_PTR_BACK(fword, p);\n\t\t    if (!spell_iswordp(p, curwin) && *preword != NUL)\n\t\t    {\n\t\t\tp = preword + STRLEN(preword);\n\t\t\tMB_PTR_BACK(preword, p);\n\t\t\tif (spell_iswordp(p, curwin))\n\t\t\t    newscore += SCORE_NONWORD;\n\t\t    }\n\n\t\t    // Give a bonus to words seen before.\n\t\t    score = score_wordcount_adj(slang,\n\t\t\t\t\t\tsp->ts_score + newscore,\n\t\t\t\t\t\tpreword + sp->ts_prewordlen,\n\t\t\t\t\t\tsp->ts_prewordlen > 0);\n\n\t\t    // Add the suggestion if the score isn't too bad.\n\t\t    if (score <= su->su_maxscore)\n\t\t    {\n\t\t\tadd_suggestion(su, &su->su_ga, preword,\n\t\t\t\t    sp->ts_fidx - repextra,\n\t\t\t\t    score, 0, FALSE, lp->lp_sallang, FALSE);\n\n\t\t\tif (su->su_badflags & WF_MIXCAP)\n\t\t\t{\n\t\t\t    // We really don't know if the word should be\n\t\t\t    // upper or lower case, add both.\n\t\t\t    c = captype(preword, NULL);\n\t\t\t    if (c == 0 || c == WF_ALLCAP)\n\t\t\t    {\n\t\t\t\tmake_case_word(tword + sp->ts_splitoff,\n\t\t\t\t\t      preword + sp->ts_prewordlen,\n\t\t\t\t\t\t      c == 0 ? WF_ALLCAP : 0);\n\n\t\t\t\tadd_suggestion(su, &su->su_ga, preword,\n\t\t\t\t\tsp->ts_fidx - repextra,\n\t\t\t\t\tscore + SCORE_ICASE, 0, FALSE,\n\t\t\t\t\tlp->lp_sallang, FALSE);\n\t\t\t    }\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\n\t    // Try word split and/or compounding.\n\t    if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends)\n\t\t    // Don't split halfway a character.\n\t\t    && (!has_mbyte || sp->ts_tcharlen == 0))\n\t    {\n\t\tint\ttry_compound;\n\t\tint\ttry_split;\n\n\t\t// If past the end of the bad word don't try a split.\n\t\t// Otherwise try changing the next word.  E.g., find\n\t\t// suggestions for \"the the\" where the second \"the\" is\n\t\t// different.  It's done like a split.\n\t\t// TODO: word split for soundfold words\n\t\ttry_split = (sp->ts_fidx - repextra < su->su_badlen)\n\t\t\t\t\t\t\t\t&& !soundfold;\n\n\t\t// Get here in several situations:\n\t\t// 1. The word in the tree ends:\n\t\t//    If the word allows compounding try that.  Otherwise try\n\t\t//    a split by inserting a space.  For both check that a\n\t\t//    valid words starts at fword[sp->ts_fidx].\n\t\t//    For NOBREAK do like compounding to be able to check if\n\t\t//    the next word is valid.\n\t\t// 2. The badword does end, but it was due to a change (e.g.,\n\t\t//    a swap).  No need to split, but do check that the\n\t\t//    following word is valid.\n\t\t// 3. The badword and the word in the tree end.  It may still\n\t\t//    be possible to compound another (short) word.\n\t\ttry_compound = FALSE;\n\t\tif (!soundfold\n\t\t\t&& !slang->sl_nocompoundsugs\n\t\t\t&& slang->sl_compprog != NULL\n\t\t\t&& ((unsigned)flags >> 24) != 0\n\t\t\t&& sp->ts_twordlen - sp->ts_splitoff\n\t\t\t\t\t\t       >= slang->sl_compminlen\n\t\t\t&& (!has_mbyte\n\t\t\t    || slang->sl_compminlen == 0\n\t\t\t    || mb_charlen(tword + sp->ts_splitoff)\n\t\t\t\t\t\t      >= slang->sl_compminlen)\n\t\t\t&& (slang->sl_compsylmax < MAXWLEN\n\t\t\t    || sp->ts_complen + 1 - sp->ts_compsplit\n\t\t\t\t\t\t\t  < slang->sl_compmax)\n\t\t\t&& (can_be_compound(sp, slang,\n\t\t\t\t\t compflags, ((unsigned)flags >> 24))))\n\n\t\t{\n\t\t    try_compound = TRUE;\n\t\t    compflags[sp->ts_complen] = ((unsigned)flags >> 24);\n\t\t    compflags[sp->ts_complen + 1] = NUL;\n\t\t}\n\n\t\t// For NOBREAK we never try splitting, it won't make any word\n\t\t// valid.\n\t\tif (slang->sl_nobreak && !slang->sl_nocompoundsugs)\n\t\t    try_compound = TRUE;\n\n\t\t// If we could add a compound word, and it's also possible to\n\t\t// split at this point, do the split first and set\n\t\t// TSF_DIDSPLIT to avoid doing it again.\n\t\telse if (!fword_ends\n\t\t\t&& try_compound\n\t\t\t&& (sp->ts_flags & TSF_DIDSPLIT) == 0)\n\t\t{\n\t\t    try_compound = FALSE;\n\t\t    sp->ts_flags |= TSF_DIDSPLIT;\n\t\t    --sp->ts_curi;\t    // do the same NUL again\n\t\t    compflags[sp->ts_complen] = NUL;\n\t\t}\n\t\telse\n\t\t    sp->ts_flags &= ~TSF_DIDSPLIT;\n\n\t\tif (try_split || try_compound)\n\t\t{\n\t\t    if (!try_compound && (!fword_ends || !goodword_ends))\n\t\t    {\n\t\t\t// If we're going to split need to check that the\n\t\t\t// words so far are valid for compounding.  If there\n\t\t\t// is only one word it must not have the NEEDCOMPOUND\n\t\t\t// flag.\n\t\t\tif (sp->ts_complen == sp->ts_compsplit\n\t\t\t\t\t\t     && (flags & WF_NEEDCOMP))\n\t\t\t    break;\n\t\t\tp = preword;\n\t\t\twhile (*skiptowhite(p) != NUL)\n\t\t\t    p = skipwhite(skiptowhite(p));\n\t\t\tif (sp->ts_complen > sp->ts_compsplit\n\t\t\t\t&& !can_compound(slang, p,\n\t\t\t\t\t\tcompflags + sp->ts_compsplit))\n\t\t\t    break;\n\n\t\t\tif (slang->sl_nosplitsugs)\n\t\t\t    newscore += SCORE_SPLIT_NO;\n\t\t\telse\n\t\t\t    newscore += SCORE_SPLIT;\n\n\t\t\t// Give a bonus to words seen before.\n\t\t\tnewscore = score_wordcount_adj(slang, newscore,\n\t\t\t\t\t   preword + sp->ts_prewordlen, TRUE);\n\t\t    }\n\n\t\t    if (TRY_DEEPER(su, stack, depth, newscore))\n\t\t    {\n\t\t\tgo_deeper(stack, depth, newscore);\n#ifdef DEBUG_TRIEWALK\n\t\t\tif (!try_compound && !fword_ends)\n\t\t\t    sprintf(changename[depth], \"%.*s-%s: split\",\n\t\t\t\t sp->ts_twordlen, tword, fword + sp->ts_fidx);\n\t\t\telse\n\t\t\t    sprintf(changename[depth], \"%.*s-%s: compound\",\n\t\t\t\t sp->ts_twordlen, tword, fword + sp->ts_fidx);\n#endif\n\t\t\t// Save things to be restored at STATE_SPLITUNDO.\n\t\t\tsp->ts_save_badflags = su->su_badflags;\n\t\t\tPROF_STORE(sp->ts_state)\n\t\t\tsp->ts_state = STATE_SPLITUNDO;\n\n\t\t\t++depth;\n\t\t\tsp = &stack[depth];\n\n\t\t\t// Append a space to preword when splitting.\n\t\t\tif (!try_compound && !fword_ends)\n\t\t\t    STRCAT(preword, \" \");\n\t\t\tsp->ts_prewordlen = (char_u)STRLEN(preword);\n\t\t\tsp->ts_splitoff = sp->ts_twordlen;\n\t\t\tsp->ts_splitfidx = sp->ts_fidx;\n\n\t\t\t// If the badword has a non-word character at this\n\t\t\t// position skip it.  That means replacing the\n\t\t\t// non-word character with a space.  Always skip a\n\t\t\t// character when the word ends.  But only when the\n\t\t\t// good word can end.\n\t\t\tif (((!try_compound && !spell_iswordp_nmw(fword\n\t\t\t\t\t\t\t       + sp->ts_fidx,\n\t\t\t\t\t\t\t       curwin))\n\t\t\t\t    || fword_ends)\n\t\t\t\t&& fword[sp->ts_fidx] != NUL\n\t\t\t\t&& goodword_ends)\n\t\t\t{\n\t\t\t    int\t    l;\n\n\t\t\t    l = mb_ptr2len(fword + sp->ts_fidx);\n\t\t\t    if (fword_ends)\n\t\t\t    {\n\t\t\t\t// Copy the skipped character to preword.\n\t\t\t\tmch_memmove(preword + sp->ts_prewordlen,\n\t\t\t\t\t\t      fword + sp->ts_fidx, l);\n\t\t\t\tsp->ts_prewordlen += l;\n\t\t\t\tpreword[sp->ts_prewordlen] = NUL;\n\t\t\t    }\n\t\t\t    else\n\t\t\t\tsp->ts_score -= SCORE_SPLIT - SCORE_SUBST;\n\t\t\t    sp->ts_fidx += l;\n\t\t\t}\n\n\t\t\t// When compounding include compound flag in\n\t\t\t// compflags[] (already set above).  When splitting we\n\t\t\t// may start compounding over again.\n\t\t\tif (try_compound)\n\t\t\t    ++sp->ts_complen;\n\t\t\telse\n\t\t\t    sp->ts_compsplit = sp->ts_complen;\n\t\t\tsp->ts_prefixdepth = PFD_NOPREFIX;\n\n\t\t\t// set su->su_badflags to the caps type at this\n\t\t\t// position\n\t\t\tif (has_mbyte)\n\t\t\t    n = nofold_len(fword, sp->ts_fidx, su->su_badptr);\n\t\t\telse\n\t\t\t    n = sp->ts_fidx;\n\t\t\tsu->su_badflags = badword_captype(su->su_badptr + n,\n\t\t\t\t\t       su->su_badptr + su->su_badlen);\n\n\t\t\t// Restart at top of the tree.\n\t\t\tsp->ts_arridx = 0;\n\n\t\t\t// If there are postponed prefixes, try these too.\n\t\t\tif (pbyts != NULL)\n\t\t\t{\n\t\t\t    byts = pbyts;\n\t\t\t    idxs = pidxs;\n\t\t\t    sp->ts_prefixdepth = PFD_PREFIXTREE;\n\t\t\t    PROF_STORE(sp->ts_state)\n\t\t\t    sp->ts_state = STATE_NOPREFIX;\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\t    break;\n\n\tcase STATE_SPLITUNDO:\n\t    // Undo the changes done for word split or compound word.\n\t    su->su_badflags = sp->ts_save_badflags;\n\n\t    // Continue looking for NUL bytes.\n\t    PROF_STORE(sp->ts_state)\n\t    sp->ts_state = STATE_START;\n\n\t    // In case we went into the prefix tree.\n\t    byts = fbyts;\n\t    idxs = fidxs;\n\t    break;\n\n\tcase STATE_ENDNUL:\n\t    // Past the NUL bytes in the node.\n\t    su->su_badflags = sp->ts_save_badflags;\n\t    if (fword[sp->ts_fidx] == NUL && sp->ts_tcharlen == 0)\n\t    {\n\t\t// The badword ends, can't use STATE_PLAIN.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_DEL;\n\t\tbreak;\n\t    }\n\t    PROF_STORE(sp->ts_state)\n\t    sp->ts_state = STATE_PLAIN;\n\t    // FALLTHROUGH\n\n\tcase STATE_PLAIN:\n\t    // Go over all possible bytes at this node, add each to tword[]\n\t    // and use child node.  \"ts_curi\" is the index.\n\t    arridx = sp->ts_arridx;\n\t    if (sp->ts_curi > byts[arridx])\n\t    {\n\t\t// Done all bytes at this node, do next state.  When still at\n\t\t// already changed bytes skip the other tricks.\n\t\tPROF_STORE(sp->ts_state)\n\t\tif (sp->ts_fidx >= sp->ts_fidxtry)\n\t\t    sp->ts_state = STATE_DEL;\n\t\telse\n\t\t    sp->ts_state = STATE_FINAL;\n\t    }\n\t    else\n\t    {\n\t\tarridx += sp->ts_curi++;\n\t\tc = byts[arridx];\n\n\t\t// Normal byte, go one level deeper.  If it's not equal to the\n\t\t// byte in the bad word adjust the score.  But don't even try\n\t\t// when the byte was already changed.  And don't try when we\n\t\t// just deleted this byte, accepting it is always cheaper than\n\t\t// delete + substitute.\n\t\tif (c == fword[sp->ts_fidx]\n\t\t\t|| (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE))\n\t\t    newscore = 0;\n\t\telse\n\t\t    newscore = SCORE_SUBST;\n\t\tif ((newscore == 0\n\t\t\t    || (sp->ts_fidx >= sp->ts_fidxtry\n\t\t\t\t&& ((sp->ts_flags & TSF_DIDDEL) == 0\n\t\t\t\t    || c != fword[sp->ts_delidx])))\n\t\t\t&& TRY_DEEPER(su, stack, depth, newscore))\n\t\t{\n\t\t    go_deeper(stack, depth, newscore);\n#ifdef DEBUG_TRIEWALK\n\t\t    if (newscore > 0)\n\t\t\tsprintf(changename[depth], \"%.*s-%s: subst %c to %c\",\n\t\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\t\tfword[sp->ts_fidx], c);\n\t\t    else\n\t\t\tsprintf(changename[depth], \"%.*s-%s: accept %c\",\n\t\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\t\tfword[sp->ts_fidx]);\n#endif\n\t\t    ++depth;\n\t\t    sp = &stack[depth];\n\t\t    if (fword[sp->ts_fidx] != NUL)\n\t\t\t++sp->ts_fidx;\n\t\t    tword[sp->ts_twordlen++] = c;\n\t\t    sp->ts_arridx = idxs[arridx];\n\t\t    if (newscore == SCORE_SUBST)\n\t\t\tsp->ts_isdiff = DIFF_YES;\n\t\t    if (has_mbyte)\n\t\t    {\n\t\t\t// Multi-byte characters are a bit complicated to\n\t\t\t// handle: They differ when any of the bytes differ\n\t\t\t// and then their length may also differ.\n\t\t\tif (sp->ts_tcharlen == 0)\n\t\t\t{\n\t\t\t    // First byte.\n\t\t\t    sp->ts_tcharidx = 0;\n\t\t\t    sp->ts_tcharlen = MB_BYTE2LEN(c);\n\t\t\t    sp->ts_fcharstart = sp->ts_fidx - 1;\n\t\t\t    sp->ts_isdiff = (newscore != 0)\n\t\t\t\t\t\t       ? DIFF_YES : DIFF_NONE;\n\t\t\t}\n\t\t\telse if (sp->ts_isdiff == DIFF_INSERT)\n\t\t\t    // When inserting trail bytes don't advance in the\n\t\t\t    // bad word.\n\t\t\t    --sp->ts_fidx;\n\t\t\tif (++sp->ts_tcharidx == sp->ts_tcharlen)\n\t\t\t{\n\t\t\t    // Last byte of character.\n\t\t\t    if (sp->ts_isdiff == DIFF_YES)\n\t\t\t    {\n\t\t\t\t// Correct ts_fidx for the byte length of the\n\t\t\t\t// character (we didn't check that before).\n\t\t\t\tsp->ts_fidx = sp->ts_fcharstart\n\t\t\t\t\t    + mb_ptr2len(\n\t\t\t\t\t\t    fword + sp->ts_fcharstart);\n\t\t\t\t// For changing a composing character adjust\n\t\t\t\t// the score from SCORE_SUBST to\n\t\t\t\t// SCORE_SUBCOMP.\n\t\t\t\tif (enc_utf8\n\t\t\t\t\t&& utf_iscomposing(\n\t\t\t\t\t    utf_ptr2char(tword\n\t\t\t\t\t\t+ sp->ts_twordlen\n\t\t\t\t\t\t\t   - sp->ts_tcharlen))\n\t\t\t\t\t&& utf_iscomposing(\n\t\t\t\t\t    utf_ptr2char(fword\n\t\t\t\t\t\t\t+ sp->ts_fcharstart)))\n\t\t\t\t    sp->ts_score -=\n\t\t\t\t\t\t  SCORE_SUBST - SCORE_SUBCOMP;\n\n\t\t\t\t// For a similar character adjust score from\n\t\t\t\t// SCORE_SUBST to SCORE_SIMILAR.\n\t\t\t\telse if (!soundfold\n\t\t\t\t\t&& slang->sl_has_map\n\t\t\t\t\t&& similar_chars(slang,\n\t\t\t\t\t    mb_ptr2char(tword\n\t\t\t\t\t\t+ sp->ts_twordlen\n\t\t\t\t\t\t\t   - sp->ts_tcharlen),\n\t\t\t\t\t    mb_ptr2char(fword\n\t\t\t\t\t\t\t+ sp->ts_fcharstart)))\n\t\t\t\t    sp->ts_score -=\n\t\t\t\t\t\t  SCORE_SUBST - SCORE_SIMILAR;\n\t\t\t    }\n\t\t\t    else if (sp->ts_isdiff == DIFF_INSERT\n\t\t\t\t\t && sp->ts_twordlen > sp->ts_tcharlen)\n\t\t\t    {\n\t\t\t\tp = tword + sp->ts_twordlen - sp->ts_tcharlen;\n\t\t\t\tc = mb_ptr2char(p);\n\t\t\t\tif (enc_utf8 && utf_iscomposing(c))\n\t\t\t\t{\n\t\t\t\t    // Inserting a composing char doesn't\n\t\t\t\t    // count that much.\n\t\t\t\t    sp->ts_score -= SCORE_INS - SCORE_INSCOMP;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t    // If the previous character was the same,\n\t\t\t\t    // thus doubling a character, give a bonus\n\t\t\t\t    // to the score.  Also for the soundfold\n\t\t\t\t    // tree (might seem illogical but does\n\t\t\t\t    // give better scores).\n\t\t\t\t    MB_PTR_BACK(tword, p);\n\t\t\t\t    if (c == mb_ptr2char(p))\n\t\t\t\t\tsp->ts_score -= SCORE_INS\n\t\t\t\t\t\t\t       - SCORE_INSDUP;\n\t\t\t\t}\n\t\t\t    }\n\n\t\t\t    // Starting a new char, reset the length.\n\t\t\t    sp->ts_tcharlen = 0;\n\t\t\t}\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\t// If we found a similar char adjust the score.\n\t\t\t// We do this after calling go_deeper() because\n\t\t\t// it's slow.\n\t\t\tif (newscore != 0\n\t\t\t\t&& !soundfold\n\t\t\t\t&& slang->sl_has_map\n\t\t\t\t&& similar_chars(slang,\n\t\t\t\t\t\t   c, fword[sp->ts_fidx - 1]))\n\t\t\t    sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR;\n\t\t    }\n\t\t}\n\t    }\n\t    break;\n\n\tcase STATE_DEL:\n\t    // When past the first byte of a multi-byte char don't try\n\t    // delete/insert/swap a character.\n\t    if (has_mbyte && sp->ts_tcharlen > 0)\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t\tbreak;\n\t    }\n\t    // Try skipping one character in the bad word (delete it).\n\t    PROF_STORE(sp->ts_state)\n\t    sp->ts_state = STATE_INS_PREP;\n\t    sp->ts_curi = 1;\n\t    if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*')\n\t\t// Deleting a vowel at the start of a word counts less, see\n\t\t// soundalike_score().\n\t\tnewscore = 2 * SCORE_DEL / 3;\n\t    else\n\t\tnewscore = SCORE_DEL;\n\t    if (fword[sp->ts_fidx] != NUL\n\t\t\t\t    && TRY_DEEPER(su, stack, depth, newscore))\n\t    {\n\t\tgo_deeper(stack, depth, newscore);\n#ifdef DEBUG_TRIEWALK\n\t\tsprintf(changename[depth], \"%.*s-%s: delete %c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tfword[sp->ts_fidx]);\n#endif\n\t\t++depth;\n\n\t\t// Remember what character we deleted, so that we can avoid\n\t\t// inserting it again.\n\t\tstack[depth].ts_flags |= TSF_DIDDEL;\n\t\tstack[depth].ts_delidx = sp->ts_fidx;\n\n\t\t// Advance over the character in fword[].  Give a bonus to the\n\t\t// score if the same character is following \"nn\" -> \"n\".  It's\n\t\t// a bit illogical for soundfold tree but it does give better\n\t\t// results.\n\t\tif (has_mbyte)\n\t\t{\n\t\t    c = mb_ptr2char(fword + sp->ts_fidx);\n\t\t    stack[depth].ts_fidx += mb_ptr2len(fword + sp->ts_fidx);\n\t\t    if (enc_utf8 && utf_iscomposing(c))\n\t\t\tstack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP;\n\t\t    else if (c == mb_ptr2char(fword + stack[depth].ts_fidx))\n\t\t\tstack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;\n\t\t}\n\t\telse\n\t\t{\n\t\t    ++stack[depth].ts_fidx;\n\t\t    if (fword[sp->ts_fidx] == fword[sp->ts_fidx + 1])\n\t\t\tstack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;\n\t\t}\n\t\tbreak;\n\t    }\n\t    // FALLTHROUGH\n\n\tcase STATE_INS_PREP:\n\t    if (sp->ts_flags & TSF_DIDDEL)\n\t    {\n\t\t// If we just deleted a byte then inserting won't make sense,\n\t\t// a substitute is always cheaper.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_SWAP;\n\t\tbreak;\n\t    }\n\n\t    // skip over NUL bytes\n\t    n = sp->ts_arridx;\n\t    for (;;)\n\t    {\n\t\tif (sp->ts_curi > byts[n])\n\t\t{\n\t\t    // Only NUL bytes at this node, go to next state.\n\t\t    PROF_STORE(sp->ts_state)\n\t\t    sp->ts_state = STATE_SWAP;\n\t\t    break;\n\t\t}\n\t\tif (byts[n + sp->ts_curi] != NUL)\n\t\t{\n\t\t    // Found a byte to insert.\n\t\t    PROF_STORE(sp->ts_state)\n\t\t    sp->ts_state = STATE_INS;\n\t\t    break;\n\t\t}\n\t\t++sp->ts_curi;\n\t    }\n\t    break;\n\n\t    // FALLTHROUGH\n\n\tcase STATE_INS:\n\t    // Insert one byte.  Repeat this for each possible byte at this\n\t    // node.\n\t    n = sp->ts_arridx;\n\t    if (sp->ts_curi > byts[n])\n\t    {\n\t\t// Done all bytes at this node, go to next state.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_SWAP;\n\t\tbreak;\n\t    }\n\n\t    // Do one more byte at this node, but:\n\t    // - Skip NUL bytes.\n\t    // - Skip the byte if it's equal to the byte in the word,\n\t    //   accepting that byte is always better.\n\t    n += sp->ts_curi++;\n\t    c = byts[n];\n\t    if (soundfold && sp->ts_twordlen == 0 && c == '*')\n\t\t// Inserting a vowel at the start of a word counts less,\n\t\t// see soundalike_score().\n\t\tnewscore = 2 * SCORE_INS / 3;\n\t    else\n\t\tnewscore = SCORE_INS;\n\t    if (c != fword[sp->ts_fidx]\n\t\t\t\t    && TRY_DEEPER(su, stack, depth, newscore))\n\t    {\n\t\tgo_deeper(stack, depth, newscore);\n#ifdef DEBUG_TRIEWALK\n\t\tsprintf(changename[depth], \"%.*s-%s: insert %c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tc);\n#endif\n\t\t++depth;\n\t\tsp = &stack[depth];\n\t\ttword[sp->ts_twordlen++] = c;\n\t\tsp->ts_arridx = idxs[n];\n\t\tif (has_mbyte)\n\t\t{\n\t\t    fl = MB_BYTE2LEN(c);\n\t\t    if (fl > 1)\n\t\t    {\n\t\t\t// There are following bytes for the same character.\n\t\t\t// We must find all bytes before trying\n\t\t\t// delete/insert/swap/etc.\n\t\t\tsp->ts_tcharlen = fl;\n\t\t\tsp->ts_tcharidx = 1;\n\t\t\tsp->ts_isdiff = DIFF_INSERT;\n\t\t    }\n\t\t}\n\t\telse\n\t\t    fl = 1;\n\t\tif (fl == 1)\n\t\t{\n\t\t    // If the previous character was the same, thus doubling a\n\t\t    // character, give a bonus to the score.  Also for\n\t\t    // soundfold words (illogical but does give a better\n\t\t    // score).\n\t\t    if (sp->ts_twordlen >= 2\n\t\t\t\t\t   && tword[sp->ts_twordlen - 2] == c)\n\t\t\tsp->ts_score -= SCORE_INS - SCORE_INSDUP;\n\t\t}\n\t    }\n\t    break;\n\n\tcase STATE_SWAP:\n\t    // Swap two bytes in the bad word: \"12\" -> \"21\".\n\t    // We change \"fword\" here, it's changed back afterwards at\n\t    // STATE_UNSWAP.\n\t    p = fword + sp->ts_fidx;\n\t    c = *p;\n\t    if (c == NUL)\n\t    {\n\t\t// End of word, can't swap or replace.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t\tbreak;\n\t    }\n\n\t    // Don't swap if the first character is not a word character.\n\t    // SWAP3 etc. also don't make sense then.\n\t    if (!soundfold && !spell_iswordp(p, curwin))\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t\tbreak;\n\t    }\n\n\t    if (has_mbyte)\n\t    {\n\t\tn = MB_CPTR2LEN(p);\n\t\tc = mb_ptr2char(p);\n\t\tif (p[n] == NUL)\n\t\t    c2 = NUL;\n\t\telse if (!soundfold && !spell_iswordp(p + n, curwin))\n\t\t    c2 = c; // don't swap non-word char\n\t\telse\n\t\t    c2 = mb_ptr2char(p + n);\n\t    }\n\t    else\n\t    {\n\t\tif (p[1] == NUL)\n\t\t    c2 = NUL;\n\t\telse if (!soundfold && !spell_iswordp(p + 1, curwin))\n\t\t    c2 = c; // don't swap non-word char\n\t\telse\n\t\t    c2 = p[1];\n\t    }\n\n\t    // When the second character is NUL we can't swap.\n\t    if (c2 == NUL)\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t\tbreak;\n\t    }\n\n\t    // When characters are identical, swap won't do anything.\n\t    // Also get here if the second char is not a word character.\n\t    if (c == c2)\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_SWAP3;\n\t\tbreak;\n\t    }\n\t    if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP))\n\t    {\n\t\tgo_deeper(stack, depth, SCORE_SWAP);\n#ifdef DEBUG_TRIEWALK\n\t\tsprintf(changename[depth], \"%.*s-%s: swap %c and %c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tc, c2);\n#endif\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_UNSWAP;\n\t\t++depth;\n\t\tif (has_mbyte)\n\t\t{\n\t\t    fl = mb_char2len(c2);\n\t\t    mch_memmove(p, p + n, fl);\n\t\t    mb_char2bytes(c, p + fl);\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;\n\t\t}\n\t\telse\n\t\t{\n\t\t    p[0] = c2;\n\t\t    p[1] = c;\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + 2;\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\t// If this swap doesn't work then SWAP3 won't either.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t    }\n\t    break;\n\n\tcase STATE_UNSWAP:\n\t    // Undo the STATE_SWAP swap: \"21\" -> \"12\".\n\t    p = fword + sp->ts_fidx;\n\t    if (has_mbyte)\n\t    {\n\t\tn = mb_ptr2len(p);\n\t\tc = mb_ptr2char(p + n);\n\t\tmch_memmove(p + mb_ptr2len(p + n), p, n);\n\t\tmb_char2bytes(c, p);\n\t    }\n\t    else\n\t    {\n\t\tc = *p;\n\t\t*p = p[1];\n\t\tp[1] = c;\n\t    }\n\t    // FALLTHROUGH\n\n\tcase STATE_SWAP3:\n\t    // Swap two bytes, skipping one: \"123\" -> \"321\".  We change\n\t    // \"fword\" here, it's changed back afterwards at STATE_UNSWAP3.\n\t    p = fword + sp->ts_fidx;\n\t    if (has_mbyte)\n\t    {\n\t\tn = MB_CPTR2LEN(p);\n\t\tc = mb_ptr2char(p);\n\t\tfl = MB_CPTR2LEN(p + n);\n\t\tc2 = mb_ptr2char(p + n);\n\t\tif (!soundfold && !spell_iswordp(p + n + fl, curwin))\n\t\t    c3 = c;\t// don't swap non-word char\n\t\telse\n\t\t    c3 = mb_ptr2char(p + n + fl);\n\t    }\n\t    else\n\t    {\n\t\tc = *p;\n\t\tc2 = p[1];\n\t\tif (!soundfold && !spell_iswordp(p + 2, curwin))\n\t\t    c3 = c;\t// don't swap non-word char\n\t\telse\n\t\t    c3 = p[2];\n\t    }\n\n\t    // When characters are identical: \"121\" then SWAP3 result is\n\t    // identical, ROT3L result is same as SWAP: \"211\", ROT3L result is\n\t    // same as SWAP on next char: \"112\".  Thus skip all swapping.\n\t    // Also skip when c3 is NUL.\n\t    // Also get here when the third character is not a word character.\n\t    // Second character may any char: \"a.b\" -> \"b.a\"\n\t    if (c == c3 || c3 == NUL)\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t\tbreak;\n\t    }\n\t    if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))\n\t    {\n\t\tgo_deeper(stack, depth, SCORE_SWAP3);\n#ifdef DEBUG_TRIEWALK\n\t\tsprintf(changename[depth], \"%.*s-%s: swap3 %c and %c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tc, c3);\n#endif\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_UNSWAP3;\n\t\t++depth;\n\t\tif (has_mbyte)\n\t\t{\n\t\t    tl = mb_char2len(c3);\n\t\t    mch_memmove(p, p + n + fl, tl);\n\t\t    mb_char2bytes(c2, p + tl);\n\t\t    mb_char2bytes(c, p + fl + tl);\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl;\n\t\t}\n\t\telse\n\t\t{\n\t\t    p[0] = p[2];\n\t\t    p[2] = c;\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + 3;\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t    }\n\t    break;\n\n\tcase STATE_UNSWAP3:\n\t    // Undo STATE_SWAP3: \"321\" -> \"123\"\n\t    p = fword + sp->ts_fidx;\n\t    if (has_mbyte)\n\t    {\n\t\tn = mb_ptr2len(p);\n\t\tc2 = mb_ptr2char(p + n);\n\t\tfl = mb_ptr2len(p + n);\n\t\tc = mb_ptr2char(p + n + fl);\n\t\ttl = mb_ptr2len(p + n + fl);\n\t\tmch_memmove(p + fl + tl, p, n);\n\t\tmb_char2bytes(c, p);\n\t\tmb_char2bytes(c2, p + tl);\n\t\tp = p + tl;\n\t    }\n\t    else\n\t    {\n\t\tc = *p;\n\t\t*p = p[2];\n\t\tp[2] = c;\n\t\t++p;\n\t    }\n\n\t    if (!soundfold && !spell_iswordp(p, curwin))\n\t    {\n\t\t// Middle char is not a word char, skip the rotate.  First and\n\t\t// third char were already checked at swap and swap3.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t\tbreak;\n\t    }\n\n\t    // Rotate three characters left: \"123\" -> \"231\".  We change\n\t    // \"fword\" here, it's changed back afterwards at STATE_UNROT3L.\n\t    if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))\n\t    {\n\t\tgo_deeper(stack, depth, SCORE_SWAP3);\n#ifdef DEBUG_TRIEWALK\n\t\tp = fword + sp->ts_fidx;\n\t\tsprintf(changename[depth], \"%.*s-%s: rotate left %c%c%c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tp[0], p[1], p[2]);\n#endif\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_UNROT3L;\n\t\t++depth;\n\t\tp = fword + sp->ts_fidx;\n\t\tif (has_mbyte)\n\t\t{\n\t\t    n = MB_CPTR2LEN(p);\n\t\t    c = mb_ptr2char(p);\n\t\t    fl = MB_CPTR2LEN(p + n);\n\t\t    fl += MB_CPTR2LEN(p + n + fl);\n\t\t    mch_memmove(p, p + n, fl);\n\t\t    mb_char2bytes(c, p + fl);\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;\n\t\t}\n\t\telse\n\t\t{\n\t\t    c = *p;\n\t\t    *p = p[1];\n\t\t    p[1] = p[2];\n\t\t    p[2] = c;\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + 3;\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t    }\n\t    break;\n\n\tcase STATE_UNROT3L:\n\t    // Undo ROT3L: \"231\" -> \"123\"\n\t    p = fword + sp->ts_fidx;\n\t    if (has_mbyte)\n\t    {\n\t\tn = mb_ptr2len(p);\n\t\tn += mb_ptr2len(p + n);\n\t\tc = mb_ptr2char(p + n);\n\t\ttl = mb_ptr2len(p + n);\n\t\tmch_memmove(p + tl, p, n);\n\t\tmb_char2bytes(c, p);\n\t    }\n\t    else\n\t    {\n\t\tc = p[2];\n\t\tp[2] = p[1];\n\t\tp[1] = *p;\n\t\t*p = c;\n\t    }\n\n\t    // Rotate three bytes right: \"123\" -> \"312\".  We change \"fword\"\n\t    // here, it's changed back afterwards at STATE_UNROT3R.\n\t    if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))\n\t    {\n\t\tgo_deeper(stack, depth, SCORE_SWAP3);\n#ifdef DEBUG_TRIEWALK\n\t\tp = fword + sp->ts_fidx;\n\t\tsprintf(changename[depth], \"%.*s-%s: rotate right %c%c%c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tp[0], p[1], p[2]);\n#endif\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_UNROT3R;\n\t\t++depth;\n\t\tp = fword + sp->ts_fidx;\n\t\tif (has_mbyte)\n\t\t{\n\t\t    n = MB_CPTR2LEN(p);\n\t\t    n += MB_CPTR2LEN(p + n);\n\t\t    c = mb_ptr2char(p + n);\n\t\t    tl = MB_CPTR2LEN(p + n);\n\t\t    mch_memmove(p + tl, p, n);\n\t\t    mb_char2bytes(c, p);\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + n + tl;\n\t\t}\n\t\telse\n\t\t{\n\t\t    c = p[2];\n\t\t    p[2] = p[1];\n\t\t    p[1] = *p;\n\t\t    *p = c;\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + 3;\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t    }\n\t    break;\n\n\tcase STATE_UNROT3R:\n\t    // Undo ROT3R: \"312\" -> \"123\"\n\t    p = fword + sp->ts_fidx;\n\t    if (has_mbyte)\n\t    {\n\t\tc = mb_ptr2char(p);\n\t\ttl = mb_ptr2len(p);\n\t\tn = mb_ptr2len(p + tl);\n\t\tn += mb_ptr2len(p + tl + n);\n\t\tmch_memmove(p, p + tl, n);\n\t\tmb_char2bytes(c, p + n);\n\t    }\n\t    else\n\t    {\n\t\tc = *p;\n\t\t*p = p[1];\n\t\tp[1] = p[2];\n\t\tp[2] = c;\n\t    }\n\t    // FALLTHROUGH\n\n\tcase STATE_REP_INI:\n\t    // Check if matching with REP items from the .aff file would work.\n\t    // Quickly skip if:\n\t    // - there are no REP items and we are not in the soundfold trie\n\t    // - the score is going to be too high anyway\n\t    // - already applied a REP item or swapped here\n\t    if ((lp->lp_replang == NULL && !soundfold)\n\t\t    || sp->ts_score + SCORE_REP >= su->su_maxscore\n\t\t    || sp->ts_fidx < sp->ts_fidxtry)\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t\tbreak;\n\t    }\n\n\t    // Use the first byte to quickly find the first entry that may\n\t    // match.  If the index is -1 there is none.\n\t    if (soundfold)\n\t\tsp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]];\n\t    else\n\t\tsp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]];\n\n\t    if (sp->ts_curi < 0)\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t\tbreak;\n\t    }\n\n\t    PROF_STORE(sp->ts_state)\n\t    sp->ts_state = STATE_REP;\n\t    // FALLTHROUGH\n\n\tcase STATE_REP:\n\t    // Try matching with REP items from the .aff file.  For each match\n\t    // replace the characters and check if the resulting word is\n\t    // valid.\n\t    p = fword + sp->ts_fidx;\n\n\t    if (soundfold)\n\t\tgap = &slang->sl_repsal;\n\t    else\n\t\tgap = &lp->lp_replang->sl_rep;\n\t    while (sp->ts_curi < gap->ga_len)\n\t    {\n\t\tftp = (fromto_T *)gap->ga_data + sp->ts_curi++;\n\t\tif (*ftp->ft_from != *p)\n\t\t{\n\t\t    // past possible matching entries\n\t\t    sp->ts_curi = gap->ga_len;\n\t\t    break;\n\t\t}\n\t\tif (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0\n\t\t\t&& TRY_DEEPER(su, stack, depth, SCORE_REP))\n\t\t{\n\t\t    go_deeper(stack, depth, SCORE_REP);\n#ifdef DEBUG_TRIEWALK\n\t\t    sprintf(changename[depth], \"%.*s-%s: replace %s with %s\",\n\t\t\t    sp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\t    ftp->ft_from, ftp->ft_to);\n#endif\n\t\t    // Need to undo this afterwards.\n\t\t    PROF_STORE(sp->ts_state)\n\t\t    sp->ts_state = STATE_REP_UNDO;\n\n\t\t    // Change the \"from\" to the \"to\" string.\n\t\t    ++depth;\n\t\t    fl = (int)STRLEN(ftp->ft_from);\n\t\t    tl = (int)STRLEN(ftp->ft_to);\n\t\t    if (fl != tl)\n\t\t    {\n\t\t\tSTRMOVE(p + tl, p + fl);\n\t\t\trepextra += tl - fl;\n\t\t    }\n\t\t    mch_memmove(p, ftp->ft_to, tl);\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + tl;\n\t\t    stack[depth].ts_tcharlen = 0;\n\t\t    break;\n\t\t}\n\t    }\n\n\t    if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP)\n\t    {\n\t\t// No (more) matches.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t    }\n\n\t    break;\n\n\tcase STATE_REP_UNDO:\n\t    // Undo a REP replacement and continue with the next one.\n\t    if (soundfold)\n\t\tgap = &slang->sl_repsal;\n\t    else\n\t\tgap = &lp->lp_replang->sl_rep;\n\t    ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1;\n\t    fl = (int)STRLEN(ftp->ft_from);\n\t    tl = (int)STRLEN(ftp->ft_to);\n\t    p = fword + sp->ts_fidx;\n\t    if (fl != tl)\n\t    {\n\t\tSTRMOVE(p + fl, p + tl);\n\t\trepextra -= tl - fl;\n\t    }\n\t    mch_memmove(p, ftp->ft_from, fl);\n\t    PROF_STORE(sp->ts_state)\n\t    sp->ts_state = STATE_REP;\n\t    break;\n\n\tdefault:\n\t    // Did all possible states at this level, go up one level.\n\t    --depth;\n\n\t    if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE)\n\t    {\n\t\t// Continue in or go back to the prefix tree.\n\t\tbyts = pbyts;\n\t\tidxs = pidxs;\n\t    }\n\n\t    // Don't check for CTRL-C too often, it takes time.\n\t    if (--breakcheckcount == 0)\n\t    {\n\t\tui_breakcheck();\n\t\tbreakcheckcount = 1000;\n#ifdef FEAT_RELTIME\n\t\tif (spell_suggest_timeout > 0\n\t\t\t\t\t  && profile_passed_limit(&time_limit))\n\t\t    got_int = TRUE;\n#endif\n\t    }\n\t}\n    }\n}", "func_hash": 86190004113264578506184029642372711349, "file_name": "spellsuggest.c", "file_hash": 224942464208559430024115846607965193151, "cwe": ["CWE-787"], "cve": "CVE-2022-2126", "cve_desc": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2126"}
{"idx": 301481, "project": "vim", "commit_id": "156d3911952d73b03d7420dc3540215247db0fe8", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/156d3911952d73b03d7420dc3540215247db0fe8", "commit_message": "patch 8.2.5123: using invalid index when looking for spell suggestions\n\nProblem:    Using invalid index when looking for spell suggestions.\nSolution:   Do not decrement the index when it is zero.", "target": 0, "func": "suggest_trie_walk(\n    suginfo_T\t*su,\n    langp_T\t*lp,\n    char_u\t*fword,\n    int\t\tsoundfold)\n{\n    char_u\ttword[MAXWLEN];\t    // good word collected so far\n    trystate_T\tstack[MAXWLEN];\n    char_u\tpreword[MAXWLEN * 3]; // word found with proper case;\n\t\t\t\t      // concatenation of prefix compound\n\t\t\t\t      // words and split word.  NUL terminated\n\t\t\t\t      // when going deeper but not when coming\n\t\t\t\t      // back.\n    char_u\tcompflags[MAXWLEN];\t// compound flags, one for each word\n    trystate_T\t*sp;\n    int\t\tnewscore;\n    int\t\tscore;\n    char_u\t*byts, *fbyts, *pbyts;\n    idx_T\t*idxs, *fidxs, *pidxs;\n    int\t\tdepth;\n    int\t\tc, c2, c3;\n    int\t\tn = 0;\n    int\t\tflags;\n    garray_T\t*gap;\n    idx_T\tarridx;\n    int\t\tlen;\n    char_u\t*p;\n    fromto_T\t*ftp;\n    int\t\tfl = 0, tl;\n    int\t\trepextra = 0;\t    // extra bytes in fword[] from REP item\n    slang_T\t*slang = lp->lp_slang;\n    int\t\tfword_ends;\n    int\t\tgoodword_ends;\n#ifdef DEBUG_TRIEWALK\n    // Stores the name of the change made at each level.\n    char_u\tchangename[MAXWLEN][80];\n#endif\n    int\t\tbreakcheckcount = 1000;\n#ifdef FEAT_RELTIME\n    proftime_T\ttime_limit;\n#endif\n    int\t\tcompound_ok;\n\n    // Go through the whole case-fold tree, try changes at each node.\n    // \"tword[]\" contains the word collected from nodes in the tree.\n    // \"fword[]\" the word we are trying to match with (initially the bad\n    // word).\n    depth = 0;\n    sp = &stack[0];\n    CLEAR_POINTER(sp);\n    sp->ts_curi = 1;\n\n    if (soundfold)\n    {\n\t// Going through the soundfold tree.\n\tbyts = fbyts = slang->sl_sbyts;\n\tidxs = fidxs = slang->sl_sidxs;\n\tpbyts = NULL;\n\tpidxs = NULL;\n\tsp->ts_prefixdepth = PFD_NOPREFIX;\n\tsp->ts_state = STATE_START;\n    }\n    else\n    {\n\t// When there are postponed prefixes we need to use these first.  At\n\t// the end of the prefix we continue in the case-fold tree.\n\tfbyts = slang->sl_fbyts;\n\tfidxs = slang->sl_fidxs;\n\tpbyts = slang->sl_pbyts;\n\tpidxs = slang->sl_pidxs;\n\tif (pbyts != NULL)\n\t{\n\t    byts = pbyts;\n\t    idxs = pidxs;\n\t    sp->ts_prefixdepth = PFD_PREFIXTREE;\n\t    sp->ts_state = STATE_NOPREFIX;\t// try without prefix first\n\t}\n\telse\n\t{\n\t    byts = fbyts;\n\t    idxs = fidxs;\n\t    sp->ts_prefixdepth = PFD_NOPREFIX;\n\t    sp->ts_state = STATE_START;\n\t}\n    }\n#ifdef FEAT_RELTIME\n    // The loop may take an indefinite amount of time. Break out after some\n    // time.\n    if (spell_suggest_timeout > 0)\n\tprofile_setlimit(spell_suggest_timeout, &time_limit);\n#endif\n\n    // Loop to find all suggestions.  At each round we either:\n    // - For the current state try one operation, advance \"ts_curi\",\n    //   increase \"depth\".\n    // - When a state is done go to the next, set \"ts_state\".\n    // - When all states are tried decrease \"depth\".\n    while (depth >= 0 && !got_int)\n    {\n\tsp = &stack[depth];\n\tswitch (sp->ts_state)\n\t{\n\tcase STATE_START:\n\tcase STATE_NOPREFIX:\n\t    // Start of node: Deal with NUL bytes, which means\n\t    // tword[] may end here.\n\t    arridx = sp->ts_arridx;\t    // current node in the tree\n\t    len = byts[arridx];\t\t    // bytes in this node\n\t    arridx += sp->ts_curi;\t    // index of current byte\n\n\t    if (sp->ts_prefixdepth == PFD_PREFIXTREE)\n\t    {\n\t\t// Skip over the NUL bytes, we use them later.\n\t\tfor (n = 0; n < len && byts[arridx + n] == 0; ++n)\n\t\t    ;\n\t\tsp->ts_curi += n;\n\n\t\t// Always past NUL bytes now.\n\t\tn = (int)sp->ts_state;\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_ENDNUL;\n\t\tsp->ts_save_badflags = su->su_badflags;\n\n\t\t// At end of a prefix or at start of prefixtree: check for\n\t\t// following word.\n\t\tif (depth < MAXWLEN - 1\n\t\t\t    && (byts[arridx] == 0 || n == (int)STATE_NOPREFIX))\n\t\t{\n\t\t    // Set su->su_badflags to the caps type at this position.\n\t\t    // Use the caps type until here for the prefix itself.\n\t\t    if (has_mbyte)\n\t\t\tn = nofold_len(fword, sp->ts_fidx, su->su_badptr);\n\t\t    else\n\t\t\tn = sp->ts_fidx;\n\t\t    flags = badword_captype(su->su_badptr, su->su_badptr + n);\n\t\t    su->su_badflags = badword_captype(su->su_badptr + n,\n\t\t\t\t\t       su->su_badptr + su->su_badlen);\n#ifdef DEBUG_TRIEWALK\n\t\t    sprintf(changename[depth], \"prefix\");\n#endif\n\t\t    go_deeper(stack, depth, 0);\n\t\t    ++depth;\n\t\t    sp = &stack[depth];\n\t\t    sp->ts_prefixdepth = depth - 1;\n\t\t    byts = fbyts;\n\t\t    idxs = fidxs;\n\t\t    sp->ts_arridx = 0;\n\n\t\t    // Move the prefix to preword[] with the right case\n\t\t    // and make find_keepcap_word() works.\n\t\t    tword[sp->ts_twordlen] = NUL;\n\t\t    make_case_word(tword + sp->ts_splitoff,\n\t\t\t\t\t  preword + sp->ts_prewordlen, flags);\n\t\t    sp->ts_prewordlen = (char_u)STRLEN(preword);\n\t\t    sp->ts_splitoff = sp->ts_twordlen;\n\t\t}\n\t\tbreak;\n\t    }\n\n\t    if (sp->ts_curi > len || byts[arridx] != 0)\n\t    {\n\t\t// Past bytes in node and/or past NUL bytes.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_ENDNUL;\n\t\tsp->ts_save_badflags = su->su_badflags;\n\t\tbreak;\n\t    }\n\n\t    // End of word in tree.\n\t    ++sp->ts_curi;\t\t// eat one NUL byte\n\n\t    flags = (int)idxs[arridx];\n\n\t    // Skip words with the NOSUGGEST flag.\n\t    if (flags & WF_NOSUGGEST)\n\t\tbreak;\n\n\t    fword_ends = (fword[sp->ts_fidx] == NUL\n\t\t\t   || (soundfold\n\t\t\t       ? VIM_ISWHITE(fword[sp->ts_fidx])\n\t\t\t       : !spell_iswordp(fword + sp->ts_fidx, curwin)));\n\t    tword[sp->ts_twordlen] = NUL;\n\n\t    if (sp->ts_prefixdepth <= PFD_NOTSPECIAL\n\t\t\t\t\t&& (sp->ts_flags & TSF_PREFIXOK) == 0\n\t\t\t\t\t&& pbyts != NULL)\n\t    {\n\t\t// There was a prefix before the word.  Check that the prefix\n\t\t// can be used with this word.\n\t\t// Count the length of the NULs in the prefix.  If there are\n\t\t// none this must be the first try without a prefix.\n\t\tn = stack[sp->ts_prefixdepth].ts_arridx;\n\t\tlen = pbyts[n++];\n\t\tfor (c = 0; c < len && pbyts[n + c] == 0; ++c)\n\t\t    ;\n\t\tif (c > 0)\n\t\t{\n\t\t    c = valid_word_prefix(c, n, flags,\n\t\t\t\t       tword + sp->ts_splitoff, slang, FALSE);\n\t\t    if (c == 0)\n\t\t\tbreak;\n\n\t\t    // Use the WF_RARE flag for a rare prefix.\n\t\t    if (c & WF_RAREPFX)\n\t\t\tflags |= WF_RARE;\n\n\t\t    // Tricky: when checking for both prefix and compounding\n\t\t    // we run into the prefix flag first.\n\t\t    // Remember that it's OK, so that we accept the prefix\n\t\t    // when arriving at a compound flag.\n\t\t    sp->ts_flags |= TSF_PREFIXOK;\n\t\t}\n\t    }\n\n\t    // Check NEEDCOMPOUND: can't use word without compounding.  Do try\n\t    // appending another compound word below.\n\t    if (sp->ts_complen == sp->ts_compsplit && fword_ends\n\t\t\t\t\t\t     && (flags & WF_NEEDCOMP))\n\t\tgoodword_ends = FALSE;\n\t    else\n\t\tgoodword_ends = TRUE;\n\n\t    p = NULL;\n\t    compound_ok = TRUE;\n\t    if (sp->ts_complen > sp->ts_compsplit)\n\t    {\n\t\tif (slang->sl_nobreak)\n\t\t{\n\t\t    // There was a word before this word.  When there was no\n\t\t    // change in this word (it was correct) add the first word\n\t\t    // as a suggestion.  If this word was corrected too, we\n\t\t    // need to check if a correct word follows.\n\t\t    if (sp->ts_fidx - sp->ts_splitfidx\n\t\t\t\t\t  == sp->ts_twordlen - sp->ts_splitoff\n\t\t\t    && STRNCMP(fword + sp->ts_splitfidx,\n\t\t\t\t\ttword + sp->ts_splitoff,\n\t\t\t\t\t sp->ts_fidx - sp->ts_splitfidx) == 0)\n\t\t    {\n\t\t\tpreword[sp->ts_prewordlen] = NUL;\n\t\t\tnewscore = score_wordcount_adj(slang, sp->ts_score,\n\t\t\t\t\t\t preword + sp->ts_prewordlen,\n\t\t\t\t\t\t sp->ts_prewordlen > 0);\n\t\t\t// Add the suggestion if the score isn't too bad.\n\t\t\tif (newscore <= su->su_maxscore)\n\t\t\t    add_suggestion(su, &su->su_ga, preword,\n\t\t\t\t    sp->ts_splitfidx - repextra,\n\t\t\t\t    newscore, 0, FALSE,\n\t\t\t\t    lp->lp_sallang, FALSE);\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    // There was a compound word before this word.  If this\n\t\t    // word does not support compounding then give up\n\t\t    // (splitting is tried for the word without compound\n\t\t    // flag).\n\t\t    if (((unsigned)flags >> 24) == 0\n\t\t\t    || sp->ts_twordlen - sp->ts_splitoff\n\t\t\t\t\t\t       < slang->sl_compminlen)\n\t\t\tbreak;\n\t\t    // For multi-byte chars check character length against\n\t\t    // COMPOUNDMIN.\n\t\t    if (has_mbyte\n\t\t\t    && slang->sl_compminlen > 0\n\t\t\t    && mb_charlen(tword + sp->ts_splitoff)\n\t\t\t\t\t\t       < slang->sl_compminlen)\n\t\t\tbreak;\n\n\t\t    compflags[sp->ts_complen] = ((unsigned)flags >> 24);\n\t\t    compflags[sp->ts_complen + 1] = NUL;\n\t\t    vim_strncpy(preword + sp->ts_prewordlen,\n\t\t\t    tword + sp->ts_splitoff,\n\t\t\t    sp->ts_twordlen - sp->ts_splitoff);\n\n\t\t    // Verify CHECKCOMPOUNDPATTERN  rules.\n\t\t    if (match_checkcompoundpattern(preword,  sp->ts_prewordlen,\n\t\t\t\t\t\t\t  &slang->sl_comppat))\n\t\t\tcompound_ok = FALSE;\n\n\t\t    if (compound_ok)\n\t\t    {\n\t\t\tp = preword;\n\t\t\twhile (*skiptowhite(p) != NUL)\n\t\t\t    p = skipwhite(skiptowhite(p));\n\t\t\tif (fword_ends && !can_compound(slang, p,\n\t\t\t\t\t\tcompflags + sp->ts_compsplit))\n\t\t\t    // Compound is not allowed.  But it may still be\n\t\t\t    // possible if we add another (short) word.\n\t\t\t    compound_ok = FALSE;\n\t\t    }\n\n\t\t    // Get pointer to last char of previous word.\n\t\t    p = preword + sp->ts_prewordlen;\n\t\t    MB_PTR_BACK(preword, p);\n\t\t}\n\t    }\n\n\t    // Form the word with proper case in preword.\n\t    // If there is a word from a previous split, append.\n\t    // For the soundfold tree don't change the case, simply append.\n\t    if (soundfold)\n\t\tSTRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff);\n\t    else if (flags & WF_KEEPCAP)\n\t\t// Must find the word in the keep-case tree.\n\t\tfind_keepcap_word(slang, tword + sp->ts_splitoff,\n\t\t\t\t\t\t preword + sp->ts_prewordlen);\n\t    else\n\t    {\n\t\t// Include badflags: If the badword is onecap or allcap\n\t\t// use that for the goodword too.  But if the badword is\n\t\t// allcap and it's only one char long use onecap.\n\t\tc = su->su_badflags;\n\t\tif ((c & WF_ALLCAP)\n\t\t\t&& su->su_badlen == (*mb_ptr2len)(su->su_badptr))\n\t\t    c = WF_ONECAP;\n\t\tc |= flags;\n\n\t\t// When appending a compound word after a word character don't\n\t\t// use Onecap.\n\t\tif (p != NULL && spell_iswordp_nmw(p, curwin))\n\t\t    c &= ~WF_ONECAP;\n\t\tmake_case_word(tword + sp->ts_splitoff,\n\t\t\t\t\t      preword + sp->ts_prewordlen, c);\n\t    }\n\n\t    if (!soundfold)\n\t    {\n\t\t// Don't use a banned word.  It may appear again as a good\n\t\t// word, thus remember it.\n\t\tif (flags & WF_BANNED)\n\t\t{\n\t\t    add_banned(su, preword + sp->ts_prewordlen);\n\t\t    break;\n\t\t}\n\t\tif ((sp->ts_complen == sp->ts_compsplit\n\t\t\t    && WAS_BANNED(su, preword + sp->ts_prewordlen))\n\t\t\t\t\t\t   || WAS_BANNED(su, preword))\n\t\t{\n\t\t    if (slang->sl_compprog == NULL)\n\t\t\tbreak;\n\t\t    // the word so far was banned but we may try compounding\n\t\t    goodword_ends = FALSE;\n\t\t}\n\t    }\n\n\t    newscore = 0;\n\t    if (!soundfold)\t// soundfold words don't have flags\n\t    {\n\t\tif ((flags & WF_REGION)\n\t\t\t    && (((unsigned)flags >> 16) & lp->lp_region) == 0)\n\t\t    newscore += SCORE_REGION;\n\t\tif (flags & WF_RARE)\n\t\t    newscore += SCORE_RARE;\n\n\t\tif (!spell_valid_case(su->su_badflags,\n\t\t\t\t  captype(preword + sp->ts_prewordlen, NULL)))\n\t\t    newscore += SCORE_ICASE;\n\t    }\n\n\t    // TODO: how about splitting in the soundfold tree?\n\t    if (fword_ends\n\t\t    && goodword_ends\n\t\t    && sp->ts_fidx >= sp->ts_fidxtry\n\t\t    && compound_ok)\n\t    {\n\t\t// The badword also ends: add suggestions.\n#ifdef DEBUG_TRIEWALK\n\t\tif (soundfold && STRCMP(preword, \"smwrd\") == 0)\n\t\t{\n\t\t    int\t    j;\n\n\t\t    // print the stack of changes that brought us here\n\t\t    smsg(\"------ %s -------\", fword);\n\t\t    for (j = 0; j < depth; ++j)\n\t\t\tsmsg(\"%s\", changename[j]);\n\t\t}\n#endif\n\t\tif (soundfold)\n\t\t{\n\t\t    // For soundfolded words we need to find the original\n\t\t    // words, the edit distance and then add them.\n\t\t    add_sound_suggest(su, preword, sp->ts_score, lp);\n\t\t}\n\t\telse if (sp->ts_fidx > 0)\n\t\t{\n\t\t    // Give a penalty when changing non-word char to word\n\t\t    // char, e.g., \"thes,\" -> \"these\".\n\t\t    p = fword + sp->ts_fidx;\n\t\t    MB_PTR_BACK(fword, p);\n\t\t    if (!spell_iswordp(p, curwin) && *preword != NUL)\n\t\t    {\n\t\t\tp = preword + STRLEN(preword);\n\t\t\tMB_PTR_BACK(preword, p);\n\t\t\tif (spell_iswordp(p, curwin))\n\t\t\t    newscore += SCORE_NONWORD;\n\t\t    }\n\n\t\t    // Give a bonus to words seen before.\n\t\t    score = score_wordcount_adj(slang,\n\t\t\t\t\t\tsp->ts_score + newscore,\n\t\t\t\t\t\tpreword + sp->ts_prewordlen,\n\t\t\t\t\t\tsp->ts_prewordlen > 0);\n\n\t\t    // Add the suggestion if the score isn't too bad.\n\t\t    if (score <= su->su_maxscore)\n\t\t    {\n\t\t\tadd_suggestion(su, &su->su_ga, preword,\n\t\t\t\t    sp->ts_fidx - repextra,\n\t\t\t\t    score, 0, FALSE, lp->lp_sallang, FALSE);\n\n\t\t\tif (su->su_badflags & WF_MIXCAP)\n\t\t\t{\n\t\t\t    // We really don't know if the word should be\n\t\t\t    // upper or lower case, add both.\n\t\t\t    c = captype(preword, NULL);\n\t\t\t    if (c == 0 || c == WF_ALLCAP)\n\t\t\t    {\n\t\t\t\tmake_case_word(tword + sp->ts_splitoff,\n\t\t\t\t\t      preword + sp->ts_prewordlen,\n\t\t\t\t\t\t      c == 0 ? WF_ALLCAP : 0);\n\n\t\t\t\tadd_suggestion(su, &su->su_ga, preword,\n\t\t\t\t\tsp->ts_fidx - repextra,\n\t\t\t\t\tscore + SCORE_ICASE, 0, FALSE,\n\t\t\t\t\tlp->lp_sallang, FALSE);\n\t\t\t    }\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\n\t    // Try word split and/or compounding.\n\t    if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends)\n\t\t    // Don't split halfway a character.\n\t\t    && (!has_mbyte || sp->ts_tcharlen == 0))\n\t    {\n\t\tint\ttry_compound;\n\t\tint\ttry_split;\n\n\t\t// If past the end of the bad word don't try a split.\n\t\t// Otherwise try changing the next word.  E.g., find\n\t\t// suggestions for \"the the\" where the second \"the\" is\n\t\t// different.  It's done like a split.\n\t\t// TODO: word split for soundfold words\n\t\ttry_split = (sp->ts_fidx - repextra < su->su_badlen)\n\t\t\t\t\t\t\t\t&& !soundfold;\n\n\t\t// Get here in several situations:\n\t\t// 1. The word in the tree ends:\n\t\t//    If the word allows compounding try that.  Otherwise try\n\t\t//    a split by inserting a space.  For both check that a\n\t\t//    valid words starts at fword[sp->ts_fidx].\n\t\t//    For NOBREAK do like compounding to be able to check if\n\t\t//    the next word is valid.\n\t\t// 2. The badword does end, but it was due to a change (e.g.,\n\t\t//    a swap).  No need to split, but do check that the\n\t\t//    following word is valid.\n\t\t// 3. The badword and the word in the tree end.  It may still\n\t\t//    be possible to compound another (short) word.\n\t\ttry_compound = FALSE;\n\t\tif (!soundfold\n\t\t\t&& !slang->sl_nocompoundsugs\n\t\t\t&& slang->sl_compprog != NULL\n\t\t\t&& ((unsigned)flags >> 24) != 0\n\t\t\t&& sp->ts_twordlen - sp->ts_splitoff\n\t\t\t\t\t\t       >= slang->sl_compminlen\n\t\t\t&& (!has_mbyte\n\t\t\t    || slang->sl_compminlen == 0\n\t\t\t    || mb_charlen(tword + sp->ts_splitoff)\n\t\t\t\t\t\t      >= slang->sl_compminlen)\n\t\t\t&& (slang->sl_compsylmax < MAXWLEN\n\t\t\t    || sp->ts_complen + 1 - sp->ts_compsplit\n\t\t\t\t\t\t\t  < slang->sl_compmax)\n\t\t\t&& (can_be_compound(sp, slang,\n\t\t\t\t\t compflags, ((unsigned)flags >> 24))))\n\n\t\t{\n\t\t    try_compound = TRUE;\n\t\t    compflags[sp->ts_complen] = ((unsigned)flags >> 24);\n\t\t    compflags[sp->ts_complen + 1] = NUL;\n\t\t}\n\n\t\t// For NOBREAK we never try splitting, it won't make any word\n\t\t// valid.\n\t\tif (slang->sl_nobreak && !slang->sl_nocompoundsugs)\n\t\t    try_compound = TRUE;\n\n\t\t// If we could add a compound word, and it's also possible to\n\t\t// split at this point, do the split first and set\n\t\t// TSF_DIDSPLIT to avoid doing it again.\n\t\telse if (!fword_ends\n\t\t\t&& try_compound\n\t\t\t&& (sp->ts_flags & TSF_DIDSPLIT) == 0)\n\t\t{\n\t\t    try_compound = FALSE;\n\t\t    sp->ts_flags |= TSF_DIDSPLIT;\n\t\t    --sp->ts_curi;\t    // do the same NUL again\n\t\t    compflags[sp->ts_complen] = NUL;\n\t\t}\n\t\telse\n\t\t    sp->ts_flags &= ~TSF_DIDSPLIT;\n\n\t\tif (try_split || try_compound)\n\t\t{\n\t\t    if (!try_compound && (!fword_ends || !goodword_ends))\n\t\t    {\n\t\t\t// If we're going to split need to check that the\n\t\t\t// words so far are valid for compounding.  If there\n\t\t\t// is only one word it must not have the NEEDCOMPOUND\n\t\t\t// flag.\n\t\t\tif (sp->ts_complen == sp->ts_compsplit\n\t\t\t\t\t\t     && (flags & WF_NEEDCOMP))\n\t\t\t    break;\n\t\t\tp = preword;\n\t\t\twhile (*skiptowhite(p) != NUL)\n\t\t\t    p = skipwhite(skiptowhite(p));\n\t\t\tif (sp->ts_complen > sp->ts_compsplit\n\t\t\t\t&& !can_compound(slang, p,\n\t\t\t\t\t\tcompflags + sp->ts_compsplit))\n\t\t\t    break;\n\n\t\t\tif (slang->sl_nosplitsugs)\n\t\t\t    newscore += SCORE_SPLIT_NO;\n\t\t\telse\n\t\t\t    newscore += SCORE_SPLIT;\n\n\t\t\t// Give a bonus to words seen before.\n\t\t\tnewscore = score_wordcount_adj(slang, newscore,\n\t\t\t\t\t   preword + sp->ts_prewordlen, TRUE);\n\t\t    }\n\n\t\t    if (TRY_DEEPER(su, stack, depth, newscore))\n\t\t    {\n\t\t\tgo_deeper(stack, depth, newscore);\n#ifdef DEBUG_TRIEWALK\n\t\t\tif (!try_compound && !fword_ends)\n\t\t\t    sprintf(changename[depth], \"%.*s-%s: split\",\n\t\t\t\t sp->ts_twordlen, tword, fword + sp->ts_fidx);\n\t\t\telse\n\t\t\t    sprintf(changename[depth], \"%.*s-%s: compound\",\n\t\t\t\t sp->ts_twordlen, tword, fword + sp->ts_fidx);\n#endif\n\t\t\t// Save things to be restored at STATE_SPLITUNDO.\n\t\t\tsp->ts_save_badflags = su->su_badflags;\n\t\t\tPROF_STORE(sp->ts_state)\n\t\t\tsp->ts_state = STATE_SPLITUNDO;\n\n\t\t\t++depth;\n\t\t\tsp = &stack[depth];\n\n\t\t\t// Append a space to preword when splitting.\n\t\t\tif (!try_compound && !fword_ends)\n\t\t\t    STRCAT(preword, \" \");\n\t\t\tsp->ts_prewordlen = (char_u)STRLEN(preword);\n\t\t\tsp->ts_splitoff = sp->ts_twordlen;\n\t\t\tsp->ts_splitfidx = sp->ts_fidx;\n\n\t\t\t// If the badword has a non-word character at this\n\t\t\t// position skip it.  That means replacing the\n\t\t\t// non-word character with a space.  Always skip a\n\t\t\t// character when the word ends.  But only when the\n\t\t\t// good word can end.\n\t\t\tif (((!try_compound && !spell_iswordp_nmw(fword\n\t\t\t\t\t\t\t       + sp->ts_fidx,\n\t\t\t\t\t\t\t       curwin))\n\t\t\t\t    || fword_ends)\n\t\t\t\t&& fword[sp->ts_fidx] != NUL\n\t\t\t\t&& goodword_ends)\n\t\t\t{\n\t\t\t    int\t    l;\n\n\t\t\t    l = mb_ptr2len(fword + sp->ts_fidx);\n\t\t\t    if (fword_ends)\n\t\t\t    {\n\t\t\t\t// Copy the skipped character to preword.\n\t\t\t\tmch_memmove(preword + sp->ts_prewordlen,\n\t\t\t\t\t\t      fword + sp->ts_fidx, l);\n\t\t\t\tsp->ts_prewordlen += l;\n\t\t\t\tpreword[sp->ts_prewordlen] = NUL;\n\t\t\t    }\n\t\t\t    else\n\t\t\t\tsp->ts_score -= SCORE_SPLIT - SCORE_SUBST;\n\t\t\t    sp->ts_fidx += l;\n\t\t\t}\n\n\t\t\t// When compounding include compound flag in\n\t\t\t// compflags[] (already set above).  When splitting we\n\t\t\t// may start compounding over again.\n\t\t\tif (try_compound)\n\t\t\t    ++sp->ts_complen;\n\t\t\telse\n\t\t\t    sp->ts_compsplit = sp->ts_complen;\n\t\t\tsp->ts_prefixdepth = PFD_NOPREFIX;\n\n\t\t\t// set su->su_badflags to the caps type at this\n\t\t\t// position\n\t\t\tif (has_mbyte)\n\t\t\t    n = nofold_len(fword, sp->ts_fidx, su->su_badptr);\n\t\t\telse\n\t\t\t    n = sp->ts_fidx;\n\t\t\tsu->su_badflags = badword_captype(su->su_badptr + n,\n\t\t\t\t\t       su->su_badptr + su->su_badlen);\n\n\t\t\t// Restart at top of the tree.\n\t\t\tsp->ts_arridx = 0;\n\n\t\t\t// If there are postponed prefixes, try these too.\n\t\t\tif (pbyts != NULL)\n\t\t\t{\n\t\t\t    byts = pbyts;\n\t\t\t    idxs = pidxs;\n\t\t\t    sp->ts_prefixdepth = PFD_PREFIXTREE;\n\t\t\t    PROF_STORE(sp->ts_state)\n\t\t\t    sp->ts_state = STATE_NOPREFIX;\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\t    break;\n\n\tcase STATE_SPLITUNDO:\n\t    // Undo the changes done for word split or compound word.\n\t    su->su_badflags = sp->ts_save_badflags;\n\n\t    // Continue looking for NUL bytes.\n\t    PROF_STORE(sp->ts_state)\n\t    sp->ts_state = STATE_START;\n\n\t    // In case we went into the prefix tree.\n\t    byts = fbyts;\n\t    idxs = fidxs;\n\t    break;\n\n\tcase STATE_ENDNUL:\n\t    // Past the NUL bytes in the node.\n\t    su->su_badflags = sp->ts_save_badflags;\n\t    if (fword[sp->ts_fidx] == NUL && sp->ts_tcharlen == 0)\n\t    {\n\t\t// The badword ends, can't use STATE_PLAIN.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_DEL;\n\t\tbreak;\n\t    }\n\t    PROF_STORE(sp->ts_state)\n\t    sp->ts_state = STATE_PLAIN;\n\t    // FALLTHROUGH\n\n\tcase STATE_PLAIN:\n\t    // Go over all possible bytes at this node, add each to tword[]\n\t    // and use child node.  \"ts_curi\" is the index.\n\t    arridx = sp->ts_arridx;\n\t    if (sp->ts_curi > byts[arridx])\n\t    {\n\t\t// Done all bytes at this node, do next state.  When still at\n\t\t// already changed bytes skip the other tricks.\n\t\tPROF_STORE(sp->ts_state)\n\t\tif (sp->ts_fidx >= sp->ts_fidxtry)\n\t\t    sp->ts_state = STATE_DEL;\n\t\telse\n\t\t    sp->ts_state = STATE_FINAL;\n\t    }\n\t    else\n\t    {\n\t\tarridx += sp->ts_curi++;\n\t\tc = byts[arridx];\n\n\t\t// Normal byte, go one level deeper.  If it's not equal to the\n\t\t// byte in the bad word adjust the score.  But don't even try\n\t\t// when the byte was already changed.  And don't try when we\n\t\t// just deleted this byte, accepting it is always cheaper than\n\t\t// delete + substitute.\n\t\tif (c == fword[sp->ts_fidx]\n\t\t\t|| (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE))\n\t\t    newscore = 0;\n\t\telse\n\t\t    newscore = SCORE_SUBST;\n\t\tif ((newscore == 0\n\t\t\t    || (sp->ts_fidx >= sp->ts_fidxtry\n\t\t\t\t&& ((sp->ts_flags & TSF_DIDDEL) == 0\n\t\t\t\t    || c != fword[sp->ts_delidx])))\n\t\t\t&& TRY_DEEPER(su, stack, depth, newscore))\n\t\t{\n\t\t    go_deeper(stack, depth, newscore);\n#ifdef DEBUG_TRIEWALK\n\t\t    if (newscore > 0)\n\t\t\tsprintf(changename[depth], \"%.*s-%s: subst %c to %c\",\n\t\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\t\tfword[sp->ts_fidx], c);\n\t\t    else\n\t\t\tsprintf(changename[depth], \"%.*s-%s: accept %c\",\n\t\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\t\tfword[sp->ts_fidx]);\n#endif\n\t\t    ++depth;\n\t\t    sp = &stack[depth];\n\t\t    if (fword[sp->ts_fidx] != NUL)\n\t\t\t++sp->ts_fidx;\n\t\t    tword[sp->ts_twordlen++] = c;\n\t\t    sp->ts_arridx = idxs[arridx];\n\t\t    if (newscore == SCORE_SUBST)\n\t\t\tsp->ts_isdiff = DIFF_YES;\n\t\t    if (has_mbyte)\n\t\t    {\n\t\t\t// Multi-byte characters are a bit complicated to\n\t\t\t// handle: They differ when any of the bytes differ\n\t\t\t// and then their length may also differ.\n\t\t\tif (sp->ts_tcharlen == 0)\n\t\t\t{\n\t\t\t    // First byte.\n\t\t\t    sp->ts_tcharidx = 0;\n\t\t\t    sp->ts_tcharlen = MB_BYTE2LEN(c);\n\t\t\t    sp->ts_fcharstart = sp->ts_fidx - 1;\n\t\t\t    sp->ts_isdiff = (newscore != 0)\n\t\t\t\t\t\t       ? DIFF_YES : DIFF_NONE;\n\t\t\t}\n\t\t\telse if (sp->ts_isdiff == DIFF_INSERT\n\t\t\t\t\t\t\t    && sp->ts_fidx > 0)\n\t\t\t    // When inserting trail bytes don't advance in the\n\t\t\t    // bad word.\n\t\t\t    --sp->ts_fidx;\n\t\t\tif (++sp->ts_tcharidx == sp->ts_tcharlen)\n\t\t\t{\n\t\t\t    // Last byte of character.\n\t\t\t    if (sp->ts_isdiff == DIFF_YES)\n\t\t\t    {\n\t\t\t\t// Correct ts_fidx for the byte length of the\n\t\t\t\t// character (we didn't check that before).\n\t\t\t\tsp->ts_fidx = sp->ts_fcharstart\n\t\t\t\t\t    + mb_ptr2len(\n\t\t\t\t\t\t    fword + sp->ts_fcharstart);\n\t\t\t\t// For changing a composing character adjust\n\t\t\t\t// the score from SCORE_SUBST to\n\t\t\t\t// SCORE_SUBCOMP.\n\t\t\t\tif (enc_utf8\n\t\t\t\t\t&& utf_iscomposing(\n\t\t\t\t\t    utf_ptr2char(tword\n\t\t\t\t\t\t+ sp->ts_twordlen\n\t\t\t\t\t\t\t   - sp->ts_tcharlen))\n\t\t\t\t\t&& utf_iscomposing(\n\t\t\t\t\t    utf_ptr2char(fword\n\t\t\t\t\t\t\t+ sp->ts_fcharstart)))\n\t\t\t\t    sp->ts_score -=\n\t\t\t\t\t\t  SCORE_SUBST - SCORE_SUBCOMP;\n\n\t\t\t\t// For a similar character adjust score from\n\t\t\t\t// SCORE_SUBST to SCORE_SIMILAR.\n\t\t\t\telse if (!soundfold\n\t\t\t\t\t&& slang->sl_has_map\n\t\t\t\t\t&& similar_chars(slang,\n\t\t\t\t\t    mb_ptr2char(tword\n\t\t\t\t\t\t+ sp->ts_twordlen\n\t\t\t\t\t\t\t   - sp->ts_tcharlen),\n\t\t\t\t\t    mb_ptr2char(fword\n\t\t\t\t\t\t\t+ sp->ts_fcharstart)))\n\t\t\t\t    sp->ts_score -=\n\t\t\t\t\t\t  SCORE_SUBST - SCORE_SIMILAR;\n\t\t\t    }\n\t\t\t    else if (sp->ts_isdiff == DIFF_INSERT\n\t\t\t\t\t && sp->ts_twordlen > sp->ts_tcharlen)\n\t\t\t    {\n\t\t\t\tp = tword + sp->ts_twordlen - sp->ts_tcharlen;\n\t\t\t\tc = mb_ptr2char(p);\n\t\t\t\tif (enc_utf8 && utf_iscomposing(c))\n\t\t\t\t{\n\t\t\t\t    // Inserting a composing char doesn't\n\t\t\t\t    // count that much.\n\t\t\t\t    sp->ts_score -= SCORE_INS - SCORE_INSCOMP;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t    // If the previous character was the same,\n\t\t\t\t    // thus doubling a character, give a bonus\n\t\t\t\t    // to the score.  Also for the soundfold\n\t\t\t\t    // tree (might seem illogical but does\n\t\t\t\t    // give better scores).\n\t\t\t\t    MB_PTR_BACK(tword, p);\n\t\t\t\t    if (c == mb_ptr2char(p))\n\t\t\t\t\tsp->ts_score -= SCORE_INS\n\t\t\t\t\t\t\t       - SCORE_INSDUP;\n\t\t\t\t}\n\t\t\t    }\n\n\t\t\t    // Starting a new char, reset the length.\n\t\t\t    sp->ts_tcharlen = 0;\n\t\t\t}\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\t// If we found a similar char adjust the score.\n\t\t\t// We do this after calling go_deeper() because\n\t\t\t// it's slow.\n\t\t\tif (newscore != 0\n\t\t\t\t&& !soundfold\n\t\t\t\t&& slang->sl_has_map\n\t\t\t\t&& similar_chars(slang,\n\t\t\t\t\t\t   c, fword[sp->ts_fidx - 1]))\n\t\t\t    sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR;\n\t\t    }\n\t\t}\n\t    }\n\t    break;\n\n\tcase STATE_DEL:\n\t    // When past the first byte of a multi-byte char don't try\n\t    // delete/insert/swap a character.\n\t    if (has_mbyte && sp->ts_tcharlen > 0)\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t\tbreak;\n\t    }\n\t    // Try skipping one character in the bad word (delete it).\n\t    PROF_STORE(sp->ts_state)\n\t    sp->ts_state = STATE_INS_PREP;\n\t    sp->ts_curi = 1;\n\t    if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*')\n\t\t// Deleting a vowel at the start of a word counts less, see\n\t\t// soundalike_score().\n\t\tnewscore = 2 * SCORE_DEL / 3;\n\t    else\n\t\tnewscore = SCORE_DEL;\n\t    if (fword[sp->ts_fidx] != NUL\n\t\t\t\t    && TRY_DEEPER(su, stack, depth, newscore))\n\t    {\n\t\tgo_deeper(stack, depth, newscore);\n#ifdef DEBUG_TRIEWALK\n\t\tsprintf(changename[depth], \"%.*s-%s: delete %c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tfword[sp->ts_fidx]);\n#endif\n\t\t++depth;\n\n\t\t// Remember what character we deleted, so that we can avoid\n\t\t// inserting it again.\n\t\tstack[depth].ts_flags |= TSF_DIDDEL;\n\t\tstack[depth].ts_delidx = sp->ts_fidx;\n\n\t\t// Advance over the character in fword[].  Give a bonus to the\n\t\t// score if the same character is following \"nn\" -> \"n\".  It's\n\t\t// a bit illogical for soundfold tree but it does give better\n\t\t// results.\n\t\tif (has_mbyte)\n\t\t{\n\t\t    c = mb_ptr2char(fword + sp->ts_fidx);\n\t\t    stack[depth].ts_fidx += mb_ptr2len(fword + sp->ts_fidx);\n\t\t    if (enc_utf8 && utf_iscomposing(c))\n\t\t\tstack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP;\n\t\t    else if (c == mb_ptr2char(fword + stack[depth].ts_fidx))\n\t\t\tstack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;\n\t\t}\n\t\telse\n\t\t{\n\t\t    ++stack[depth].ts_fidx;\n\t\t    if (fword[sp->ts_fidx] == fword[sp->ts_fidx + 1])\n\t\t\tstack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;\n\t\t}\n\t\tbreak;\n\t    }\n\t    // FALLTHROUGH\n\n\tcase STATE_INS_PREP:\n\t    if (sp->ts_flags & TSF_DIDDEL)\n\t    {\n\t\t// If we just deleted a byte then inserting won't make sense,\n\t\t// a substitute is always cheaper.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_SWAP;\n\t\tbreak;\n\t    }\n\n\t    // skip over NUL bytes\n\t    n = sp->ts_arridx;\n\t    for (;;)\n\t    {\n\t\tif (sp->ts_curi > byts[n])\n\t\t{\n\t\t    // Only NUL bytes at this node, go to next state.\n\t\t    PROF_STORE(sp->ts_state)\n\t\t    sp->ts_state = STATE_SWAP;\n\t\t    break;\n\t\t}\n\t\tif (byts[n + sp->ts_curi] != NUL)\n\t\t{\n\t\t    // Found a byte to insert.\n\t\t    PROF_STORE(sp->ts_state)\n\t\t    sp->ts_state = STATE_INS;\n\t\t    break;\n\t\t}\n\t\t++sp->ts_curi;\n\t    }\n\t    break;\n\n\t    // FALLTHROUGH\n\n\tcase STATE_INS:\n\t    // Insert one byte.  Repeat this for each possible byte at this\n\t    // node.\n\t    n = sp->ts_arridx;\n\t    if (sp->ts_curi > byts[n])\n\t    {\n\t\t// Done all bytes at this node, go to next state.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_SWAP;\n\t\tbreak;\n\t    }\n\n\t    // Do one more byte at this node, but:\n\t    // - Skip NUL bytes.\n\t    // - Skip the byte if it's equal to the byte in the word,\n\t    //   accepting that byte is always better.\n\t    n += sp->ts_curi++;\n\t    c = byts[n];\n\t    if (soundfold && sp->ts_twordlen == 0 && c == '*')\n\t\t// Inserting a vowel at the start of a word counts less,\n\t\t// see soundalike_score().\n\t\tnewscore = 2 * SCORE_INS / 3;\n\t    else\n\t\tnewscore = SCORE_INS;\n\t    if (c != fword[sp->ts_fidx]\n\t\t\t\t    && TRY_DEEPER(su, stack, depth, newscore))\n\t    {\n\t\tgo_deeper(stack, depth, newscore);\n#ifdef DEBUG_TRIEWALK\n\t\tsprintf(changename[depth], \"%.*s-%s: insert %c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tc);\n#endif\n\t\t++depth;\n\t\tsp = &stack[depth];\n\t\ttword[sp->ts_twordlen++] = c;\n\t\tsp->ts_arridx = idxs[n];\n\t\tif (has_mbyte)\n\t\t{\n\t\t    fl = MB_BYTE2LEN(c);\n\t\t    if (fl > 1)\n\t\t    {\n\t\t\t// There are following bytes for the same character.\n\t\t\t// We must find all bytes before trying\n\t\t\t// delete/insert/swap/etc.\n\t\t\tsp->ts_tcharlen = fl;\n\t\t\tsp->ts_tcharidx = 1;\n\t\t\tsp->ts_isdiff = DIFF_INSERT;\n\t\t    }\n\t\t}\n\t\telse\n\t\t    fl = 1;\n\t\tif (fl == 1)\n\t\t{\n\t\t    // If the previous character was the same, thus doubling a\n\t\t    // character, give a bonus to the score.  Also for\n\t\t    // soundfold words (illogical but does give a better\n\t\t    // score).\n\t\t    if (sp->ts_twordlen >= 2\n\t\t\t\t\t   && tword[sp->ts_twordlen - 2] == c)\n\t\t\tsp->ts_score -= SCORE_INS - SCORE_INSDUP;\n\t\t}\n\t    }\n\t    break;\n\n\tcase STATE_SWAP:\n\t    // Swap two bytes in the bad word: \"12\" -> \"21\".\n\t    // We change \"fword\" here, it's changed back afterwards at\n\t    // STATE_UNSWAP.\n\t    p = fword + sp->ts_fidx;\n\t    c = *p;\n\t    if (c == NUL)\n\t    {\n\t\t// End of word, can't swap or replace.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t\tbreak;\n\t    }\n\n\t    // Don't swap if the first character is not a word character.\n\t    // SWAP3 etc. also don't make sense then.\n\t    if (!soundfold && !spell_iswordp(p, curwin))\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t\tbreak;\n\t    }\n\n\t    if (has_mbyte)\n\t    {\n\t\tn = MB_CPTR2LEN(p);\n\t\tc = mb_ptr2char(p);\n\t\tif (p[n] == NUL)\n\t\t    c2 = NUL;\n\t\telse if (!soundfold && !spell_iswordp(p + n, curwin))\n\t\t    c2 = c; // don't swap non-word char\n\t\telse\n\t\t    c2 = mb_ptr2char(p + n);\n\t    }\n\t    else\n\t    {\n\t\tif (p[1] == NUL)\n\t\t    c2 = NUL;\n\t\telse if (!soundfold && !spell_iswordp(p + 1, curwin))\n\t\t    c2 = c; // don't swap non-word char\n\t\telse\n\t\t    c2 = p[1];\n\t    }\n\n\t    // When the second character is NUL we can't swap.\n\t    if (c2 == NUL)\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t\tbreak;\n\t    }\n\n\t    // When characters are identical, swap won't do anything.\n\t    // Also get here if the second char is not a word character.\n\t    if (c == c2)\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_SWAP3;\n\t\tbreak;\n\t    }\n\t    if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP))\n\t    {\n\t\tgo_deeper(stack, depth, SCORE_SWAP);\n#ifdef DEBUG_TRIEWALK\n\t\tsprintf(changename[depth], \"%.*s-%s: swap %c and %c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tc, c2);\n#endif\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_UNSWAP;\n\t\t++depth;\n\t\tif (has_mbyte)\n\t\t{\n\t\t    fl = mb_char2len(c2);\n\t\t    mch_memmove(p, p + n, fl);\n\t\t    mb_char2bytes(c, p + fl);\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;\n\t\t}\n\t\telse\n\t\t{\n\t\t    p[0] = c2;\n\t\t    p[1] = c;\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + 2;\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\t// If this swap doesn't work then SWAP3 won't either.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t    }\n\t    break;\n\n\tcase STATE_UNSWAP:\n\t    // Undo the STATE_SWAP swap: \"21\" -> \"12\".\n\t    p = fword + sp->ts_fidx;\n\t    if (has_mbyte)\n\t    {\n\t\tn = mb_ptr2len(p);\n\t\tc = mb_ptr2char(p + n);\n\t\tmch_memmove(p + mb_ptr2len(p + n), p, n);\n\t\tmb_char2bytes(c, p);\n\t    }\n\t    else\n\t    {\n\t\tc = *p;\n\t\t*p = p[1];\n\t\tp[1] = c;\n\t    }\n\t    // FALLTHROUGH\n\n\tcase STATE_SWAP3:\n\t    // Swap two bytes, skipping one: \"123\" -> \"321\".  We change\n\t    // \"fword\" here, it's changed back afterwards at STATE_UNSWAP3.\n\t    p = fword + sp->ts_fidx;\n\t    if (has_mbyte)\n\t    {\n\t\tn = MB_CPTR2LEN(p);\n\t\tc = mb_ptr2char(p);\n\t\tfl = MB_CPTR2LEN(p + n);\n\t\tc2 = mb_ptr2char(p + n);\n\t\tif (!soundfold && !spell_iswordp(p + n + fl, curwin))\n\t\t    c3 = c;\t// don't swap non-word char\n\t\telse\n\t\t    c3 = mb_ptr2char(p + n + fl);\n\t    }\n\t    else\n\t    {\n\t\tc = *p;\n\t\tc2 = p[1];\n\t\tif (!soundfold && !spell_iswordp(p + 2, curwin))\n\t\t    c3 = c;\t// don't swap non-word char\n\t\telse\n\t\t    c3 = p[2];\n\t    }\n\n\t    // When characters are identical: \"121\" then SWAP3 result is\n\t    // identical, ROT3L result is same as SWAP: \"211\", ROT3L result is\n\t    // same as SWAP on next char: \"112\".  Thus skip all swapping.\n\t    // Also skip when c3 is NUL.\n\t    // Also get here when the third character is not a word character.\n\t    // Second character may any char: \"a.b\" -> \"b.a\"\n\t    if (c == c3 || c3 == NUL)\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t\tbreak;\n\t    }\n\t    if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))\n\t    {\n\t\tgo_deeper(stack, depth, SCORE_SWAP3);\n#ifdef DEBUG_TRIEWALK\n\t\tsprintf(changename[depth], \"%.*s-%s: swap3 %c and %c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tc, c3);\n#endif\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_UNSWAP3;\n\t\t++depth;\n\t\tif (has_mbyte)\n\t\t{\n\t\t    tl = mb_char2len(c3);\n\t\t    mch_memmove(p, p + n + fl, tl);\n\t\t    mb_char2bytes(c2, p + tl);\n\t\t    mb_char2bytes(c, p + fl + tl);\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl;\n\t\t}\n\t\telse\n\t\t{\n\t\t    p[0] = p[2];\n\t\t    p[2] = c;\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + 3;\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t    }\n\t    break;\n\n\tcase STATE_UNSWAP3:\n\t    // Undo STATE_SWAP3: \"321\" -> \"123\"\n\t    p = fword + sp->ts_fidx;\n\t    if (has_mbyte)\n\t    {\n\t\tn = mb_ptr2len(p);\n\t\tc2 = mb_ptr2char(p + n);\n\t\tfl = mb_ptr2len(p + n);\n\t\tc = mb_ptr2char(p + n + fl);\n\t\ttl = mb_ptr2len(p + n + fl);\n\t\tmch_memmove(p + fl + tl, p, n);\n\t\tmb_char2bytes(c, p);\n\t\tmb_char2bytes(c2, p + tl);\n\t\tp = p + tl;\n\t    }\n\t    else\n\t    {\n\t\tc = *p;\n\t\t*p = p[2];\n\t\tp[2] = c;\n\t\t++p;\n\t    }\n\n\t    if (!soundfold && !spell_iswordp(p, curwin))\n\t    {\n\t\t// Middle char is not a word char, skip the rotate.  First and\n\t\t// third char were already checked at swap and swap3.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t\tbreak;\n\t    }\n\n\t    // Rotate three characters left: \"123\" -> \"231\".  We change\n\t    // \"fword\" here, it's changed back afterwards at STATE_UNROT3L.\n\t    if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))\n\t    {\n\t\tgo_deeper(stack, depth, SCORE_SWAP3);\n#ifdef DEBUG_TRIEWALK\n\t\tp = fword + sp->ts_fidx;\n\t\tsprintf(changename[depth], \"%.*s-%s: rotate left %c%c%c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tp[0], p[1], p[2]);\n#endif\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_UNROT3L;\n\t\t++depth;\n\t\tp = fword + sp->ts_fidx;\n\t\tif (has_mbyte)\n\t\t{\n\t\t    n = MB_CPTR2LEN(p);\n\t\t    c = mb_ptr2char(p);\n\t\t    fl = MB_CPTR2LEN(p + n);\n\t\t    fl += MB_CPTR2LEN(p + n + fl);\n\t\t    mch_memmove(p, p + n, fl);\n\t\t    mb_char2bytes(c, p + fl);\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;\n\t\t}\n\t\telse\n\t\t{\n\t\t    c = *p;\n\t\t    *p = p[1];\n\t\t    p[1] = p[2];\n\t\t    p[2] = c;\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + 3;\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t    }\n\t    break;\n\n\tcase STATE_UNROT3L:\n\t    // Undo ROT3L: \"231\" -> \"123\"\n\t    p = fword + sp->ts_fidx;\n\t    if (has_mbyte)\n\t    {\n\t\tn = mb_ptr2len(p);\n\t\tn += mb_ptr2len(p + n);\n\t\tc = mb_ptr2char(p + n);\n\t\ttl = mb_ptr2len(p + n);\n\t\tmch_memmove(p + tl, p, n);\n\t\tmb_char2bytes(c, p);\n\t    }\n\t    else\n\t    {\n\t\tc = p[2];\n\t\tp[2] = p[1];\n\t\tp[1] = *p;\n\t\t*p = c;\n\t    }\n\n\t    // Rotate three bytes right: \"123\" -> \"312\".  We change \"fword\"\n\t    // here, it's changed back afterwards at STATE_UNROT3R.\n\t    if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))\n\t    {\n\t\tgo_deeper(stack, depth, SCORE_SWAP3);\n#ifdef DEBUG_TRIEWALK\n\t\tp = fword + sp->ts_fidx;\n\t\tsprintf(changename[depth], \"%.*s-%s: rotate right %c%c%c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tp[0], p[1], p[2]);\n#endif\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_UNROT3R;\n\t\t++depth;\n\t\tp = fword + sp->ts_fidx;\n\t\tif (has_mbyte)\n\t\t{\n\t\t    n = MB_CPTR2LEN(p);\n\t\t    n += MB_CPTR2LEN(p + n);\n\t\t    c = mb_ptr2char(p + n);\n\t\t    tl = MB_CPTR2LEN(p + n);\n\t\t    mch_memmove(p + tl, p, n);\n\t\t    mb_char2bytes(c, p);\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + n + tl;\n\t\t}\n\t\telse\n\t\t{\n\t\t    c = p[2];\n\t\t    p[2] = p[1];\n\t\t    p[1] = *p;\n\t\t    *p = c;\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + 3;\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t    }\n\t    break;\n\n\tcase STATE_UNROT3R:\n\t    // Undo ROT3R: \"312\" -> \"123\"\n\t    p = fword + sp->ts_fidx;\n\t    if (has_mbyte)\n\t    {\n\t\tc = mb_ptr2char(p);\n\t\ttl = mb_ptr2len(p);\n\t\tn = mb_ptr2len(p + tl);\n\t\tn += mb_ptr2len(p + tl + n);\n\t\tmch_memmove(p, p + tl, n);\n\t\tmb_char2bytes(c, p + n);\n\t    }\n\t    else\n\t    {\n\t\tc = *p;\n\t\t*p = p[1];\n\t\tp[1] = p[2];\n\t\tp[2] = c;\n\t    }\n\t    // FALLTHROUGH\n\n\tcase STATE_REP_INI:\n\t    // Check if matching with REP items from the .aff file would work.\n\t    // Quickly skip if:\n\t    // - there are no REP items and we are not in the soundfold trie\n\t    // - the score is going to be too high anyway\n\t    // - already applied a REP item or swapped here\n\t    if ((lp->lp_replang == NULL && !soundfold)\n\t\t    || sp->ts_score + SCORE_REP >= su->su_maxscore\n\t\t    || sp->ts_fidx < sp->ts_fidxtry)\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t\tbreak;\n\t    }\n\n\t    // Use the first byte to quickly find the first entry that may\n\t    // match.  If the index is -1 there is none.\n\t    if (soundfold)\n\t\tsp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]];\n\t    else\n\t\tsp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]];\n\n\t    if (sp->ts_curi < 0)\n\t    {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t\tbreak;\n\t    }\n\n\t    PROF_STORE(sp->ts_state)\n\t    sp->ts_state = STATE_REP;\n\t    // FALLTHROUGH\n\n\tcase STATE_REP:\n\t    // Try matching with REP items from the .aff file.  For each match\n\t    // replace the characters and check if the resulting word is\n\t    // valid.\n\t    p = fword + sp->ts_fidx;\n\n\t    if (soundfold)\n\t\tgap = &slang->sl_repsal;\n\t    else\n\t\tgap = &lp->lp_replang->sl_rep;\n\t    while (sp->ts_curi < gap->ga_len)\n\t    {\n\t\tftp = (fromto_T *)gap->ga_data + sp->ts_curi++;\n\t\tif (*ftp->ft_from != *p)\n\t\t{\n\t\t    // past possible matching entries\n\t\t    sp->ts_curi = gap->ga_len;\n\t\t    break;\n\t\t}\n\t\tif (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0\n\t\t\t&& TRY_DEEPER(su, stack, depth, SCORE_REP))\n\t\t{\n\t\t    go_deeper(stack, depth, SCORE_REP);\n#ifdef DEBUG_TRIEWALK\n\t\t    sprintf(changename[depth], \"%.*s-%s: replace %s with %s\",\n\t\t\t    sp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\t    ftp->ft_from, ftp->ft_to);\n#endif\n\t\t    // Need to undo this afterwards.\n\t\t    PROF_STORE(sp->ts_state)\n\t\t    sp->ts_state = STATE_REP_UNDO;\n\n\t\t    // Change the \"from\" to the \"to\" string.\n\t\t    ++depth;\n\t\t    fl = (int)STRLEN(ftp->ft_from);\n\t\t    tl = (int)STRLEN(ftp->ft_to);\n\t\t    if (fl != tl)\n\t\t    {\n\t\t\tSTRMOVE(p + tl, p + fl);\n\t\t\trepextra += tl - fl;\n\t\t    }\n\t\t    mch_memmove(p, ftp->ft_to, tl);\n\t\t    stack[depth].ts_fidxtry = sp->ts_fidx + tl;\n\t\t    stack[depth].ts_tcharlen = 0;\n\t\t    break;\n\t\t}\n\t    }\n\n\t    if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP)\n\t    {\n\t\t// No (more) matches.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t    }\n\n\t    break;\n\n\tcase STATE_REP_UNDO:\n\t    // Undo a REP replacement and continue with the next one.\n\t    if (soundfold)\n\t\tgap = &slang->sl_repsal;\n\t    else\n\t\tgap = &lp->lp_replang->sl_rep;\n\t    ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1;\n\t    fl = (int)STRLEN(ftp->ft_from);\n\t    tl = (int)STRLEN(ftp->ft_to);\n\t    p = fword + sp->ts_fidx;\n\t    if (fl != tl)\n\t    {\n\t\tSTRMOVE(p + fl, p + tl);\n\t\trepextra -= tl - fl;\n\t    }\n\t    mch_memmove(p, ftp->ft_from, fl);\n\t    PROF_STORE(sp->ts_state)\n\t    sp->ts_state = STATE_REP;\n\t    break;\n\n\tdefault:\n\t    // Did all possible states at this level, go up one level.\n\t    --depth;\n\n\t    if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE)\n\t    {\n\t\t// Continue in or go back to the prefix tree.\n\t\tbyts = pbyts;\n\t\tidxs = pidxs;\n\t    }\n\n\t    // Don't check for CTRL-C too often, it takes time.\n\t    if (--breakcheckcount == 0)\n\t    {\n\t\tui_breakcheck();\n\t\tbreakcheckcount = 1000;\n#ifdef FEAT_RELTIME\n\t\tif (spell_suggest_timeout > 0\n\t\t\t\t\t  && profile_passed_limit(&time_limit))\n\t\t    got_int = TRUE;\n#endif\n\t    }\n\t}\n    }\n}", "func_hash": 165297537933585359474732803706192755392, "file_name": "spellsuggest.c", "file_hash": 24915610722049363928699434605775326954, "cwe": ["CWE-787"], "cve": "CVE-2022-2126", "cve_desc": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2126"}
{"idx": 200379, "project": "radare2", "commit_id": "48f0ea79f99174fb0a62cb2354e13496ce5b7c44", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/48f0ea79f99174fb0a62cb2354e13496ce5b7c44", "commit_message": "Fix null deref in ne parser ##crash\n\n* Reported by @cnitlrt via huntr.dev\n* BountyID: d8b6d239-6d7b-4783-b26b-5be848c01aa1/\n* Reproducer: nenull", "target": 1, "func": "RList *r_bin_ne_get_segments(r_bin_ne_obj_t *bin) {\n\tint i;\n\tif (!bin) {\n\t\treturn NULL;\n\t}\n\tRList *segments = r_list_newf (free);\n\tfor (i = 0; i < bin->ne_header->SegCount; i++) {\n\t\tRBinSection *bs = R_NEW0 (RBinSection);\n\t\tif (!bs) {\n\t\t\treturn segments;\n\t\t}\n\t\tNE_image_segment_entry *se = &bin->segment_entries[i];\n\t\tbs->size = se->length;\n\t\tbs->vsize = se->minAllocSz ? se->minAllocSz : 64000;\n\t\tbs->bits = R_SYS_BITS_16;\n\t\tbs->is_data = se->flags & IS_DATA;\n\t\tbs->perm = __translate_perms (se->flags);\n\t\tbs->paddr = (ut64)se->offset * bin->alignment;\n\t\tbs->name = r_str_newf (\"%s.%\" PFMT64d, se->flags & IS_MOVEABLE ? \"MOVEABLE\" : \"FIXED\", bs->paddr);\n\t\tbs->is_segment = true;\n\t\tr_list_append (segments, bs);\n\t}\n\tbin->segments = segments;\n\treturn segments;\n}", "func_hash": 32265811031369210493685487313253460681, "file_name": "ne.c", "file_hash": 158187364999589473605822811150926540610, "cwe": ["CWE-476"], "cve": "CVE-2022-1382", "cve_desc": "NULL Pointer Dereference in GitHub repository radareorg/radare2 prior to 5.6.8. This vulnerability is capable of making the radare2 crash, thus affecting the availability of the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1382"}
{"idx": 302095, "project": "radare2", "commit_id": "48f0ea79f99174fb0a62cb2354e13496ce5b7c44", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/48f0ea79f99174fb0a62cb2354e13496ce5b7c44", "commit_message": "Fix null deref in ne parser ##crash\n\n* Reported by @cnitlrt via huntr.dev\n* BountyID: d8b6d239-6d7b-4783-b26b-5be848c01aa1/\n* Reproducer: nenull", "target": 0, "func": "RList *r_bin_ne_get_segments(r_bin_ne_obj_t *bin) {\n\tint i;\n\tif (!bin || !bin->segment_entries) {\n\t\treturn NULL;\n\t}\n\tRList *segments = r_list_newf (free);\n\tfor (i = 0; i < bin->ne_header->SegCount; i++) {\n\t\tRBinSection *bs = R_NEW0 (RBinSection);\n\t\tif (!bs) {\n\t\t\treturn segments;\n\t\t}\n\t\tNE_image_segment_entry *se = &bin->segment_entries[i];\n\t\tbs->size = se->length;\n\t\tbs->vsize = se->minAllocSz ? se->minAllocSz : 64000;\n\t\tbs->bits = R_SYS_BITS_16;\n\t\tbs->is_data = se->flags & IS_DATA;\n\t\tbs->perm = __translate_perms (se->flags);\n\t\tbs->paddr = (ut64)se->offset * bin->alignment;\n\t\tbs->name = r_str_newf (\"%s.%\" PFMT64d, se->flags & IS_MOVEABLE ? \"MOVEABLE\" : \"FIXED\", bs->paddr);\n\t\tbs->is_segment = true;\n\t\tr_list_append (segments, bs);\n\t}\n\tbin->segments = segments;\n\treturn segments;\n}", "func_hash": 16263805032815021006718433120091850858, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2022-1382", "cve_desc": "NULL Pointer Dereference in GitHub repository radareorg/radare2 prior to 5.6.8. This vulnerability is capable of making the radare2 crash, thus affecting the availability of the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1382"}
{"idx": 200695, "project": "linux", "commit_id": "fc739a058d99c9297ef6bfd923b809d85855b9a9", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/fc739a058d99c9297ef6bfd923b809d85855b9a9", "commit_message": "misc: fastrpc: prevent memory leak in fastrpc_dma_buf_attach\n\nIn fastrpc_dma_buf_attach if dma_get_sgtable fails the allocated memory\nfor a should be released.\n\nSigned-off-by: Navid Emamdoost \nLink: https://lore.kernel.org/r/20190925152742.16258-1-navid.emamdoost@gmail.com\nSigned-off-by: Greg Kroah-Hartman ", "target": 1, "func": "static int fastrpc_dma_buf_attach(struct dma_buf *dmabuf,\n\t\t\t\t  struct dma_buf_attachment *attachment)\n{\n\tstruct fastrpc_dma_buf_attachment *a;\n\tstruct fastrpc_buf *buffer = dmabuf->priv;\n\tint ret;\n\n\ta = kzalloc(sizeof(*a), GFP_KERNEL);\n\tif (!a)\n\t\treturn -ENOMEM;\n\n\tret = dma_get_sgtable(buffer->dev, &a->sgt, buffer->virt,\n\t\t\t      FASTRPC_PHYS(buffer->phys), buffer->size);\n\tif (ret < 0) {\n\t\tdev_err(buffer->dev, \"failed to get scatterlist from DMA API\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\ta->dev = attachment->dev;\n\tINIT_LIST_HEAD(&a->node);\n\tattachment->priv = a;\n\n\tmutex_lock(&buffer->lock);\n\tlist_add(&a->node, &buffer->attachments);\n\tmutex_unlock(&buffer->lock);\n\n\treturn 0;\n}", "func_hash": 226882745088672382788622327400287132857, "file_name": "fastrpc.c", "file_hash": 22170772729445349597675548574301219151, "cwe": ["CWE-401"], "cve": "CVE-2019-19069", "cve_desc": "A memory leak in the fastrpc_dma_buf_attach() function in drivers/misc/fastrpc.c in the Linux kernel before 5.3.9 allows attackers to cause a denial of service (memory consumption) by triggering dma_get_sgtable() failures, aka CID-fc739a058d99.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19069"}
{"idx": 308163, "project": "linux", "commit_id": "fc739a058d99c9297ef6bfd923b809d85855b9a9", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/fc739a058d99c9297ef6bfd923b809d85855b9a9", "commit_message": "misc: fastrpc: prevent memory leak in fastrpc_dma_buf_attach\n\nIn fastrpc_dma_buf_attach if dma_get_sgtable fails the allocated memory\nfor a should be released.\n\nSigned-off-by: Navid Emamdoost \nLink: https://lore.kernel.org/r/20190925152742.16258-1-navid.emamdoost@gmail.com\nSigned-off-by: Greg Kroah-Hartman ", "target": 0, "func": "static int fastrpc_dma_buf_attach(struct dma_buf *dmabuf,\n\t\t\t\t  struct dma_buf_attachment *attachment)\n{\n\tstruct fastrpc_dma_buf_attachment *a;\n\tstruct fastrpc_buf *buffer = dmabuf->priv;\n\tint ret;\n\n\ta = kzalloc(sizeof(*a), GFP_KERNEL);\n\tif (!a)\n\t\treturn -ENOMEM;\n\n\tret = dma_get_sgtable(buffer->dev, &a->sgt, buffer->virt,\n\t\t\t      FASTRPC_PHYS(buffer->phys), buffer->size);\n\tif (ret < 0) {\n\t\tdev_err(buffer->dev, \"failed to get scatterlist from DMA API\\n\");\n\t\tkfree(a);\n\t\treturn -EINVAL;\n\t}\n\n\ta->dev = attachment->dev;\n\tINIT_LIST_HEAD(&a->node);\n\tattachment->priv = a;\n\n\tmutex_lock(&buffer->lock);\n\tlist_add(&a->node, &buffer->attachments);\n\tmutex_unlock(&buffer->lock);\n\n\treturn 0;\n}", "func_hash": 207220312586035988811790061557628451284, "file_name": "fastrpc.c", "file_hash": 163997548888586618383929907046515889539, "cwe": ["CWE-401"], "cve": "CVE-2019-19069", "cve_desc": "A memory leak in the fastrpc_dma_buf_attach() function in drivers/misc/fastrpc.c in the Linux kernel before 5.3.9 allows attackers to cause a denial of service (memory consumption) by triggering dma_get_sgtable() failures, aka CID-fc739a058d99.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19069"}
{"idx": 200781, "project": "ncurses", "commit_id": "790a85dbd4a81d5f5d8dd02a44d84f01512ef443", "project_url": "https://github.com/mirror/ncurses", "commit_url": "https://github.com/mirror/ncurses/commit/790a85dbd4a81d5f5d8dd02a44d84f01512ef443#diff-7e95c7bc5f213e9be438e69a9d5d0f261a14952bcbd692f7b9014217b8047340", "commit_message": "ncurses 6.2 - patch 20200531\n\n+ correct configure version-check/warnng for g++ to allow for 10.x\n+ re-enable \"bel\" in konsole-base (report by Nia Huang)\n+ add linux-s entry (patch by Alexandre Montaron).\n+ drop long-obsolete convert_configure.pl\n+ add test/test_parm.c, for checking tparm changes.\n+ improve parameter-checking for tparm, adding function _nc_tiparm() to\n  handle the most-used case, which accepts only numeric parameters\n  (report/testcase by \"puppet-meteor\").\n+ use a more conservative estimate of the buffer-size in lib_tparm.c's\n  save_text() and save_number(), in case the sprintf() function\n  passes-through unexpected characters from a format specifier\n  (report/testcase by \"puppet-meteor\").\n+ add a check for end-of-string in cvtchar to handle a malformed\n  string in infotocap (report/testcase by \"puppet-meteor\").", "target": 1, "func": "cvtchar(register const char *sp)\n/* convert a character to a terminfo push */\n{\n    unsigned char c = 0;\n    int len;\n\n    switch (*sp) {\n    case '\\\\':\n\tswitch (*++sp) {\n\tcase '\\'':\n\tcase '$':\n\tcase '\\\\':\n\tcase '%':\n\t    c = UChar(*sp);\n\t    len = 2;\n\t    break;\n\tcase '\\0':\n\t    c = '\\\\';\n\t    len = 1;\n\t    break;\n\tcase '0':\n\tcase '1':\n\tcase '2':\n\tcase '3':\n\t    len = 1;\n\t    while (isdigit(UChar(*sp))) {\n\t\tc = UChar(8 * c + (*sp++ - '0'));\n\t\tlen++;\n\t    }\n\t    break;\n\tdefault:\n\t    c = UChar(*sp);\n\t    len = (c != '\\0') ? 2 : 1;\n\t    break;\n\t}\n\tbreak;\n    case '^':\n\tc = UChar(*++sp);\n\tif (c == '?')\n\t    c = 127;\n\telse\n\t    c &= 0x1f;\n\tlen = 2;\n\tbreak;\n    default:\n\tc = UChar(*sp);\n\tlen = (c != '\\0') ? 1 : 0;\n    }\n    if (isgraph(c) && c != ',' && c != '\\'' && c != '\\\\' && c != ':') {\n\tdp = save_string(dp, \"%\\'\");\n\tdp = save_char(dp, c);\n\tdp = save_char(dp, '\\'');\n    } else if (c != '\\0') {\n\tdp = save_string(dp, \"%{\");\n\tif (c > 99)\n\t    dp = save_char(dp, c / 100 + '0');\n\tif (c > 9)\n\t    dp = save_char(dp, ((int) (c / 10)) % 10 + '0');\n\tdp = save_char(dp, c % 10 + '0');\n\tdp = save_char(dp, '}');\n    }\n    return len;\n}", "func_hash": 56621931750240830327732003181202918311, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2021-39537", "cve_desc": "An issue was discovered in ncurses through v6.2-1. _nc_captoinfo in captoinfo.c has a heap-based buffer overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-39537"}
{"idx": 309831, "project": "ncurses", "commit_id": "790a85dbd4a81d5f5d8dd02a44d84f01512ef443", "project_url": "https://github.com/mirror/ncurses", "commit_url": "https://github.com/mirror/ncurses/commit/790a85dbd4a81d5f5d8dd02a44d84f01512ef443#diff-7e95c7bc5f213e9be438e69a9d5d0f261a14952bcbd692f7b9014217b8047340", "commit_message": "ncurses 6.2 - patch 20200531\n\n+ correct configure version-check/warnng for g++ to allow for 10.x\n+ re-enable \"bel\" in konsole-base (report by Nia Huang)\n+ add linux-s entry (patch by Alexandre Montaron).\n+ drop long-obsolete convert_configure.pl\n+ add test/test_parm.c, for checking tparm changes.\n+ improve parameter-checking for tparm, adding function _nc_tiparm() to\n  handle the most-used case, which accepts only numeric parameters\n  (report/testcase by \"puppet-meteor\").\n+ use a more conservative estimate of the buffer-size in lib_tparm.c's\n  save_text() and save_number(), in case the sprintf() function\n  passes-through unexpected characters from a format specifier\n  (report/testcase by \"puppet-meteor\").\n+ add a check for end-of-string in cvtchar to handle a malformed\n  string in infotocap (report/testcase by \"puppet-meteor\").", "target": 0, "func": "cvtchar(register const char *sp)\n/* convert a character to a terminfo push */\n{\n    unsigned char c = 0;\n    int len;\n\n    switch (*sp) {\n    case '\\\\':\n\tswitch (*++sp) {\n\tcase '\\'':\n\tcase '$':\n\tcase '\\\\':\n\tcase '%':\n\t    c = UChar(*sp);\n\t    len = 2;\n\t    break;\n\tcase '\\0':\n\t    c = '\\\\';\n\t    len = 1;\n\t    break;\n\tcase '0':\n\tcase '1':\n\tcase '2':\n\tcase '3':\n\t    len = 1;\n\t    while (isdigit(UChar(*sp))) {\n\t\tc = UChar(8 * c + (*sp++ - '0'));\n\t\tlen++;\n\t    }\n\t    break;\n\tdefault:\n\t    c = UChar(*sp);\n\t    len = (c != '\\0') ? 2 : 1;\n\t    break;\n\t}\n\tbreak;\n    case '^':\n\tlen = 2;\n\tc = UChar(*++sp);\n\tif (c == '?') {\n\t    c = 127;\n\t} else if (c == '\\0') {\n\t    len = 1;\n\t} else {\n\t    c &= 0x1f;\n\t}\n\tbreak;\n    default:\n\tc = UChar(*sp);\n\tlen = (c != '\\0') ? 1 : 0;\n    }\n    if (isgraph(c) && c != ',' && c != '\\'' && c != '\\\\' && c != ':') {\n\tdp = save_string(dp, \"%\\'\");\n\tdp = save_char(dp, c);\n\tdp = save_char(dp, '\\'');\n    } else if (c != '\\0') {\n\tdp = save_string(dp, \"%{\");\n\tif (c > 99)\n\t    dp = save_char(dp, c / 100 + '0');\n\tif (c > 9)\n\t    dp = save_char(dp, ((int) (c / 10)) % 10 + '0');\n\tdp = save_char(dp, c % 10 + '0');\n\tdp = save_char(dp, '}');\n    }\n    return len;\n}", "func_hash": 173803971118928045075700643623936984208, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2021-39537", "cve_desc": "An issue was discovered in ncurses through v6.2-1. _nc_captoinfo in captoinfo.c has a heap-based buffer overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-39537"}
{"idx": 200895, "project": "vim", "commit_id": "d6c67629ed05aae436164eec474832daf8ba7420", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/d6c67629ed05aae436164eec474832daf8ba7420", "commit_message": "patch 9.0.0260: using freed memory when using 'quickfixtextfunc' recursively\n\nProblem:    Using freed memory when using 'quickfixtextfunc' recursively.\nSolution:   Do not allow for recursion.", "target": 1, "func": "call_qftf_func(qf_list_T *qfl, int qf_winid, long start_idx, long end_idx)\n{\n    callback_T\t*cb = &qftf_cb;\n    list_T\t*qftf_list = NULL;\n\n    // If 'quickfixtextfunc' is set, then use the user-supplied function to get\n    // the text to display. Use the local value of 'quickfixtextfunc' if it is\n    // set.\n    if (qfl->qf_qftf_cb.cb_name != NULL)\n\tcb = &qfl->qf_qftf_cb;\n    if (cb->cb_name != NULL)\n    {\n\ttypval_T\targs[1];\n\tdict_T\t\t*d;\n\ttypval_T\trettv;\n\n\t// create the dict argument\n\tif ((d = dict_alloc_lock(VAR_FIXED)) == NULL)\n\t    return NULL;\n\tdict_add_number(d, \"quickfix\", (long)IS_QF_LIST(qfl));\n\tdict_add_number(d, \"winid\", (long)qf_winid);\n\tdict_add_number(d, \"id\", (long)qfl->qf_id);\n\tdict_add_number(d, \"start_idx\", start_idx);\n\tdict_add_number(d, \"end_idx\", end_idx);\n\t++d->dv_refcount;\n\targs[0].v_type = VAR_DICT;\n\targs[0].vval.v_dict = d;\n\n\tqftf_list = NULL;\n\tif (call_callback(cb, 0, &rettv, 1, args) != FAIL)\n\t{\n\t    if (rettv.v_type == VAR_LIST)\n\t    {\n\t\tqftf_list = rettv.vval.v_list;\n\t\tqftf_list->lv_refcount++;\n\t    }\n\t    clear_tv(&rettv);\n\t}\n\tdict_unref(d);\n    }\n\n    return qftf_list;\n}", "func_hash": 339333086271181560510428879683096773754, "file_name": "None", "file_hash": null, "cwe": ["CWE-703"], "cve": "CVE-2022-2982", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 9.0.0260.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2982"}
{"idx": 312399, "project": "vim", "commit_id": "d6c67629ed05aae436164eec474832daf8ba7420", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/d6c67629ed05aae436164eec474832daf8ba7420", "commit_message": "patch 9.0.0260: using freed memory when using 'quickfixtextfunc' recursively\n\nProblem:    Using freed memory when using 'quickfixtextfunc' recursively.\nSolution:   Do not allow for recursion.", "target": 0, "func": "call_qftf_func(qf_list_T *qfl, int qf_winid, long start_idx, long end_idx)\n{\n    callback_T\t*cb = &qftf_cb;\n    list_T\t*qftf_list = NULL;\n    static int\trecursive = FALSE;\n\n    if (recursive)\n\treturn NULL;  // this doesn't work properly recursively\n    recursive = TRUE;\n\n    // If 'quickfixtextfunc' is set, then use the user-supplied function to get\n    // the text to display. Use the local value of 'quickfixtextfunc' if it is\n    // set.\n    if (qfl->qf_qftf_cb.cb_name != NULL)\n\tcb = &qfl->qf_qftf_cb;\n    if (cb->cb_name != NULL)\n    {\n\ttypval_T\targs[1];\n\tdict_T\t\t*d;\n\ttypval_T\trettv;\n\n\t// create the dict argument\n\tif ((d = dict_alloc_lock(VAR_FIXED)) == NULL)\n\t{\n\t    recursive = FALSE;\n\t    return NULL;\n\t}\n\tdict_add_number(d, \"quickfix\", (long)IS_QF_LIST(qfl));\n\tdict_add_number(d, \"winid\", (long)qf_winid);\n\tdict_add_number(d, \"id\", (long)qfl->qf_id);\n\tdict_add_number(d, \"start_idx\", start_idx);\n\tdict_add_number(d, \"end_idx\", end_idx);\n\t++d->dv_refcount;\n\targs[0].v_type = VAR_DICT;\n\targs[0].vval.v_dict = d;\n\n\tqftf_list = NULL;\n\tif (call_callback(cb, 0, &rettv, 1, args) != FAIL)\n\t{\n\t    if (rettv.v_type == VAR_LIST)\n\t    {\n\t\tqftf_list = rettv.vval.v_list;\n\t\tqftf_list->lv_refcount++;\n\t    }\n\t    clear_tv(&rettv);\n\t}\n\tdict_unref(d);\n    }\n\n    recursive = FALSE;\n    return qftf_list;\n}", "func_hash": 274532016932228792070981910727654880739, "file_name": "quickfix.c", "file_hash": 221790887990910120742119728344121157301, "cwe": ["CWE-703"], "cve": "CVE-2022-2982", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 9.0.0260.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2982"}
{"idx": 200934, "project": "libvirt", "commit_id": "524de6cc35d3b222f0e940bb0fd027f5482572c5", "project_url": "https://github.com/libvirt/libvirt", "commit_url": "https://github.com/libvirt/libvirt/commit/524de6cc35d3b222f0e940bb0fd027f5482572c5", "commit_message": "virstoragetest: testBackingParse: Use VIR_DOMAIN_DEF_FORMAT_SECURE when formatting xml\n\nWe want to format even the secure information in tests.\n\nSigned-off-by: Peter Krempa \nReviewed-by: Erik Skultety ", "target": 1, "func": "testBackingParse(const void *args)\n{\n    const struct testBackingParseData *data = args;\n    g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;\n    g_autofree char *xml = NULL;\n    g_autoptr(virStorageSource) src = NULL;\n    int rc;\n    int erc = data->rv;\n\n    /* expect failure return code with NULL expected data */\n    if (!data->expect)\n        erc = -1;\n\n    if ((rc = virStorageSourceNewFromBackingAbsolute(data->backing, &src)) != erc) {\n        fprintf(stderr, \"expected return value '%d' actual '%d'\\n\", erc, rc);\n        return -1;\n    }\n\n    if (!src)\n        return 0;\n\n    if (src && !data->expect) {\n        fprintf(stderr, \"parsing of backing store string '%s' should \"\n                        \"have failed\\n\", data->backing);\n        return -1;\n    }\n\n    if (virDomainDiskSourceFormat(&buf, src, \"source\", 0, false, 0, true, NULL) < 0 ||\n        !(xml = virBufferContentAndReset(&buf))) {\n        fprintf(stderr, \"failed to format disk source xml\\n\");\n        return -1;\n    }\n\n    if (STRNEQ(xml, data->expect)) {\n        fprintf(stderr, \"\\n backing store string '%s'\\n\"\n                        \"expected storage source xml:\\n%s\\n\"\n                        \"actual storage source xml:\\n%s\\n\",\n                        data->backing, data->expect, xml);\n        return -1;\n    }\n\n    return 0;\n}", "func_hash": 11097234962036893945341293376039418410, "file_name": "virstoragetest.c", "file_hash": 229136922246575533938843249875631381172, "cwe": ["CWE-212"], "cve": "CVE-2020-14301", "cve_desc": "An information disclosure vulnerability was found in libvirt in versions before 6.3.0. HTTP cookies used to access network-based disks were saved in the XML dump of the guest domain. This flaw allows an attacker to access potentially sensitive information in the domain configuration via the `dumpxml` command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-14301"}
{"idx": 313134, "project": "libvirt", "commit_id": "524de6cc35d3b222f0e940bb0fd027f5482572c5", "project_url": "https://github.com/libvirt/libvirt", "commit_url": "https://github.com/libvirt/libvirt/commit/524de6cc35d3b222f0e940bb0fd027f5482572c5", "commit_message": "virstoragetest: testBackingParse: Use VIR_DOMAIN_DEF_FORMAT_SECURE when formatting xml\n\nWe want to format even the secure information in tests.\n\nSigned-off-by: Peter Krempa \nReviewed-by: Erik Skultety ", "target": 0, "func": "testBackingParse(const void *args)\n{\n    const struct testBackingParseData *data = args;\n    g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;\n    g_autofree char *xml = NULL;\n    g_autoptr(virStorageSource) src = NULL;\n    int rc;\n    int erc = data->rv;\n    unsigned int xmlformatflags = VIR_DOMAIN_DEF_FORMAT_SECURE;\n\n    /* expect failure return code with NULL expected data */\n    if (!data->expect)\n        erc = -1;\n\n    if ((rc = virStorageSourceNewFromBackingAbsolute(data->backing, &src)) != erc) {\n        fprintf(stderr, \"expected return value '%d' actual '%d'\\n\", erc, rc);\n        return -1;\n    }\n\n    if (!src)\n        return 0;\n\n    if (src && !data->expect) {\n        fprintf(stderr, \"parsing of backing store string '%s' should \"\n                        \"have failed\\n\", data->backing);\n        return -1;\n    }\n\n    if (virDomainDiskSourceFormat(&buf, src, \"source\", 0, false, xmlformatflags, true, NULL) < 0 ||\n        !(xml = virBufferContentAndReset(&buf))) {\n        fprintf(stderr, \"failed to format disk source xml\\n\");\n        return -1;\n    }\n\n    if (STRNEQ(xml, data->expect)) {\n        fprintf(stderr, \"\\n backing store string '%s'\\n\"\n                        \"expected storage source xml:\\n%s\\n\"\n                        \"actual storage source xml:\\n%s\\n\",\n                        data->backing, data->expect, xml);\n        return -1;\n    }\n\n    return 0;\n}", "func_hash": 323157311431778658152105206238946839547, "file_name": "virstoragetest.c", "file_hash": 268394034841003390499099830389942989362, "cwe": ["CWE-212"], "cve": "CVE-2020-14301", "cve_desc": "An information disclosure vulnerability was found in libvirt in versions before 6.3.0. HTTP cookies used to access network-based disks were saved in the XML dump of the guest domain. This flaw allows an attacker to access potentially sensitive information in the domain configuration via the `dumpxml` command.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-14301"}
{"idx": 200976, "project": "vim", "commit_id": "395bd1f6d3edc9f7edb5d1f2d7deaf5a9e3ab93c", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/395bd1f6d3edc9f7edb5d1f2d7deaf5a9e3ab93c", "commit_message": "patch 8.2.4956: reading past end of line with \"gf\" in Visual block mode\n\nProblem:    Reading past end of line with \"gf\" in Visual block mode.\nSolution:   Do not include the NUL in the length.", "target": 1, "func": "get_visual_text(\n    cmdarg_T\t*cap,\n    char_u\t**pp,\t    // return: start of selected text\n    int\t\t*lenp)\t    // return: length of selected text\n{\n    if (VIsual_mode != 'V')\n\tunadjust_for_sel();\n    if (VIsual.lnum != curwin->w_cursor.lnum)\n    {\n\tif (cap != NULL)\n\t    clearopbeep(cap->oap);\n\treturn FAIL;\n    }\n    if (VIsual_mode == 'V')\n    {\n\t*pp = ml_get_curline();\n\t*lenp = (int)STRLEN(*pp);\n    }\n    else\n    {\n\tif (LT_POS(curwin->w_cursor, VIsual))\n\t{\n\t    *pp = ml_get_pos(&curwin->w_cursor);\n\t    *lenp = VIsual.col - curwin->w_cursor.col + 1;\n\t}\n\telse\n\t{\n\t    *pp = ml_get_pos(&VIsual);\n\t    *lenp = curwin->w_cursor.col - VIsual.col + 1;\n\t}\n\tif (**pp == NUL)\n\t    *lenp = 0;\n\tif (has_mbyte && *lenp > 0)\n\t    // Correct the length to include all bytes of the last character.\n\t    *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1;\n    }\n    reset_VIsual_and_resel();\n    return OK;\n}", "func_hash": 284497166738290361019440448049627151253, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-1720", "cve_desc": "Buffer Over-read in function grab_file_name in GitHub repository vim/vim prior to 8.2.4956. This vulnerability is capable of crashing the software, memory modification, and possible remote execution.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1720"}
{"idx": 313850, "project": "vim", "commit_id": "395bd1f6d3edc9f7edb5d1f2d7deaf5a9e3ab93c", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/395bd1f6d3edc9f7edb5d1f2d7deaf5a9e3ab93c", "commit_message": "patch 8.2.4956: reading past end of line with \"gf\" in Visual block mode\n\nProblem:    Reading past end of line with \"gf\" in Visual block mode.\nSolution:   Do not include the NUL in the length.", "target": 0, "func": "get_visual_text(\n    cmdarg_T\t*cap,\n    char_u\t**pp,\t    // return: start of selected text\n    int\t\t*lenp)\t    // return: length of selected text\n{\n    if (VIsual_mode != 'V')\n\tunadjust_for_sel();\n    if (VIsual.lnum != curwin->w_cursor.lnum)\n    {\n\tif (cap != NULL)\n\t    clearopbeep(cap->oap);\n\treturn FAIL;\n    }\n    if (VIsual_mode == 'V')\n    {\n\t*pp = ml_get_curline();\n\t*lenp = (int)STRLEN(*pp);\n    }\n    else\n    {\n\tif (LT_POS(curwin->w_cursor, VIsual))\n\t{\n\t    *pp = ml_get_pos(&curwin->w_cursor);\n\t    *lenp = VIsual.col - curwin->w_cursor.col + 1;\n\t}\n\telse\n\t{\n\t    *pp = ml_get_pos(&VIsual);\n\t    *lenp = curwin->w_cursor.col - VIsual.col + 1;\n\t}\n\tif (**pp == NUL)\n\t    *lenp = 0;\n\tif (*lenp > 0)\n\t{\n\t    if (has_mbyte)\n\t\t// Correct the length to include all bytes of the last\n\t\t// character.\n\t\t*lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1;\n\t    else if ((*pp)[*lenp - 1] == NUL)\n\t\t// Do not include a trailing NUL.\n\t\t*lenp -= 1;\n\t}\n    }\n    reset_VIsual_and_resel();\n    return OK;\n}", "func_hash": 15864851933404674407235198527938236742, "file_name": "normal.c", "file_hash": 69342701404952166153136910551883160678, "cwe": ["CWE-787"], "cve": "CVE-2022-1720", "cve_desc": "Buffer Over-read in function grab_file_name in GitHub repository vim/vim prior to 8.2.4956. This vulnerability is capable of crashing the software, memory modification, and possible remote execution.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1720"}
{"idx": 201007, "project": "pjproject", "commit_id": "560a1346f87aabe126509bb24930106dea292b00", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/560a1346f87aabe126509bb24930106dea292b00", "commit_message": "Merge pull request from GHSA-f5qg-pqcg-765m", "target": 1, "func": "static int print_media_desc(const pjmedia_sdp_media *m, char *buf, pj_size_t len)\n{\n    char *p = buf;\n    char *end = buf+len;\n    unsigned i;\n    int printed;\n\n    /* check length for the \"m=\" line. */\n    if (len < (pj_size_t)m->desc.media.slen+m->desc.transport.slen+12+24) {\n\treturn -1;\n    }\n    *p++ = 'm';\t    /* m= */\n    *p++ = '=';\n    pj_memcpy(p, m->desc.media.ptr, m->desc.media.slen);\n    p += m->desc.media.slen;\n    *p++ = ' ';\n    printed = pj_utoa(m->desc.port, p);\n    p += printed;\n    if (m->desc.port_count > 1) {\n\t*p++ = '/';\n\tprinted = pj_utoa(m->desc.port_count, p);\n\tp += printed;\n    }\n    *p++ = ' ';\n    pj_memcpy(p, m->desc.transport.ptr, m->desc.transport.slen);\n    p += m->desc.transport.slen;\n    for (i=0; idesc.fmt_count; ++i) {\n\t*p++ = ' ';\n\tpj_memcpy(p, m->desc.fmt[i].ptr, m->desc.fmt[i].slen);\n\tp += m->desc.fmt[i].slen;\n    }\n    *p++ = '\\r';\n    *p++ = '\\n';\n\n    /* print connection info, if present. */\n    if (m->conn) {\n\tprinted = print_connection_info(m->conn, p, (int)(end-p));\n\tif (printed < 0) {\n\t    return -1;\n\t}\n\tp += printed;\n    }\n    \n    /* print optional bandwidth info. */\n    for (i=0; ibandw_count; ++i) {\n\tprinted = (int)print_bandw(m->bandw[i], p, end-p);\n\tif (printed < 0) {\n\t    return -1;\n\t}\n\tp += printed;\n    }\n\n    /* print attributes. */\n    for (i=0; iattr_count; ++i) {\n\tprinted = (int)print_attr(m->attr[i], p, end-p);\n\tif (printed < 0) {\n\t    return -1;\n\t}\n\tp += printed;\n    }\n\n    return (int)(p-buf);\n}", "func_hash": 243109353869436532488614405590479215364, "file_name": "sdp.c", "file_hash": 204440288713003047579803744169338279171, "cwe": ["CWE-787"], "cve": "CVE-2022-24764", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C. Versions 2.12 and prior contain a stack buffer overflow vulnerability that affects PJSUA2 users or users that call the API `pjmedia_sdp_print(), pjmedia_sdp_media_print()`. Applications that do not use PJSUA2 and do not directly call `pjmedia_sdp_print()` or `pjmedia_sdp_media_print()` should not be affected. A patch is available on the `master` branch of the `pjsip/pjproject` GitHub repository. There are currently no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24764"}
{"idx": 314536, "project": "pjproject", "commit_id": "560a1346f87aabe126509bb24930106dea292b00", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/560a1346f87aabe126509bb24930106dea292b00", "commit_message": "Merge pull request from GHSA-f5qg-pqcg-765m", "target": 0, "func": "static int print_media_desc(const pjmedia_sdp_media *m, char *buf, pj_size_t len)\n{\n    char *p = buf;\n    char *end = buf+len;\n    unsigned i;\n    int printed;\n\n    /* check length for the \"m=\" line. */\n    if (len < (pj_size_t)m->desc.media.slen+m->desc.transport.slen+12+24) {\n\treturn -1;\n    }\n    *p++ = 'm';\t    /* m= */\n    *p++ = '=';\n    pj_memcpy(p, m->desc.media.ptr, m->desc.media.slen);\n    p += m->desc.media.slen;\n    *p++ = ' ';\n    printed = pj_utoa(m->desc.port, p);\n    p += printed;\n    if (m->desc.port_count > 1) {\n\t*p++ = '/';\n\tprinted = pj_utoa(m->desc.port_count, p);\n\tp += printed;\n    }\n    *p++ = ' ';\n    pj_memcpy(p, m->desc.transport.ptr, m->desc.transport.slen);\n    p += m->desc.transport.slen;\n    for (i=0; idesc.fmt_count; ++i) {\n\tif (end-p > m->desc.fmt[i].slen) {\n\t    *p++ = ' ';\n\t    pj_memcpy(p, m->desc.fmt[i].ptr, m->desc.fmt[i].slen);\n\t    p += m->desc.fmt[i].slen;\n\t} else {\n\t    return -1;\n\t}\n    }\n\n    if (end-p >= 2) {\n\t*p++ = '\\r';\n\t*p++ = '\\n';\n    } else {\n\treturn -1;\n    }\n\n    /* print connection info, if present. */\n    if (m->conn) {\n\tprinted = print_connection_info(m->conn, p, (int)(end-p));\n\tif (printed < 0) {\n\t    return -1;\n\t}\n\tp += printed;\n    }\n    \n    /* print optional bandwidth info. */\n    for (i=0; ibandw_count; ++i) {\n\tprinted = (int)print_bandw(m->bandw[i], p, end-p);\n\tif (printed < 0) {\n\t    return -1;\n\t}\n\tp += printed;\n    }\n\n    /* print attributes. */\n    for (i=0; iattr_count; ++i) {\n\tprinted = (int)print_attr(m->attr[i], p, end-p);\n\tif (printed < 0) {\n\t    return -1;\n\t}\n\tp += printed;\n    }\n\n    return (int)(p-buf);\n}", "func_hash": 281187495727100348867210742014490000849, "file_name": "sdp.c", "file_hash": 260444738794842919556316298921063524881, "cwe": ["CWE-787"], "cve": "CVE-2022-24764", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C. Versions 2.12 and prior contain a stack buffer overflow vulnerability that affects PJSUA2 users or users that call the API `pjmedia_sdp_print(), pjmedia_sdp_media_print()`. Applications that do not use PJSUA2 and do not directly call `pjmedia_sdp_print()` or `pjmedia_sdp_media_print()` should not be affected. A patch is available on the `master` branch of the `pjsip/pjproject` GitHub repository. There are currently no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24764"}
{"idx": 201343, "project": "linux", "commit_id": "a3727a8bac0a9e77c70820655fd8715523ba3db7", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=a3727a8bac0a9e77c70820655fd8715523ba3db7", "commit_message": "selinux,smack: fix subjective/objective credential use mixups\n\nJann Horn reported a problem with commit eb1231f73c4d (\"selinux:\nclarify task subjective and objective credentials\") where some LSM\nhooks were attempting to access the subjective credentials of a task\nother than the current task.  Generally speaking, it is not safe to\naccess another task's subjective credentials and doing so can cause\na number of problems.\n\nFurther, while looking into the problem, I realized that Smack was\nsuffering from a similar problem brought about by a similar commit\n1fb057dcde11 (\"smack: differentiate between subjective and objective\ntask credentials\").\n\nThis patch addresses this problem by restoring the use of the task's\nobjective credentials in those cases where the task is other than the\ncurrent executing task.  Not only does this resolve the problem\nreported by Jann, it is arguably the correct thing to do in these\ncases.\n\nCc: stable@vger.kernel.org\nFixes: eb1231f73c4d (\"selinux: clarify task subjective and objective credentials\")\nFixes: 1fb057dcde11 (\"smack: differentiate between subjective and objective task credentials\")\nReported-by: Jann Horn \nAcked-by: Eric W. Biederman \nAcked-by: Casey Schaufler \nSigned-off-by: Paul Moore ", "target": 1, "func": "static int selinux_ptrace_traceme(struct task_struct *parent)\n{\n\treturn avc_has_perm(&selinux_state,\n\t\t\t    task_sid_subj(parent), task_sid_obj(current),\n\t\t\t    SECCLASS_PROCESS, PROCESS__PTRACE, NULL);\n}", "func_hash": 244235637020461368565337014513482216980, "file_name": "None", "file_hash": null, "cwe": ["CWE-416"], "cve": "CVE-2021-43057", "cve_desc": "An issue was discovered in the Linux kernel before 5.14.8. A use-after-free in selinux_ptrace_traceme (aka the SELinux handler for PTRACE_TRACEME) could be used by local attackers to cause memory corruption and escalate privileges, aka CID-a3727a8bac0a. This occurs because of an attempt to access the subjective credentials of another task.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43057"}
{"idx": 317271, "project": "linux", "commit_id": "a3727a8bac0a9e77c70820655fd8715523ba3db7", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=a3727a8bac0a9e77c70820655fd8715523ba3db7", "commit_message": "selinux,smack: fix subjective/objective credential use mixups\n\nJann Horn reported a problem with commit eb1231f73c4d (\"selinux:\nclarify task subjective and objective credentials\") where some LSM\nhooks were attempting to access the subjective credentials of a task\nother than the current task.  Generally speaking, it is not safe to\naccess another task's subjective credentials and doing so can cause\na number of problems.\n\nFurther, while looking into the problem, I realized that Smack was\nsuffering from a similar problem brought about by a similar commit\n1fb057dcde11 (\"smack: differentiate between subjective and objective\ntask credentials\").\n\nThis patch addresses this problem by restoring the use of the task's\nobjective credentials in those cases where the task is other than the\ncurrent executing task.  Not only does this resolve the problem\nreported by Jann, it is arguably the correct thing to do in these\ncases.\n\nCc: stable@vger.kernel.org\nFixes: eb1231f73c4d (\"selinux: clarify task subjective and objective credentials\")\nFixes: 1fb057dcde11 (\"smack: differentiate between subjective and objective task credentials\")\nReported-by: Jann Horn \nAcked-by: Eric W. Biederman \nAcked-by: Casey Schaufler \nSigned-off-by: Paul Moore ", "target": 0, "func": "static int selinux_ptrace_traceme(struct task_struct *parent)\n{\n\treturn avc_has_perm(&selinux_state,\n\t\t\t    task_sid_obj(parent), task_sid_obj(current),\n\t\t\t    SECCLASS_PROCESS, PROCESS__PTRACE, NULL);\n}", "func_hash": 139750086657330219714927956175340059557, "file_name": "None", "file_hash": null, "cwe": ["CWE-416"], "cve": "CVE-2021-43057", "cve_desc": "An issue was discovered in the Linux kernel before 5.14.8. A use-after-free in selinux_ptrace_traceme (aka the SELinux handler for PTRACE_TRACEME) could be used by local attackers to cause memory corruption and escalate privileges, aka CID-a3727a8bac0a. This occurs because of an attempt to access the subjective credentials of another task.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43057"}
{"idx": 201353, "project": "wireless-drivers", "commit_id": "8b51dc7291473093c821195c4b6af85fadedbc2f", "project_url": "https://git.kernel.org/pub/scm/linux/kernel/git/kvalo/wireless-drivers", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/kvalo/wireless-drivers.git/commit/?id=8b51dc7291473093c821195c4b6af85fadedbc2f", "commit_message": "rsi: fix a double free bug in rsi_91x_deinit()\n\n`dev` (struct rsi_91x_usbdev *) field of adapter\n(struct rsi_91x_usbdev *) is allocated  and initialized in\n`rsi_init_usb_interface`. If any error is detected in information\nread from the device side,  `rsi_init_usb_interface` will be\nfreed. However, in the higher level error handling code in\n`rsi_probe`, if error is detected, `rsi_91x_deinit` is called\nagain, in which `dev` will be freed again, resulting double free.\n\nThis patch fixes the double free by removing the free operation on\n`dev` in `rsi_init_usb_interface`, because `rsi_91x_deinit` is also\nused in `rsi_disconnect`, in that code path, the `dev` field is not\n (and thus needs to be) freed.\n\nThis bug was found in v4.19, but is also present in the latest version\nof kernel. Fixes CVE-2019-15504.\n\nReported-by: Hui Peng \nReported-by: Mathias Payer \nSigned-off-by: Hui Peng \nReviewed-by: Guenter Roeck \nSigned-off-by: Kalle Valo ", "target": 1, "func": "static int rsi_init_usb_interface(struct rsi_hw *adapter,\n\t\t\t\t  struct usb_interface *pfunction)\n{\n\tstruct rsi_91x_usbdev *rsi_dev;\n\tint status;\n\n\trsi_dev = kzalloc(sizeof(*rsi_dev), GFP_KERNEL);\n\tif (!rsi_dev)\n\t\treturn -ENOMEM;\n\n\tadapter->rsi_dev = rsi_dev;\n\trsi_dev->usbdev = interface_to_usbdev(pfunction);\n\trsi_dev->priv = (void *)adapter;\n\n\tif (rsi_find_bulk_in_and_out_endpoints(pfunction, adapter)) {\n\t\tstatus = -EINVAL;\n\t\tgoto fail_eps;\n\t}\n\n\tadapter->device = &pfunction->dev;\n\tusb_set_intfdata(pfunction, adapter);\n\n\trsi_dev->tx_buffer = kmalloc(2048, GFP_KERNEL);\n\tif (!rsi_dev->tx_buffer) {\n\t\tstatus = -ENOMEM;\n\t\tgoto fail_eps;\n\t}\n\n\tif (rsi_usb_init_rx(adapter)) {\n\t\trsi_dbg(ERR_ZONE, \"Failed to init RX handle\\n\");\n\t\tstatus = -ENOMEM;\n\t\tgoto fail_rx;\n\t}\n\n\trsi_dev->tx_blk_size = 252;\n\tadapter->block_size = rsi_dev->tx_blk_size;\n\n\t/* Initializing function callbacks */\n\tadapter->check_hw_queue_status = rsi_usb_check_queue_status;\n\tadapter->determine_event_timeout = rsi_usb_event_timeout;\n\tadapter->rsi_host_intf = RSI_HOST_INTF_USB;\n\tadapter->host_intf_ops = &usb_host_intf_ops;\n\n#ifdef CONFIG_RSI_DEBUGFS\n\t/* In USB, one less than the MAX_DEBUGFS_ENTRIES entries is required */\n\tadapter->num_debugfs_entries = (MAX_DEBUGFS_ENTRIES - 1);\n#endif\n\n\trsi_dbg(INIT_ZONE, \"%s: Enabled the interface\\n\", __func__);\n\treturn 0;\n\nfail_rx:\n\tkfree(rsi_dev->tx_buffer);\n\nfail_eps:\n\tkfree(rsi_dev);\n\n\treturn status;\n}", "func_hash": 38914523915054214786919182237560230029, "file_name": "rsi_91x_usb.c", "file_hash": 337775591275050809530599688018008269692, "cwe": ["CWE-415"], "cve": "CVE-2019-15504", "cve_desc": "drivers/net/wireless/rsi/rsi_91x_usb.c in the Linux kernel through 5.2.9 has a Double Free via crafted USB device traffic (which may be remote via usbip or usbredir).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-15504"}
{"idx": 318099, "project": "wireless-drivers", "commit_id": "8b51dc7291473093c821195c4b6af85fadedbc2f", "project_url": "https://git.kernel.org/pub/scm/linux/kernel/git/kvalo/wireless-drivers", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/kvalo/wireless-drivers.git/commit/?id=8b51dc7291473093c821195c4b6af85fadedbc2f", "commit_message": "rsi: fix a double free bug in rsi_91x_deinit()\n\n`dev` (struct rsi_91x_usbdev *) field of adapter\n(struct rsi_91x_usbdev *) is allocated  and initialized in\n`rsi_init_usb_interface`. If any error is detected in information\nread from the device side,  `rsi_init_usb_interface` will be\nfreed. However, in the higher level error handling code in\n`rsi_probe`, if error is detected, `rsi_91x_deinit` is called\nagain, in which `dev` will be freed again, resulting double free.\n\nThis patch fixes the double free by removing the free operation on\n`dev` in `rsi_init_usb_interface`, because `rsi_91x_deinit` is also\nused in `rsi_disconnect`, in that code path, the `dev` field is not\n (and thus needs to be) freed.\n\nThis bug was found in v4.19, but is also present in the latest version\nof kernel. Fixes CVE-2019-15504.\n\nReported-by: Hui Peng \nReported-by: Mathias Payer \nSigned-off-by: Hui Peng \nReviewed-by: Guenter Roeck \nSigned-off-by: Kalle Valo ", "target": 0, "func": "static int rsi_init_usb_interface(struct rsi_hw *adapter,\n\t\t\t\t  struct usb_interface *pfunction)\n{\n\tstruct rsi_91x_usbdev *rsi_dev;\n\tint status;\n\n\trsi_dev = kzalloc(sizeof(*rsi_dev), GFP_KERNEL);\n\tif (!rsi_dev)\n\t\treturn -ENOMEM;\n\n\tadapter->rsi_dev = rsi_dev;\n\trsi_dev->usbdev = interface_to_usbdev(pfunction);\n\trsi_dev->priv = (void *)adapter;\n\n\tif (rsi_find_bulk_in_and_out_endpoints(pfunction, adapter)) {\n\t\tstatus = -EINVAL;\n\t\tgoto fail_eps;\n\t}\n\n\tadapter->device = &pfunction->dev;\n\tusb_set_intfdata(pfunction, adapter);\n\n\trsi_dev->tx_buffer = kmalloc(2048, GFP_KERNEL);\n\tif (!rsi_dev->tx_buffer) {\n\t\tstatus = -ENOMEM;\n\t\tgoto fail_eps;\n\t}\n\n\tif (rsi_usb_init_rx(adapter)) {\n\t\trsi_dbg(ERR_ZONE, \"Failed to init RX handle\\n\");\n\t\tstatus = -ENOMEM;\n\t\tgoto fail_rx;\n\t}\n\n\trsi_dev->tx_blk_size = 252;\n\tadapter->block_size = rsi_dev->tx_blk_size;\n\n\t/* Initializing function callbacks */\n\tadapter->check_hw_queue_status = rsi_usb_check_queue_status;\n\tadapter->determine_event_timeout = rsi_usb_event_timeout;\n\tadapter->rsi_host_intf = RSI_HOST_INTF_USB;\n\tadapter->host_intf_ops = &usb_host_intf_ops;\n\n#ifdef CONFIG_RSI_DEBUGFS\n\t/* In USB, one less than the MAX_DEBUGFS_ENTRIES entries is required */\n\tadapter->num_debugfs_entries = (MAX_DEBUGFS_ENTRIES - 1);\n#endif\n\n\trsi_dbg(INIT_ZONE, \"%s: Enabled the interface\\n\", __func__);\n\treturn 0;\n\nfail_rx:\n\tkfree(rsi_dev->tx_buffer);\n\nfail_eps:\n\n\treturn status;\n}", "func_hash": 146493112175404963554656325384374694285, "file_name": "rsi_91x_usb.c", "file_hash": 273043712433748171090882476377434422928, "cwe": ["CWE-415"], "cve": "CVE-2019-15504", "cve_desc": "drivers/net/wireless/rsi/rsi_91x_usb.c in the Linux kernel through 5.2.9 has a Double Free via crafted USB device traffic (which may be remote via usbip or usbredir).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-15504"}
{"idx": 201382, "project": "gerbv", "commit_id": "672214abb47a802fc000125996e6e0a46c623a4e", "project_url": "https://github.com/gerbv/gerbv", "commit_url": "https://github.com/gerbv/gerbv/commit/672214abb47a802fc000125996e6e0a46c623a4e", "commit_message": "Add test to demonstrate buffer overrun", "target": 1, "func": "drill_parse_T_code(gerb_file_t *fd, drill_state_t *state,\n\t\t\tgerbv_image_t *image, ssize_t file_line)\n{\n    int tool_num;\n    gboolean done = FALSE;\n    int temp;\n    double size;\n    gerbv_drill_stats_t *stats = image->drill_stats;\n    gerbv_aperture_t *apert;\n    gchar *tmps;\n    gchar *string;\n\n    dprintf(\"---> entering %s()...\\n\", __FUNCTION__);\n\n    /* Sneak a peek at what's hiding after the 'T'. Ugly fix for\n       broken headers from Orcad, which is crap */\n    temp = gerb_fgetc(fd);\n    dprintf(\"  Found a char '%s' (0x%02x) after the T\\n\",\n\t    gerbv_escape_char(temp), temp);\n    \n    /* might be a tool tool change stop switch on/off*/\n    if((temp == 'C') && ((fd->ptr + 2) < fd->datalen)){\n    \tif(gerb_fgetc(fd) == 'S'){\n    \t    if (gerb_fgetc(fd) == 'T' ){\n    \t  \tfd->ptr -= 4;\n    \t  \ttmps = get_line(fd++);\n    \t  \tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_NOTE, -1,\n\t\t\t_(\"Tool change stop switch found \\\"%s\\\" \"\n\t\t\t    \"at line %ld in file \\\"%s\\\"\"),\n\t\t\ttmps, file_line, fd->filename);\n\t  \tg_free (tmps);\n\n\t  \treturn -1;\n\t    }\n\t    gerb_ungetc(fd);\n\t}\n\tgerb_ungetc(fd);\n    }\n\n    if( !(isdigit(temp) != 0 || temp == '+' || temp =='-') ) {\n\tif(temp != EOF) {\n\t    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,\n\t\t   _(\"OrCAD bug: Junk text found in place of tool definition\"));\n\t    tmps = get_line(fd);\n\t    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,\n\t\t    _(\"Junk text \\\"%s\\\" \"\n\t\t\t\"at line %ld in file \\\"%s\\\"\"),\n\t\t    tmps, file_line, fd->filename);\n\t    g_free (tmps);\n\t    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,\n\t\t\t\t  _(\"Ignoring junk text\"));\n\t}\n\treturn -1;\n    }\n    gerb_ungetc(fd);\n\n    tool_num = (int) gerb_fgetint(fd, NULL);\n    dprintf (\"  Handling tool T%d at line %ld\\n\", tool_num, file_line);\n\n    if (tool_num == 0) \n\treturn tool_num; /* T00 is a command to unload the drill */\n\n    if (tool_num < TOOL_MIN || tool_num >= TOOL_MAX) {\n\tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,\n\t\t_(\"Out of bounds drill number %d \"\n\t\t    \"at line %ld in file \\\"%s\\\"\"),\n\t\ttool_num, file_line, fd->filename);\n    }\n\n    /* Set the current tool to the correct one */\n    state->current_tool = tool_num;\n    apert = image->aperture[tool_num];\n\n    /* Check for a size definition */\n    temp = gerb_fgetc(fd);\n\n    /* This bit of code looks for a tool definition by scanning for strings\n     * of form TxxC, TxxF, TxxS.  */\n    while (!done) {\n\tswitch((char)temp) {\n\tcase 'C':\n\t    size = read_double(fd, state->header_number_format, GERBV_OMIT_ZEROS_TRAILING, state->decimals);\n\t    dprintf (\"  Read a size of %g\\n\", size);\n\n\t    if (state->unit == GERBV_UNIT_MM) {\n\t\tsize /= 25.4;\n\t    } else if(size >= 4.0) {\n\t\t/* If the drill size is >= 4 inches, assume that this\n\t\t   must be wrong and that the units are mils.\n\t\t   The limit being 4 inches is because the smallest drill\n\t\t   I've ever seen used is 0,3mm(about 12mil). Half of that\n\t\t   seemed a bit too small a margin, so a third it is */\n\n\t\tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,\n\t\t\t_(\"Read a drill of diameter %g inches \"\n\t\t\t    \"at line %ld in file \\\"%s\\\"\"),\n\t\t\t    size, file_line, fd->filename);\n\t\tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,\n\t\t\t_(\"Assuming units are mils\"));\n\t\tsize /= 1000.0;\n\t    }\n\n\t    if (size <= 0. || size >= 10000.) {\n\t\tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,\n\t\t\t_(\"Unreasonable drill size %g found for drill %d \"\n\t\t\t    \"at line %ld in file \\\"%s\\\"\"),\n\t\t\t    size, tool_num, file_line, fd->filename);\n\t    } else {\n\t\tif (apert != NULL) {\n\t\t    /* allow a redefine of a tool only if the new definition is exactly the same.\n\t\t     * This avoid lots of spurious complaints with the output of some cad\n\t\t     * tools while keeping complaints if there is a true problem\n\t\t     */\n\t\t    if (apert->parameter[0] != size\n\t\t    ||  apert->type != GERBV_APTYPE_CIRCLE\n\t\t    ||  apert->nuf_parameters != 1\n\t\t    ||  apert->unit != GERBV_UNIT_INCH) {\n\n\t\t\tgerbv_stats_printf(stats->error_list,\n\t\t\t\tGERBV_MESSAGE_ERROR, -1,\n\t\t\t\t_(\"Found redefinition of drill %d \"\n\t\t\t\t\"at line %ld in file \\\"%s\\\"\"),\n\t\t\t\ttool_num, file_line, fd->filename);\n\t\t    }\n\t\t} else {\n\t\t    apert = image->aperture[tool_num] =\n\t\t\t\t\t\tg_new0(gerbv_aperture_t, 1);\n\t\t    if (apert == NULL)\n\t\t\tGERB_FATAL_ERROR(\"malloc tool failed in %s()\",\n\t\t\t\t\t__FUNCTION__);\n\n\t\t    /* There's really no way of knowing what unit the tools\n\t\t       are defined in without sneaking a peek in the rest of\n\t\t       the file first. That's done in drill_guess_format() */\n\t\t    apert->parameter[0] = size;\n\t\t    apert->type = GERBV_APTYPE_CIRCLE;\n\t\t    apert->nuf_parameters = 1;\n\t\t    apert->unit = GERBV_UNIT_INCH;\n\t\t}\n\t    }\n\t    \n\t    /* Add the tool whose definition we just found into the list\n\t     * of tools for this layer used to generate statistics. */\n\t    stats = image->drill_stats;\n\t    string = g_strdup_printf(\"%s\", (state->unit == GERBV_UNIT_MM ? _(\"mm\") : _(\"inch\")));\n\t    drill_stats_add_to_drill_list(stats->drill_list, \n\t\t\t\t\t  tool_num, \n\t\t\t\t\t  state->unit == GERBV_UNIT_MM ? size*25.4 : size, \n\t\t\t\t\t  string);\n\t    g_free(string);\n\t    break;\n\n\tcase 'F':\n\tcase 'S' :\n\t    /* Silently ignored. They're not important. */\n\t    gerb_fgetint(fd, NULL);\n\t    break;\n\n\tdefault:\n\t    /* Stop when finding anything but what's expected\n\t       (and put it back) */\n\t    gerb_ungetc(fd);\n\t    done = TRUE;\n\t    break;\n\t}  /* switch((char)temp) */\n\n\ttemp = gerb_fgetc(fd);\n\tif (EOF == temp) {\n\t    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,\n\t\t    _(\"Unexpected EOF encountered in header of \"\n\t\t\t\"drill file \\\"%s\\\"\"), fd->filename);\n\n\t/* Restore new line character for processing */\n\tif ('\\n' == temp || '\\r' == temp)\n\t    gerb_ungetc(fd);\n\t}\n    }   /* while(!done) */  /* Done looking at tool definitions */\n\n    /* Catch the tools that aren't defined.\n       This isn't strictly a good thing, but at least something is shown */\n    if (apert == NULL) {\n        double dia;\n\n\tapert = image->aperture[tool_num] = g_new0(gerbv_aperture_t, 1);\n\tif (apert == NULL)\n\t    GERB_FATAL_ERROR(\"malloc tool failed in %s()\", __FUNCTION__);\n\n        /* See if we have the tool table */\n        dia = gerbv_get_tool_diameter(tool_num);\n        if (dia <= 0) {\n            /*\n             * There is no tool. So go out and make some.\n             * This size calculation is, of course, totally bogus.\n             */\n            dia = (double)(16 + 8 * tool_num) / 1000;\n            /*\n             * Oooh, this is sooo ugly. But some CAD systems seem to always\n             * use T00 at the end of the file while others that don't have\n             * tool definitions inside the file never seem to use T00 at all.\n             */\n            if (tool_num != 0) {\n\t\tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,\n\t\t\t_(\"Tool %02d used without being defined \"\n\t\t\t    \"at line %ld in file \\\"%s\\\"\"),\n\t\t\ttool_num, file_line, fd->filename);\n\t\tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,\n\t\t\t_(\"Setting a default size of %g\\\"\"), dia);\n            }\n\t}\n\n\tapert->type = GERBV_APTYPE_CIRCLE;\n\tapert->nuf_parameters = 1;\n\tapert->parameter[0] = dia;\n\n\t/* Add the tool whose definition we just found into the list\n\t * of tools for this layer used to generate statistics. */\n\tif (tool_num != 0) {  /* Only add non-zero tool nums.  \n\t\t\t       * Zero = unload command. */\n\t    stats = image->drill_stats;\n\t    string = g_strdup_printf(\"%s\", \n\t\t\t\t     (state->unit == GERBV_UNIT_MM ? _(\"mm\") : _(\"inch\")));\n\t    drill_stats_add_to_drill_list(stats->drill_list, \n\t\t\t\t\t  tool_num, \n\t\t\t\t\t  state->unit == GERBV_UNIT_MM ? dia*25.4 : dia,\n\t\t\t\t\t  string);\n\t    g_free(string);\n\t}\n    } /* if(image->aperture[tool_num] == NULL) */\t\n    \n    dprintf(\"<----  ...leaving %s()\\n\", __FUNCTION__);\n\n    return tool_num;\n} /* drill_parse_T_code() */", "func_hash": 185752158214328372341115505036759500651, "file_name": "drill.c", "file_hash": 62463866492734341751893387181625909179, "cwe": ["CWE-787"], "cve": "CVE-2021-40391", "cve_desc": "An out-of-bounds write vulnerability exists in the drill format T-code tool number functionality of Gerbv 2.7.0, dev (commit b5f1eacd), and the forked version of Gerbv (commit 71493260). A specially-crafted drill file can lead to code execution. An attacker can provide a malicious file to trigger this vulnerability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40391"}
{"idx": 318781, "project": "gerbv", "commit_id": "672214abb47a802fc000125996e6e0a46c623a4e", "project_url": "https://github.com/gerbv/gerbv", "commit_url": "https://github.com/gerbv/gerbv/commit/672214abb47a802fc000125996e6e0a46c623a4e", "commit_message": "Add test to demonstrate buffer overrun", "target": 0, "func": "drill_parse_T_code(gerb_file_t *fd, drill_state_t *state,\n\t\t\tgerbv_image_t *image, ssize_t file_line)\n{\n    int tool_num;\n    gboolean done = FALSE;\n    int temp;\n    double size;\n    gerbv_drill_stats_t *stats = image->drill_stats;\n    gerbv_aperture_t *apert;\n    gchar *tmps;\n    gchar *string;\n\n    dprintf(\"---> entering %s()...\\n\", __FUNCTION__);\n\n    /* Sneak a peek at what's hiding after the 'T'. Ugly fix for\n       broken headers from Orcad, which is crap */\n    temp = gerb_fgetc(fd);\n    dprintf(\"  Found a char '%s' (0x%02x) after the T\\n\",\n\t    gerbv_escape_char(temp), temp);\n    \n    /* might be a tool tool change stop switch on/off*/\n    if((temp == 'C') && ((fd->ptr + 2) < fd->datalen)){\n    \tif(gerb_fgetc(fd) == 'S'){\n    \t    if (gerb_fgetc(fd) == 'T' ){\n    \t  \tfd->ptr -= 4;\n    \t  \ttmps = get_line(fd++);\n    \t  \tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_NOTE, -1,\n\t\t\t_(\"Tool change stop switch found \\\"%s\\\" \"\n\t\t\t    \"at line %ld in file \\\"%s\\\"\"),\n\t\t\ttmps, file_line, fd->filename);\n\t  \tg_free (tmps);\n\n\t  \treturn -1;\n\t    }\n\t    gerb_ungetc(fd);\n\t}\n\tgerb_ungetc(fd);\n    }\n\n    if( !(isdigit(temp) != 0 || temp == '+' || temp =='-') ) {\n\tif(temp != EOF) {\n\t    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,\n\t\t   _(\"OrCAD bug: Junk text found in place of tool definition\"));\n\t    tmps = get_line(fd);\n\t    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,\n\t\t    _(\"Junk text \\\"%s\\\" \"\n\t\t\t\"at line %ld in file \\\"%s\\\"\"),\n\t\t    tmps, file_line, fd->filename);\n\t    g_free (tmps);\n\t    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,\n\t\t\t\t  _(\"Ignoring junk text\"));\n\t}\n\treturn -1;\n    }\n    gerb_ungetc(fd);\n\n    tool_num = (int) gerb_fgetint(fd, NULL);\n    dprintf (\"  Handling tool T%d at line %ld\\n\", tool_num, file_line);\n\n    if (tool_num == 0) \n\treturn tool_num; /* T00 is a command to unload the drill */\n\n    if (tool_num < TOOL_MIN || tool_num >= TOOL_MAX) {\n\tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,\n\t\t_(\"Out of bounds drill number %d \"\n\t\t    \"at line %ld in file \\\"%s\\\"\"),\n\t\ttool_num, file_line, fd->filename);\n\treturn -1;\n    }\n\n    /* Set the current tool to the correct one */\n    state->current_tool = tool_num;\n    apert = image->aperture[tool_num];\n\n    /* Check for a size definition */\n    temp = gerb_fgetc(fd);\n\n    /* This bit of code looks for a tool definition by scanning for strings\n     * of form TxxC, TxxF, TxxS.  */\n    while (!done) {\n\tswitch((char)temp) {\n\tcase 'C':\n\t    size = read_double(fd, state->header_number_format, GERBV_OMIT_ZEROS_TRAILING, state->decimals);\n\t    dprintf (\"  Read a size of %g\\n\", size);\n\n\t    if (state->unit == GERBV_UNIT_MM) {\n\t\tsize /= 25.4;\n\t    } else if(size >= 4.0) {\n\t\t/* If the drill size is >= 4 inches, assume that this\n\t\t   must be wrong and that the units are mils.\n\t\t   The limit being 4 inches is because the smallest drill\n\t\t   I've ever seen used is 0,3mm(about 12mil). Half of that\n\t\t   seemed a bit too small a margin, so a third it is */\n\n\t\tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,\n\t\t\t_(\"Read a drill of diameter %g inches \"\n\t\t\t    \"at line %ld in file \\\"%s\\\"\"),\n\t\t\t    size, file_line, fd->filename);\n\t\tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,\n\t\t\t_(\"Assuming units are mils\"));\n\t\tsize /= 1000.0;\n\t    }\n\n\t    if (size <= 0. || size >= 10000.) {\n\t\tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,\n\t\t\t_(\"Unreasonable drill size %g found for drill %d \"\n\t\t\t    \"at line %ld in file \\\"%s\\\"\"),\n\t\t\t    size, tool_num, file_line, fd->filename);\n\t    } else {\n\t\tif (apert != NULL) {\n\t\t    /* allow a redefine of a tool only if the new definition is exactly the same.\n\t\t     * This avoid lots of spurious complaints with the output of some cad\n\t\t     * tools while keeping complaints if there is a true problem\n\t\t     */\n\t\t    if (apert->parameter[0] != size\n\t\t    ||  apert->type != GERBV_APTYPE_CIRCLE\n\t\t    ||  apert->nuf_parameters != 1\n\t\t    ||  apert->unit != GERBV_UNIT_INCH) {\n\n\t\t\tgerbv_stats_printf(stats->error_list,\n\t\t\t\tGERBV_MESSAGE_ERROR, -1,\n\t\t\t\t_(\"Found redefinition of drill %d \"\n\t\t\t\t\"at line %ld in file \\\"%s\\\"\"),\n\t\t\t\ttool_num, file_line, fd->filename);\n\t\t    }\n\t\t} else {\n\t\t    apert = image->aperture[tool_num] =\n\t\t\t\t\t\tg_new0(gerbv_aperture_t, 1);\n\t\t    if (apert == NULL)\n\t\t\tGERB_FATAL_ERROR(\"malloc tool failed in %s()\",\n\t\t\t\t\t__FUNCTION__);\n\n\t\t    /* There's really no way of knowing what unit the tools\n\t\t       are defined in without sneaking a peek in the rest of\n\t\t       the file first. That's done in drill_guess_format() */\n\t\t    apert->parameter[0] = size;\n\t\t    apert->type = GERBV_APTYPE_CIRCLE;\n\t\t    apert->nuf_parameters = 1;\n\t\t    apert->unit = GERBV_UNIT_INCH;\n\t\t}\n\t    }\n\t    \n\t    /* Add the tool whose definition we just found into the list\n\t     * of tools for this layer used to generate statistics. */\n\t    stats = image->drill_stats;\n\t    string = g_strdup_printf(\"%s\", (state->unit == GERBV_UNIT_MM ? _(\"mm\") : _(\"inch\")));\n\t    drill_stats_add_to_drill_list(stats->drill_list, \n\t\t\t\t\t  tool_num, \n\t\t\t\t\t  state->unit == GERBV_UNIT_MM ? size*25.4 : size, \n\t\t\t\t\t  string);\n\t    g_free(string);\n\t    break;\n\n\tcase 'F':\n\tcase 'S' :\n\t    /* Silently ignored. They're not important. */\n\t    gerb_fgetint(fd, NULL);\n\t    break;\n\n\tdefault:\n\t    /* Stop when finding anything but what's expected\n\t       (and put it back) */\n\t    gerb_ungetc(fd);\n\t    done = TRUE;\n\t    break;\n\t}  /* switch((char)temp) */\n\n\ttemp = gerb_fgetc(fd);\n\tif (EOF == temp) {\n\t    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,\n\t\t    _(\"Unexpected EOF encountered in header of \"\n\t\t\t\"drill file \\\"%s\\\"\"), fd->filename);\n\n\t/* Restore new line character for processing */\n\tif ('\\n' == temp || '\\r' == temp)\n\t    gerb_ungetc(fd);\n\t}\n    }   /* while(!done) */  /* Done looking at tool definitions */\n\n    /* Catch the tools that aren't defined.\n       This isn't strictly a good thing, but at least something is shown */\n    if (apert == NULL) {\n        double dia;\n\n\tapert = image->aperture[tool_num] = g_new0(gerbv_aperture_t, 1);\n\tif (apert == NULL)\n\t    GERB_FATAL_ERROR(\"malloc tool failed in %s()\", __FUNCTION__);\n\n        /* See if we have the tool table */\n        dia = gerbv_get_tool_diameter(tool_num);\n        if (dia <= 0) {\n            /*\n             * There is no tool. So go out and make some.\n             * This size calculation is, of course, totally bogus.\n             */\n            dia = (double)(16 + 8 * tool_num) / 1000;\n            /*\n             * Oooh, this is sooo ugly. But some CAD systems seem to always\n             * use T00 at the end of the file while others that don't have\n             * tool definitions inside the file never seem to use T00 at all.\n             */\n            if (tool_num != 0) {\n\t\tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,\n\t\t\t_(\"Tool %02d used without being defined \"\n\t\t\t    \"at line %ld in file \\\"%s\\\"\"),\n\t\t\ttool_num, file_line, fd->filename);\n\t\tgerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,\n\t\t\t_(\"Setting a default size of %g\\\"\"), dia);\n            }\n\t}\n\n\tapert->type = GERBV_APTYPE_CIRCLE;\n\tapert->nuf_parameters = 1;\n\tapert->parameter[0] = dia;\n\n\t/* Add the tool whose definition we just found into the list\n\t * of tools for this layer used to generate statistics. */\n\tif (tool_num != 0) {  /* Only add non-zero tool nums.  \n\t\t\t       * Zero = unload command. */\n\t    stats = image->drill_stats;\n\t    string = g_strdup_printf(\"%s\", \n\t\t\t\t     (state->unit == GERBV_UNIT_MM ? _(\"mm\") : _(\"inch\")));\n\t    drill_stats_add_to_drill_list(stats->drill_list, \n\t\t\t\t\t  tool_num, \n\t\t\t\t\t  state->unit == GERBV_UNIT_MM ? dia*25.4 : dia,\n\t\t\t\t\t  string);\n\t    g_free(string);\n\t}\n    } /* if(image->aperture[tool_num] == NULL) */\t\n    \n    dprintf(\"<----  ...leaving %s()\\n\", __FUNCTION__);\n\n    return tool_num;\n} /* drill_parse_T_code() */", "func_hash": 295658284034771468073191411727984025582, "file_name": "drill.c", "file_hash": 33522367220484611799947615316913326815, "cwe": ["CWE-787"], "cve": "CVE-2021-40391", "cve_desc": "An out-of-bounds write vulnerability exists in the drill format T-code tool number functionality of Gerbv 2.7.0, dev (commit b5f1eacd), and the forked version of Gerbv (commit 71493260). A specially-crafted drill file can lead to code execution. An attacker can provide a malicious file to trigger this vulnerability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40391"}
{"idx": 201384, "project": "vim", "commit_id": "34f8117dec685ace52cd9e578e2729db278163fc", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/34f8117dec685ace52cd9e578e2729db278163fc", "commit_message": "patch 8.2.4397: crash when using many composing characters in error message\n\nProblem:    Crash when using many composing characters in error message.\nSolution:   Use mb_cptr2char_adv() instead of mb_ptr2char_adv().", "target": 1, "func": "ga_concat_shorten_esc(garray_T *gap, char_u *str)\n{\n    char_u  *p;\n    char_u  *s;\n    int\t    c;\n    int\t    clen;\n    char_u  buf[NUMBUFLEN];\n    int\t    same_len;\n\n    if (str == NULL)\n    {\n\tga_concat(gap, (char_u *)\"NULL\");\n\treturn;\n    }\n\n    for (p = str; *p != NUL; ++p)\n    {\n\tsame_len = 1;\n\ts = p;\n\tc = mb_ptr2char_adv(&s);\n\tclen = s - p;\n\twhile (*s != NUL && c == mb_ptr2char(s))\n\t{\n\t    ++same_len;\n\t    s += clen;\n\t}\n\tif (same_len > 20)\n\t{\n\t    ga_concat(gap, (char_u *)\"\\\\[\");\n\t    ga_concat_esc(gap, p, clen);\n\t    ga_concat(gap, (char_u *)\" occurs \");\n\t    vim_snprintf((char *)buf, NUMBUFLEN, \"%d\", same_len);\n\t    ga_concat(gap, buf);\n\t    ga_concat(gap, (char_u *)\" times]\");\n\t    p = s - 1;\n\t}\n\telse\n\t    ga_concat_esc(gap, p, clen);\n    }\n}", "func_hash": 50963215449221402235184881814854547880, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-0629", "cve_desc": "Stack-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0629"}
{"idx": 318962, "project": "vim", "commit_id": "34f8117dec685ace52cd9e578e2729db278163fc", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/34f8117dec685ace52cd9e578e2729db278163fc", "commit_message": "patch 8.2.4397: crash when using many composing characters in error message\n\nProblem:    Crash when using many composing characters in error message.\nSolution:   Use mb_cptr2char_adv() instead of mb_ptr2char_adv().", "target": 0, "func": "ga_concat_shorten_esc(garray_T *gap, char_u *str)\n{\n    char_u  *p;\n    char_u  *s;\n    int\t    c;\n    int\t    clen;\n    char_u  buf[NUMBUFLEN];\n    int\t    same_len;\n\n    if (str == NULL)\n    {\n\tga_concat(gap, (char_u *)\"NULL\");\n\treturn;\n    }\n\n    for (p = str; *p != NUL; ++p)\n    {\n\tsame_len = 1;\n\ts = p;\n\tc = mb_cptr2char_adv(&s);\n\tclen = s - p;\n\twhile (*s != NUL && c == mb_ptr2char(s))\n\t{\n\t    ++same_len;\n\t    s += clen;\n\t}\n\tif (same_len > 20)\n\t{\n\t    ga_concat(gap, (char_u *)\"\\\\[\");\n\t    ga_concat_esc(gap, p, clen);\n\t    ga_concat(gap, (char_u *)\" occurs \");\n\t    vim_snprintf((char *)buf, NUMBUFLEN, \"%d\", same_len);\n\t    ga_concat(gap, buf);\n\t    ga_concat(gap, (char_u *)\" times]\");\n\t    p = s - 1;\n\t}\n\telse\n\t    ga_concat_esc(gap, p, clen);\n    }\n}", "func_hash": 80466370940770826127245028745875582474, "file_name": "testing.c", "file_hash": 163762640026672977997843160219561641403, "cwe": ["CWE-787"], "cve": "CVE-2022-0629", "cve_desc": "Stack-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0629"}
{"idx": 201451, "project": "ImageMagick6", "commit_id": "e6ea5876e0228165ee3abc6e959aa174cee06680", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/e6ea5876e0228165ee3abc6e959aa174cee06680", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/4988", "target": 1, "func": "static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define MonoColorType  1\n#define RGBColorType  3\n\n  char\n    property[MaxTextExtent];\n\n  CINInfo\n    cin;\n\n  Image\n    *image;\n\n  MagickBooleanType\n    status;\n\n  MagickOffsetType\n    offset;\n\n  QuantumInfo\n    *quantum_info;\n\n  QuantumType\n    quantum_type;\n\n  ssize_t\n    i;\n\n  PixelPacket\n    *q;\n\n  size_t\n    extent,\n    length;\n\n  ssize_t\n    count,\n    y;\n\n  unsigned char\n    magick[4],\n    *pixels;\n\n  /*\n    Open image file.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  image=AcquireImage(image_info);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n    File information.\n  */\n  offset=0;\n  count=ReadBlob(image,4,magick);\n  offset+=count;\n  if ((count != 4) ||\n      ((LocaleNCompare((char *) magick,\"\\200\\052\\137\\327\",4) != 0)))\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  memset(&cin,0,sizeof(cin));\n  image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&\n    (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;\n  cin.file.image_offset=ReadBlobLong(image);\n  offset+=4;\n  cin.file.generic_length=ReadBlobLong(image);\n  offset+=4;\n  cin.file.industry_length=ReadBlobLong(image);\n  offset+=4;\n  cin.file.user_length=ReadBlobLong(image);\n  offset+=4;\n  cin.file.file_size=ReadBlobLong(image);\n  offset+=4;\n  offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)\n    cin.file.version);\n  (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));\n  (void) SetImageProperty(image,\"dpx:file.version\",property);\n  offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)\n    cin.file.filename);\n  (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));\n  (void) SetImageProperty(image,\"dpx:file.filename\",property);\n  offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)\n    cin.file.create_date);\n  (void) CopyMagickString(property,cin.file.create_date,\n    sizeof(cin.file.create_date));\n  (void) SetImageProperty(image,\"dpx:file.create_date\",property);\n  offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)\n    cin.file.create_time);\n  (void) CopyMagickString(property,cin.file.create_time,\n     sizeof(cin.file.create_time));\n  (void) SetImageProperty(image,\"dpx:file.create_time\",property);\n  offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)\n    cin.file.reserve);\n  /*\n    Image information.\n  */\n  cin.image.orientation=(unsigned char) ReadBlobByte(image);\n  offset++;\n  if (cin.image.orientation != (unsigned char) (~0))\n    (void) FormatImageProperty(image,\"dpx:image.orientation\",\"%d\",\n      cin.image.orientation);\n  switch (cin.image.orientation)\n  {\n    default:\n    case 0: image->orientation=TopLeftOrientation; break;\n    case 1: image->orientation=TopRightOrientation; break;\n    case 2: image->orientation=BottomLeftOrientation; break;\n    case 3: image->orientation=BottomRightOrientation; break;\n    case 4: image->orientation=LeftTopOrientation; break;\n    case 5: image->orientation=RightTopOrientation; break;\n    case 6: image->orientation=LeftBottomOrientation; break;\n    case 7: image->orientation=RightBottomOrientation; break;\n  }\n  cin.image.number_channels=(unsigned char) ReadBlobByte(image);\n  offset++;\n  offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)\n    cin.image.reserve1);\n  for (i=0; i < 8; i++)\n  {\n    cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].pixels_per_line=ReadBlobLong(image);\n    offset+=4;\n    cin.image.channel[i].lines_per_image=ReadBlobLong(image);\n    offset+=4;\n    cin.image.channel[i].min_data=ReadBlobFloat(image);\n    offset+=4;\n    cin.image.channel[i].min_quantity=ReadBlobFloat(image);\n    offset+=4;\n    cin.image.channel[i].max_data=ReadBlobFloat(image);\n    offset+=4;\n    cin.image.channel[i].max_quantity=ReadBlobFloat(image);\n    offset+=4;\n  }\n  cin.image.white_point[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)\n    image->chromaticity.white_point.x=cin.image.white_point[0];\n  cin.image.white_point[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)\n    image->chromaticity.white_point.y=cin.image.white_point[1];\n  cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)\n    image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];\n  cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)\n    image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];\n  cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)\n    image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];\n  cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)\n    image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];\n  cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)\n    image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];\n  cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)\n    image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];\n  offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)\n    cin.image.label);\n  (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));\n  (void) SetImageProperty(image,\"dpx:image.label\",property);\n  offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)\n    cin.image.reserve);\n  /*\n    Image data format information.\n  */\n  cin.data_format.interleave=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.packing=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.sign=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.sense=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.line_pad=ReadBlobLong(image);\n  offset+=4;\n  cin.data_format.channel_pad=ReadBlobLong(image);\n  offset+=4;\n  offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)\n    cin.data_format.reserve);\n  /*\n    Image origination information.\n  */\n  cin.origination.x_offset=ReadBlobSignedLong(image);\n  offset+=4;\n  if ((size_t) cin.origination.x_offset != ~0UL)\n    (void) FormatImageProperty(image,\"dpx:origination.x_offset\",\"%.20g\",\n      (double) cin.origination.x_offset);\n  cin.origination.y_offset=(ssize_t) ReadBlobLong(image);\n  offset+=4;\n  if ((size_t) cin.origination.y_offset != ~0UL)\n    (void) FormatImageProperty(image,\"dpx:origination.y_offset\",\"%.20g\",\n      (double) cin.origination.y_offset);\n  offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)\n    cin.origination.filename);\n  (void) CopyMagickString(property,cin.origination.filename,\n    sizeof(cin.origination.filename));\n  (void) SetImageProperty(image,\"dpx:origination.filename\",property);\n  offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)\n    cin.origination.create_date);\n  (void) CopyMagickString(property,cin.origination.create_date,\n    sizeof(cin.origination.create_date));\n  (void) SetImageProperty(image,\"dpx:origination.create_date\",property);\n  offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)\n    cin.origination.create_time);\n  (void) CopyMagickString(property,cin.origination.create_time,\n    sizeof(cin.origination.create_time));\n  (void) SetImageProperty(image,\"dpx:origination.create_time\",property);\n  offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)\n    cin.origination.device);\n  (void) CopyMagickString(property,cin.origination.device,\n    sizeof(cin.origination.device));\n  (void) SetImageProperty(image,\"dpx:origination.device\",property);\n  offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)\n    cin.origination.model);\n  (void) CopyMagickString(property,cin.origination.model,\n    sizeof(cin.origination.model));\n  (void) SetImageProperty(image,\"dpx:origination.model\",property);\n  (void) memset(cin.origination.serial,0,\n    sizeof(cin.origination.serial));\n  offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)\n    cin.origination.serial);\n  (void) CopyMagickString(property,cin.origination.serial,\n    sizeof(cin.origination.serial));\n  (void) SetImageProperty(image,\"dpx:origination.serial\",property);\n  cin.origination.x_pitch=ReadBlobFloat(image);\n  offset+=4;\n  cin.origination.y_pitch=ReadBlobFloat(image);\n  offset+=4;\n  cin.origination.gamma=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.origination.gamma) != MagickFalse)\n    image->gamma=cin.origination.gamma;\n  offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)\n    cin.origination.reserve);\n  if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))\n    {\n      int\n        c;\n\n      /*\n        Image film information.\n      */\n      cin.film.id=ReadBlobByte(image);\n      offset++;\n      c=cin.film.id;\n      if (c != ~0)\n        (void) FormatImageProperty(image,\"dpx:film.id\",\"%d\",cin.film.id);\n      cin.film.type=ReadBlobByte(image);\n      offset++;\n      c=cin.film.type;\n      if (c != ~0)\n        (void) FormatImageProperty(image,\"dpx:film.type\",\"%d\",cin.film.type);\n      cin.film.offset=ReadBlobByte(image);\n      offset++;\n      c=cin.film.offset;\n      if (c != ~0)\n        (void) FormatImageProperty(image,\"dpx:film.offset\",\"%d\",\n          cin.film.offset);\n      cin.film.reserve1=ReadBlobByte(image);\n      offset++;\n      cin.film.prefix=ReadBlobLong(image);\n      offset+=4;\n      if (cin.film.prefix != ~0UL)\n        (void) FormatImageProperty(image,\"dpx:film.prefix\",\"%.20g\",(double)\n          cin.film.prefix);\n      cin.film.count=ReadBlobLong(image);\n      offset+=4;\n      offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)\n        cin.film.format);\n      (void) CopyMagickString(property,cin.film.format,\n        sizeof(cin.film.format));\n      (void) SetImageProperty(image,\"dpx:film.format\",property);\n      cin.film.frame_position=ReadBlobLong(image);\n      offset+=4;\n      if (cin.film.frame_position != ~0UL)\n        (void) FormatImageProperty(image,\"dpx:film.frame_position\",\"%.20g\",\n          (double) cin.film.frame_position);\n      cin.film.frame_rate=ReadBlobFloat(image);\n      offset+=4;\n      if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)\n        (void) FormatImageProperty(image,\"dpx:film.frame_rate\",\"%g\",\n          cin.film.frame_rate);\n      offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)\n        cin.film.frame_id);\n      (void) CopyMagickString(property,cin.film.frame_id,\n        sizeof(cin.film.frame_id));\n      (void) SetImageProperty(image,\"dpx:film.frame_id\",property);\n      offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)\n        cin.film.slate_info);\n      (void) CopyMagickString(property,cin.film.slate_info,\n        sizeof(cin.film.slate_info));\n      (void) SetImageProperty(image,\"dpx:film.slate_info\",property);\n      offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)\n        cin.film.reserve);\n    }\n  if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))\n    {\n      StringInfo\n        *profile;\n\n      /*\n        User defined data.\n      */\n      if (cin.file.user_length > GetBlobSize(image))\n        ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n      profile=BlobToStringInfo((const void *) NULL,cin.file.user_length);\n      if (profile == (StringInfo *) NULL)\n        ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n      offset+=ReadBlob(image,GetStringInfoLength(profile),\n        GetStringInfoDatum(profile));\n      (void) SetImageProfile(image,\"dpx:user.data\",profile);\n      profile=DestroyStringInfo(profile);\n    }\n  image->depth=cin.image.channel[0].bits_per_pixel;\n  image->columns=cin.image.channel[0].pixels_per_line;\n  image->rows=cin.image.channel[0].lines_per_image;\n  if (image_info->ping != MagickFalse)\n    {\n      (void) CloseBlob(image);\n      return(image);\n    }\n  if (((MagickSizeType) image->columns*image->rows/8) > GetBlobSize(image))\n    ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n  for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)\n  {\n    int\n      c;\n\n    c=ReadBlobByte(image);\n    if (c == EOF)\n      break;\n  }\n  if (offset < (MagickOffsetType) cin.file.image_offset)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  status=SetImageExtent(image,image->columns,image->rows);\n  if (status == MagickFalse)\n    {\n      InheritException(exception,&image->exception);\n      return(DestroyImageList(image));\n    }\n  (void) SetImageBackgroundColor(image);\n  /*\n    Convert CIN raster image to pixel packets.\n  */\n  quantum_info=AcquireQuantumInfo(image_info,image);\n  if (quantum_info == (QuantumInfo *) NULL)\n    ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n  SetQuantumQuantum(quantum_info,32);\n  SetQuantumPack(quantum_info,MagickFalse);\n  quantum_type=RGBQuantum;\n  extent=GetQuantumExtent(image,quantum_info,quantum_type);\n  (void) extent;\n  length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);\n  if (cin.image.number_channels == 1)\n    {\n      quantum_type=GrayQuantum;\n      length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);\n    }\n  status=SetQuantumPad(image,quantum_info,0);\n  pixels=GetQuantumPixels(quantum_info);\n  for (y=0; y < (ssize_t) image->rows; y++)\n  {\n    const void\n      *stream;\n\n    q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n    if (q == (PixelPacket *) NULL)\n      break;\n    stream=ReadBlobStream(image,length,pixels,&count);\n    if (count != (ssize_t) length)\n      break;\n    (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n      quantum_type,(unsigned char *) stream,exception);\n    if (SyncAuthenticPixels(image,exception) == MagickFalse)\n      break;\n    if (image->previous == (Image *) NULL)\n      {\n        status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n          image->rows);\n        if (status == MagickFalse)\n          break;\n      }\n  }\n  SetQuantumImageType(image,quantum_type);\n  quantum_info=DestroyQuantumInfo(quantum_info);\n  if (EOFBlob(image) != MagickFalse)\n    ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n      image->filename);\n  SetImageColorspace(image,LogColorspace);\n  (void) CloseBlob(image);\n  return(GetFirstImageInList(image));\n}", "func_hash": 230911711267539175049972905344313345647, "file_name": "cin.c", "file_hash": 249228869233078232834553857521337694406, "cwe": ["CWE-787"], "cve": "CVE-2022-28463", "cve_desc": "ImageMagick 7.1.0-27 is vulnerable to Buffer Overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-28463"}
{"idx": 319422, "project": "ImageMagick6", "commit_id": "e6ea5876e0228165ee3abc6e959aa174cee06680", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/e6ea5876e0228165ee3abc6e959aa174cee06680", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/4988", "target": 0, "func": "static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define MonoColorType  1\n#define RGBColorType  3\n\n  char\n    property[MaxTextExtent];\n\n  CINInfo\n    cin;\n\n  Image\n    *image;\n\n  MagickBooleanType\n    status;\n\n  MagickOffsetType\n    offset;\n\n  QuantumInfo\n    *quantum_info;\n\n  QuantumType\n    quantum_type;\n\n  ssize_t\n    i;\n\n  PixelPacket\n    *q;\n\n  size_t\n    extent,\n    length;\n\n  ssize_t\n    count,\n    y;\n\n  unsigned char\n    magick[4],\n    *pixels;\n\n  /*\n    Open image file.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  image=AcquireImage(image_info);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n    File information.\n  */\n  offset=0;\n  count=ReadBlob(image,4,magick);\n  offset+=count;\n  if ((count != 4) ||\n      ((LocaleNCompare((char *) magick,\"\\200\\052\\137\\327\",4) != 0)))\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  memset(&cin,0,sizeof(cin));\n  image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&\n    (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;\n  cin.file.image_offset=ReadBlobLong(image);\n  if (cin.file.image_offset < 712)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  offset+=4;\n  cin.file.generic_length=ReadBlobLong(image);\n  offset+=4;\n  cin.file.industry_length=ReadBlobLong(image);\n  offset+=4;\n  cin.file.user_length=ReadBlobLong(image);\n  offset+=4;\n  cin.file.file_size=ReadBlobLong(image);\n  offset+=4;\n  offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)\n    cin.file.version);\n  (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));\n  (void) SetImageProperty(image,\"dpx:file.version\",property);\n  offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)\n    cin.file.filename);\n  (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));\n  (void) SetImageProperty(image,\"dpx:file.filename\",property);\n  offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)\n    cin.file.create_date);\n  (void) CopyMagickString(property,cin.file.create_date,\n    sizeof(cin.file.create_date));\n  (void) SetImageProperty(image,\"dpx:file.create_date\",property);\n  offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)\n    cin.file.create_time);\n  (void) CopyMagickString(property,cin.file.create_time,\n     sizeof(cin.file.create_time));\n  (void) SetImageProperty(image,\"dpx:file.create_time\",property);\n  offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)\n    cin.file.reserve);\n  /*\n    Image information.\n  */\n  cin.image.orientation=(unsigned char) ReadBlobByte(image);\n  offset++;\n  if (cin.image.orientation != (unsigned char) (~0))\n    (void) FormatImageProperty(image,\"dpx:image.orientation\",\"%d\",\n      cin.image.orientation);\n  switch (cin.image.orientation)\n  {\n    default:\n    case 0: image->orientation=TopLeftOrientation; break;\n    case 1: image->orientation=TopRightOrientation; break;\n    case 2: image->orientation=BottomLeftOrientation; break;\n    case 3: image->orientation=BottomRightOrientation; break;\n    case 4: image->orientation=LeftTopOrientation; break;\n    case 5: image->orientation=RightTopOrientation; break;\n    case 6: image->orientation=LeftBottomOrientation; break;\n    case 7: image->orientation=RightBottomOrientation; break;\n  }\n  cin.image.number_channels=(unsigned char) ReadBlobByte(image);\n  offset++;\n  offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)\n    cin.image.reserve1);\n  for (i=0; i < 8; i++)\n  {\n    cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].pixels_per_line=ReadBlobLong(image);\n    offset+=4;\n    cin.image.channel[i].lines_per_image=ReadBlobLong(image);\n    offset+=4;\n    cin.image.channel[i].min_data=ReadBlobFloat(image);\n    offset+=4;\n    cin.image.channel[i].min_quantity=ReadBlobFloat(image);\n    offset+=4;\n    cin.image.channel[i].max_data=ReadBlobFloat(image);\n    offset+=4;\n    cin.image.channel[i].max_quantity=ReadBlobFloat(image);\n    offset+=4;\n  }\n  cin.image.white_point[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)\n    image->chromaticity.white_point.x=cin.image.white_point[0];\n  cin.image.white_point[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)\n    image->chromaticity.white_point.y=cin.image.white_point[1];\n  cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)\n    image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];\n  cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)\n    image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];\n  cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)\n    image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];\n  cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)\n    image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];\n  cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)\n    image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];\n  cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)\n    image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];\n  offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)\n    cin.image.label);\n  (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));\n  (void) SetImageProperty(image,\"dpx:image.label\",property);\n  offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)\n    cin.image.reserve);\n  /*\n    Image data format information.\n  */\n  cin.data_format.interleave=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.packing=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.sign=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.sense=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.line_pad=ReadBlobLong(image);\n  offset+=4;\n  cin.data_format.channel_pad=ReadBlobLong(image);\n  offset+=4;\n  offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)\n    cin.data_format.reserve);\n  /*\n    Image origination information.\n  */\n  cin.origination.x_offset=ReadBlobSignedLong(image);\n  offset+=4;\n  if ((size_t) cin.origination.x_offset != ~0UL)\n    (void) FormatImageProperty(image,\"dpx:origination.x_offset\",\"%.20g\",\n      (double) cin.origination.x_offset);\n  cin.origination.y_offset=(ssize_t) ReadBlobLong(image);\n  offset+=4;\n  if ((size_t) cin.origination.y_offset != ~0UL)\n    (void) FormatImageProperty(image,\"dpx:origination.y_offset\",\"%.20g\",\n      (double) cin.origination.y_offset);\n  offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)\n    cin.origination.filename);\n  (void) CopyMagickString(property,cin.origination.filename,\n    sizeof(cin.origination.filename));\n  (void) SetImageProperty(image,\"dpx:origination.filename\",property);\n  offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)\n    cin.origination.create_date);\n  (void) CopyMagickString(property,cin.origination.create_date,\n    sizeof(cin.origination.create_date));\n  (void) SetImageProperty(image,\"dpx:origination.create_date\",property);\n  offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)\n    cin.origination.create_time);\n  (void) CopyMagickString(property,cin.origination.create_time,\n    sizeof(cin.origination.create_time));\n  (void) SetImageProperty(image,\"dpx:origination.create_time\",property);\n  offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)\n    cin.origination.device);\n  (void) CopyMagickString(property,cin.origination.device,\n    sizeof(cin.origination.device));\n  (void) SetImageProperty(image,\"dpx:origination.device\",property);\n  offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)\n    cin.origination.model);\n  (void) CopyMagickString(property,cin.origination.model,\n    sizeof(cin.origination.model));\n  (void) SetImageProperty(image,\"dpx:origination.model\",property);\n  (void) memset(cin.origination.serial,0,\n    sizeof(cin.origination.serial));\n  offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)\n    cin.origination.serial);\n  (void) CopyMagickString(property,cin.origination.serial,\n    sizeof(cin.origination.serial));\n  (void) SetImageProperty(image,\"dpx:origination.serial\",property);\n  cin.origination.x_pitch=ReadBlobFloat(image);\n  offset+=4;\n  cin.origination.y_pitch=ReadBlobFloat(image);\n  offset+=4;\n  cin.origination.gamma=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.origination.gamma) != MagickFalse)\n    image->gamma=cin.origination.gamma;\n  offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)\n    cin.origination.reserve);\n  if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))\n    {\n      int\n        c;\n\n      /*\n        Image film information.\n      */\n      cin.film.id=ReadBlobByte(image);\n      offset++;\n      c=cin.film.id;\n      if (c != ~0)\n        (void) FormatImageProperty(image,\"dpx:film.id\",\"%d\",cin.film.id);\n      cin.film.type=ReadBlobByte(image);\n      offset++;\n      c=cin.film.type;\n      if (c != ~0)\n        (void) FormatImageProperty(image,\"dpx:film.type\",\"%d\",cin.film.type);\n      cin.film.offset=ReadBlobByte(image);\n      offset++;\n      c=cin.film.offset;\n      if (c != ~0)\n        (void) FormatImageProperty(image,\"dpx:film.offset\",\"%d\",\n          cin.film.offset);\n      cin.film.reserve1=ReadBlobByte(image);\n      offset++;\n      cin.film.prefix=ReadBlobLong(image);\n      offset+=4;\n      if (cin.film.prefix != ~0UL)\n        (void) FormatImageProperty(image,\"dpx:film.prefix\",\"%.20g\",(double)\n          cin.film.prefix);\n      cin.film.count=ReadBlobLong(image);\n      offset+=4;\n      offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)\n        cin.film.format);\n      (void) CopyMagickString(property,cin.film.format,\n        sizeof(cin.film.format));\n      (void) SetImageProperty(image,\"dpx:film.format\",property);\n      cin.film.frame_position=ReadBlobLong(image);\n      offset+=4;\n      if (cin.film.frame_position != ~0UL)\n        (void) FormatImageProperty(image,\"dpx:film.frame_position\",\"%.20g\",\n          (double) cin.film.frame_position);\n      cin.film.frame_rate=ReadBlobFloat(image);\n      offset+=4;\n      if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)\n        (void) FormatImageProperty(image,\"dpx:film.frame_rate\",\"%g\",\n          cin.film.frame_rate);\n      offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)\n        cin.film.frame_id);\n      (void) CopyMagickString(property,cin.film.frame_id,\n        sizeof(cin.film.frame_id));\n      (void) SetImageProperty(image,\"dpx:film.frame_id\",property);\n      offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)\n        cin.film.slate_info);\n      (void) CopyMagickString(property,cin.film.slate_info,\n        sizeof(cin.film.slate_info));\n      (void) SetImageProperty(image,\"dpx:film.slate_info\",property);\n      offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)\n        cin.film.reserve);\n    }\n  if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))\n    {\n      StringInfo\n        *profile;\n\n      /*\n        User defined data.\n      */\n      if (cin.file.user_length > GetBlobSize(image))\n        ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n      profile=BlobToStringInfo((const void *) NULL,cin.file.user_length);\n      if (profile == (StringInfo *) NULL)\n        ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n      offset+=ReadBlob(image,GetStringInfoLength(profile),\n        GetStringInfoDatum(profile));\n      (void) SetImageProfile(image,\"dpx:user.data\",profile);\n      profile=DestroyStringInfo(profile);\n    }\n  image->depth=cin.image.channel[0].bits_per_pixel;\n  image->columns=cin.image.channel[0].pixels_per_line;\n  image->rows=cin.image.channel[0].lines_per_image;\n  if (image_info->ping != MagickFalse)\n    {\n      (void) CloseBlob(image);\n      return(image);\n    }\n  if (((MagickSizeType) image->columns*image->rows/8) > GetBlobSize(image))\n    ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n  for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)\n  {\n    int\n      c;\n\n    c=ReadBlobByte(image);\n    if (c == EOF)\n      break;\n  }\n  if (offset < (MagickOffsetType) cin.file.image_offset)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  status=SetImageExtent(image,image->columns,image->rows);\n  if (status == MagickFalse)\n    {\n      InheritException(exception,&image->exception);\n      return(DestroyImageList(image));\n    }\n  (void) SetImageBackgroundColor(image);\n  /*\n    Convert CIN raster image to pixel packets.\n  */\n  quantum_info=AcquireQuantumInfo(image_info,image);\n  if (quantum_info == (QuantumInfo *) NULL)\n    ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n  SetQuantumQuantum(quantum_info,32);\n  SetQuantumPack(quantum_info,MagickFalse);\n  quantum_type=RGBQuantum;\n  extent=GetQuantumExtent(image,quantum_info,quantum_type);\n  (void) extent;\n  length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);\n  if (cin.image.number_channels == 1)\n    {\n      quantum_type=GrayQuantum;\n      length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);\n    }\n  status=SetQuantumPad(image,quantum_info,0);\n  pixels=GetQuantumPixels(quantum_info);\n  for (y=0; y < (ssize_t) image->rows; y++)\n  {\n    const void\n      *stream;\n\n    q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n    if (q == (PixelPacket *) NULL)\n      break;\n    stream=ReadBlobStream(image,length,pixels,&count);\n    if (count != (ssize_t) length)\n      break;\n    (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n      quantum_type,(unsigned char *) stream,exception);\n    if (SyncAuthenticPixels(image,exception) == MagickFalse)\n      break;\n    if (image->previous == (Image *) NULL)\n      {\n        status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n          image->rows);\n        if (status == MagickFalse)\n          break;\n      }\n  }\n  SetQuantumImageType(image,quantum_type);\n  quantum_info=DestroyQuantumInfo(quantum_info);\n  if (EOFBlob(image) != MagickFalse)\n    ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n      image->filename);\n  SetImageColorspace(image,LogColorspace);\n  (void) CloseBlob(image);\n  return(GetFirstImageInList(image));\n}", "func_hash": 125198761122342315192980410159814316224, "file_name": "cin.c", "file_hash": 162029268319562364339376626172641683991, "cwe": ["CWE-787"], "cve": "CVE-2022-28463", "cve_desc": "ImageMagick 7.1.0-27 is vulnerable to Buffer Overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-28463"}
{"idx": 201872, "project": "gnutls", "commit_id": "20a98e817713764b9df5306286091df1b61190d9", "project_url": "http://git.savannah.gnu.org/cgit/gnutls", "commit_url": "https://gitlab.com/gnutls/gnutls/commit/20a98e817713764b9df5306286091df1b61190d9", "commit_message": "handshake: check inappropriate fallback against the configured max version\n\nThat allows to operate on a server which is explicitly configured to\nutilize earlier than TLS 1.2 versions.", "target": 1, "func": "_gnutls_server_select_suite(gnutls_session_t session, uint8_t * data,\n\t\t\t    unsigned int datalen)\n{\n\tint ret;\n\tunsigned int i, j, cipher_suites_size;\n\tsize_t pk_algos_size;\n\tuint8_t cipher_suites[MAX_CIPHERSUITE_SIZE];\n\tint retval;\n\tgnutls_pk_algorithm_t pk_algos[MAX_ALGOS];\t/* will hold the pk algorithms\n\t\t\t\t\t\t\t * supported by the peer.\n\t\t\t\t\t\t\t */\n\n\tfor (i = 0; i < datalen; i += 2) {\n\t\t/* TLS_RENEGO_PROTECTION_REQUEST = { 0x00, 0xff } */\n\t\tif (session->internals.priorities.sr != SR_DISABLED &&\n\t\t    data[i] == GNUTLS_RENEGO_PROTECTION_REQUEST_MAJOR &&\n\t\t    data[i + 1] == GNUTLS_RENEGO_PROTECTION_REQUEST_MINOR) {\n\t\t\t_gnutls_handshake_log\n\t\t\t    (\"HSK[%p]: Received safe renegotiation CS\\n\",\n\t\t\t     session);\n\t\t\tretval = _gnutls_ext_sr_recv_cs(session);\n\t\t\tif (retval < 0) {\n\t\t\t\tgnutls_assert();\n\t\t\t\treturn retval;\n\t\t\t}\n\t\t}\n\n\t\t/* TLS_FALLBACK_SCSV */\n\t\tif (data[i] == GNUTLS_FALLBACK_SCSV_MAJOR &&\n\t\t    data[i + 1] == GNUTLS_FALLBACK_SCSV_MINOR) {\n\t\t\t_gnutls_handshake_log\n\t\t\t    (\"HSK[%p]: Received fallback CS\\n\",\n\t\t\t     session);\n\n\t\t\tif (gnutls_protocol_get_version(session) !=\n\t\t\t    GNUTLS_TLS_VERSION_MAX)\n\t\t\t\treturn GNUTLS_E_INAPPROPRIATE_FALLBACK;\n\t\t}\n\t}\n\n\tpk_algos_size = MAX_ALGOS;\n\tret =\n\t    server_find_pk_algos_in_ciphersuites(data, datalen, pk_algos,\n\t\t\t\t\t\t &pk_algos_size);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tret =\n\t    _gnutls_supported_ciphersuites(session, cipher_suites,\n\t\t\t\t\t   sizeof(cipher_suites));\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tcipher_suites_size = ret;\n\n\t/* Here we remove any ciphersuite that does not conform\n\t * the certificate requested, or to the\n\t * authentication requested (e.g. SRP).\n\t */\n\tret =\n\t    _gnutls_remove_unwanted_ciphersuites(session, cipher_suites,\n\t\t\t\t\t\t cipher_suites_size,\n\t\t\t\t\t\t pk_algos, pk_algos_size);\n\tif (ret <= 0) {\n\t\tgnutls_assert();\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t\telse\n\t\t\treturn GNUTLS_E_UNKNOWN_CIPHER_SUITE;\n\t}\n\n\tcipher_suites_size = ret;\n\n\t/* Data length should be zero mod 2 since\n\t * every ciphersuite is 2 bytes. (this check is needed\n\t * see below).\n\t */\n\tif (datalen % 2 != 0) {\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_UNEXPECTED_PACKET_LENGTH;\n\t}\n\n\tmemset(session->security_parameters.cipher_suite, 0, 2);\n\n\tretval = GNUTLS_E_UNKNOWN_CIPHER_SUITE;\n\n\t_gnutls_handshake_log\n\t    (\"HSK[%p]: Requested cipher suites[size: %d]: \\n\", session,\n\t     (int) datalen);\n\n\tif (session->internals.priorities.server_precedence == 0) {\n\t\tfor (j = 0; j < datalen; j += 2) {\n\t\t\t_gnutls_handshake_log(\"\\t0x%.2x, 0x%.2x %s\\n\",\n\t\t\t\t\t      data[j], data[j + 1],\n\t\t\t\t\t      _gnutls_cipher_suite_get_name\n\t\t\t\t\t      (&data[j]));\n\t\t\tfor (i = 0; i < cipher_suites_size; i += 2) {\n\t\t\t\tif (memcmp(&cipher_suites[i], &data[j], 2)\n\t\t\t\t    == 0) {\n\t\t\t\t\t_gnutls_handshake_log\n\t\t\t\t\t    (\"HSK[%p]: Selected cipher suite: %s\\n\",\n\t\t\t\t\t     session,\n\t\t\t\t\t     _gnutls_cipher_suite_get_name\n\t\t\t\t\t     (&data[j]));\n\t\t\t\t\tmemcpy(session->\n\t\t\t\t\t       security_parameters.\n\t\t\t\t\t       cipher_suite,\n\t\t\t\t\t       &cipher_suites[i], 2);\n\t\t\t\t\t_gnutls_epoch_set_cipher_suite\n\t\t\t\t\t    (session, EPOCH_NEXT,\n\t\t\t\t\t     session->security_parameters.\n\t\t\t\t\t     cipher_suite);\n\n\n\t\t\t\t\tretval = 0;\n\t\t\t\t\tgoto finish;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\t\t/* server selects */\n\n\t\tfor (i = 0; i < cipher_suites_size; i += 2) {\n\t\t\tfor (j = 0; j < datalen; j += 2) {\n\t\t\t\tif (memcmp(&cipher_suites[i], &data[j], 2)\n\t\t\t\t    == 0) {\n\t\t\t\t\t_gnutls_handshake_log\n\t\t\t\t\t    (\"HSK[%p]: Selected cipher suite: %s\\n\",\n\t\t\t\t\t     session,\n\t\t\t\t\t     _gnutls_cipher_suite_get_name\n\t\t\t\t\t     (&data[j]));\n\t\t\t\t\tmemcpy(session->\n\t\t\t\t\t       security_parameters.\n\t\t\t\t\t       cipher_suite,\n\t\t\t\t\t       &cipher_suites[i], 2);\n\t\t\t\t\t_gnutls_epoch_set_cipher_suite\n\t\t\t\t\t    (session, EPOCH_NEXT,\n\t\t\t\t\t     session->security_parameters.\n\t\t\t\t\t     cipher_suite);\n\n\n\t\t\t\t\tretval = 0;\n\t\t\t\t\tgoto finish;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n      finish:\n\n\tif (retval != 0) {\n\t\tgnutls_assert();\n\t\treturn retval;\n\t}\n\n\t/* check if the credentials (username, public key etc.) are ok\n\t */\n\tif (_gnutls_get_kx_cred\n\t    (session,\n\t     _gnutls_cipher_suite_get_kx_algo(session->security_parameters.\n\t\t\t\t\t      cipher_suite)) == NULL) {\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_INSUFFICIENT_CREDENTIALS;\n\t}\n\n\n\t/* set the mod_auth_st to the appropriate struct\n\t * according to the KX algorithm. This is needed since all the\n\t * handshake functions are read from there;\n\t */\n\tsession->internals.auth_struct =\n\t    _gnutls_kx_auth_struct(_gnutls_cipher_suite_get_kx_algo\n\t\t\t\t   (session->security_parameters.\n\t\t\t\t    cipher_suite));\n\tif (session->internals.auth_struct == NULL) {\n\n\t\t_gnutls_handshake_log\n\t\t    (\"HSK[%p]: Cannot find the appropriate handler for the KX algorithm\\n\",\n\t\t     session);\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_INTERNAL_ERROR;\n\t}\n\n\treturn 0;\n\n}", "func_hash": 43939075651028590089831343195417108850, "file_name": "gnutls_handshake.c", "file_hash": 33222600436004333309471609542396279978, "cwe": ["CWE-310"], "cve": "CVE-2014-3566", "cve_desc": "The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other products, uses nondeterministic CBC padding, which makes it easier for man-in-the-middle attackers to obtain cleartext data via a padding-oracle attack, aka the \"POODLE\" issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-3566"}
{"idx": 325821, "project": "gnutls", "commit_id": "20a98e817713764b9df5306286091df1b61190d9", "project_url": "http://git.savannah.gnu.org/cgit/gnutls", "commit_url": "https://gitlab.com/gnutls/gnutls/commit/20a98e817713764b9df5306286091df1b61190d9", "commit_message": "handshake: check inappropriate fallback against the configured max version\n\nThat allows to operate on a server which is explicitly configured to\nutilize earlier than TLS 1.2 versions.", "target": 0, "func": "_gnutls_server_select_suite(gnutls_session_t session, uint8_t * data,\n\t\t\t    unsigned int datalen)\n{\n\tint ret;\n\tunsigned int i, j, cipher_suites_size;\n\tsize_t pk_algos_size;\n\tuint8_t cipher_suites[MAX_CIPHERSUITE_SIZE];\n\tint retval;\n\tgnutls_pk_algorithm_t pk_algos[MAX_ALGOS];\t/* will hold the pk algorithms\n\t\t\t\t\t\t\t * supported by the peer.\n\t\t\t\t\t\t\t */\n\n\tfor (i = 0; i < datalen; i += 2) {\n\t\t/* TLS_RENEGO_PROTECTION_REQUEST = { 0x00, 0xff } */\n\t\tif (session->internals.priorities.sr != SR_DISABLED &&\n\t\t    data[i] == GNUTLS_RENEGO_PROTECTION_REQUEST_MAJOR &&\n\t\t    data[i + 1] == GNUTLS_RENEGO_PROTECTION_REQUEST_MINOR) {\n\t\t\t_gnutls_handshake_log\n\t\t\t    (\"HSK[%p]: Received safe renegotiation CS\\n\",\n\t\t\t     session);\n\t\t\tretval = _gnutls_ext_sr_recv_cs(session);\n\t\t\tif (retval < 0) {\n\t\t\t\tgnutls_assert();\n\t\t\t\treturn retval;\n\t\t\t}\n\t\t}\n\n\t\t/* TLS_FALLBACK_SCSV */\n\t\tif (data[i] == GNUTLS_FALLBACK_SCSV_MAJOR &&\n\t\t    data[i + 1] == GNUTLS_FALLBACK_SCSV_MINOR) {\n\t\t\tunsigned max = _gnutls_version_max(session);\n\t\t\t_gnutls_handshake_log\n\t\t\t    (\"HSK[%p]: Received fallback CS\\n\",\n\t\t\t     session);\n\n\t\t\tif (gnutls_protocol_get_version(session) != max)\n\t\t\t\treturn gnutls_assert_val(GNUTLS_E_INAPPROPRIATE_FALLBACK);\n\t\t}\n\t}\n\n\tpk_algos_size = MAX_ALGOS;\n\tret =\n\t    server_find_pk_algos_in_ciphersuites(data, datalen, pk_algos,\n\t\t\t\t\t\t &pk_algos_size);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tret =\n\t    _gnutls_supported_ciphersuites(session, cipher_suites,\n\t\t\t\t\t   sizeof(cipher_suites));\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tcipher_suites_size = ret;\n\n\t/* Here we remove any ciphersuite that does not conform\n\t * the certificate requested, or to the\n\t * authentication requested (e.g. SRP).\n\t */\n\tret =\n\t    _gnutls_remove_unwanted_ciphersuites(session, cipher_suites,\n\t\t\t\t\t\t cipher_suites_size,\n\t\t\t\t\t\t pk_algos, pk_algos_size);\n\tif (ret <= 0) {\n\t\tgnutls_assert();\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t\telse\n\t\t\treturn GNUTLS_E_UNKNOWN_CIPHER_SUITE;\n\t}\n\n\tcipher_suites_size = ret;\n\n\t/* Data length should be zero mod 2 since\n\t * every ciphersuite is 2 bytes. (this check is needed\n\t * see below).\n\t */\n\tif (datalen % 2 != 0) {\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_UNEXPECTED_PACKET_LENGTH;\n\t}\n\n\tmemset(session->security_parameters.cipher_suite, 0, 2);\n\n\tretval = GNUTLS_E_UNKNOWN_CIPHER_SUITE;\n\n\t_gnutls_handshake_log\n\t    (\"HSK[%p]: Requested cipher suites[size: %d]: \\n\", session,\n\t     (int) datalen);\n\n\tif (session->internals.priorities.server_precedence == 0) {\n\t\tfor (j = 0; j < datalen; j += 2) {\n\t\t\t_gnutls_handshake_log(\"\\t0x%.2x, 0x%.2x %s\\n\",\n\t\t\t\t\t      data[j], data[j + 1],\n\t\t\t\t\t      _gnutls_cipher_suite_get_name\n\t\t\t\t\t      (&data[j]));\n\t\t\tfor (i = 0; i < cipher_suites_size; i += 2) {\n\t\t\t\tif (memcmp(&cipher_suites[i], &data[j], 2)\n\t\t\t\t    == 0) {\n\t\t\t\t\t_gnutls_handshake_log\n\t\t\t\t\t    (\"HSK[%p]: Selected cipher suite: %s\\n\",\n\t\t\t\t\t     session,\n\t\t\t\t\t     _gnutls_cipher_suite_get_name\n\t\t\t\t\t     (&data[j]));\n\t\t\t\t\tmemcpy(session->\n\t\t\t\t\t       security_parameters.\n\t\t\t\t\t       cipher_suite,\n\t\t\t\t\t       &cipher_suites[i], 2);\n\t\t\t\t\t_gnutls_epoch_set_cipher_suite\n\t\t\t\t\t    (session, EPOCH_NEXT,\n\t\t\t\t\t     session->security_parameters.\n\t\t\t\t\t     cipher_suite);\n\n\n\t\t\t\t\tretval = 0;\n\t\t\t\t\tgoto finish;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\t\t/* server selects */\n\n\t\tfor (i = 0; i < cipher_suites_size; i += 2) {\n\t\t\tfor (j = 0; j < datalen; j += 2) {\n\t\t\t\tif (memcmp(&cipher_suites[i], &data[j], 2)\n\t\t\t\t    == 0) {\n\t\t\t\t\t_gnutls_handshake_log\n\t\t\t\t\t    (\"HSK[%p]: Selected cipher suite: %s\\n\",\n\t\t\t\t\t     session,\n\t\t\t\t\t     _gnutls_cipher_suite_get_name\n\t\t\t\t\t     (&data[j]));\n\t\t\t\t\tmemcpy(session->\n\t\t\t\t\t       security_parameters.\n\t\t\t\t\t       cipher_suite,\n\t\t\t\t\t       &cipher_suites[i], 2);\n\t\t\t\t\t_gnutls_epoch_set_cipher_suite\n\t\t\t\t\t    (session, EPOCH_NEXT,\n\t\t\t\t\t     session->security_parameters.\n\t\t\t\t\t     cipher_suite);\n\n\n\t\t\t\t\tretval = 0;\n\t\t\t\t\tgoto finish;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n      finish:\n\n\tif (retval != 0) {\n\t\tgnutls_assert();\n\t\treturn retval;\n\t}\n\n\t/* check if the credentials (username, public key etc.) are ok\n\t */\n\tif (_gnutls_get_kx_cred\n\t    (session,\n\t     _gnutls_cipher_suite_get_kx_algo(session->security_parameters.\n\t\t\t\t\t      cipher_suite)) == NULL) {\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_INSUFFICIENT_CREDENTIALS;\n\t}\n\n\n\t/* set the mod_auth_st to the appropriate struct\n\t * according to the KX algorithm. This is needed since all the\n\t * handshake functions are read from there;\n\t */\n\tsession->internals.auth_struct =\n\t    _gnutls_kx_auth_struct(_gnutls_cipher_suite_get_kx_algo\n\t\t\t\t   (session->security_parameters.\n\t\t\t\t    cipher_suite));\n\tif (session->internals.auth_struct == NULL) {\n\n\t\t_gnutls_handshake_log\n\t\t    (\"HSK[%p]: Cannot find the appropriate handler for the KX algorithm\\n\",\n\t\t     session);\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_INTERNAL_ERROR;\n\t}\n\n\treturn 0;\n\n}", "func_hash": 258083912886334761023165928095225492685, "file_name": "gnutls_handshake.c", "file_hash": 160528780373648505874425532995323250651, "cwe": ["CWE-310"], "cve": "CVE-2014-3566", "cve_desc": "The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other products, uses nondeterministic CBC padding, which makes it easier for man-in-the-middle attackers to obtain cleartext data via a padding-oracle attack, aka the \"POODLE\" issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-3566"}
{"idx": 201885, "project": "vim", "commit_id": "b55986c52d4cd88a22d0b0b0e8a79547ba13e1d5", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/b55986c52d4cd88a22d0b0b0e8a79547ba13e1d5", "commit_message": "patch 8.2.4646: using buffer line after it has been freed\n\nProblem:    Using buffer line after it has been freed in old regexp engine.\nSolution:   After getting mark get the line again.", "target": 1, "func": "regmatch(\n    char_u\t*scan,\t\t    // Current node.\n    proftime_T\t*tm UNUSED,\t    // timeout limit or NULL\n    int\t\t*timed_out UNUSED)  // flag set on timeout or NULL\n{\n  char_u\t*next;\t\t// Next node.\n  int\t\top;\n  int\t\tc;\n  regitem_T\t*rp;\n  int\t\tno;\n  int\t\tstatus;\t\t// one of the RA_ values:\n#ifdef FEAT_RELTIME\n  int\t\ttm_count = 0;\n#endif\n\n  // Make \"regstack\" and \"backpos\" empty.  They are allocated and freed in\n  // bt_regexec_both() to reduce malloc()/free() calls.\n  regstack.ga_len = 0;\n  backpos.ga_len = 0;\n\n  // Repeat until \"regstack\" is empty.\n  for (;;)\n  {\n    // Some patterns may take a long time to match, e.g., \"\\([a-z]\\+\\)\\+Q\".\n    // Allow interrupting them with CTRL-C.\n    fast_breakcheck();\n\n#ifdef DEBUG\n    if (scan != NULL && regnarrate)\n    {\n\tmch_errmsg((char *)regprop(scan));\n\tmch_errmsg(\"(\\n\");\n    }\n#endif\n\n    // Repeat for items that can be matched sequentially, without using the\n    // regstack.\n    for (;;)\n    {\n\tif (got_int || scan == NULL)\n\t{\n\t    status = RA_FAIL;\n\t    break;\n\t}\n#ifdef FEAT_RELTIME\n\t// Check for timeout once in a 100 times to avoid overhead.\n\tif (tm != NULL && ++tm_count == 100)\n\t{\n\t    tm_count = 0;\n\t    if (profile_passed_limit(tm))\n\t    {\n\t\tif (timed_out != NULL)\n\t\t    *timed_out = TRUE;\n\t\tstatus = RA_FAIL;\n\t\tbreak;\n\t    }\n\t}\n#endif\n\tstatus = RA_CONT;\n\n#ifdef DEBUG\n\tif (regnarrate)\n\t{\n\t    mch_errmsg((char *)regprop(scan));\n\t    mch_errmsg(\"...\\n\");\n# ifdef FEAT_SYN_HL\n\t    if (re_extmatch_in != NULL)\n\t    {\n\t\tint i;\n\n\t\tmch_errmsg(_(\"External submatches:\\n\"));\n\t\tfor (i = 0; i < NSUBEXP; i++)\n\t\t{\n\t\t    mch_errmsg(\"    \\\"\");\n\t\t    if (re_extmatch_in->matches[i] != NULL)\n\t\t\tmch_errmsg((char *)re_extmatch_in->matches[i]);\n\t\t    mch_errmsg(\"\\\"\\n\");\n\t\t}\n\t    }\n# endif\n\t}\n#endif\n\tnext = regnext(scan);\n\n\top = OP(scan);\n\t// Check for character class with NL added.\n\tif (!rex.reg_line_lbr && WITH_NL(op) && REG_MULTI\n\t\t\t     && *rex.input == NUL && rex.lnum <= rex.reg_maxline)\n\t{\n\t    reg_nextline();\n\t}\n\telse if (rex.reg_line_lbr && WITH_NL(op) && *rex.input == '\\n')\n\t{\n\t    ADVANCE_REGINPUT();\n\t}\n\telse\n\t{\n\t  if (WITH_NL(op))\n\t      op -= ADD_NL;\n\t  if (has_mbyte)\n\t      c = (*mb_ptr2char)(rex.input);\n\t  else\n\t      c = *rex.input;\n\t  switch (op)\n\t  {\n\t  case BOL:\n\t    if (rex.input != rex.line)\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case EOL:\n\t    if (c != NUL)\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case RE_BOF:\n\t    // We're not at the beginning of the file when below the first\n\t    // line where we started, not at the start of the line or we\n\t    // didn't start at the first line of the buffer.\n\t    if (rex.lnum != 0 || rex.input != rex.line\n\t\t\t\t       || (REG_MULTI && rex.reg_firstlnum > 1))\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case RE_EOF:\n\t    if (rex.lnum != rex.reg_maxline || c != NUL)\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case CURSOR:\n\t    // Check if the buffer is in a window and compare the\n\t    // rex.reg_win->w_cursor position to the match position.\n\t    if (rex.reg_win == NULL\n\t\t    || (rex.lnum + rex.reg_firstlnum\n\t\t\t\t\t\t != rex.reg_win->w_cursor.lnum)\n\t\t    || ((colnr_T)(rex.input - rex.line)\n\t\t\t\t\t\t != rex.reg_win->w_cursor.col))\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case RE_MARK:\n\t    // Compare the mark position to the match position.\n\t    {\n\t\tint\tmark = OPERAND(scan)[0];\n\t\tint\tcmp = OPERAND(scan)[1];\n\t\tpos_T\t*pos;\n\n\t\tpos = getmark_buf(rex.reg_buf, mark, FALSE);\n\t\tif (pos == NULL\t\t     // mark doesn't exist\n\t\t\t|| pos->lnum <= 0)   // mark isn't set in reg_buf\n\t\t{\n\t\t    status = RA_NOMATCH;\n\t\t}\n\t\telse\n\t\t{\n\t\t    colnr_T pos_col = pos->lnum == rex.lnum + rex.reg_firstlnum\n\t\t\t\t\t\t\t  && pos->col == MAXCOL\n\t\t\t\t      ? (colnr_T)STRLEN(reg_getline(\n\t\t\t\t\t\tpos->lnum - rex.reg_firstlnum))\n\t\t\t\t      : pos->col;\n\n\t\t    if ((pos->lnum == rex.lnum + rex.reg_firstlnum\n\t\t\t\t? (pos_col == (colnr_T)(rex.input - rex.line)\n\t\t\t\t    ? (cmp == '<' || cmp == '>')\n\t\t\t\t    : (pos_col < (colnr_T)(rex.input - rex.line)\n\t\t\t\t\t? cmp != '>'\n\t\t\t\t\t: cmp != '<'))\n\t\t\t\t: (pos->lnum < rex.lnum + rex.reg_firstlnum\n\t\t\t\t    ? cmp != '>'\n\t\t\t\t    : cmp != '<')))\n\t\t    status = RA_NOMATCH;\n\t\t}\n\t    }\n\t    break;\n\n\t  case RE_VISUAL:\n\t    if (!reg_match_visual())\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case RE_LNUM:\n\t    if (!REG_MULTI || !re_num_cmp((long_u)(rex.lnum + rex.reg_firstlnum),\n\t\t\t\t\t\t\t\t\tscan))\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case RE_COL:\n\t    if (!re_num_cmp((long_u)(rex.input - rex.line) + 1, scan))\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case RE_VCOL:\n\t    if (!re_num_cmp((long_u)win_linetabsize(\n\t\t\t    rex.reg_win == NULL ? curwin : rex.reg_win,\n\t\t\t    rex.line, (colnr_T)(rex.input - rex.line)) + 1, scan))\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case BOW:\t// \\ rex.line\n\t\t\t\t&& vim_iswordc_buf(rex.input[-1], rex.reg_buf)))\n\t\t    status = RA_NOMATCH;\n\t    }\n\t    break;\n\n\t  case EOW:\t// word\\>; rex.input points after d\n\t    if (rex.input == rex.line)    // Can't match at start of line\n\t\tstatus = RA_NOMATCH;\n\t    else if (has_mbyte)\n\t    {\n\t\tint this_class, prev_class;\n\n\t\t// Get class of current and previous char (if it exists).\n\t\tthis_class = mb_get_class_buf(rex.input, rex.reg_buf);\n\t\tprev_class = reg_prev_class();\n\t\tif (this_class == prev_class\n\t\t\t|| prev_class == 0 || prev_class == 1)\n\t\t    status = RA_NOMATCH;\n\t    }\n\t    else\n\t    {\n\t\tif (!vim_iswordc_buf(rex.input[-1], rex.reg_buf)\n\t\t\t|| (rex.input[0] != NUL\n\t\t\t\t\t   && vim_iswordc_buf(c, rex.reg_buf)))\n\t\t    status = RA_NOMATCH;\n\t    }\n\t    break; // Matched with EOW\n\n\t  case ANY:\n\t    // ANY does not match new lines.\n\t    if (c == NUL)\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case IDENT:\n\t    if (!vim_isIDc(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case SIDENT:\n\t    if (VIM_ISDIGIT(*rex.input) || !vim_isIDc(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case KWORD:\n\t    if (!vim_iswordp_buf(rex.input, rex.reg_buf))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case SKWORD:\n\t    if (VIM_ISDIGIT(*rex.input)\n\t\t\t\t    || !vim_iswordp_buf(rex.input, rex.reg_buf))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case FNAME:\n\t    if (!vim_isfilec(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case SFNAME:\n\t    if (VIM_ISDIGIT(*rex.input) || !vim_isfilec(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case PRINT:\n\t    if (!vim_isprintc(PTR2CHAR(rex.input)))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case SPRINT:\n\t    if (VIM_ISDIGIT(*rex.input) || !vim_isprintc(PTR2CHAR(rex.input)))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case WHITE:\n\t    if (!VIM_ISWHITE(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NWHITE:\n\t    if (c == NUL || VIM_ISWHITE(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case DIGIT:\n\t    if (!ri_digit(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NDIGIT:\n\t    if (c == NUL || ri_digit(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case HEX:\n\t    if (!ri_hex(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NHEX:\n\t    if (c == NUL || ri_hex(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case OCTAL:\n\t    if (!ri_octal(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NOCTAL:\n\t    if (c == NUL || ri_octal(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case WORD:\n\t    if (!ri_word(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NWORD:\n\t    if (c == NUL || ri_word(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case HEAD:\n\t    if (!ri_head(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NHEAD:\n\t    if (c == NUL || ri_head(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case ALPHA:\n\t    if (!ri_alpha(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NALPHA:\n\t    if (c == NUL || ri_alpha(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case LOWER:\n\t    if (!ri_lower(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NLOWER:\n\t    if (c == NUL || ri_lower(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case UPPER:\n\t    if (!ri_upper(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NUPPER:\n\t    if (c == NUL || ri_upper(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case EXACTLY:\n\t    {\n\t\tint\tlen;\n\t\tchar_u\t*opnd;\n\n\t\topnd = OPERAND(scan);\n\t\t// Inline the first byte, for speed.\n\t\tif (*opnd != *rex.input\n\t\t\t&& (!rex.reg_ic\n\t\t\t    || (!enc_utf8\n\t\t\t      && MB_TOLOWER(*opnd) != MB_TOLOWER(*rex.input))))\n\t\t    status = RA_NOMATCH;\n\t\telse if (*opnd == NUL)\n\t\t{\n\t\t    // match empty string always works; happens when \"~\" is\n\t\t    // empty.\n\t\t}\n\t\telse\n\t\t{\n\t\t    if (opnd[1] == NUL && !(enc_utf8 && rex.reg_ic))\n\t\t    {\n\t\t\tlen = 1;\t// matched a single byte above\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\t// Need to match first byte again for multi-byte.\n\t\t\tlen = (int)STRLEN(opnd);\n\t\t\tif (cstrncmp(opnd, rex.input, &len) != 0)\n\t\t\t    status = RA_NOMATCH;\n\t\t    }\n\t\t    // Check for following composing character, unless %C\n\t\t    // follows (skips over all composing chars).\n\t\t    if (status != RA_NOMATCH\n\t\t\t    && enc_utf8\n\t\t\t    && UTF_COMPOSINGLIKE(rex.input, rex.input + len)\n\t\t\t    && !rex.reg_icombine\n\t\t\t    && OP(next) != RE_COMPOSING)\n\t\t    {\n\t\t\t// raaron: This code makes a composing character get\n\t\t\t// ignored, which is the correct behavior (sometimes)\n\t\t\t// for voweled Hebrew texts.\n\t\t\tstatus = RA_NOMATCH;\n\t\t    }\n\t\t    if (status != RA_NOMATCH)\n\t\t\trex.input += len;\n\t\t}\n\t    }\n\t    break;\n\n\t  case ANYOF:\n\t  case ANYBUT:\n\t    if (c == NUL)\n\t\tstatus = RA_NOMATCH;\n\t    else if ((cstrchr(OPERAND(scan), c) == NULL) == (op == ANYOF))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case MULTIBYTECODE:\n\t    if (has_mbyte)\n\t    {\n\t\tint\ti, len;\n\t\tchar_u\t*opnd;\n\t\tint\topndc = 0, inpc;\n\n\t\topnd = OPERAND(scan);\n\t\t// Safety check (just in case 'encoding' was changed since\n\t\t// compiling the program).\n\t\tif ((len = (*mb_ptr2len)(opnd)) < 2)\n\t\t{\n\t\t    status = RA_NOMATCH;\n\t\t    break;\n\t\t}\n\t\tif (enc_utf8)\n\t\t    opndc = utf_ptr2char(opnd);\n\t\tif (enc_utf8 && utf_iscomposing(opndc))\n\t\t{\n\t\t    // When only a composing char is given match at any\n\t\t    // position where that composing char appears.\n\t\t    status = RA_NOMATCH;\n\t\t    for (i = 0; rex.input[i] != NUL;\n\t\t\t\t\t\ti += utf_ptr2len(rex.input + i))\n\t\t    {\n\t\t\tinpc = utf_ptr2char(rex.input + i);\n\t\t\tif (!utf_iscomposing(inpc))\n\t\t\t{\n\t\t\t    if (i > 0)\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (opndc == inpc)\n\t\t\t{\n\t\t\t    // Include all following composing chars.\n\t\t\t    len = i + utfc_ptr2len(rex.input + i);\n\t\t\t    status = RA_MATCH;\n\t\t\t    break;\n\t\t\t}\n\t\t    }\n\t\t}\n\t\telse\n\t\t    for (i = 0; i < len; ++i)\n\t\t\tif (opnd[i] != rex.input[i])\n\t\t\t{\n\t\t\t    status = RA_NOMATCH;\n\t\t\t    break;\n\t\t\t}\n\t\trex.input += len;\n\t    }\n\t    else\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\t  case RE_COMPOSING:\n\t    if (enc_utf8)\n\t    {\n\t\t// Skip composing characters.\n\t\twhile (utf_iscomposing(utf_ptr2char(rex.input)))\n\t\t    MB_CPTR_ADV(rex.input);\n\t    }\n\t    break;\n\n\t  case NOTHING:\n\t    break;\n\n\t  case BACK:\n\t    {\n\t\tint\t\ti;\n\t\tbackpos_T\t*bp;\n\n\t\t// When we run into BACK we need to check if we don't keep\n\t\t// looping without matching any input.  The second and later\n\t\t// times a BACK is encountered it fails if the input is still\n\t\t// at the same position as the previous time.\n\t\t// The positions are stored in \"backpos\" and found by the\n\t\t// current value of \"scan\", the position in the RE program.\n\t\tbp = (backpos_T *)backpos.ga_data;\n\t\tfor (i = 0; i < backpos.ga_len; ++i)\n\t\t    if (bp[i].bp_scan == scan)\n\t\t\tbreak;\n\t\tif (i == backpos.ga_len)\n\t\t{\n\t\t    // First time at this BACK, make room to store the pos.\n\t\t    if (ga_grow(&backpos, 1) == FAIL)\n\t\t\tstatus = RA_FAIL;\n\t\t    else\n\t\t    {\n\t\t\t// get \"ga_data\" again, it may have changed\n\t\t\tbp = (backpos_T *)backpos.ga_data;\n\t\t\tbp[i].bp_scan = scan;\n\t\t\t++backpos.ga_len;\n\t\t    }\n\t\t}\n\t\telse if (reg_save_equal(&bp[i].bp_pos))\n\t\t    // Still at same position as last time, fail.\n\t\t    status = RA_NOMATCH;\n\n\t\tif (status != RA_FAIL && status != RA_NOMATCH)\n\t\t    reg_save(&bp[i].bp_pos, &backpos);\n\t    }\n\t    break;\n\n\t  case MOPEN + 0:   // Match start: \\zs\n\t  case MOPEN + 1:   // \\(\n\t  case MOPEN + 2:\n\t  case MOPEN + 3:\n\t  case MOPEN + 4:\n\t  case MOPEN + 5:\n\t  case MOPEN + 6:\n\t  case MOPEN + 7:\n\t  case MOPEN + 8:\n\t  case MOPEN + 9:\n\t    {\n\t\tno = op - MOPEN;\n\t\tcleanup_subexpr();\n\t\trp = regstack_push(RS_MOPEN, scan);\n\t\tif (rp == NULL)\n\t\t    status = RA_FAIL;\n\t\telse\n\t\t{\n\t\t    rp->rs_no = no;\n\t\t    save_se(&rp->rs_un.sesave, &rex.reg_startpos[no],\n\t\t\t\t\t\t\t  &rex.reg_startp[no]);\n\t\t    // We simply continue and handle the result when done.\n\t\t}\n\t    }\n\t    break;\n\n\t  case NOPEN:\t    // \\%(\n\t  case NCLOSE:\t    // \\) after \\%(\n\t\tif (regstack_push(RS_NOPEN, scan) == NULL)\n\t\t    status = RA_FAIL;\n\t\t// We simply continue and handle the result when done.\n\t\tbreak;\n\n#ifdef FEAT_SYN_HL\n\t  case ZOPEN + 1:\n\t  case ZOPEN + 2:\n\t  case ZOPEN + 3:\n\t  case ZOPEN + 4:\n\t  case ZOPEN + 5:\n\t  case ZOPEN + 6:\n\t  case ZOPEN + 7:\n\t  case ZOPEN + 8:\n\t  case ZOPEN + 9:\n\t    {\n\t\tno = op - ZOPEN;\n\t\tcleanup_zsubexpr();\n\t\trp = regstack_push(RS_ZOPEN, scan);\n\t\tif (rp == NULL)\n\t\t    status = RA_FAIL;\n\t\telse\n\t\t{\n\t\t    rp->rs_no = no;\n\t\t    save_se(&rp->rs_un.sesave, ®_startzpos[no],\n\t\t\t\t\t\t\t     ®_startzp[no]);\n\t\t    // We simply continue and handle the result when done.\n\t\t}\n\t    }\n\t    break;\n#endif\n\n\t  case MCLOSE + 0:  // Match end: \\ze\n\t  case MCLOSE + 1:  // \\)\n\t  case MCLOSE + 2:\n\t  case MCLOSE + 3:\n\t  case MCLOSE + 4:\n\t  case MCLOSE + 5:\n\t  case MCLOSE + 6:\n\t  case MCLOSE + 7:\n\t  case MCLOSE + 8:\n\t  case MCLOSE + 9:\n\t    {\n\t\tno = op - MCLOSE;\n\t\tcleanup_subexpr();\n\t\trp = regstack_push(RS_MCLOSE, scan);\n\t\tif (rp == NULL)\n\t\t    status = RA_FAIL;\n\t\telse\n\t\t{\n\t\t    rp->rs_no = no;\n\t\t    save_se(&rp->rs_un.sesave, &rex.reg_endpos[no],\n\t\t\t\t\t\t\t    &rex.reg_endp[no]);\n\t\t    // We simply continue and handle the result when done.\n\t\t}\n\t    }\n\t    break;\n\n#ifdef FEAT_SYN_HL\n\t  case ZCLOSE + 1:  // \\) after \\z(\n\t  case ZCLOSE + 2:\n\t  case ZCLOSE + 3:\n\t  case ZCLOSE + 4:\n\t  case ZCLOSE + 5:\n\t  case ZCLOSE + 6:\n\t  case ZCLOSE + 7:\n\t  case ZCLOSE + 8:\n\t  case ZCLOSE + 9:\n\t    {\n\t\tno = op - ZCLOSE;\n\t\tcleanup_zsubexpr();\n\t\trp = regstack_push(RS_ZCLOSE, scan);\n\t\tif (rp == NULL)\n\t\t    status = RA_FAIL;\n\t\telse\n\t\t{\n\t\t    rp->rs_no = no;\n\t\t    save_se(&rp->rs_un.sesave, ®_endzpos[no],\n\t\t\t\t\t\t\t      ®_endzp[no]);\n\t\t    // We simply continue and handle the result when done.\n\t\t}\n\t    }\n\t    break;\n#endif\n\n\t  case BACKREF + 1:\n\t  case BACKREF + 2:\n\t  case BACKREF + 3:\n\t  case BACKREF + 4:\n\t  case BACKREF + 5:\n\t  case BACKREF + 6:\n\t  case BACKREF + 7:\n\t  case BACKREF + 8:\n\t  case BACKREF + 9:\n\t    {\n\t\tint\t\tlen;\n\n\t\tno = op - BACKREF;\n\t\tcleanup_subexpr();\n\t\tif (!REG_MULTI)\t\t// Single-line regexp\n\t\t{\n\t\t    if (rex.reg_startp[no] == NULL || rex.reg_endp[no] == NULL)\n\t\t    {\n\t\t\t// Backref was not set: Match an empty string.\n\t\t\tlen = 0;\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\t// Compare current input with back-ref in the same\n\t\t\t// line.\n\t\t\tlen = (int)(rex.reg_endp[no] - rex.reg_startp[no]);\n\t\t\tif (cstrncmp(rex.reg_startp[no], rex.input, &len) != 0)\n\t\t\t    status = RA_NOMATCH;\n\t\t    }\n\t\t}\n\t\telse\t\t\t\t// Multi-line regexp\n\t\t{\n\t\t    if (rex.reg_startpos[no].lnum < 0\n\t\t\t\t\t\t|| rex.reg_endpos[no].lnum < 0)\n\t\t    {\n\t\t\t// Backref was not set: Match an empty string.\n\t\t\tlen = 0;\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\tif (rex.reg_startpos[no].lnum == rex.lnum\n\t\t\t\t&& rex.reg_endpos[no].lnum == rex.lnum)\n\t\t\t{\n\t\t\t    // Compare back-ref within the current line.\n\t\t\t    len = rex.reg_endpos[no].col\n\t\t\t\t\t\t    - rex.reg_startpos[no].col;\n\t\t\t    if (cstrncmp(rex.line + rex.reg_startpos[no].col,\n\t\t\t\t\t\t\t  rex.input, &len) != 0)\n\t\t\t\tstatus = RA_NOMATCH;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t    // Messy situation: Need to compare between two\n\t\t\t    // lines.\n\t\t\t    int r = match_with_backref(\n\t\t\t\t\t    rex.reg_startpos[no].lnum,\n\t\t\t\t\t    rex.reg_startpos[no].col,\n\t\t\t\t\t    rex.reg_endpos[no].lnum,\n\t\t\t\t\t    rex.reg_endpos[no].col,\n\t\t\t\t\t    &len);\n\n\t\t\t    if (r != RA_MATCH)\n\t\t\t\tstatus = r;\n\t\t\t}\n\t\t    }\n\t\t}\n\n\t\t// Matched the backref, skip over it.\n\t\trex.input += len;\n\t    }\n\t    break;\n\n#ifdef FEAT_SYN_HL\n\t  case ZREF + 1:\n\t  case ZREF + 2:\n\t  case ZREF + 3:\n\t  case ZREF + 4:\n\t  case ZREF + 5:\n\t  case ZREF + 6:\n\t  case ZREF + 7:\n\t  case ZREF + 8:\n\t  case ZREF + 9:\n\t    {\n\t\tint\tlen;\n\n\t\tcleanup_zsubexpr();\n\t\tno = op - ZREF;\n\t\tif (re_extmatch_in != NULL\n\t\t\t&& re_extmatch_in->matches[no] != NULL)\n\t\t{\n\t\t    len = (int)STRLEN(re_extmatch_in->matches[no]);\n\t\t    if (cstrncmp(re_extmatch_in->matches[no],\n\t\t\t\t\t\t\t  rex.input, &len) != 0)\n\t\t\tstatus = RA_NOMATCH;\n\t\t    else\n\t\t\trex.input += len;\n\t\t}\n\t\telse\n\t\t{\n\t\t    // Backref was not set: Match an empty string.\n\t\t}\n\t    }\n\t    break;\n#endif\n\n\t  case BRANCH:\n\t    {\n\t\tif (OP(next) != BRANCH) // No choice.\n\t\t    next = OPERAND(scan);\t// Avoid recursion.\n\t\telse\n\t\t{\n\t\t    rp = regstack_push(RS_BRANCH, scan);\n\t\t    if (rp == NULL)\n\t\t\tstatus = RA_FAIL;\n\t\t    else\n\t\t\tstatus = RA_BREAK;\t// rest is below\n\t\t}\n\t    }\n\t    break;\n\n\t  case BRACE_LIMITS:\n\t    {\n\t\tif (OP(next) == BRACE_SIMPLE)\n\t\t{\n\t\t    bl_minval = OPERAND_MIN(scan);\n\t\t    bl_maxval = OPERAND_MAX(scan);\n\t\t}\n\t\telse if (OP(next) >= BRACE_COMPLEX\n\t\t\t&& OP(next) < BRACE_COMPLEX + 10)\n\t\t{\n\t\t    no = OP(next) - BRACE_COMPLEX;\n\t\t    brace_min[no] = OPERAND_MIN(scan);\n\t\t    brace_max[no] = OPERAND_MAX(scan);\n\t\t    brace_count[no] = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t    internal_error(\"BRACE_LIMITS\");\n\t\t    status = RA_FAIL;\n\t\t}\n\t    }\n\t    break;\n\n\t  case BRACE_COMPLEX + 0:\n\t  case BRACE_COMPLEX + 1:\n\t  case BRACE_COMPLEX + 2:\n\t  case BRACE_COMPLEX + 3:\n\t  case BRACE_COMPLEX + 4:\n\t  case BRACE_COMPLEX + 5:\n\t  case BRACE_COMPLEX + 6:\n\t  case BRACE_COMPLEX + 7:\n\t  case BRACE_COMPLEX + 8:\n\t  case BRACE_COMPLEX + 9:\n\t    {\n\t\tno = op - BRACE_COMPLEX;\n\t\t++brace_count[no];\n\n\t\t// If not matched enough times yet, try one more\n\t\tif (brace_count[no] <= (brace_min[no] <= brace_max[no]\n\t\t\t\t\t     ? brace_min[no] : brace_max[no]))\n\t\t{\n\t\t    rp = regstack_push(RS_BRCPLX_MORE, scan);\n\t\t    if (rp == NULL)\n\t\t\tstatus = RA_FAIL;\n\t\t    else\n\t\t    {\n\t\t\trp->rs_no = no;\n\t\t\treg_save(&rp->rs_un.regsave, &backpos);\n\t\t\tnext = OPERAND(scan);\n\t\t\t// We continue and handle the result when done.\n\t\t    }\n\t\t    break;\n\t\t}\n\n\t\t// If matched enough times, may try matching some more\n\t\tif (brace_min[no] <= brace_max[no])\n\t\t{\n\t\t    // Range is the normal way around, use longest match\n\t\t    if (brace_count[no] <= brace_max[no])\n\t\t    {\n\t\t\trp = regstack_push(RS_BRCPLX_LONG, scan);\n\t\t\tif (rp == NULL)\n\t\t\t    status = RA_FAIL;\n\t\t\telse\n\t\t\t{\n\t\t\t    rp->rs_no = no;\n\t\t\t    reg_save(&rp->rs_un.regsave, &backpos);\n\t\t\t    next = OPERAND(scan);\n\t\t\t    // We continue and handle the result when done.\n\t\t\t}\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    // Range is backwards, use shortest match first\n\t\t    if (brace_count[no] <= brace_min[no])\n\t\t    {\n\t\t\trp = regstack_push(RS_BRCPLX_SHORT, scan);\n\t\t\tif (rp == NULL)\n\t\t\t    status = RA_FAIL;\n\t\t\telse\n\t\t\t{\n\t\t\t    reg_save(&rp->rs_un.regsave, &backpos);\n\t\t\t    // We continue and handle the result when done.\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\t    break;\n\n\t  case BRACE_SIMPLE:\n\t  case STAR:\n\t  case PLUS:\n\t    {\n\t\tregstar_T\trst;\n\n\t\t// Lookahead to avoid useless match attempts when we know\n\t\t// what character comes next.\n\t\tif (OP(next) == EXACTLY)\n\t\t{\n\t\t    rst.nextb = *OPERAND(next);\n\t\t    if (rex.reg_ic)\n\t\t    {\n\t\t\tif (MB_ISUPPER(rst.nextb))\n\t\t\t    rst.nextb_ic = MB_TOLOWER(rst.nextb);\n\t\t\telse\n\t\t\t    rst.nextb_ic = MB_TOUPPER(rst.nextb);\n\t\t    }\n\t\t    else\n\t\t\trst.nextb_ic = rst.nextb;\n\t\t}\n\t\telse\n\t\t{\n\t\t    rst.nextb = NUL;\n\t\t    rst.nextb_ic = NUL;\n\t\t}\n\t\tif (op != BRACE_SIMPLE)\n\t\t{\n\t\t    rst.minval = (op == STAR) ? 0 : 1;\n\t\t    rst.maxval = MAX_LIMIT;\n\t\t}\n\t\telse\n\t\t{\n\t\t    rst.minval = bl_minval;\n\t\t    rst.maxval = bl_maxval;\n\t\t}\n\n\t\t// When maxval > minval, try matching as much as possible, up\n\t\t// to maxval.  When maxval < minval, try matching at least the\n\t\t// minimal number (since the range is backwards, that's also\n\t\t// maxval!).\n\t\trst.count = regrepeat(OPERAND(scan), rst.maxval);\n\t\tif (got_int)\n\t\t{\n\t\t    status = RA_FAIL;\n\t\t    break;\n\t\t}\n\t\tif (rst.minval <= rst.maxval\n\t\t\t  ? rst.count >= rst.minval : rst.count >= rst.maxval)\n\t\t{\n\t\t    // It could match.  Prepare for trying to match what\n\t\t    // follows.  The code is below.  Parameters are stored in\n\t\t    // a regstar_T on the regstack.\n\t\t    if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)\n\t\t    {\n\t\t\temsg(_(e_pattern_uses_more_memory_than_maxmempattern));\n\t\t\tstatus = RA_FAIL;\n\t\t    }\n\t\t    else if (ga_grow(®stack, sizeof(regstar_T)) == FAIL)\n\t\t\tstatus = RA_FAIL;\n\t\t    else\n\t\t    {\n\t\t\tregstack.ga_len += sizeof(regstar_T);\n\t\t\trp = regstack_push(rst.minval <= rst.maxval\n\t\t\t\t\t? RS_STAR_LONG : RS_STAR_SHORT, scan);\n\t\t\tif (rp == NULL)\n\t\t\t    status = RA_FAIL;\n\t\t\telse\n\t\t\t{\n\t\t\t    *(((regstar_T *)rp) - 1) = rst;\n\t\t\t    status = RA_BREAK;\t    // skip the restore bits\n\t\t\t}\n\t\t    }\n\t\t}\n\t\telse\n\t\t    status = RA_NOMATCH;\n\n\t    }\n\t    break;\n\n\t  case NOMATCH:\n\t  case MATCH:\n\t  case SUBPAT:\n\t    rp = regstack_push(RS_NOMATCH, scan);\n\t    if (rp == NULL)\n\t\tstatus = RA_FAIL;\n\t    else\n\t    {\n\t\trp->rs_no = op;\n\t\treg_save(&rp->rs_un.regsave, &backpos);\n\t\tnext = OPERAND(scan);\n\t\t// We continue and handle the result when done.\n\t    }\n\t    break;\n\n\t  case BEHIND:\n\t  case NOBEHIND:\n\t    // Need a bit of room to store extra positions.\n\t    if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)\n\t    {\n\t\temsg(_(e_pattern_uses_more_memory_than_maxmempattern));\n\t\tstatus = RA_FAIL;\n\t    }\n\t    else if (ga_grow(®stack, sizeof(regbehind_T)) == FAIL)\n\t\tstatus = RA_FAIL;\n\t    else\n\t    {\n\t\tregstack.ga_len += sizeof(regbehind_T);\n\t\trp = regstack_push(RS_BEHIND1, scan);\n\t\tif (rp == NULL)\n\t\t    status = RA_FAIL;\n\t\telse\n\t\t{\n\t\t    // Need to save the subexpr to be able to restore them\n\t\t    // when there is a match but we don't use it.\n\t\t    save_subexpr(((regbehind_T *)rp) - 1);\n\n\t\t    rp->rs_no = op;\n\t\t    reg_save(&rp->rs_un.regsave, &backpos);\n\t\t    // First try if what follows matches.  If it does then we\n\t\t    // check the behind match by looping.\n\t\t}\n\t    }\n\t    break;\n\n\t  case BHPOS:\n\t    if (REG_MULTI)\n\t    {\n\t\tif (behind_pos.rs_u.pos.col != (colnr_T)(rex.input - rex.line)\n\t\t\t|| behind_pos.rs_u.pos.lnum != rex.lnum)\n\t\t    status = RA_NOMATCH;\n\t    }\n\t    else if (behind_pos.rs_u.ptr != rex.input)\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case NEWL:\n\t    if ((c != NUL || !REG_MULTI || rex.lnum > rex.reg_maxline\n\t\t\t     || rex.reg_line_lbr)\n\t\t\t\t\t   && (c != '\\n' || !rex.reg_line_lbr))\n\t\tstatus = RA_NOMATCH;\n\t    else if (rex.reg_line_lbr)\n\t\tADVANCE_REGINPUT();\n\t    else\n\t\treg_nextline();\n\t    break;\n\n\t  case END:\n\t    status = RA_MATCH;\t// Success!\n\t    break;\n\n\t  default:\n\t    iemsg(_(e_corrupted_regexp_program));\n#ifdef DEBUG\n\t    printf(\"Illegal op code %d\\n\", op);\n#endif\n\t    status = RA_FAIL;\n\t    break;\n\t  }\n\t}\n\n\t// If we can't continue sequentially, break the inner loop.\n\tif (status != RA_CONT)\n\t    break;\n\n\t// Continue in inner loop, advance to next item.\n\tscan = next;\n\n    } // end of inner loop\n\n    // If there is something on the regstack execute the code for the state.\n    // If the state is popped then loop and use the older state.\n    while (regstack.ga_len > 0 && status != RA_FAIL)\n    {\n\trp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;\n\tswitch (rp->rs_state)\n\t{\n\t  case RS_NOPEN:\n\t    // Result is passed on as-is, simply pop the state.\n\t    regstack_pop(&scan);\n\t    break;\n\n\t  case RS_MOPEN:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t\trestore_se(&rp->rs_un.sesave, &rex.reg_startpos[rp->rs_no],\n\t\t\t\t\t\t  &rex.reg_startp[rp->rs_no]);\n\t    regstack_pop(&scan);\n\t    break;\n\n#ifdef FEAT_SYN_HL\n\t  case RS_ZOPEN:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t\trestore_se(&rp->rs_un.sesave, ®_startzpos[rp->rs_no],\n\t\t\t\t\t\t ®_startzp[rp->rs_no]);\n\t    regstack_pop(&scan);\n\t    break;\n#endif\n\n\t  case RS_MCLOSE:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t\trestore_se(&rp->rs_un.sesave, &rex.reg_endpos[rp->rs_no],\n\t\t\t\t\t\t    &rex.reg_endp[rp->rs_no]);\n\t    regstack_pop(&scan);\n\t    break;\n\n#ifdef FEAT_SYN_HL\n\t  case RS_ZCLOSE:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t\trestore_se(&rp->rs_un.sesave, ®_endzpos[rp->rs_no],\n\t\t\t\t\t\t   ®_endzp[rp->rs_no]);\n\t    regstack_pop(&scan);\n\t    break;\n#endif\n\n\t  case RS_BRANCH:\n\t    if (status == RA_MATCH)\n\t\t// this branch matched, use it\n\t\tregstack_pop(&scan);\n\t    else\n\t    {\n\t\tif (status != RA_BREAK)\n\t\t{\n\t\t    // After a non-matching branch: try next one.\n\t\t    reg_restore(&rp->rs_un.regsave, &backpos);\n\t\t    scan = rp->rs_scan;\n\t\t}\n\t\tif (scan == NULL || OP(scan) != BRANCH)\n\t\t{\n\t\t    // no more branches, didn't find a match\n\t\t    status = RA_NOMATCH;\n\t\t    regstack_pop(&scan);\n\t\t}\n\t\telse\n\t\t{\n\t\t    // Prepare to try a branch.\n\t\t    rp->rs_scan = regnext(scan);\n\t\t    reg_save(&rp->rs_un.regsave, &backpos);\n\t\t    scan = OPERAND(scan);\n\t\t}\n\t    }\n\t    break;\n\n\t  case RS_BRCPLX_MORE:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t    {\n\t\treg_restore(&rp->rs_un.regsave, &backpos);\n\t\t--brace_count[rp->rs_no];\t// decrement match count\n\t    }\n\t    regstack_pop(&scan);\n\t    break;\n\n\t  case RS_BRCPLX_LONG:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t    {\n\t\t// There was no match, but we did find enough matches.\n\t\treg_restore(&rp->rs_un.regsave, &backpos);\n\t\t--brace_count[rp->rs_no];\n\t\t// continue with the items after \"\\{}\"\n\t\tstatus = RA_CONT;\n\t    }\n\t    regstack_pop(&scan);\n\t    if (status == RA_CONT)\n\t\tscan = regnext(scan);\n\t    break;\n\n\t  case RS_BRCPLX_SHORT:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t\t// There was no match, try to match one more item.\n\t\treg_restore(&rp->rs_un.regsave, &backpos);\n\t    regstack_pop(&scan);\n\t    if (status == RA_NOMATCH)\n\t    {\n\t\tscan = OPERAND(scan);\n\t\tstatus = RA_CONT;\n\t    }\n\t    break;\n\n\t  case RS_NOMATCH:\n\t    // Pop the state.  If the operand matches for NOMATCH or\n\t    // doesn't match for MATCH/SUBPAT, we fail.  Otherwise backup,\n\t    // except for SUBPAT, and continue with the next item.\n\t    if (status == (rp->rs_no == NOMATCH ? RA_MATCH : RA_NOMATCH))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t    {\n\t\tstatus = RA_CONT;\n\t\tif (rp->rs_no != SUBPAT)\t// zero-width\n\t\t    reg_restore(&rp->rs_un.regsave, &backpos);\n\t    }\n\t    regstack_pop(&scan);\n\t    if (status == RA_CONT)\n\t\tscan = regnext(scan);\n\t    break;\n\n\t  case RS_BEHIND1:\n\t    if (status == RA_NOMATCH)\n\t    {\n\t\tregstack_pop(&scan);\n\t\tregstack.ga_len -= sizeof(regbehind_T);\n\t    }\n\t    else\n\t    {\n\t\t// The stuff after BEHIND/NOBEHIND matches.  Now try if\n\t\t// the behind part does (not) match before the current\n\t\t// position in the input.  This must be done at every\n\t\t// position in the input and checking if the match ends at\n\t\t// the current position.\n\n\t\t// save the position after the found match for next\n\t\treg_save(&(((regbehind_T *)rp) - 1)->save_after, &backpos);\n\n\t\t// Start looking for a match with operand at the current\n\t\t// position.  Go back one character until we find the\n\t\t// result, hitting the start of the line or the previous\n\t\t// line (for multi-line matching).\n\t\t// Set behind_pos to where the match should end, BHPOS\n\t\t// will match it.  Save the current value.\n\t\t(((regbehind_T *)rp) - 1)->save_behind = behind_pos;\n\t\tbehind_pos = rp->rs_un.regsave;\n\n\t\trp->rs_state = RS_BEHIND2;\n\n\t\treg_restore(&rp->rs_un.regsave, &backpos);\n\t\tscan = OPERAND(rp->rs_scan) + 4;\n\t    }\n\t    break;\n\n\t  case RS_BEHIND2:\n\t    // Looping for BEHIND / NOBEHIND match.\n\t    if (status == RA_MATCH && reg_save_equal(&behind_pos))\n\t    {\n\t\t// found a match that ends where \"next\" started\n\t\tbehind_pos = (((regbehind_T *)rp) - 1)->save_behind;\n\t\tif (rp->rs_no == BEHIND)\n\t\t    reg_restore(&(((regbehind_T *)rp) - 1)->save_after,\n\t\t\t\t\t\t\t\t    &backpos);\n\t\telse\n\t\t{\n\t\t    // But we didn't want a match.  Need to restore the\n\t\t    // subexpr, because what follows matched, so they have\n\t\t    // been set.\n\t\t    status = RA_NOMATCH;\n\t\t    restore_subexpr(((regbehind_T *)rp) - 1);\n\t\t}\n\t\tregstack_pop(&scan);\n\t\tregstack.ga_len -= sizeof(regbehind_T);\n\t    }\n\t    else\n\t    {\n\t\tlong limit;\n\n\t\t// No match or a match that doesn't end where we want it: Go\n\t\t// back one character.  May go to previous line once.\n\t\tno = OK;\n\t\tlimit = OPERAND_MIN(rp->rs_scan);\n\t\tif (REG_MULTI)\n\t\t{\n\t\t    if (limit > 0\n\t\t\t    && ((rp->rs_un.regsave.rs_u.pos.lnum\n\t\t\t\t\t\t    < behind_pos.rs_u.pos.lnum\n\t\t\t\t    ? (colnr_T)STRLEN(rex.line)\n\t\t\t\t    : behind_pos.rs_u.pos.col)\n\t\t\t\t- rp->rs_un.regsave.rs_u.pos.col >= limit))\n\t\t\tno = FAIL;\n\t\t    else if (rp->rs_un.regsave.rs_u.pos.col == 0)\n\t\t    {\n\t\t\tif (rp->rs_un.regsave.rs_u.pos.lnum\n\t\t\t\t\t< behind_pos.rs_u.pos.lnum\n\t\t\t\t|| reg_getline(\n\t\t\t\t\t--rp->rs_un.regsave.rs_u.pos.lnum)\n\t\t\t\t\t\t\t\t  == NULL)\n\t\t\t    no = FAIL;\n\t\t\telse\n\t\t\t{\n\t\t\t    reg_restore(&rp->rs_un.regsave, &backpos);\n\t\t\t    rp->rs_un.regsave.rs_u.pos.col =\n\t\t\t\t\t\t (colnr_T)STRLEN(rex.line);\n\t\t\t}\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\tif (has_mbyte)\n\t\t\t{\n\t\t\t    char_u *line =\n\t\t\t\t  reg_getline(rp->rs_un.regsave.rs_u.pos.lnum);\n\n\t\t\t    rp->rs_un.regsave.rs_u.pos.col -=\n\t\t\t\t(*mb_head_off)(line, line\n\t\t\t\t    + rp->rs_un.regsave.rs_u.pos.col - 1) + 1;\n\t\t\t}\n\t\t\telse\n\t\t\t    --rp->rs_un.regsave.rs_u.pos.col;\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    if (rp->rs_un.regsave.rs_u.ptr == rex.line)\n\t\t\tno = FAIL;\n\t\t    else\n\t\t    {\n\t\t\tMB_PTR_BACK(rex.line, rp->rs_un.regsave.rs_u.ptr);\n\t\t\tif (limit > 0 && (long)(behind_pos.rs_u.ptr\n\t\t\t\t     - rp->rs_un.regsave.rs_u.ptr) > limit)\n\t\t\t    no = FAIL;\n\t\t    }\n\t\t}\n\t\tif (no == OK)\n\t\t{\n\t\t    // Advanced, prepare for finding match again.\n\t\t    reg_restore(&rp->rs_un.regsave, &backpos);\n\t\t    scan = OPERAND(rp->rs_scan) + 4;\n\t\t    if (status == RA_MATCH)\n\t\t    {\n\t\t\t// We did match, so subexpr may have been changed,\n\t\t\t// need to restore them for the next try.\n\t\t\tstatus = RA_NOMATCH;\n\t\t\trestore_subexpr(((regbehind_T *)rp) - 1);\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    // Can't advance.  For NOBEHIND that's a match.\n\t\t    behind_pos = (((regbehind_T *)rp) - 1)->save_behind;\n\t\t    if (rp->rs_no == NOBEHIND)\n\t\t    {\n\t\t\treg_restore(&(((regbehind_T *)rp) - 1)->save_after,\n\t\t\t\t\t\t\t\t    &backpos);\n\t\t\tstatus = RA_MATCH;\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\t// We do want a proper match.  Need to restore the\n\t\t\t// subexpr if we had a match, because they may have\n\t\t\t// been set.\n\t\t\tif (status == RA_MATCH)\n\t\t\t{\n\t\t\t    status = RA_NOMATCH;\n\t\t\t    restore_subexpr(((regbehind_T *)rp) - 1);\n\t\t\t}\n\t\t    }\n\t\t    regstack_pop(&scan);\n\t\t    regstack.ga_len -= sizeof(regbehind_T);\n\t\t}\n\t    }\n\t    break;\n\n\t  case RS_STAR_LONG:\n\t  case RS_STAR_SHORT:\n\t    {\n\t\tregstar_T\t    *rst = ((regstar_T *)rp) - 1;\n\n\t\tif (status == RA_MATCH)\n\t\t{\n\t\t    regstack_pop(&scan);\n\t\t    regstack.ga_len -= sizeof(regstar_T);\n\t\t    break;\n\t\t}\n\n\t\t// Tried once already, restore input pointers.\n\t\tif (status != RA_BREAK)\n\t\t    reg_restore(&rp->rs_un.regsave, &backpos);\n\n\t\t// Repeat until we found a position where it could match.\n\t\tfor (;;)\n\t\t{\n\t\t    if (status != RA_BREAK)\n\t\t    {\n\t\t\t// Tried first position already, advance.\n\t\t\tif (rp->rs_state == RS_STAR_LONG)\n\t\t\t{\n\t\t\t    // Trying for longest match, but couldn't or\n\t\t\t    // didn't match -- back up one char.\n\t\t\t    if (--rst->count < rst->minval)\n\t\t\t\tbreak;\n\t\t\t    if (rex.input == rex.line)\n\t\t\t    {\n\t\t\t\t// backup to last char of previous line\n\t\t\t\tif (rex.lnum == 0)\n\t\t\t\t{\n\t\t\t\t    status = RA_NOMATCH;\n\t\t\t\t    break;\n\t\t\t\t}\n\t\t\t\t--rex.lnum;\n\t\t\t\trex.line = reg_getline(rex.lnum);\n\t\t\t\t// Just in case regrepeat() didn't count\n\t\t\t\t// right.\n\t\t\t\tif (rex.line == NULL)\n\t\t\t\t    break;\n\t\t\t\trex.input = rex.line + STRLEN(rex.line);\n\t\t\t\tfast_breakcheck();\n\t\t\t    }\n\t\t\t    else\n\t\t\t\tMB_PTR_BACK(rex.line, rex.input);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t    // Range is backwards, use shortest match first.\n\t\t\t    // Careful: maxval and minval are exchanged!\n\t\t\t    // Couldn't or didn't match: try advancing one\n\t\t\t    // char.\n\t\t\t    if (rst->count == rst->minval\n\t\t\t\t  || regrepeat(OPERAND(rp->rs_scan), 1L) == 0)\n\t\t\t\tbreak;\n\t\t\t    ++rst->count;\n\t\t\t}\n\t\t\tif (got_int)\n\t\t\t    break;\n\t\t    }\n\t\t    else\n\t\t\tstatus = RA_NOMATCH;\n\n\t\t    // If it could match, try it.\n\t\t    if (rst->nextb == NUL || *rex.input == rst->nextb\n\t\t\t\t\t     || *rex.input == rst->nextb_ic)\n\t\t    {\n\t\t\treg_save(&rp->rs_un.regsave, &backpos);\n\t\t\tscan = regnext(rp->rs_scan);\n\t\t\tstatus = RA_CONT;\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t\tif (status != RA_CONT)\n\t\t{\n\t\t    // Failed.\n\t\t    regstack_pop(&scan);\n\t\t    regstack.ga_len -= sizeof(regstar_T);\n\t\t    status = RA_NOMATCH;\n\t\t}\n\t    }\n\t    break;\n\t}\n\n\t// If we want to continue the inner loop or didn't pop a state\n\t// continue matching loop\n\tif (status == RA_CONT || rp == (regitem_T *)\n\t\t\t     ((char *)regstack.ga_data + regstack.ga_len) - 1)\n\t    break;\n    }\n\n    // May need to continue with the inner loop, starting at \"scan\".\n    if (status == RA_CONT)\n\tcontinue;\n\n    // If the regstack is empty or something failed we are done.\n    if (regstack.ga_len == 0 || status == RA_FAIL)\n    {\n\tif (scan == NULL)\n\t{\n\t    // We get here only if there's trouble -- normally \"case END\" is\n\t    // the terminating point.\n\t    iemsg(_(e_corrupted_regexp_program));\n#ifdef DEBUG\n\t    printf(\"Premature EOL\\n\");\n#endif\n\t}\n\treturn (status == RA_MATCH);\n    }\n\n  } // End of loop until the regstack is empty.\n\n  // NOTREACHED\n}", "func_hash": 155703094073588454659918901719534941663, "file_name": "regexp_bt.c", "file_hash": 104418656195819662091775816956319387020, "cwe": ["CWE-416"], "cve": "CVE-2022-1154", "cve_desc": "Use after free in utf_ptr2char in GitHub repository vim/vim prior to 8.2.4646.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1154"}
{"idx": 326119, "project": "vim", "commit_id": "b55986c52d4cd88a22d0b0b0e8a79547ba13e1d5", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/b55986c52d4cd88a22d0b0b0e8a79547ba13e1d5", "commit_message": "patch 8.2.4646: using buffer line after it has been freed\n\nProblem:    Using buffer line after it has been freed in old regexp engine.\nSolution:   After getting mark get the line again.", "target": 0, "func": "regmatch(\n    char_u\t*scan,\t\t    // Current node.\n    proftime_T\t*tm UNUSED,\t    // timeout limit or NULL\n    int\t\t*timed_out UNUSED)  // flag set on timeout or NULL\n{\n  char_u\t*next;\t\t// Next node.\n  int\t\top;\n  int\t\tc;\n  regitem_T\t*rp;\n  int\t\tno;\n  int\t\tstatus;\t\t// one of the RA_ values:\n#ifdef FEAT_RELTIME\n  int\t\ttm_count = 0;\n#endif\n\n  // Make \"regstack\" and \"backpos\" empty.  They are allocated and freed in\n  // bt_regexec_both() to reduce malloc()/free() calls.\n  regstack.ga_len = 0;\n  backpos.ga_len = 0;\n\n  // Repeat until \"regstack\" is empty.\n  for (;;)\n  {\n    // Some patterns may take a long time to match, e.g., \"\\([a-z]\\+\\)\\+Q\".\n    // Allow interrupting them with CTRL-C.\n    fast_breakcheck();\n\n#ifdef DEBUG\n    if (scan != NULL && regnarrate)\n    {\n\tmch_errmsg((char *)regprop(scan));\n\tmch_errmsg(\"(\\n\");\n    }\n#endif\n\n    // Repeat for items that can be matched sequentially, without using the\n    // regstack.\n    for (;;)\n    {\n\tif (got_int || scan == NULL)\n\t{\n\t    status = RA_FAIL;\n\t    break;\n\t}\n#ifdef FEAT_RELTIME\n\t// Check for timeout once in a 100 times to avoid overhead.\n\tif (tm != NULL && ++tm_count == 100)\n\t{\n\t    tm_count = 0;\n\t    if (profile_passed_limit(tm))\n\t    {\n\t\tif (timed_out != NULL)\n\t\t    *timed_out = TRUE;\n\t\tstatus = RA_FAIL;\n\t\tbreak;\n\t    }\n\t}\n#endif\n\tstatus = RA_CONT;\n\n#ifdef DEBUG\n\tif (regnarrate)\n\t{\n\t    mch_errmsg((char *)regprop(scan));\n\t    mch_errmsg(\"...\\n\");\n# ifdef FEAT_SYN_HL\n\t    if (re_extmatch_in != NULL)\n\t    {\n\t\tint i;\n\n\t\tmch_errmsg(_(\"External submatches:\\n\"));\n\t\tfor (i = 0; i < NSUBEXP; i++)\n\t\t{\n\t\t    mch_errmsg(\"    \\\"\");\n\t\t    if (re_extmatch_in->matches[i] != NULL)\n\t\t\tmch_errmsg((char *)re_extmatch_in->matches[i]);\n\t\t    mch_errmsg(\"\\\"\\n\");\n\t\t}\n\t    }\n# endif\n\t}\n#endif\n\tnext = regnext(scan);\n\n\top = OP(scan);\n\t// Check for character class with NL added.\n\tif (!rex.reg_line_lbr && WITH_NL(op) && REG_MULTI\n\t\t\t     && *rex.input == NUL && rex.lnum <= rex.reg_maxline)\n\t{\n\t    reg_nextline();\n\t}\n\telse if (rex.reg_line_lbr && WITH_NL(op) && *rex.input == '\\n')\n\t{\n\t    ADVANCE_REGINPUT();\n\t}\n\telse\n\t{\n\t  if (WITH_NL(op))\n\t      op -= ADD_NL;\n\t  if (has_mbyte)\n\t      c = (*mb_ptr2char)(rex.input);\n\t  else\n\t      c = *rex.input;\n\t  switch (op)\n\t  {\n\t  case BOL:\n\t    if (rex.input != rex.line)\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case EOL:\n\t    if (c != NUL)\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case RE_BOF:\n\t    // We're not at the beginning of the file when below the first\n\t    // line where we started, not at the start of the line or we\n\t    // didn't start at the first line of the buffer.\n\t    if (rex.lnum != 0 || rex.input != rex.line\n\t\t\t\t       || (REG_MULTI && rex.reg_firstlnum > 1))\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case RE_EOF:\n\t    if (rex.lnum != rex.reg_maxline || c != NUL)\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case CURSOR:\n\t    // Check if the buffer is in a window and compare the\n\t    // rex.reg_win->w_cursor position to the match position.\n\t    if (rex.reg_win == NULL\n\t\t    || (rex.lnum + rex.reg_firstlnum\n\t\t\t\t\t\t != rex.reg_win->w_cursor.lnum)\n\t\t    || ((colnr_T)(rex.input - rex.line)\n\t\t\t\t\t\t != rex.reg_win->w_cursor.col))\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case RE_MARK:\n\t    // Compare the mark position to the match position.\n\t    {\n\t\tint\tmark = OPERAND(scan)[0];\n\t\tint\tcmp = OPERAND(scan)[1];\n\t\tpos_T\t*pos;\n\t\tsize_t\tcol = REG_MULTI ? rex.input - rex.line : 0;\n\n\t\tpos = getmark_buf(rex.reg_buf, mark, FALSE);\n\n\t\t// Line may have been freed, get it again.\n\t\tif (REG_MULTI)\n\t\t{\n\t\t    rex.line = reg_getline(rex.lnum);\n\t\t    rex.input = rex.line + col;\n\t\t}\n\n\t\tif (pos == NULL\t\t     // mark doesn't exist\n\t\t\t|| pos->lnum <= 0)   // mark isn't set in reg_buf\n\t\t{\n\t\t    status = RA_NOMATCH;\n\t\t}\n\t\telse\n\t\t{\n\t\t    colnr_T pos_col = pos->lnum == rex.lnum + rex.reg_firstlnum\n\t\t\t\t\t\t\t  && pos->col == MAXCOL\n\t\t\t\t      ? (colnr_T)STRLEN(reg_getline(\n\t\t\t\t\t\tpos->lnum - rex.reg_firstlnum))\n\t\t\t\t      : pos->col;\n\n\t\t    if ((pos->lnum == rex.lnum + rex.reg_firstlnum\n\t\t\t\t? (pos_col == (colnr_T)(rex.input - rex.line)\n\t\t\t\t    ? (cmp == '<' || cmp == '>')\n\t\t\t\t    : (pos_col < (colnr_T)(rex.input - rex.line)\n\t\t\t\t\t? cmp != '>'\n\t\t\t\t\t: cmp != '<'))\n\t\t\t\t: (pos->lnum < rex.lnum + rex.reg_firstlnum\n\t\t\t\t    ? cmp != '>'\n\t\t\t\t    : cmp != '<')))\n\t\t    status = RA_NOMATCH;\n\t\t}\n\t    }\n\t    break;\n\n\t  case RE_VISUAL:\n\t    if (!reg_match_visual())\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case RE_LNUM:\n\t    if (!REG_MULTI || !re_num_cmp((long_u)(rex.lnum + rex.reg_firstlnum),\n\t\t\t\t\t\t\t\t\tscan))\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case RE_COL:\n\t    if (!re_num_cmp((long_u)(rex.input - rex.line) + 1, scan))\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case RE_VCOL:\n\t    if (!re_num_cmp((long_u)win_linetabsize(\n\t\t\t    rex.reg_win == NULL ? curwin : rex.reg_win,\n\t\t\t    rex.line, (colnr_T)(rex.input - rex.line)) + 1, scan))\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case BOW:\t// \\ rex.line\n\t\t\t\t&& vim_iswordc_buf(rex.input[-1], rex.reg_buf)))\n\t\t    status = RA_NOMATCH;\n\t    }\n\t    break;\n\n\t  case EOW:\t// word\\>; rex.input points after d\n\t    if (rex.input == rex.line)    // Can't match at start of line\n\t\tstatus = RA_NOMATCH;\n\t    else if (has_mbyte)\n\t    {\n\t\tint this_class, prev_class;\n\n\t\t// Get class of current and previous char (if it exists).\n\t\tthis_class = mb_get_class_buf(rex.input, rex.reg_buf);\n\t\tprev_class = reg_prev_class();\n\t\tif (this_class == prev_class\n\t\t\t|| prev_class == 0 || prev_class == 1)\n\t\t    status = RA_NOMATCH;\n\t    }\n\t    else\n\t    {\n\t\tif (!vim_iswordc_buf(rex.input[-1], rex.reg_buf)\n\t\t\t|| (rex.input[0] != NUL\n\t\t\t\t\t   && vim_iswordc_buf(c, rex.reg_buf)))\n\t\t    status = RA_NOMATCH;\n\t    }\n\t    break; // Matched with EOW\n\n\t  case ANY:\n\t    // ANY does not match new lines.\n\t    if (c == NUL)\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case IDENT:\n\t    if (!vim_isIDc(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case SIDENT:\n\t    if (VIM_ISDIGIT(*rex.input) || !vim_isIDc(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case KWORD:\n\t    if (!vim_iswordp_buf(rex.input, rex.reg_buf))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case SKWORD:\n\t    if (VIM_ISDIGIT(*rex.input)\n\t\t\t\t    || !vim_iswordp_buf(rex.input, rex.reg_buf))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case FNAME:\n\t    if (!vim_isfilec(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case SFNAME:\n\t    if (VIM_ISDIGIT(*rex.input) || !vim_isfilec(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case PRINT:\n\t    if (!vim_isprintc(PTR2CHAR(rex.input)))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case SPRINT:\n\t    if (VIM_ISDIGIT(*rex.input) || !vim_isprintc(PTR2CHAR(rex.input)))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case WHITE:\n\t    if (!VIM_ISWHITE(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NWHITE:\n\t    if (c == NUL || VIM_ISWHITE(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case DIGIT:\n\t    if (!ri_digit(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NDIGIT:\n\t    if (c == NUL || ri_digit(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case HEX:\n\t    if (!ri_hex(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NHEX:\n\t    if (c == NUL || ri_hex(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case OCTAL:\n\t    if (!ri_octal(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NOCTAL:\n\t    if (c == NUL || ri_octal(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case WORD:\n\t    if (!ri_word(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NWORD:\n\t    if (c == NUL || ri_word(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case HEAD:\n\t    if (!ri_head(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NHEAD:\n\t    if (c == NUL || ri_head(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case ALPHA:\n\t    if (!ri_alpha(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NALPHA:\n\t    if (c == NUL || ri_alpha(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case LOWER:\n\t    if (!ri_lower(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NLOWER:\n\t    if (c == NUL || ri_lower(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case UPPER:\n\t    if (!ri_upper(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case NUPPER:\n\t    if (c == NUL || ri_upper(c))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case EXACTLY:\n\t    {\n\t\tint\tlen;\n\t\tchar_u\t*opnd;\n\n\t\topnd = OPERAND(scan);\n\t\t// Inline the first byte, for speed.\n\t\tif (*opnd != *rex.input\n\t\t\t&& (!rex.reg_ic\n\t\t\t    || (!enc_utf8\n\t\t\t      && MB_TOLOWER(*opnd) != MB_TOLOWER(*rex.input))))\n\t\t    status = RA_NOMATCH;\n\t\telse if (*opnd == NUL)\n\t\t{\n\t\t    // match empty string always works; happens when \"~\" is\n\t\t    // empty.\n\t\t}\n\t\telse\n\t\t{\n\t\t    if (opnd[1] == NUL && !(enc_utf8 && rex.reg_ic))\n\t\t    {\n\t\t\tlen = 1;\t// matched a single byte above\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\t// Need to match first byte again for multi-byte.\n\t\t\tlen = (int)STRLEN(opnd);\n\t\t\tif (cstrncmp(opnd, rex.input, &len) != 0)\n\t\t\t    status = RA_NOMATCH;\n\t\t    }\n\t\t    // Check for following composing character, unless %C\n\t\t    // follows (skips over all composing chars).\n\t\t    if (status != RA_NOMATCH\n\t\t\t    && enc_utf8\n\t\t\t    && UTF_COMPOSINGLIKE(rex.input, rex.input + len)\n\t\t\t    && !rex.reg_icombine\n\t\t\t    && OP(next) != RE_COMPOSING)\n\t\t    {\n\t\t\t// raaron: This code makes a composing character get\n\t\t\t// ignored, which is the correct behavior (sometimes)\n\t\t\t// for voweled Hebrew texts.\n\t\t\tstatus = RA_NOMATCH;\n\t\t    }\n\t\t    if (status != RA_NOMATCH)\n\t\t\trex.input += len;\n\t\t}\n\t    }\n\t    break;\n\n\t  case ANYOF:\n\t  case ANYBUT:\n\t    if (c == NUL)\n\t\tstatus = RA_NOMATCH;\n\t    else if ((cstrchr(OPERAND(scan), c) == NULL) == (op == ANYOF))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t\tADVANCE_REGINPUT();\n\t    break;\n\n\t  case MULTIBYTECODE:\n\t    if (has_mbyte)\n\t    {\n\t\tint\ti, len;\n\t\tchar_u\t*opnd;\n\t\tint\topndc = 0, inpc;\n\n\t\topnd = OPERAND(scan);\n\t\t// Safety check (just in case 'encoding' was changed since\n\t\t// compiling the program).\n\t\tif ((len = (*mb_ptr2len)(opnd)) < 2)\n\t\t{\n\t\t    status = RA_NOMATCH;\n\t\t    break;\n\t\t}\n\t\tif (enc_utf8)\n\t\t    opndc = utf_ptr2char(opnd);\n\t\tif (enc_utf8 && utf_iscomposing(opndc))\n\t\t{\n\t\t    // When only a composing char is given match at any\n\t\t    // position where that composing char appears.\n\t\t    status = RA_NOMATCH;\n\t\t    for (i = 0; rex.input[i] != NUL;\n\t\t\t\t\t\ti += utf_ptr2len(rex.input + i))\n\t\t    {\n\t\t\tinpc = utf_ptr2char(rex.input + i);\n\t\t\tif (!utf_iscomposing(inpc))\n\t\t\t{\n\t\t\t    if (i > 0)\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (opndc == inpc)\n\t\t\t{\n\t\t\t    // Include all following composing chars.\n\t\t\t    len = i + utfc_ptr2len(rex.input + i);\n\t\t\t    status = RA_MATCH;\n\t\t\t    break;\n\t\t\t}\n\t\t    }\n\t\t}\n\t\telse\n\t\t    for (i = 0; i < len; ++i)\n\t\t\tif (opnd[i] != rex.input[i])\n\t\t\t{\n\t\t\t    status = RA_NOMATCH;\n\t\t\t    break;\n\t\t\t}\n\t\trex.input += len;\n\t    }\n\t    else\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\t  case RE_COMPOSING:\n\t    if (enc_utf8)\n\t    {\n\t\t// Skip composing characters.\n\t\twhile (utf_iscomposing(utf_ptr2char(rex.input)))\n\t\t    MB_CPTR_ADV(rex.input);\n\t    }\n\t    break;\n\n\t  case NOTHING:\n\t    break;\n\n\t  case BACK:\n\t    {\n\t\tint\t\ti;\n\t\tbackpos_T\t*bp;\n\n\t\t// When we run into BACK we need to check if we don't keep\n\t\t// looping without matching any input.  The second and later\n\t\t// times a BACK is encountered it fails if the input is still\n\t\t// at the same position as the previous time.\n\t\t// The positions are stored in \"backpos\" and found by the\n\t\t// current value of \"scan\", the position in the RE program.\n\t\tbp = (backpos_T *)backpos.ga_data;\n\t\tfor (i = 0; i < backpos.ga_len; ++i)\n\t\t    if (bp[i].bp_scan == scan)\n\t\t\tbreak;\n\t\tif (i == backpos.ga_len)\n\t\t{\n\t\t    // First time at this BACK, make room to store the pos.\n\t\t    if (ga_grow(&backpos, 1) == FAIL)\n\t\t\tstatus = RA_FAIL;\n\t\t    else\n\t\t    {\n\t\t\t// get \"ga_data\" again, it may have changed\n\t\t\tbp = (backpos_T *)backpos.ga_data;\n\t\t\tbp[i].bp_scan = scan;\n\t\t\t++backpos.ga_len;\n\t\t    }\n\t\t}\n\t\telse if (reg_save_equal(&bp[i].bp_pos))\n\t\t    // Still at same position as last time, fail.\n\t\t    status = RA_NOMATCH;\n\n\t\tif (status != RA_FAIL && status != RA_NOMATCH)\n\t\t    reg_save(&bp[i].bp_pos, &backpos);\n\t    }\n\t    break;\n\n\t  case MOPEN + 0:   // Match start: \\zs\n\t  case MOPEN + 1:   // \\(\n\t  case MOPEN + 2:\n\t  case MOPEN + 3:\n\t  case MOPEN + 4:\n\t  case MOPEN + 5:\n\t  case MOPEN + 6:\n\t  case MOPEN + 7:\n\t  case MOPEN + 8:\n\t  case MOPEN + 9:\n\t    {\n\t\tno = op - MOPEN;\n\t\tcleanup_subexpr();\n\t\trp = regstack_push(RS_MOPEN, scan);\n\t\tif (rp == NULL)\n\t\t    status = RA_FAIL;\n\t\telse\n\t\t{\n\t\t    rp->rs_no = no;\n\t\t    save_se(&rp->rs_un.sesave, &rex.reg_startpos[no],\n\t\t\t\t\t\t\t  &rex.reg_startp[no]);\n\t\t    // We simply continue and handle the result when done.\n\t\t}\n\t    }\n\t    break;\n\n\t  case NOPEN:\t    // \\%(\n\t  case NCLOSE:\t    // \\) after \\%(\n\t\tif (regstack_push(RS_NOPEN, scan) == NULL)\n\t\t    status = RA_FAIL;\n\t\t// We simply continue and handle the result when done.\n\t\tbreak;\n\n#ifdef FEAT_SYN_HL\n\t  case ZOPEN + 1:\n\t  case ZOPEN + 2:\n\t  case ZOPEN + 3:\n\t  case ZOPEN + 4:\n\t  case ZOPEN + 5:\n\t  case ZOPEN + 6:\n\t  case ZOPEN + 7:\n\t  case ZOPEN + 8:\n\t  case ZOPEN + 9:\n\t    {\n\t\tno = op - ZOPEN;\n\t\tcleanup_zsubexpr();\n\t\trp = regstack_push(RS_ZOPEN, scan);\n\t\tif (rp == NULL)\n\t\t    status = RA_FAIL;\n\t\telse\n\t\t{\n\t\t    rp->rs_no = no;\n\t\t    save_se(&rp->rs_un.sesave, ®_startzpos[no],\n\t\t\t\t\t\t\t     ®_startzp[no]);\n\t\t    // We simply continue and handle the result when done.\n\t\t}\n\t    }\n\t    break;\n#endif\n\n\t  case MCLOSE + 0:  // Match end: \\ze\n\t  case MCLOSE + 1:  // \\)\n\t  case MCLOSE + 2:\n\t  case MCLOSE + 3:\n\t  case MCLOSE + 4:\n\t  case MCLOSE + 5:\n\t  case MCLOSE + 6:\n\t  case MCLOSE + 7:\n\t  case MCLOSE + 8:\n\t  case MCLOSE + 9:\n\t    {\n\t\tno = op - MCLOSE;\n\t\tcleanup_subexpr();\n\t\trp = regstack_push(RS_MCLOSE, scan);\n\t\tif (rp == NULL)\n\t\t    status = RA_FAIL;\n\t\telse\n\t\t{\n\t\t    rp->rs_no = no;\n\t\t    save_se(&rp->rs_un.sesave, &rex.reg_endpos[no],\n\t\t\t\t\t\t\t    &rex.reg_endp[no]);\n\t\t    // We simply continue and handle the result when done.\n\t\t}\n\t    }\n\t    break;\n\n#ifdef FEAT_SYN_HL\n\t  case ZCLOSE + 1:  // \\) after \\z(\n\t  case ZCLOSE + 2:\n\t  case ZCLOSE + 3:\n\t  case ZCLOSE + 4:\n\t  case ZCLOSE + 5:\n\t  case ZCLOSE + 6:\n\t  case ZCLOSE + 7:\n\t  case ZCLOSE + 8:\n\t  case ZCLOSE + 9:\n\t    {\n\t\tno = op - ZCLOSE;\n\t\tcleanup_zsubexpr();\n\t\trp = regstack_push(RS_ZCLOSE, scan);\n\t\tif (rp == NULL)\n\t\t    status = RA_FAIL;\n\t\telse\n\t\t{\n\t\t    rp->rs_no = no;\n\t\t    save_se(&rp->rs_un.sesave, ®_endzpos[no],\n\t\t\t\t\t\t\t      ®_endzp[no]);\n\t\t    // We simply continue and handle the result when done.\n\t\t}\n\t    }\n\t    break;\n#endif\n\n\t  case BACKREF + 1:\n\t  case BACKREF + 2:\n\t  case BACKREF + 3:\n\t  case BACKREF + 4:\n\t  case BACKREF + 5:\n\t  case BACKREF + 6:\n\t  case BACKREF + 7:\n\t  case BACKREF + 8:\n\t  case BACKREF + 9:\n\t    {\n\t\tint\t\tlen;\n\n\t\tno = op - BACKREF;\n\t\tcleanup_subexpr();\n\t\tif (!REG_MULTI)\t\t// Single-line regexp\n\t\t{\n\t\t    if (rex.reg_startp[no] == NULL || rex.reg_endp[no] == NULL)\n\t\t    {\n\t\t\t// Backref was not set: Match an empty string.\n\t\t\tlen = 0;\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\t// Compare current input with back-ref in the same\n\t\t\t// line.\n\t\t\tlen = (int)(rex.reg_endp[no] - rex.reg_startp[no]);\n\t\t\tif (cstrncmp(rex.reg_startp[no], rex.input, &len) != 0)\n\t\t\t    status = RA_NOMATCH;\n\t\t    }\n\t\t}\n\t\telse\t\t\t\t// Multi-line regexp\n\t\t{\n\t\t    if (rex.reg_startpos[no].lnum < 0\n\t\t\t\t\t\t|| rex.reg_endpos[no].lnum < 0)\n\t\t    {\n\t\t\t// Backref was not set: Match an empty string.\n\t\t\tlen = 0;\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\tif (rex.reg_startpos[no].lnum == rex.lnum\n\t\t\t\t&& rex.reg_endpos[no].lnum == rex.lnum)\n\t\t\t{\n\t\t\t    // Compare back-ref within the current line.\n\t\t\t    len = rex.reg_endpos[no].col\n\t\t\t\t\t\t    - rex.reg_startpos[no].col;\n\t\t\t    if (cstrncmp(rex.line + rex.reg_startpos[no].col,\n\t\t\t\t\t\t\t  rex.input, &len) != 0)\n\t\t\t\tstatus = RA_NOMATCH;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t    // Messy situation: Need to compare between two\n\t\t\t    // lines.\n\t\t\t    int r = match_with_backref(\n\t\t\t\t\t    rex.reg_startpos[no].lnum,\n\t\t\t\t\t    rex.reg_startpos[no].col,\n\t\t\t\t\t    rex.reg_endpos[no].lnum,\n\t\t\t\t\t    rex.reg_endpos[no].col,\n\t\t\t\t\t    &len);\n\n\t\t\t    if (r != RA_MATCH)\n\t\t\t\tstatus = r;\n\t\t\t}\n\t\t    }\n\t\t}\n\n\t\t// Matched the backref, skip over it.\n\t\trex.input += len;\n\t    }\n\t    break;\n\n#ifdef FEAT_SYN_HL\n\t  case ZREF + 1:\n\t  case ZREF + 2:\n\t  case ZREF + 3:\n\t  case ZREF + 4:\n\t  case ZREF + 5:\n\t  case ZREF + 6:\n\t  case ZREF + 7:\n\t  case ZREF + 8:\n\t  case ZREF + 9:\n\t    {\n\t\tint\tlen;\n\n\t\tcleanup_zsubexpr();\n\t\tno = op - ZREF;\n\t\tif (re_extmatch_in != NULL\n\t\t\t&& re_extmatch_in->matches[no] != NULL)\n\t\t{\n\t\t    len = (int)STRLEN(re_extmatch_in->matches[no]);\n\t\t    if (cstrncmp(re_extmatch_in->matches[no],\n\t\t\t\t\t\t\t  rex.input, &len) != 0)\n\t\t\tstatus = RA_NOMATCH;\n\t\t    else\n\t\t\trex.input += len;\n\t\t}\n\t\telse\n\t\t{\n\t\t    // Backref was not set: Match an empty string.\n\t\t}\n\t    }\n\t    break;\n#endif\n\n\t  case BRANCH:\n\t    {\n\t\tif (OP(next) != BRANCH) // No choice.\n\t\t    next = OPERAND(scan);\t// Avoid recursion.\n\t\telse\n\t\t{\n\t\t    rp = regstack_push(RS_BRANCH, scan);\n\t\t    if (rp == NULL)\n\t\t\tstatus = RA_FAIL;\n\t\t    else\n\t\t\tstatus = RA_BREAK;\t// rest is below\n\t\t}\n\t    }\n\t    break;\n\n\t  case BRACE_LIMITS:\n\t    {\n\t\tif (OP(next) == BRACE_SIMPLE)\n\t\t{\n\t\t    bl_minval = OPERAND_MIN(scan);\n\t\t    bl_maxval = OPERAND_MAX(scan);\n\t\t}\n\t\telse if (OP(next) >= BRACE_COMPLEX\n\t\t\t&& OP(next) < BRACE_COMPLEX + 10)\n\t\t{\n\t\t    no = OP(next) - BRACE_COMPLEX;\n\t\t    brace_min[no] = OPERAND_MIN(scan);\n\t\t    brace_max[no] = OPERAND_MAX(scan);\n\t\t    brace_count[no] = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t    internal_error(\"BRACE_LIMITS\");\n\t\t    status = RA_FAIL;\n\t\t}\n\t    }\n\t    break;\n\n\t  case BRACE_COMPLEX + 0:\n\t  case BRACE_COMPLEX + 1:\n\t  case BRACE_COMPLEX + 2:\n\t  case BRACE_COMPLEX + 3:\n\t  case BRACE_COMPLEX + 4:\n\t  case BRACE_COMPLEX + 5:\n\t  case BRACE_COMPLEX + 6:\n\t  case BRACE_COMPLEX + 7:\n\t  case BRACE_COMPLEX + 8:\n\t  case BRACE_COMPLEX + 9:\n\t    {\n\t\tno = op - BRACE_COMPLEX;\n\t\t++brace_count[no];\n\n\t\t// If not matched enough times yet, try one more\n\t\tif (brace_count[no] <= (brace_min[no] <= brace_max[no]\n\t\t\t\t\t     ? brace_min[no] : brace_max[no]))\n\t\t{\n\t\t    rp = regstack_push(RS_BRCPLX_MORE, scan);\n\t\t    if (rp == NULL)\n\t\t\tstatus = RA_FAIL;\n\t\t    else\n\t\t    {\n\t\t\trp->rs_no = no;\n\t\t\treg_save(&rp->rs_un.regsave, &backpos);\n\t\t\tnext = OPERAND(scan);\n\t\t\t// We continue and handle the result when done.\n\t\t    }\n\t\t    break;\n\t\t}\n\n\t\t// If matched enough times, may try matching some more\n\t\tif (brace_min[no] <= brace_max[no])\n\t\t{\n\t\t    // Range is the normal way around, use longest match\n\t\t    if (brace_count[no] <= brace_max[no])\n\t\t    {\n\t\t\trp = regstack_push(RS_BRCPLX_LONG, scan);\n\t\t\tif (rp == NULL)\n\t\t\t    status = RA_FAIL;\n\t\t\telse\n\t\t\t{\n\t\t\t    rp->rs_no = no;\n\t\t\t    reg_save(&rp->rs_un.regsave, &backpos);\n\t\t\t    next = OPERAND(scan);\n\t\t\t    // We continue and handle the result when done.\n\t\t\t}\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    // Range is backwards, use shortest match first\n\t\t    if (brace_count[no] <= brace_min[no])\n\t\t    {\n\t\t\trp = regstack_push(RS_BRCPLX_SHORT, scan);\n\t\t\tif (rp == NULL)\n\t\t\t    status = RA_FAIL;\n\t\t\telse\n\t\t\t{\n\t\t\t    reg_save(&rp->rs_un.regsave, &backpos);\n\t\t\t    // We continue and handle the result when done.\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\t    break;\n\n\t  case BRACE_SIMPLE:\n\t  case STAR:\n\t  case PLUS:\n\t    {\n\t\tregstar_T\trst;\n\n\t\t// Lookahead to avoid useless match attempts when we know\n\t\t// what character comes next.\n\t\tif (OP(next) == EXACTLY)\n\t\t{\n\t\t    rst.nextb = *OPERAND(next);\n\t\t    if (rex.reg_ic)\n\t\t    {\n\t\t\tif (MB_ISUPPER(rst.nextb))\n\t\t\t    rst.nextb_ic = MB_TOLOWER(rst.nextb);\n\t\t\telse\n\t\t\t    rst.nextb_ic = MB_TOUPPER(rst.nextb);\n\t\t    }\n\t\t    else\n\t\t\trst.nextb_ic = rst.nextb;\n\t\t}\n\t\telse\n\t\t{\n\t\t    rst.nextb = NUL;\n\t\t    rst.nextb_ic = NUL;\n\t\t}\n\t\tif (op != BRACE_SIMPLE)\n\t\t{\n\t\t    rst.minval = (op == STAR) ? 0 : 1;\n\t\t    rst.maxval = MAX_LIMIT;\n\t\t}\n\t\telse\n\t\t{\n\t\t    rst.minval = bl_minval;\n\t\t    rst.maxval = bl_maxval;\n\t\t}\n\n\t\t// When maxval > minval, try matching as much as possible, up\n\t\t// to maxval.  When maxval < minval, try matching at least the\n\t\t// minimal number (since the range is backwards, that's also\n\t\t// maxval!).\n\t\trst.count = regrepeat(OPERAND(scan), rst.maxval);\n\t\tif (got_int)\n\t\t{\n\t\t    status = RA_FAIL;\n\t\t    break;\n\t\t}\n\t\tif (rst.minval <= rst.maxval\n\t\t\t  ? rst.count >= rst.minval : rst.count >= rst.maxval)\n\t\t{\n\t\t    // It could match.  Prepare for trying to match what\n\t\t    // follows.  The code is below.  Parameters are stored in\n\t\t    // a regstar_T on the regstack.\n\t\t    if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)\n\t\t    {\n\t\t\temsg(_(e_pattern_uses_more_memory_than_maxmempattern));\n\t\t\tstatus = RA_FAIL;\n\t\t    }\n\t\t    else if (ga_grow(®stack, sizeof(regstar_T)) == FAIL)\n\t\t\tstatus = RA_FAIL;\n\t\t    else\n\t\t    {\n\t\t\tregstack.ga_len += sizeof(regstar_T);\n\t\t\trp = regstack_push(rst.minval <= rst.maxval\n\t\t\t\t\t? RS_STAR_LONG : RS_STAR_SHORT, scan);\n\t\t\tif (rp == NULL)\n\t\t\t    status = RA_FAIL;\n\t\t\telse\n\t\t\t{\n\t\t\t    *(((regstar_T *)rp) - 1) = rst;\n\t\t\t    status = RA_BREAK;\t    // skip the restore bits\n\t\t\t}\n\t\t    }\n\t\t}\n\t\telse\n\t\t    status = RA_NOMATCH;\n\n\t    }\n\t    break;\n\n\t  case NOMATCH:\n\t  case MATCH:\n\t  case SUBPAT:\n\t    rp = regstack_push(RS_NOMATCH, scan);\n\t    if (rp == NULL)\n\t\tstatus = RA_FAIL;\n\t    else\n\t    {\n\t\trp->rs_no = op;\n\t\treg_save(&rp->rs_un.regsave, &backpos);\n\t\tnext = OPERAND(scan);\n\t\t// We continue and handle the result when done.\n\t    }\n\t    break;\n\n\t  case BEHIND:\n\t  case NOBEHIND:\n\t    // Need a bit of room to store extra positions.\n\t    if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)\n\t    {\n\t\temsg(_(e_pattern_uses_more_memory_than_maxmempattern));\n\t\tstatus = RA_FAIL;\n\t    }\n\t    else if (ga_grow(®stack, sizeof(regbehind_T)) == FAIL)\n\t\tstatus = RA_FAIL;\n\t    else\n\t    {\n\t\tregstack.ga_len += sizeof(regbehind_T);\n\t\trp = regstack_push(RS_BEHIND1, scan);\n\t\tif (rp == NULL)\n\t\t    status = RA_FAIL;\n\t\telse\n\t\t{\n\t\t    // Need to save the subexpr to be able to restore them\n\t\t    // when there is a match but we don't use it.\n\t\t    save_subexpr(((regbehind_T *)rp) - 1);\n\n\t\t    rp->rs_no = op;\n\t\t    reg_save(&rp->rs_un.regsave, &backpos);\n\t\t    // First try if what follows matches.  If it does then we\n\t\t    // check the behind match by looping.\n\t\t}\n\t    }\n\t    break;\n\n\t  case BHPOS:\n\t    if (REG_MULTI)\n\t    {\n\t\tif (behind_pos.rs_u.pos.col != (colnr_T)(rex.input - rex.line)\n\t\t\t|| behind_pos.rs_u.pos.lnum != rex.lnum)\n\t\t    status = RA_NOMATCH;\n\t    }\n\t    else if (behind_pos.rs_u.ptr != rex.input)\n\t\tstatus = RA_NOMATCH;\n\t    break;\n\n\t  case NEWL:\n\t    if ((c != NUL || !REG_MULTI || rex.lnum > rex.reg_maxline\n\t\t\t     || rex.reg_line_lbr)\n\t\t\t\t\t   && (c != '\\n' || !rex.reg_line_lbr))\n\t\tstatus = RA_NOMATCH;\n\t    else if (rex.reg_line_lbr)\n\t\tADVANCE_REGINPUT();\n\t    else\n\t\treg_nextline();\n\t    break;\n\n\t  case END:\n\t    status = RA_MATCH;\t// Success!\n\t    break;\n\n\t  default:\n\t    iemsg(_(e_corrupted_regexp_program));\n#ifdef DEBUG\n\t    printf(\"Illegal op code %d\\n\", op);\n#endif\n\t    status = RA_FAIL;\n\t    break;\n\t  }\n\t}\n\n\t// If we can't continue sequentially, break the inner loop.\n\tif (status != RA_CONT)\n\t    break;\n\n\t// Continue in inner loop, advance to next item.\n\tscan = next;\n\n    } // end of inner loop\n\n    // If there is something on the regstack execute the code for the state.\n    // If the state is popped then loop and use the older state.\n    while (regstack.ga_len > 0 && status != RA_FAIL)\n    {\n\trp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;\n\tswitch (rp->rs_state)\n\t{\n\t  case RS_NOPEN:\n\t    // Result is passed on as-is, simply pop the state.\n\t    regstack_pop(&scan);\n\t    break;\n\n\t  case RS_MOPEN:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t\trestore_se(&rp->rs_un.sesave, &rex.reg_startpos[rp->rs_no],\n\t\t\t\t\t\t  &rex.reg_startp[rp->rs_no]);\n\t    regstack_pop(&scan);\n\t    break;\n\n#ifdef FEAT_SYN_HL\n\t  case RS_ZOPEN:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t\trestore_se(&rp->rs_un.sesave, ®_startzpos[rp->rs_no],\n\t\t\t\t\t\t ®_startzp[rp->rs_no]);\n\t    regstack_pop(&scan);\n\t    break;\n#endif\n\n\t  case RS_MCLOSE:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t\trestore_se(&rp->rs_un.sesave, &rex.reg_endpos[rp->rs_no],\n\t\t\t\t\t\t    &rex.reg_endp[rp->rs_no]);\n\t    regstack_pop(&scan);\n\t    break;\n\n#ifdef FEAT_SYN_HL\n\t  case RS_ZCLOSE:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t\trestore_se(&rp->rs_un.sesave, ®_endzpos[rp->rs_no],\n\t\t\t\t\t\t   ®_endzp[rp->rs_no]);\n\t    regstack_pop(&scan);\n\t    break;\n#endif\n\n\t  case RS_BRANCH:\n\t    if (status == RA_MATCH)\n\t\t// this branch matched, use it\n\t\tregstack_pop(&scan);\n\t    else\n\t    {\n\t\tif (status != RA_BREAK)\n\t\t{\n\t\t    // After a non-matching branch: try next one.\n\t\t    reg_restore(&rp->rs_un.regsave, &backpos);\n\t\t    scan = rp->rs_scan;\n\t\t}\n\t\tif (scan == NULL || OP(scan) != BRANCH)\n\t\t{\n\t\t    // no more branches, didn't find a match\n\t\t    status = RA_NOMATCH;\n\t\t    regstack_pop(&scan);\n\t\t}\n\t\telse\n\t\t{\n\t\t    // Prepare to try a branch.\n\t\t    rp->rs_scan = regnext(scan);\n\t\t    reg_save(&rp->rs_un.regsave, &backpos);\n\t\t    scan = OPERAND(scan);\n\t\t}\n\t    }\n\t    break;\n\n\t  case RS_BRCPLX_MORE:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t    {\n\t\treg_restore(&rp->rs_un.regsave, &backpos);\n\t\t--brace_count[rp->rs_no];\t// decrement match count\n\t    }\n\t    regstack_pop(&scan);\n\t    break;\n\n\t  case RS_BRCPLX_LONG:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t    {\n\t\t// There was no match, but we did find enough matches.\n\t\treg_restore(&rp->rs_un.regsave, &backpos);\n\t\t--brace_count[rp->rs_no];\n\t\t// continue with the items after \"\\{}\"\n\t\tstatus = RA_CONT;\n\t    }\n\t    regstack_pop(&scan);\n\t    if (status == RA_CONT)\n\t\tscan = regnext(scan);\n\t    break;\n\n\t  case RS_BRCPLX_SHORT:\n\t    // Pop the state.  Restore pointers when there is no match.\n\t    if (status == RA_NOMATCH)\n\t\t// There was no match, try to match one more item.\n\t\treg_restore(&rp->rs_un.regsave, &backpos);\n\t    regstack_pop(&scan);\n\t    if (status == RA_NOMATCH)\n\t    {\n\t\tscan = OPERAND(scan);\n\t\tstatus = RA_CONT;\n\t    }\n\t    break;\n\n\t  case RS_NOMATCH:\n\t    // Pop the state.  If the operand matches for NOMATCH or\n\t    // doesn't match for MATCH/SUBPAT, we fail.  Otherwise backup,\n\t    // except for SUBPAT, and continue with the next item.\n\t    if (status == (rp->rs_no == NOMATCH ? RA_MATCH : RA_NOMATCH))\n\t\tstatus = RA_NOMATCH;\n\t    else\n\t    {\n\t\tstatus = RA_CONT;\n\t\tif (rp->rs_no != SUBPAT)\t// zero-width\n\t\t    reg_restore(&rp->rs_un.regsave, &backpos);\n\t    }\n\t    regstack_pop(&scan);\n\t    if (status == RA_CONT)\n\t\tscan = regnext(scan);\n\t    break;\n\n\t  case RS_BEHIND1:\n\t    if (status == RA_NOMATCH)\n\t    {\n\t\tregstack_pop(&scan);\n\t\tregstack.ga_len -= sizeof(regbehind_T);\n\t    }\n\t    else\n\t    {\n\t\t// The stuff after BEHIND/NOBEHIND matches.  Now try if\n\t\t// the behind part does (not) match before the current\n\t\t// position in the input.  This must be done at every\n\t\t// position in the input and checking if the match ends at\n\t\t// the current position.\n\n\t\t// save the position after the found match for next\n\t\treg_save(&(((regbehind_T *)rp) - 1)->save_after, &backpos);\n\n\t\t// Start looking for a match with operand at the current\n\t\t// position.  Go back one character until we find the\n\t\t// result, hitting the start of the line or the previous\n\t\t// line (for multi-line matching).\n\t\t// Set behind_pos to where the match should end, BHPOS\n\t\t// will match it.  Save the current value.\n\t\t(((regbehind_T *)rp) - 1)->save_behind = behind_pos;\n\t\tbehind_pos = rp->rs_un.regsave;\n\n\t\trp->rs_state = RS_BEHIND2;\n\n\t\treg_restore(&rp->rs_un.regsave, &backpos);\n\t\tscan = OPERAND(rp->rs_scan) + 4;\n\t    }\n\t    break;\n\n\t  case RS_BEHIND2:\n\t    // Looping for BEHIND / NOBEHIND match.\n\t    if (status == RA_MATCH && reg_save_equal(&behind_pos))\n\t    {\n\t\t// found a match that ends where \"next\" started\n\t\tbehind_pos = (((regbehind_T *)rp) - 1)->save_behind;\n\t\tif (rp->rs_no == BEHIND)\n\t\t    reg_restore(&(((regbehind_T *)rp) - 1)->save_after,\n\t\t\t\t\t\t\t\t    &backpos);\n\t\telse\n\t\t{\n\t\t    // But we didn't want a match.  Need to restore the\n\t\t    // subexpr, because what follows matched, so they have\n\t\t    // been set.\n\t\t    status = RA_NOMATCH;\n\t\t    restore_subexpr(((regbehind_T *)rp) - 1);\n\t\t}\n\t\tregstack_pop(&scan);\n\t\tregstack.ga_len -= sizeof(regbehind_T);\n\t    }\n\t    else\n\t    {\n\t\tlong limit;\n\n\t\t// No match or a match that doesn't end where we want it: Go\n\t\t// back one character.  May go to previous line once.\n\t\tno = OK;\n\t\tlimit = OPERAND_MIN(rp->rs_scan);\n\t\tif (REG_MULTI)\n\t\t{\n\t\t    if (limit > 0\n\t\t\t    && ((rp->rs_un.regsave.rs_u.pos.lnum\n\t\t\t\t\t\t    < behind_pos.rs_u.pos.lnum\n\t\t\t\t    ? (colnr_T)STRLEN(rex.line)\n\t\t\t\t    : behind_pos.rs_u.pos.col)\n\t\t\t\t- rp->rs_un.regsave.rs_u.pos.col >= limit))\n\t\t\tno = FAIL;\n\t\t    else if (rp->rs_un.regsave.rs_u.pos.col == 0)\n\t\t    {\n\t\t\tif (rp->rs_un.regsave.rs_u.pos.lnum\n\t\t\t\t\t< behind_pos.rs_u.pos.lnum\n\t\t\t\t|| reg_getline(\n\t\t\t\t\t--rp->rs_un.regsave.rs_u.pos.lnum)\n\t\t\t\t\t\t\t\t  == NULL)\n\t\t\t    no = FAIL;\n\t\t\telse\n\t\t\t{\n\t\t\t    reg_restore(&rp->rs_un.regsave, &backpos);\n\t\t\t    rp->rs_un.regsave.rs_u.pos.col =\n\t\t\t\t\t\t (colnr_T)STRLEN(rex.line);\n\t\t\t}\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\tif (has_mbyte)\n\t\t\t{\n\t\t\t    char_u *line =\n\t\t\t\t  reg_getline(rp->rs_un.regsave.rs_u.pos.lnum);\n\n\t\t\t    rp->rs_un.regsave.rs_u.pos.col -=\n\t\t\t\t(*mb_head_off)(line, line\n\t\t\t\t    + rp->rs_un.regsave.rs_u.pos.col - 1) + 1;\n\t\t\t}\n\t\t\telse\n\t\t\t    --rp->rs_un.regsave.rs_u.pos.col;\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    if (rp->rs_un.regsave.rs_u.ptr == rex.line)\n\t\t\tno = FAIL;\n\t\t    else\n\t\t    {\n\t\t\tMB_PTR_BACK(rex.line, rp->rs_un.regsave.rs_u.ptr);\n\t\t\tif (limit > 0 && (long)(behind_pos.rs_u.ptr\n\t\t\t\t     - rp->rs_un.regsave.rs_u.ptr) > limit)\n\t\t\t    no = FAIL;\n\t\t    }\n\t\t}\n\t\tif (no == OK)\n\t\t{\n\t\t    // Advanced, prepare for finding match again.\n\t\t    reg_restore(&rp->rs_un.regsave, &backpos);\n\t\t    scan = OPERAND(rp->rs_scan) + 4;\n\t\t    if (status == RA_MATCH)\n\t\t    {\n\t\t\t// We did match, so subexpr may have been changed,\n\t\t\t// need to restore them for the next try.\n\t\t\tstatus = RA_NOMATCH;\n\t\t\trestore_subexpr(((regbehind_T *)rp) - 1);\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    // Can't advance.  For NOBEHIND that's a match.\n\t\t    behind_pos = (((regbehind_T *)rp) - 1)->save_behind;\n\t\t    if (rp->rs_no == NOBEHIND)\n\t\t    {\n\t\t\treg_restore(&(((regbehind_T *)rp) - 1)->save_after,\n\t\t\t\t\t\t\t\t    &backpos);\n\t\t\tstatus = RA_MATCH;\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\t// We do want a proper match.  Need to restore the\n\t\t\t// subexpr if we had a match, because they may have\n\t\t\t// been set.\n\t\t\tif (status == RA_MATCH)\n\t\t\t{\n\t\t\t    status = RA_NOMATCH;\n\t\t\t    restore_subexpr(((regbehind_T *)rp) - 1);\n\t\t\t}\n\t\t    }\n\t\t    regstack_pop(&scan);\n\t\t    regstack.ga_len -= sizeof(regbehind_T);\n\t\t}\n\t    }\n\t    break;\n\n\t  case RS_STAR_LONG:\n\t  case RS_STAR_SHORT:\n\t    {\n\t\tregstar_T\t    *rst = ((regstar_T *)rp) - 1;\n\n\t\tif (status == RA_MATCH)\n\t\t{\n\t\t    regstack_pop(&scan);\n\t\t    regstack.ga_len -= sizeof(regstar_T);\n\t\t    break;\n\t\t}\n\n\t\t// Tried once already, restore input pointers.\n\t\tif (status != RA_BREAK)\n\t\t    reg_restore(&rp->rs_un.regsave, &backpos);\n\n\t\t// Repeat until we found a position where it could match.\n\t\tfor (;;)\n\t\t{\n\t\t    if (status != RA_BREAK)\n\t\t    {\n\t\t\t// Tried first position already, advance.\n\t\t\tif (rp->rs_state == RS_STAR_LONG)\n\t\t\t{\n\t\t\t    // Trying for longest match, but couldn't or\n\t\t\t    // didn't match -- back up one char.\n\t\t\t    if (--rst->count < rst->minval)\n\t\t\t\tbreak;\n\t\t\t    if (rex.input == rex.line)\n\t\t\t    {\n\t\t\t\t// backup to last char of previous line\n\t\t\t\tif (rex.lnum == 0)\n\t\t\t\t{\n\t\t\t\t    status = RA_NOMATCH;\n\t\t\t\t    break;\n\t\t\t\t}\n\t\t\t\t--rex.lnum;\n\t\t\t\trex.line = reg_getline(rex.lnum);\n\t\t\t\t// Just in case regrepeat() didn't count\n\t\t\t\t// right.\n\t\t\t\tif (rex.line == NULL)\n\t\t\t\t    break;\n\t\t\t\trex.input = rex.line + STRLEN(rex.line);\n\t\t\t\tfast_breakcheck();\n\t\t\t    }\n\t\t\t    else\n\t\t\t\tMB_PTR_BACK(rex.line, rex.input);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t    // Range is backwards, use shortest match first.\n\t\t\t    // Careful: maxval and minval are exchanged!\n\t\t\t    // Couldn't or didn't match: try advancing one\n\t\t\t    // char.\n\t\t\t    if (rst->count == rst->minval\n\t\t\t\t  || regrepeat(OPERAND(rp->rs_scan), 1L) == 0)\n\t\t\t\tbreak;\n\t\t\t    ++rst->count;\n\t\t\t}\n\t\t\tif (got_int)\n\t\t\t    break;\n\t\t    }\n\t\t    else\n\t\t\tstatus = RA_NOMATCH;\n\n\t\t    // If it could match, try it.\n\t\t    if (rst->nextb == NUL || *rex.input == rst->nextb\n\t\t\t\t\t     || *rex.input == rst->nextb_ic)\n\t\t    {\n\t\t\treg_save(&rp->rs_un.regsave, &backpos);\n\t\t\tscan = regnext(rp->rs_scan);\n\t\t\tstatus = RA_CONT;\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t\tif (status != RA_CONT)\n\t\t{\n\t\t    // Failed.\n\t\t    regstack_pop(&scan);\n\t\t    regstack.ga_len -= sizeof(regstar_T);\n\t\t    status = RA_NOMATCH;\n\t\t}\n\t    }\n\t    break;\n\t}\n\n\t// If we want to continue the inner loop or didn't pop a state\n\t// continue matching loop\n\tif (status == RA_CONT || rp == (regitem_T *)\n\t\t\t     ((char *)regstack.ga_data + regstack.ga_len) - 1)\n\t    break;\n    }\n\n    // May need to continue with the inner loop, starting at \"scan\".\n    if (status == RA_CONT)\n\tcontinue;\n\n    // If the regstack is empty or something failed we are done.\n    if (regstack.ga_len == 0 || status == RA_FAIL)\n    {\n\tif (scan == NULL)\n\t{\n\t    // We get here only if there's trouble -- normally \"case END\" is\n\t    // the terminating point.\n\t    iemsg(_(e_corrupted_regexp_program));\n#ifdef DEBUG\n\t    printf(\"Premature EOL\\n\");\n#endif\n\t}\n\treturn (status == RA_MATCH);\n    }\n\n  } // End of loop until the regstack is empty.\n\n  // NOTREACHED\n}", "func_hash": 159439689195764393844711247359472650436, "file_name": "regexp_bt.c", "file_hash": 101007884968871143689098417071305864398, "cwe": ["CWE-416"], "cve": "CVE-2022-1154", "cve_desc": "Use after free in utf_ptr2char in GitHub repository vim/vim prior to 8.2.4646.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1154"}
{"idx": 201913, "project": "libarchive", "commit_id": "e2ad1a2c3064fa9eba6274b3641c4c1beed25c0b", "project_url": "https://github.com/libarchive/libarchive", "commit_url": "https://github.com/libarchive/libarchive/commit/e2ad1a2c3064fa9eba6274b3641c4c1beed25c0b", "commit_message": "Never follow symlinks when setting file flags on Linux\n\nWhen opening a file descriptor to set file flags on linux, ensure\nno symbolic links are followed. This fixes the case when an archive\ncontains a directory entry followed by a symlink entry with the same\npath. The fixup code would modify file flags of the symlink target.", "target": 1, "func": "set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,\n    mode_t mode, unsigned long set, unsigned long clear)\n{\n\tint\t\t ret;\n\tint\t\t myfd = fd;\n\tint newflags, oldflags;\n\t/*\n\t * Linux has no define for the flags that are only settable by\n\t * the root user.  This code may seem a little complex, but\n\t * there seem to be some Linux systems that lack these\n\t * defines. (?)  The code below degrades reasonably gracefully\n\t * if sf_mask is incomplete.\n\t */\n\tconst int sf_mask = 0\n#if defined(FS_IMMUTABLE_FL)\n\t    | FS_IMMUTABLE_FL\n#elif defined(EXT2_IMMUTABLE_FL)\n\t    | EXT2_IMMUTABLE_FL\n#endif\n#if defined(FS_APPEND_FL)\n\t    | FS_APPEND_FL\n#elif defined(EXT2_APPEND_FL)\n\t    | EXT2_APPEND_FL\n#endif\n#if defined(FS_JOURNAL_DATA_FL)\n\t    | FS_JOURNAL_DATA_FL\n#endif\n\t;\n\n\tif (set == 0 && clear == 0)\n\t\treturn (ARCHIVE_OK);\n\t/* Only regular files and dirs can have flags. */\n\tif (!S_ISREG(mode) && !S_ISDIR(mode))\n\t\treturn (ARCHIVE_OK);\n\n\t/* If we weren't given an fd, open it ourselves. */\n\tif (myfd < 0) {\n\t\tmyfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC);\n\t\t__archive_ensure_cloexec_flag(myfd);\n\t}\n\tif (myfd < 0)\n\t\treturn (ARCHIVE_OK);\n\n\t/*\n\t * XXX As above, this would be way simpler if we didn't have\n\t * to read the current flags from disk. XXX\n\t */\n\tret = ARCHIVE_OK;\n\n\t/* Read the current file flags. */\n\tif (ioctl(myfd,\n#ifdef FS_IOC_GETFLAGS\n\t    FS_IOC_GETFLAGS,\n#else\n\t    EXT2_IOC_GETFLAGS,\n#endif\n\t    &oldflags) < 0)\n\t\tgoto fail;\n\n\t/* Try setting the flags as given. */\n\tnewflags = (oldflags & ~clear) | set;\n\tif (ioctl(myfd,\n#ifdef FS_IOC_SETFLAGS\n\t    FS_IOC_SETFLAGS,\n#else\n\t    EXT2_IOC_SETFLAGS,\n#endif\n\t    &newflags) >= 0)\n\t\tgoto cleanup;\n\tif (errno != EPERM)\n\t\tgoto fail;\n\n\t/* If we couldn't set all the flags, try again with a subset. */\n\tnewflags &= ~sf_mask;\n\toldflags &= sf_mask;\n\tnewflags |= oldflags;\n\tif (ioctl(myfd,\n#ifdef FS_IOC_SETFLAGS\n\t    FS_IOC_SETFLAGS,\n#else\n\t    EXT2_IOC_SETFLAGS,\n#endif\n\t    &newflags) >= 0)\n\t\tgoto cleanup;\n\n\t/* We couldn't set the flags, so report the failure. */\nfail:\n\tarchive_set_error(&a->archive, errno,\n\t    \"Failed to set file flags\");\n\tret = ARCHIVE_WARN;\ncleanup:\n\tif (fd < 0)\n\t\tclose(myfd);\n\treturn (ret);\n}", "func_hash": 23055553245958282946404395843765567799, "file_name": "None", "file_hash": null, "cwe": ["CWE-59"], "cve": "CVE-2021-31566", "cve_desc": "An improper link resolution flaw can occur while extracting an archive leading to changing modes, times, access control lists, and flags of a file outside of the archive. An attacker may provide a malicious archive to a victim user, who would trigger this flaw when trying to extract the archive. A local attacker may use this flaw to gain more privileges in a system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31566"}
{"idx": 326629, "project": "libarchive", "commit_id": "e2ad1a2c3064fa9eba6274b3641c4c1beed25c0b", "project_url": "https://github.com/libarchive/libarchive", "commit_url": "https://github.com/libarchive/libarchive/commit/e2ad1a2c3064fa9eba6274b3641c4c1beed25c0b", "commit_message": "Never follow symlinks when setting file flags on Linux\n\nWhen opening a file descriptor to set file flags on linux, ensure\nno symbolic links are followed. This fixes the case when an archive\ncontains a directory entry followed by a symlink entry with the same\npath. The fixup code would modify file flags of the symlink target.", "target": 0, "func": "set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,\n    mode_t mode, unsigned long set, unsigned long clear)\n{\n\tint\t\t ret;\n\tint\t\t myfd = fd;\n\tint newflags, oldflags;\n\t/*\n\t * Linux has no define for the flags that are only settable by\n\t * the root user.  This code may seem a little complex, but\n\t * there seem to be some Linux systems that lack these\n\t * defines. (?)  The code below degrades reasonably gracefully\n\t * if sf_mask is incomplete.\n\t */\n\tconst int sf_mask = 0\n#if defined(FS_IMMUTABLE_FL)\n\t    | FS_IMMUTABLE_FL\n#elif defined(EXT2_IMMUTABLE_FL)\n\t    | EXT2_IMMUTABLE_FL\n#endif\n#if defined(FS_APPEND_FL)\n\t    | FS_APPEND_FL\n#elif defined(EXT2_APPEND_FL)\n\t    | EXT2_APPEND_FL\n#endif\n#if defined(FS_JOURNAL_DATA_FL)\n\t    | FS_JOURNAL_DATA_FL\n#endif\n\t;\n\n\tif (set == 0 && clear == 0)\n\t\treturn (ARCHIVE_OK);\n\t/* Only regular files and dirs can have flags. */\n\tif (!S_ISREG(mode) && !S_ISDIR(mode))\n\t\treturn (ARCHIVE_OK);\n\n\t/* If we weren't given an fd, open it ourselves. */\n\tif (myfd < 0) {\n\t\tmyfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY |\n\t\t    O_CLOEXEC | O_NOFOLLOW);\n\t\t__archive_ensure_cloexec_flag(myfd);\n\t}\n\tif (myfd < 0)\n\t\treturn (ARCHIVE_OK);\n\n\t/*\n\t * XXX As above, this would be way simpler if we didn't have\n\t * to read the current flags from disk. XXX\n\t */\n\tret = ARCHIVE_OK;\n\n\t/* Read the current file flags. */\n\tif (ioctl(myfd,\n#ifdef FS_IOC_GETFLAGS\n\t    FS_IOC_GETFLAGS,\n#else\n\t    EXT2_IOC_GETFLAGS,\n#endif\n\t    &oldflags) < 0)\n\t\tgoto fail;\n\n\t/* Try setting the flags as given. */\n\tnewflags = (oldflags & ~clear) | set;\n\tif (ioctl(myfd,\n#ifdef FS_IOC_SETFLAGS\n\t    FS_IOC_SETFLAGS,\n#else\n\t    EXT2_IOC_SETFLAGS,\n#endif\n\t    &newflags) >= 0)\n\t\tgoto cleanup;\n\tif (errno != EPERM)\n\t\tgoto fail;\n\n\t/* If we couldn't set all the flags, try again with a subset. */\n\tnewflags &= ~sf_mask;\n\toldflags &= sf_mask;\n\tnewflags |= oldflags;\n\tif (ioctl(myfd,\n#ifdef FS_IOC_SETFLAGS\n\t    FS_IOC_SETFLAGS,\n#else\n\t    EXT2_IOC_SETFLAGS,\n#endif\n\t    &newflags) >= 0)\n\t\tgoto cleanup;\n\n\t/* We couldn't set the flags, so report the failure. */\nfail:\n\tarchive_set_error(&a->archive, errno,\n\t    \"Failed to set file flags\");\n\tret = ARCHIVE_WARN;\ncleanup:\n\tif (fd < 0)\n\t\tclose(myfd);\n\treturn (ret);\n}", "func_hash": 157089393893012994634493859286178863768, "file_name": "None", "file_hash": null, "cwe": ["CWE-59"], "cve": "CVE-2021-31566", "cve_desc": "An improper link resolution flaw can occur while extracting an archive leading to changing modes, times, access control lists, and flags of a file outside of the archive. An attacker may provide a malicious archive to a victim user, who would trigger this flaw when trying to extract the archive. A local attacker may use this flaw to gain more privileges in a system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-31566"}
{"idx": 201925, "project": "linux", "commit_id": "e6a21a14106d9718aa4f8e115b1e474888eeba44", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?h=v5.19-rc2&id=e6a21a14106d9718aa4f8e115b1e474888eeba44", "commit_message": "media: vidtv: Check for null return of vzalloc\n\nAs the possible failure of the vzalloc(), e->encoder_buf might be NULL.\nTherefore, it should be better to check it in order\nto guarantee the success of the initialization.\nIf fails, we need to free not only 'e' but also 'e->name'.\nAlso, if the allocation for ctx fails, we need to free 'e->encoder_buf'\nelse.\n\nFixes: f90cf6079bf6 (\"media: vidtv: add a bridge driver\")\nSigned-off-by: Jiasheng Jiang \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab ", "target": 1, "func": "*vidtv_s302m_encoder_init(struct vidtv_s302m_encoder_init_args args)\n{\n\tu32 priv_sz = sizeof(struct vidtv_s302m_ctx);\n\tstruct vidtv_s302m_ctx *ctx;\n\tstruct vidtv_encoder *e;\n\n\te = kzalloc(sizeof(*e), GFP_KERNEL);\n\tif (!e)\n\t\treturn NULL;\n\n\te->id = S302M;\n\n\tif (args.name)\n\t\te->name = kstrdup(args.name, GFP_KERNEL);\n\n\te->encoder_buf = vzalloc(VIDTV_S302M_BUF_SZ);\n\te->encoder_buf_sz = VIDTV_S302M_BUF_SZ;\n\te->encoder_buf_offset = 0;\n\n\te->sample_count = 0;\n\n\te->src_buf = (args.src_buf) ? args.src_buf : NULL;\n\te->src_buf_sz = (args.src_buf) ? args.src_buf_sz : 0;\n\te->src_buf_offset = 0;\n\n\te->is_video_encoder = false;\n\n\tctx = kzalloc(priv_sz, GFP_KERNEL);\n\tif (!ctx) {\n\t\tkfree(e);\n\t\treturn NULL;\n\t}\n\n\te->ctx = ctx;\n\tctx->last_duration = 0;\n\n\te->encode = vidtv_s302m_encode;\n\te->clear = vidtv_s302m_clear;\n\n\te->es_pid = cpu_to_be16(args.es_pid);\n\te->stream_id = cpu_to_be16(PES_PRIVATE_STREAM_1);\n\n\te->sync = args.sync;\n\te->sampling_rate_hz = S302M_SAMPLING_RATE_HZ;\n\n\te->last_sample_cb = args.last_sample_cb;\n\n\te->destroy = vidtv_s302m_encoder_destroy;\n\n\tif (args.head) {\n\t\twhile (args.head->next)\n\t\t\targs.head = args.head->next;\n\n\t\targs.head->next = e;\n\t}\n\n\te->next = NULL;\n\n\treturn e;\n}", "func_hash": 307197700459438224437569031592965319191, "file_name": "vidtv_s302m.c", "file_hash": 175282066138932855398445510418968204882, "cwe": ["CWE-476"], "cve": "CVE-2022-3078", "cve_desc": "An issue was discovered in the Linux kernel through 5.16-rc6. There is a lack of check after calling vzalloc() and lack of free after allocation in drivers/media/test-drivers/vidtv/vidtv_s302m.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3078"}
{"idx": 326914, "project": "linux", "commit_id": "e6a21a14106d9718aa4f8e115b1e474888eeba44", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?h=v5.19-rc2&id=e6a21a14106d9718aa4f8e115b1e474888eeba44", "commit_message": "media: vidtv: Check for null return of vzalloc\n\nAs the possible failure of the vzalloc(), e->encoder_buf might be NULL.\nTherefore, it should be better to check it in order\nto guarantee the success of the initialization.\nIf fails, we need to free not only 'e' but also 'e->name'.\nAlso, if the allocation for ctx fails, we need to free 'e->encoder_buf'\nelse.\n\nFixes: f90cf6079bf6 (\"media: vidtv: add a bridge driver\")\nSigned-off-by: Jiasheng Jiang \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab ", "target": 0, "func": "*vidtv_s302m_encoder_init(struct vidtv_s302m_encoder_init_args args)\n{\n\tu32 priv_sz = sizeof(struct vidtv_s302m_ctx);\n\tstruct vidtv_s302m_ctx *ctx;\n\tstruct vidtv_encoder *e;\n\n\te = kzalloc(sizeof(*e), GFP_KERNEL);\n\tif (!e)\n\t\treturn NULL;\n\n\te->id = S302M;\n\n\tif (args.name)\n\t\te->name = kstrdup(args.name, GFP_KERNEL);\n\n\te->encoder_buf = vzalloc(VIDTV_S302M_BUF_SZ);\n\tif (!e->encoder_buf)\n\t\tgoto out_kfree_e;\n\n\te->encoder_buf_sz = VIDTV_S302M_BUF_SZ;\n\te->encoder_buf_offset = 0;\n\n\te->sample_count = 0;\n\n\te->src_buf = (args.src_buf) ? args.src_buf : NULL;\n\te->src_buf_sz = (args.src_buf) ? args.src_buf_sz : 0;\n\te->src_buf_offset = 0;\n\n\te->is_video_encoder = false;\n\n\tctx = kzalloc(priv_sz, GFP_KERNEL);\n\tif (!ctx)\n\t\tgoto out_kfree_buf;\n\n\te->ctx = ctx;\n\tctx->last_duration = 0;\n\n\te->encode = vidtv_s302m_encode;\n\te->clear = vidtv_s302m_clear;\n\n\te->es_pid = cpu_to_be16(args.es_pid);\n\te->stream_id = cpu_to_be16(PES_PRIVATE_STREAM_1);\n\n\te->sync = args.sync;\n\te->sampling_rate_hz = S302M_SAMPLING_RATE_HZ;\n\n\te->last_sample_cb = args.last_sample_cb;\n\n\te->destroy = vidtv_s302m_encoder_destroy;\n\n\tif (args.head) {\n\t\twhile (args.head->next)\n\t\t\targs.head = args.head->next;\n\n\t\targs.head->next = e;\n\t}\n\n\te->next = NULL;\n\n\treturn e;\n\nout_kfree_buf:\n\tkfree(e->encoder_buf);\n\nout_kfree_e:\n\tkfree(e->name);\n\tkfree(e);\n\treturn NULL;\n}", "func_hash": 87669194077051159663465560005531170449, "file_name": "vidtv_s302m.c", "file_hash": 52146840416955452550200941985312251483, "cwe": ["CWE-476"], "cve": "CVE-2022-3078", "cve_desc": "An issue was discovered in the Linux kernel through 5.16-rc6. There is a lack of check after calling vzalloc() and lack of free after allocation in drivers/media/test-drivers/vidtv/vidtv_s302m.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3078"}
{"idx": 202081, "project": "vim", "commit_id": "d25f003342aca9889067f2e839963dfeccf1fe05", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/d25f003342aca9889067f2e839963dfeccf1fe05", "commit_message": "patch 9.0.0011: reading beyond the end of the line with put command\n\nProblem:    Reading beyond the end of the line with put command.\nSolution:   Adjust the end mark position.", "target": 1, "func": "do_put(\n    int\t\tregname,\n    char_u\t*expr_result,\t// result for regname \"=\" when compiled\n    int\t\tdir,\t\t// BACKWARD for 'P', FORWARD for 'p'\n    long\tcount,\n    int\t\tflags)\n{\n    char_u\t*ptr;\n    char_u\t*newp, *oldp;\n    int\t\tyanklen;\n    int\t\ttotlen = 0;\t\t// init for gcc\n    linenr_T\tlnum;\n    colnr_T\tcol;\n    long\ti;\t\t\t// index in y_array[]\n    int\t\ty_type;\n    long\ty_size;\n    int\t\toldlen;\n    long\ty_width = 0;\n    colnr_T\tvcol;\n    int\t\tdelcount;\n    int\t\tincr = 0;\n    long\tj;\n    struct block_def bd;\n    char_u\t**y_array = NULL;\n    yankreg_T\t*y_current_used = NULL;\n    long\tnr_lines = 0;\n    pos_T\tnew_cursor;\n    int\t\tindent;\n    int\t\torig_indent = 0;\t// init for gcc\n    int\t\tindent_diff = 0;\t// init for gcc\n    int\t\tfirst_indent = TRUE;\n    int\t\tlendiff = 0;\n    pos_T\told_pos;\n    char_u\t*insert_string = NULL;\n    int\t\tallocated = FALSE;\n    long\tcnt;\n    pos_T\torig_start = curbuf->b_op_start;\n    pos_T\torig_end = curbuf->b_op_end;\n    unsigned int cur_ve_flags = get_ve_flags();\n\n#ifdef FEAT_CLIPBOARD\n    // Adjust register name for \"unnamed\" in 'clipboard'.\n    adjust_clip_reg(®name);\n    (void)may_get_selection(regname);\n#endif\n\n    if (flags & PUT_FIXINDENT)\n\torig_indent = get_indent();\n\n    curbuf->b_op_start = curwin->w_cursor;\t// default for '[ mark\n    curbuf->b_op_end = curwin->w_cursor;\t// default for '] mark\n\n    // Using inserted text works differently, because the register includes\n    // special characters (newlines, etc.).\n    if (regname == '.')\n    {\n\tif (VIsual_active)\n\t    stuffcharReadbuff(VIsual_mode);\n\t(void)stuff_inserted((dir == FORWARD ? (count == -1 ? 'o' : 'a') :\n\t\t\t\t    (count == -1 ? 'O' : 'i')), count, FALSE);\n\t// Putting the text is done later, so can't really move the cursor to\n\t// the next character.  Use \"l\" to simulate it.\n\tif ((flags & PUT_CURSEND) && gchar_cursor() != NUL)\n\t    stuffcharReadbuff('l');\n\treturn;\n    }\n\n    // For special registers '%' (file name), '#' (alternate file name) and\n    // ':' (last command line), etc. we have to create a fake yank register.\n    // For compiled code \"expr_result\" holds the expression result.\n    if (regname == '=' && expr_result != NULL)\n\tinsert_string = expr_result;\n    else if (get_spec_reg(regname, &insert_string, &allocated, TRUE)\n\t\t&& insert_string == NULL)\n\treturn;\n\n    // Autocommands may be executed when saving lines for undo.  This might\n    // make \"y_array\" invalid, so we start undo now to avoid that.\n    if (u_save(curwin->w_cursor.lnum, curwin->w_cursor.lnum + 1) == FAIL)\n\tgoto end;\n\n    if (insert_string != NULL)\n    {\n\ty_type = MCHAR;\n#ifdef FEAT_EVAL\n\tif (regname == '=')\n\t{\n\t    // For the = register we need to split the string at NL\n\t    // characters.\n\t    // Loop twice: count the number of lines and save them.\n\t    for (;;)\n\t    {\n\t\ty_size = 0;\n\t\tptr = insert_string;\n\t\twhile (ptr != NULL)\n\t\t{\n\t\t    if (y_array != NULL)\n\t\t\ty_array[y_size] = ptr;\n\t\t    ++y_size;\n\t\t    ptr = vim_strchr(ptr, '\\n');\n\t\t    if (ptr != NULL)\n\t\t    {\n\t\t\tif (y_array != NULL)\n\t\t\t    *ptr = NUL;\n\t\t\t++ptr;\n\t\t\t// A trailing '\\n' makes the register linewise.\n\t\t\tif (*ptr == NUL)\n\t\t\t{\n\t\t\t    y_type = MLINE;\n\t\t\t    break;\n\t\t\t}\n\t\t    }\n\t\t}\n\t\tif (y_array != NULL)\n\t\t    break;\n\t\ty_array = ALLOC_MULT(char_u *, y_size);\n\t\tif (y_array == NULL)\n\t\t    goto end;\n\t    }\n\t}\n\telse\n#endif\n\t{\n\t    y_size = 1;\t\t// use fake one-line yank register\n\t    y_array = &insert_string;\n\t}\n    }\n    else\n    {\n\tget_yank_register(regname, FALSE);\n\n\ty_type = y_current->y_type;\n\ty_width = y_current->y_width;\n\ty_size = y_current->y_size;\n\ty_array = y_current->y_array;\n\ty_current_used = y_current;\n    }\n\n    if (y_type == MLINE)\n    {\n\tif (flags & PUT_LINE_SPLIT)\n\t{\n\t    char_u *p;\n\n\t    // \"p\" or \"P\" in Visual mode: split the lines to put the text in\n\t    // between.\n\t    if (u_save_cursor() == FAIL)\n\t\tgoto end;\n\t    p = ml_get_cursor();\n\t    if (dir == FORWARD && *p != NUL)\n\t\tMB_PTR_ADV(p);\n\t    ptr = vim_strsave(p);\n\t    if (ptr == NULL)\n\t\tgoto end;\n\t    ml_append(curwin->w_cursor.lnum, ptr, (colnr_T)0, FALSE);\n\t    vim_free(ptr);\n\n\t    oldp = ml_get_curline();\n\t    p = oldp + curwin->w_cursor.col;\n\t    if (dir == FORWARD && *p != NUL)\n\t\tMB_PTR_ADV(p);\n\t    ptr = vim_strnsave(oldp, p - oldp);\n\t    if (ptr == NULL)\n\t\tgoto end;\n\t    ml_replace(curwin->w_cursor.lnum, ptr, FALSE);\n\t    ++nr_lines;\n\t    dir = FORWARD;\n\t}\n\tif (flags & PUT_LINE_FORWARD)\n\t{\n\t    // Must be \"p\" for a Visual block, put lines below the block.\n\t    curwin->w_cursor = curbuf->b_visual.vi_end;\n\t    dir = FORWARD;\n\t}\n\tcurbuf->b_op_start = curwin->w_cursor;\t// default for '[ mark\n\tcurbuf->b_op_end = curwin->w_cursor;\t// default for '] mark\n    }\n\n    if (flags & PUT_LINE)\t// :put command or \"p\" in Visual line mode.\n\ty_type = MLINE;\n\n    if (y_size == 0 || y_array == NULL)\n    {\n\tsemsg(_(e_nothing_in_register_str),\n\t\t  regname == 0 ? (char_u *)\"\\\"\" : transchar(regname));\n\tgoto end;\n    }\n\n    if (y_type == MBLOCK)\n    {\n\tlnum = curwin->w_cursor.lnum + y_size + 1;\n\tif (lnum > curbuf->b_ml.ml_line_count)\n\t    lnum = curbuf->b_ml.ml_line_count + 1;\n\tif (u_save(curwin->w_cursor.lnum - 1, lnum) == FAIL)\n\t    goto end;\n    }\n    else if (y_type == MLINE)\n    {\n\tlnum = curwin->w_cursor.lnum;\n#ifdef FEAT_FOLDING\n\t// Correct line number for closed fold.  Don't move the cursor yet,\n\t// u_save() uses it.\n\tif (dir == BACKWARD)\n\t    (void)hasFolding(lnum, &lnum, NULL);\n\telse\n\t    (void)hasFolding(lnum, NULL, &lnum);\n#endif\n\tif (dir == FORWARD)\n\t    ++lnum;\n\t// In an empty buffer the empty line is going to be replaced, include\n\t// it in the saved lines.\n\tif ((BUFEMPTY() ? u_save(0, 2) : u_save(lnum - 1, lnum)) == FAIL)\n\t    goto end;\n#ifdef FEAT_FOLDING\n\tif (dir == FORWARD)\n\t    curwin->w_cursor.lnum = lnum - 1;\n\telse\n\t    curwin->w_cursor.lnum = lnum;\n\tcurbuf->b_op_start = curwin->w_cursor;\t// for mark_adjust()\n#endif\n    }\n    else if (u_save_cursor() == FAIL)\n\tgoto end;\n\n    yanklen = (int)STRLEN(y_array[0]);\n\n    if (cur_ve_flags == VE_ALL && y_type == MCHAR)\n    {\n\tif (gchar_cursor() == TAB)\n\t{\n\t    int viscol = getviscol();\n\t    int ts = curbuf->b_p_ts;\n\n\t    // Don't need to insert spaces when \"p\" on the last position of a\n\t    // tab or \"P\" on the first position.\n\t    if (dir == FORWARD ?\n#ifdef FEAT_VARTABS\n\t\t    tabstop_padding(viscol, ts, curbuf->b_p_vts_array) != 1\n#else\n\t\t    ts - (viscol % ts) != 1\n#endif\n\t\t    : curwin->w_cursor.coladd > 0)\n\t\tcoladvance_force(viscol);\n\t    else\n\t\tcurwin->w_cursor.coladd = 0;\n\t}\n\telse if (curwin->w_cursor.coladd > 0 || gchar_cursor() == NUL)\n\t    coladvance_force(getviscol() + (dir == FORWARD));\n    }\n\n    lnum = curwin->w_cursor.lnum;\n    col = curwin->w_cursor.col;\n\n    // Block mode\n    if (y_type == MBLOCK)\n    {\n\tint\tc = gchar_cursor();\n\tcolnr_T\tendcol2 = 0;\n\n\tif (dir == FORWARD && c != NUL)\n\t{\n\t    if (cur_ve_flags == VE_ALL)\n\t\tgetvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);\n\t    else\n\t\tgetvcol(curwin, &curwin->w_cursor, NULL, NULL, &col);\n\n\t    if (has_mbyte)\n\t\t// move to start of next multi-byte character\n\t\tcurwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());\n\t    else\n\t    if (c != TAB || cur_ve_flags != VE_ALL)\n\t\t++curwin->w_cursor.col;\n\t    ++col;\n\t}\n\telse\n\t    getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);\n\n\tcol += curwin->w_cursor.coladd;\n\tif (cur_ve_flags == VE_ALL\n\t\t&& (curwin->w_cursor.coladd > 0\n\t\t    || endcol2 == curwin->w_cursor.col))\n\t{\n\t    if (dir == FORWARD && c == NUL)\n\t\t++col;\n\t    if (dir != FORWARD && c != NUL && curwin->w_cursor.coladd > 0)\n\t\t++curwin->w_cursor.col;\n\t    if (c == TAB)\n\t    {\n\t\tif (dir == BACKWARD && curwin->w_cursor.col)\n\t\t    curwin->w_cursor.col--;\n\t\tif (dir == FORWARD && col - 1 == endcol2)\n\t\t    curwin->w_cursor.col++;\n\t    }\n\t}\n\tcurwin->w_cursor.coladd = 0;\n\tbd.textcol = 0;\n\tfor (i = 0; i < y_size; ++i)\n\t{\n\t    int spaces = 0;\n\t    char shortline;\n\n\t    bd.startspaces = 0;\n\t    bd.endspaces = 0;\n\t    vcol = 0;\n\t    delcount = 0;\n\n\t    // add a new line\n\t    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)\n\t    {\n\t\tif (ml_append(curbuf->b_ml.ml_line_count, (char_u *)\"\",\n\t\t\t\t\t\t   (colnr_T)1, FALSE) == FAIL)\n\t\t    break;\n\t\t++nr_lines;\n\t    }\n\t    // get the old line and advance to the position to insert at\n\t    oldp = ml_get_curline();\n\t    oldlen = (int)STRLEN(oldp);\n\t    for (ptr = oldp; vcol < col && *ptr; )\n\t    {\n\t\t// Count a tab for what it's worth (if list mode not on)\n\t\tincr = lbr_chartabsize_adv(oldp, &ptr, vcol);\n\t\tvcol += incr;\n\t    }\n\t    bd.textcol = (colnr_T)(ptr - oldp);\n\n\t    shortline = (vcol < col) || (vcol == col && !*ptr) ;\n\n\t    if (vcol < col) // line too short, padd with spaces\n\t\tbd.startspaces = col - vcol;\n\t    else if (vcol > col)\n\t    {\n\t\tbd.endspaces = vcol - col;\n\t\tbd.startspaces = incr - bd.endspaces;\n\t\t--bd.textcol;\n\t\tdelcount = 1;\n\t\tif (has_mbyte)\n\t\t    bd.textcol -= (*mb_head_off)(oldp, oldp + bd.textcol);\n\t\tif (oldp[bd.textcol] != TAB)\n\t\t{\n\t\t    // Only a Tab can be split into spaces.  Other\n\t\t    // characters will have to be moved to after the\n\t\t    // block, causing misalignment.\n\t\t    delcount = 0;\n\t\t    bd.endspaces = 0;\n\t\t}\n\t    }\n\n\t    yanklen = (int)STRLEN(y_array[i]);\n\n\t    if ((flags & PUT_BLOCK_INNER) == 0)\n\t    {\n\t\t// calculate number of spaces required to fill right side of\n\t\t// block\n\t\tspaces = y_width + 1;\n\t\tfor (j = 0; j < yanklen; j++)\n\t\t    spaces -= lbr_chartabsize(NULL, &y_array[i][j], 0);\n\t\tif (spaces < 0)\n\t\t    spaces = 0;\n\t    }\n\n\t    // Insert the new text.\n\t    // First check for multiplication overflow.\n\t    if (yanklen + spaces != 0\n\t\t     && count > ((INT_MAX - (bd.startspaces + bd.endspaces))\n\t\t\t\t\t\t\t/ (yanklen + spaces)))\n\t    {\n\t\temsg(_(e_resulting_text_too_long));\n\t\tbreak;\n\t    }\n\n\t    totlen = count * (yanklen + spaces) + bd.startspaces + bd.endspaces;\n\t    newp = alloc(totlen + oldlen + 1);\n\t    if (newp == NULL)\n\t\tbreak;\n\n\t    // copy part up to cursor to new line\n\t    ptr = newp;\n\t    mch_memmove(ptr, oldp, (size_t)bd.textcol);\n\t    ptr += bd.textcol;\n\n\t    // may insert some spaces before the new text\n\t    vim_memset(ptr, ' ', (size_t)bd.startspaces);\n\t    ptr += bd.startspaces;\n\n\t    // insert the new text\n\t    for (j = 0; j < count; ++j)\n\t    {\n\t\tmch_memmove(ptr, y_array[i], (size_t)yanklen);\n\t\tptr += yanklen;\n\n\t\t// insert block's trailing spaces only if there's text behind\n\t\tif ((j < count - 1 || !shortline) && spaces)\n\t\t{\n\t\t    vim_memset(ptr, ' ', (size_t)spaces);\n\t\t    ptr += spaces;\n\t\t}\n\t    }\n\n\t    // may insert some spaces after the new text\n\t    vim_memset(ptr, ' ', (size_t)bd.endspaces);\n\t    ptr += bd.endspaces;\n\n\t    // move the text after the cursor to the end of the line.\n\t    mch_memmove(ptr, oldp + bd.textcol + delcount,\n\t\t\t\t(size_t)(oldlen - bd.textcol - delcount + 1));\n\t    ml_replace(curwin->w_cursor.lnum, newp, FALSE);\n\n\t    ++curwin->w_cursor.lnum;\n\t    if (i == 0)\n\t\tcurwin->w_cursor.col += bd.startspaces;\n\t}\n\n\tchanged_lines(lnum, 0, curwin->w_cursor.lnum, nr_lines);\n\n\t// Set '[ mark.\n\tcurbuf->b_op_start = curwin->w_cursor;\n\tcurbuf->b_op_start.lnum = lnum;\n\n\t// adjust '] mark\n\tcurbuf->b_op_end.lnum = curwin->w_cursor.lnum - 1;\n\tcurbuf->b_op_end.col = bd.textcol + totlen - 1;\n\tcurbuf->b_op_end.coladd = 0;\n\tif (flags & PUT_CURSEND)\n\t{\n\t    colnr_T len;\n\n\t    curwin->w_cursor = curbuf->b_op_end;\n\t    curwin->w_cursor.col++;\n\n\t    // in Insert mode we might be after the NUL, correct for that\n\t    len = (colnr_T)STRLEN(ml_get_curline());\n\t    if (curwin->w_cursor.col > len)\n\t\tcurwin->w_cursor.col = len;\n\t}\n\telse\n\t    curwin->w_cursor.lnum = lnum;\n    }\n    else\n    {\n\t// Character or Line mode\n\tif (y_type == MCHAR)\n\t{\n\t    // if type is MCHAR, FORWARD is the same as BACKWARD on the next\n\t    // char\n\t    if (dir == FORWARD && gchar_cursor() != NUL)\n\t    {\n\t\tif (has_mbyte)\n\t\t{\n\t\t    int bytelen = (*mb_ptr2len)(ml_get_cursor());\n\n\t\t    // put it on the next of the multi-byte character.\n\t\t    col += bytelen;\n\t\t    if (yanklen)\n\t\t    {\n\t\t\tcurwin->w_cursor.col += bytelen;\n\t\t\tcurbuf->b_op_end.col += bytelen;\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    ++col;\n\t\t    if (yanklen)\n\t\t    {\n\t\t\t++curwin->w_cursor.col;\n\t\t\t++curbuf->b_op_end.col;\n\t\t    }\n\t\t}\n\t    }\n\t    curbuf->b_op_start = curwin->w_cursor;\n\t}\n\t// Line mode: BACKWARD is the same as FORWARD on the previous line\n\telse if (dir == BACKWARD)\n\t    --lnum;\n\tnew_cursor = curwin->w_cursor;\n\n\t// simple case: insert into one line at a time\n\tif (y_type == MCHAR && y_size == 1)\n\t{\n\t    linenr_T\tend_lnum = 0; // init for gcc\n\t    linenr_T\tstart_lnum = lnum;\n\t    int\t\tfirst_byte_off = 0;\n\n\t    if (VIsual_active)\n\t    {\n\t\tend_lnum = curbuf->b_visual.vi_end.lnum;\n\t\tif (end_lnum < curbuf->b_visual.vi_start.lnum)\n\t\t    end_lnum = curbuf->b_visual.vi_start.lnum;\n\t\tif (end_lnum > start_lnum)\n\t\t{\n\t\t    pos_T   pos;\n\n\t\t    // \"col\" is valid for the first line, in following lines\n\t\t    // the virtual column needs to be used.  Matters for\n\t\t    // multi-byte characters.\n\t\t    pos.lnum = lnum;\n\t\t    pos.col = col;\n\t\t    pos.coladd = 0;\n\t\t    getvcol(curwin, &pos, NULL, &vcol, NULL);\n\t\t}\n\t    }\n\n\t    if (count == 0 || yanklen == 0)\n\t    {\n\t\tif (VIsual_active)\n\t\t    lnum = end_lnum;\n\t    }\n\t    else if (count > INT_MAX / yanklen)\n\t\t// multiplication overflow\n\t\temsg(_(e_resulting_text_too_long));\n\t    else\n\t    {\n\t\ttotlen = count * yanklen;\n\t\tdo {\n\t\t    oldp = ml_get(lnum);\n\t\t    oldlen = (int)STRLEN(oldp);\n\t\t    if (lnum > start_lnum)\n\t\t    {\n\t\t\tpos_T   pos;\n\n\t\t\tpos.lnum = lnum;\n\t\t\tif (getvpos(&pos, vcol) == OK)\n\t\t\t    col = pos.col;\n\t\t\telse\n\t\t\t    col = MAXCOL;\n\t\t    }\n\t\t    if (VIsual_active && col > oldlen)\n\t\t    {\n\t\t\tlnum++;\n\t\t\tcontinue;\n\t\t    }\n\t\t    newp = alloc(totlen + oldlen + 1);\n\t\t    if (newp == NULL)\n\t\t\tgoto end;\t// alloc() gave an error message\n\t\t    mch_memmove(newp, oldp, (size_t)col);\n\t\t    ptr = newp + col;\n\t\t    for (i = 0; i < count; ++i)\n\t\t    {\n\t\t\tmch_memmove(ptr, y_array[0], (size_t)yanklen);\n\t\t\tptr += yanklen;\n\t\t    }\n\t\t    STRMOVE(ptr, oldp + col);\n\t\t    ml_replace(lnum, newp, FALSE);\n\n\t\t    // compute the byte offset for the last character\n\t\t    first_byte_off = mb_head_off(newp, ptr - 1);\n\n\t\t    // Place cursor on last putted char.\n\t\t    if (lnum == curwin->w_cursor.lnum)\n\t\t    {\n\t\t\t// make sure curwin->w_virtcol is updated\n\t\t\tchanged_cline_bef_curs();\n\t\t\tcurwin->w_cursor.col += (colnr_T)(totlen - 1);\n\t\t    }\n\t\t    if (VIsual_active)\n\t\t\tlnum++;\n\t\t} while (VIsual_active && lnum <= end_lnum);\n\n\t\tif (VIsual_active) // reset lnum to the last visual line\n\t\t    lnum--;\n\t    }\n\n\t    // put '] at the first byte of the last character\n\t    curbuf->b_op_end = curwin->w_cursor;\n\t    curbuf->b_op_end.col -= first_byte_off;\n\n\t    // For \"CTRL-O p\" in Insert mode, put cursor after last char\n\t    if (totlen && (restart_edit != 0 || (flags & PUT_CURSEND)))\n\t\t++curwin->w_cursor.col;\n\t    else\n\t\tcurwin->w_cursor.col -= first_byte_off;\n\t    changed_bytes(lnum, col);\n\t}\n\telse\n\t{\n\t    linenr_T\tnew_lnum = new_cursor.lnum;\n\t    size_t\tlen;\n\n\t    // Insert at least one line.  When y_type is MCHAR, break the first\n\t    // line in two.\n\t    for (cnt = 1; cnt <= count; ++cnt)\n\t    {\n\t\ti = 0;\n\t\tif (y_type == MCHAR)\n\t\t{\n\t\t    // Split the current line in two at the insert position.\n\t\t    // First insert y_array[size - 1] in front of second line.\n\t\t    // Then append y_array[0] to first line.\n\t\t    lnum = new_cursor.lnum;\n\t\t    ptr = ml_get(lnum) + col;\n\t\t    totlen = (int)STRLEN(y_array[y_size - 1]);\n\t\t    newp = alloc(STRLEN(ptr) + totlen + 1);\n\t\t    if (newp == NULL)\n\t\t\tgoto error;\n\t\t    STRCPY(newp, y_array[y_size - 1]);\n\t\t    STRCAT(newp, ptr);\n\t\t    // insert second line\n\t\t    ml_append(lnum, newp, (colnr_T)0, FALSE);\n\t\t    ++new_lnum;\n\t\t    vim_free(newp);\n\n\t\t    oldp = ml_get(lnum);\n\t\t    newp = alloc(col + yanklen + 1);\n\t\t    if (newp == NULL)\n\t\t\tgoto error;\n\t\t\t\t\t    // copy first part of line\n\t\t    mch_memmove(newp, oldp, (size_t)col);\n\t\t\t\t\t    // append to first line\n\t\t    mch_memmove(newp + col, y_array[0], (size_t)(yanklen + 1));\n\t\t    ml_replace(lnum, newp, FALSE);\n\n\t\t    curwin->w_cursor.lnum = lnum;\n\t\t    i = 1;\n\t\t}\n\n\t\tfor (; i < y_size; ++i)\n\t\t{\n\t\t    if (y_type != MCHAR || i < y_size - 1)\n\t\t    {\n\t\t\tif (ml_append(lnum, y_array[i], (colnr_T)0, FALSE)\n\t\t\t\t\t\t\t\t      == FAIL)\n\t\t\t    goto error;\n\t\t\tnew_lnum++;\n\t\t    }\n\t\t    lnum++;\n\t\t    ++nr_lines;\n\t\t    if (flags & PUT_FIXINDENT)\n\t\t    {\n\t\t\told_pos = curwin->w_cursor;\n\t\t\tcurwin->w_cursor.lnum = lnum;\n\t\t\tptr = ml_get(lnum);\n\t\t\tif (cnt == count && i == y_size - 1)\n\t\t\t    lendiff = (int)STRLEN(ptr);\n\t\t\tif (*ptr == '#' && preprocs_left())\n\t\t\t    indent = 0;     // Leave # lines at start\n\t\t\telse\n\t\t\t     if (*ptr == NUL)\n\t\t\t    indent = 0;     // Ignore empty lines\n\t\t\telse if (first_indent)\n\t\t\t{\n\t\t\t    indent_diff = orig_indent - get_indent();\n\t\t\t    indent = orig_indent;\n\t\t\t    first_indent = FALSE;\n\t\t\t}\n\t\t\telse if ((indent = get_indent() + indent_diff) < 0)\n\t\t\t    indent = 0;\n\t\t\t(void)set_indent(indent, 0);\n\t\t\tcurwin->w_cursor = old_pos;\n\t\t\t// remember how many chars were removed\n\t\t\tif (cnt == count && i == y_size - 1)\n\t\t\t    lendiff -= (int)STRLEN(ml_get(lnum));\n\t\t    }\n\t\t}\n\t\tif (cnt == 1)\n\t\t    new_lnum = lnum;\n\t    }\n\nerror:\n\t    // Adjust marks.\n\t    if (y_type == MLINE)\n\t    {\n\t\tcurbuf->b_op_start.col = 0;\n\t\tif (dir == FORWARD)\n\t\t    curbuf->b_op_start.lnum++;\n\t    }\n\t    // Skip mark_adjust when adding lines after the last one, there\n\t    // can't be marks there. But still needed in diff mode.\n\t    if (curbuf->b_op_start.lnum + (y_type == MCHAR) - 1 + nr_lines\n\t\t\t\t\t\t < curbuf->b_ml.ml_line_count\n#ifdef FEAT_DIFF\n\t\t\t\t\t\t || curwin->w_p_diff\n#endif\n\t\t\t\t\t\t )\n\t\tmark_adjust(curbuf->b_op_start.lnum + (y_type == MCHAR),\n\t\t\t\t\t     (linenr_T)MAXLNUM, nr_lines, 0L);\n\n\t    // note changed text for displaying and folding\n\t    if (y_type == MCHAR)\n\t\tchanged_lines(curwin->w_cursor.lnum, col,\n\t\t\t\t\t curwin->w_cursor.lnum + 1, nr_lines);\n\t    else\n\t\tchanged_lines(curbuf->b_op_start.lnum, 0,\n\t\t\t\t\t   curbuf->b_op_start.lnum, nr_lines);\n\t    if (y_current_used != NULL && (y_current_used != y_current\n\t\t\t\t\t     || y_current->y_array != y_array))\n\t    {\n\t\t// Something invoked through changed_lines() has changed the\n\t\t// yank buffer, e.g. a GUI clipboard callback.\n\t\temsg(_(e_yank_register_changed_while_using_it));\n\t\tgoto end;\n\t    }\n\n\t    // Put the '] mark on the first byte of the last inserted character.\n\t    // Correct the length for change in indent.\n\t    curbuf->b_op_end.lnum = new_lnum;\n\t    len = STRLEN(y_array[y_size - 1]);\n\t    col = (colnr_T)len - lendiff;\n\t    if (col > 1)\n\t    {\n\t\tcurbuf->b_op_end.col = col - 1;\n\t\tif (len > 0)\n\t\t    curbuf->b_op_end.col -= mb_head_off(y_array[y_size - 1],\n\t\t\t\t\t\ty_array[y_size - 1] + len - 1);\n\t    }\n\t    else\n\t\tcurbuf->b_op_end.col = 0;\n\n\t    if (flags & PUT_CURSLINE)\n\t    {\n\t\t// \":put\": put cursor on last inserted line\n\t\tcurwin->w_cursor.lnum = lnum;\n\t\tbeginline(BL_WHITE | BL_FIX);\n\t    }\n\t    else if (flags & PUT_CURSEND)\n\t    {\n\t\t// put cursor after inserted text\n\t\tif (y_type == MLINE)\n\t\t{\n\t\t    if (lnum >= curbuf->b_ml.ml_line_count)\n\t\t\tcurwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;\n\t\t    else\n\t\t\tcurwin->w_cursor.lnum = lnum + 1;\n\t\t    curwin->w_cursor.col = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t    curwin->w_cursor.lnum = new_lnum;\n\t\t    curwin->w_cursor.col = col;\n\t\t    curbuf->b_op_end = curwin->w_cursor;\n\t\t    if (col > 1)\n\t\t\tcurbuf->b_op_end.col = col - 1;\n\t\t}\n\t    }\n\t    else if (y_type == MLINE)\n\t    {\n\t\t// put cursor on first non-blank in first inserted line\n\t\tcurwin->w_cursor.col = 0;\n\t\tif (dir == FORWARD)\n\t\t    ++curwin->w_cursor.lnum;\n\t\tbeginline(BL_WHITE | BL_FIX);\n\t    }\n\t    else\t// put cursor on first inserted character\n\t\tcurwin->w_cursor = new_cursor;\n\t}\n    }\n\n    msgmore(nr_lines);\n    curwin->w_set_curswant = TRUE;\n\nend:\n    if (cmdmod.cmod_flags & CMOD_LOCKMARKS)\n    {\n\tcurbuf->b_op_start = orig_start;\n\tcurbuf->b_op_end = orig_end;\n    }\n    if (allocated)\n\tvim_free(insert_string);\n    if (regname == '=')\n\tvim_free(y_array);\n\n    VIsual_active = FALSE;\n\n    // If the cursor is past the end of the line put it at the end.\n    adjust_cursor_eol();\n}", "func_hash": 187254536140993008558175231359072054124, "file_name": "register.c", "file_hash": 222058692998248357317124529383370719702, "cwe": ["CWE-787"], "cve": "CVE-2022-2264", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2264"}
{"idx": 328807, "project": "vim", "commit_id": "d25f003342aca9889067f2e839963dfeccf1fe05", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/d25f003342aca9889067f2e839963dfeccf1fe05", "commit_message": "patch 9.0.0011: reading beyond the end of the line with put command\n\nProblem:    Reading beyond the end of the line with put command.\nSolution:   Adjust the end mark position.", "target": 0, "func": "do_put(\n    int\t\tregname,\n    char_u\t*expr_result,\t// result for regname \"=\" when compiled\n    int\t\tdir,\t\t// BACKWARD for 'P', FORWARD for 'p'\n    long\tcount,\n    int\t\tflags)\n{\n    char_u\t*ptr;\n    char_u\t*newp, *oldp;\n    int\t\tyanklen;\n    int\t\ttotlen = 0;\t\t// init for gcc\n    linenr_T\tlnum;\n    colnr_T\tcol;\n    long\ti;\t\t\t// index in y_array[]\n    int\t\ty_type;\n    long\ty_size;\n    int\t\toldlen;\n    long\ty_width = 0;\n    colnr_T\tvcol;\n    int\t\tdelcount;\n    int\t\tincr = 0;\n    long\tj;\n    struct block_def bd;\n    char_u\t**y_array = NULL;\n    yankreg_T\t*y_current_used = NULL;\n    long\tnr_lines = 0;\n    pos_T\tnew_cursor;\n    int\t\tindent;\n    int\t\torig_indent = 0;\t// init for gcc\n    int\t\tindent_diff = 0;\t// init for gcc\n    int\t\tfirst_indent = TRUE;\n    int\t\tlendiff = 0;\n    pos_T\told_pos;\n    char_u\t*insert_string = NULL;\n    int\t\tallocated = FALSE;\n    long\tcnt;\n    pos_T\torig_start = curbuf->b_op_start;\n    pos_T\torig_end = curbuf->b_op_end;\n    unsigned int cur_ve_flags = get_ve_flags();\n\n#ifdef FEAT_CLIPBOARD\n    // Adjust register name for \"unnamed\" in 'clipboard'.\n    adjust_clip_reg(®name);\n    (void)may_get_selection(regname);\n#endif\n\n    if (flags & PUT_FIXINDENT)\n\torig_indent = get_indent();\n\n    curbuf->b_op_start = curwin->w_cursor;\t// default for '[ mark\n    curbuf->b_op_end = curwin->w_cursor;\t// default for '] mark\n\n    // Using inserted text works differently, because the register includes\n    // special characters (newlines, etc.).\n    if (regname == '.')\n    {\n\tif (VIsual_active)\n\t    stuffcharReadbuff(VIsual_mode);\n\t(void)stuff_inserted((dir == FORWARD ? (count == -1 ? 'o' : 'a') :\n\t\t\t\t    (count == -1 ? 'O' : 'i')), count, FALSE);\n\t// Putting the text is done later, so can't really move the cursor to\n\t// the next character.  Use \"l\" to simulate it.\n\tif ((flags & PUT_CURSEND) && gchar_cursor() != NUL)\n\t    stuffcharReadbuff('l');\n\treturn;\n    }\n\n    // For special registers '%' (file name), '#' (alternate file name) and\n    // ':' (last command line), etc. we have to create a fake yank register.\n    // For compiled code \"expr_result\" holds the expression result.\n    if (regname == '=' && expr_result != NULL)\n\tinsert_string = expr_result;\n    else if (get_spec_reg(regname, &insert_string, &allocated, TRUE)\n\t\t&& insert_string == NULL)\n\treturn;\n\n    // Autocommands may be executed when saving lines for undo.  This might\n    // make \"y_array\" invalid, so we start undo now to avoid that.\n    if (u_save(curwin->w_cursor.lnum, curwin->w_cursor.lnum + 1) == FAIL)\n\tgoto end;\n\n    if (insert_string != NULL)\n    {\n\ty_type = MCHAR;\n#ifdef FEAT_EVAL\n\tif (regname == '=')\n\t{\n\t    // For the = register we need to split the string at NL\n\t    // characters.\n\t    // Loop twice: count the number of lines and save them.\n\t    for (;;)\n\t    {\n\t\ty_size = 0;\n\t\tptr = insert_string;\n\t\twhile (ptr != NULL)\n\t\t{\n\t\t    if (y_array != NULL)\n\t\t\ty_array[y_size] = ptr;\n\t\t    ++y_size;\n\t\t    ptr = vim_strchr(ptr, '\\n');\n\t\t    if (ptr != NULL)\n\t\t    {\n\t\t\tif (y_array != NULL)\n\t\t\t    *ptr = NUL;\n\t\t\t++ptr;\n\t\t\t// A trailing '\\n' makes the register linewise.\n\t\t\tif (*ptr == NUL)\n\t\t\t{\n\t\t\t    y_type = MLINE;\n\t\t\t    break;\n\t\t\t}\n\t\t    }\n\t\t}\n\t\tif (y_array != NULL)\n\t\t    break;\n\t\ty_array = ALLOC_MULT(char_u *, y_size);\n\t\tif (y_array == NULL)\n\t\t    goto end;\n\t    }\n\t}\n\telse\n#endif\n\t{\n\t    y_size = 1;\t\t// use fake one-line yank register\n\t    y_array = &insert_string;\n\t}\n    }\n    else\n    {\n\tget_yank_register(regname, FALSE);\n\n\ty_type = y_current->y_type;\n\ty_width = y_current->y_width;\n\ty_size = y_current->y_size;\n\ty_array = y_current->y_array;\n\ty_current_used = y_current;\n    }\n\n    if (y_type == MLINE)\n    {\n\tif (flags & PUT_LINE_SPLIT)\n\t{\n\t    char_u *p;\n\n\t    // \"p\" or \"P\" in Visual mode: split the lines to put the text in\n\t    // between.\n\t    if (u_save_cursor() == FAIL)\n\t\tgoto end;\n\t    p = ml_get_cursor();\n\t    if (dir == FORWARD && *p != NUL)\n\t\tMB_PTR_ADV(p);\n\t    ptr = vim_strsave(p);\n\t    if (ptr == NULL)\n\t\tgoto end;\n\t    ml_append(curwin->w_cursor.lnum, ptr, (colnr_T)0, FALSE);\n\t    vim_free(ptr);\n\n\t    oldp = ml_get_curline();\n\t    p = oldp + curwin->w_cursor.col;\n\t    if (dir == FORWARD && *p != NUL)\n\t\tMB_PTR_ADV(p);\n\t    ptr = vim_strnsave(oldp, p - oldp);\n\t    if (ptr == NULL)\n\t\tgoto end;\n\t    ml_replace(curwin->w_cursor.lnum, ptr, FALSE);\n\t    ++nr_lines;\n\t    dir = FORWARD;\n\t}\n\tif (flags & PUT_LINE_FORWARD)\n\t{\n\t    // Must be \"p\" for a Visual block, put lines below the block.\n\t    curwin->w_cursor = curbuf->b_visual.vi_end;\n\t    dir = FORWARD;\n\t}\n\tcurbuf->b_op_start = curwin->w_cursor;\t// default for '[ mark\n\tcurbuf->b_op_end = curwin->w_cursor;\t// default for '] mark\n    }\n\n    if (flags & PUT_LINE)\t// :put command or \"p\" in Visual line mode.\n\ty_type = MLINE;\n\n    if (y_size == 0 || y_array == NULL)\n    {\n\tsemsg(_(e_nothing_in_register_str),\n\t\t  regname == 0 ? (char_u *)\"\\\"\" : transchar(regname));\n\tgoto end;\n    }\n\n    if (y_type == MBLOCK)\n    {\n\tlnum = curwin->w_cursor.lnum + y_size + 1;\n\tif (lnum > curbuf->b_ml.ml_line_count)\n\t    lnum = curbuf->b_ml.ml_line_count + 1;\n\tif (u_save(curwin->w_cursor.lnum - 1, lnum) == FAIL)\n\t    goto end;\n    }\n    else if (y_type == MLINE)\n    {\n\tlnum = curwin->w_cursor.lnum;\n#ifdef FEAT_FOLDING\n\t// Correct line number for closed fold.  Don't move the cursor yet,\n\t// u_save() uses it.\n\tif (dir == BACKWARD)\n\t    (void)hasFolding(lnum, &lnum, NULL);\n\telse\n\t    (void)hasFolding(lnum, NULL, &lnum);\n#endif\n\tif (dir == FORWARD)\n\t    ++lnum;\n\t// In an empty buffer the empty line is going to be replaced, include\n\t// it in the saved lines.\n\tif ((BUFEMPTY() ? u_save(0, 2) : u_save(lnum - 1, lnum)) == FAIL)\n\t    goto end;\n#ifdef FEAT_FOLDING\n\tif (dir == FORWARD)\n\t    curwin->w_cursor.lnum = lnum - 1;\n\telse\n\t    curwin->w_cursor.lnum = lnum;\n\tcurbuf->b_op_start = curwin->w_cursor;\t// for mark_adjust()\n#endif\n    }\n    else if (u_save_cursor() == FAIL)\n\tgoto end;\n\n    yanklen = (int)STRLEN(y_array[0]);\n\n    if (cur_ve_flags == VE_ALL && y_type == MCHAR)\n    {\n\tif (gchar_cursor() == TAB)\n\t{\n\t    int viscol = getviscol();\n\t    int ts = curbuf->b_p_ts;\n\n\t    // Don't need to insert spaces when \"p\" on the last position of a\n\t    // tab or \"P\" on the first position.\n\t    if (dir == FORWARD ?\n#ifdef FEAT_VARTABS\n\t\t    tabstop_padding(viscol, ts, curbuf->b_p_vts_array) != 1\n#else\n\t\t    ts - (viscol % ts) != 1\n#endif\n\t\t    : curwin->w_cursor.coladd > 0)\n\t\tcoladvance_force(viscol);\n\t    else\n\t\tcurwin->w_cursor.coladd = 0;\n\t}\n\telse if (curwin->w_cursor.coladd > 0 || gchar_cursor() == NUL)\n\t    coladvance_force(getviscol() + (dir == FORWARD));\n    }\n\n    lnum = curwin->w_cursor.lnum;\n    col = curwin->w_cursor.col;\n\n    // Block mode\n    if (y_type == MBLOCK)\n    {\n\tint\tc = gchar_cursor();\n\tcolnr_T\tendcol2 = 0;\n\n\tif (dir == FORWARD && c != NUL)\n\t{\n\t    if (cur_ve_flags == VE_ALL)\n\t\tgetvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);\n\t    else\n\t\tgetvcol(curwin, &curwin->w_cursor, NULL, NULL, &col);\n\n\t    if (has_mbyte)\n\t\t// move to start of next multi-byte character\n\t\tcurwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());\n\t    else\n\t    if (c != TAB || cur_ve_flags != VE_ALL)\n\t\t++curwin->w_cursor.col;\n\t    ++col;\n\t}\n\telse\n\t    getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);\n\n\tcol += curwin->w_cursor.coladd;\n\tif (cur_ve_flags == VE_ALL\n\t\t&& (curwin->w_cursor.coladd > 0\n\t\t    || endcol2 == curwin->w_cursor.col))\n\t{\n\t    if (dir == FORWARD && c == NUL)\n\t\t++col;\n\t    if (dir != FORWARD && c != NUL && curwin->w_cursor.coladd > 0)\n\t\t++curwin->w_cursor.col;\n\t    if (c == TAB)\n\t    {\n\t\tif (dir == BACKWARD && curwin->w_cursor.col)\n\t\t    curwin->w_cursor.col--;\n\t\tif (dir == FORWARD && col - 1 == endcol2)\n\t\t    curwin->w_cursor.col++;\n\t    }\n\t}\n\tcurwin->w_cursor.coladd = 0;\n\tbd.textcol = 0;\n\tfor (i = 0; i < y_size; ++i)\n\t{\n\t    int spaces = 0;\n\t    char shortline;\n\n\t    bd.startspaces = 0;\n\t    bd.endspaces = 0;\n\t    vcol = 0;\n\t    delcount = 0;\n\n\t    // add a new line\n\t    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)\n\t    {\n\t\tif (ml_append(curbuf->b_ml.ml_line_count, (char_u *)\"\",\n\t\t\t\t\t\t   (colnr_T)1, FALSE) == FAIL)\n\t\t    break;\n\t\t++nr_lines;\n\t    }\n\t    // get the old line and advance to the position to insert at\n\t    oldp = ml_get_curline();\n\t    oldlen = (int)STRLEN(oldp);\n\t    for (ptr = oldp; vcol < col && *ptr; )\n\t    {\n\t\t// Count a tab for what it's worth (if list mode not on)\n\t\tincr = lbr_chartabsize_adv(oldp, &ptr, vcol);\n\t\tvcol += incr;\n\t    }\n\t    bd.textcol = (colnr_T)(ptr - oldp);\n\n\t    shortline = (vcol < col) || (vcol == col && !*ptr) ;\n\n\t    if (vcol < col) // line too short, padd with spaces\n\t\tbd.startspaces = col - vcol;\n\t    else if (vcol > col)\n\t    {\n\t\tbd.endspaces = vcol - col;\n\t\tbd.startspaces = incr - bd.endspaces;\n\t\t--bd.textcol;\n\t\tdelcount = 1;\n\t\tif (has_mbyte)\n\t\t    bd.textcol -= (*mb_head_off)(oldp, oldp + bd.textcol);\n\t\tif (oldp[bd.textcol] != TAB)\n\t\t{\n\t\t    // Only a Tab can be split into spaces.  Other\n\t\t    // characters will have to be moved to after the\n\t\t    // block, causing misalignment.\n\t\t    delcount = 0;\n\t\t    bd.endspaces = 0;\n\t\t}\n\t    }\n\n\t    yanklen = (int)STRLEN(y_array[i]);\n\n\t    if ((flags & PUT_BLOCK_INNER) == 0)\n\t    {\n\t\t// calculate number of spaces required to fill right side of\n\t\t// block\n\t\tspaces = y_width + 1;\n\t\tfor (j = 0; j < yanklen; j++)\n\t\t    spaces -= lbr_chartabsize(NULL, &y_array[i][j], 0);\n\t\tif (spaces < 0)\n\t\t    spaces = 0;\n\t    }\n\n\t    // Insert the new text.\n\t    // First check for multiplication overflow.\n\t    if (yanklen + spaces != 0\n\t\t     && count > ((INT_MAX - (bd.startspaces + bd.endspaces))\n\t\t\t\t\t\t\t/ (yanklen + spaces)))\n\t    {\n\t\temsg(_(e_resulting_text_too_long));\n\t\tbreak;\n\t    }\n\n\t    totlen = count * (yanklen + spaces) + bd.startspaces + bd.endspaces;\n\t    newp = alloc(totlen + oldlen + 1);\n\t    if (newp == NULL)\n\t\tbreak;\n\n\t    // copy part up to cursor to new line\n\t    ptr = newp;\n\t    mch_memmove(ptr, oldp, (size_t)bd.textcol);\n\t    ptr += bd.textcol;\n\n\t    // may insert some spaces before the new text\n\t    vim_memset(ptr, ' ', (size_t)bd.startspaces);\n\t    ptr += bd.startspaces;\n\n\t    // insert the new text\n\t    for (j = 0; j < count; ++j)\n\t    {\n\t\tmch_memmove(ptr, y_array[i], (size_t)yanklen);\n\t\tptr += yanklen;\n\n\t\t// insert block's trailing spaces only if there's text behind\n\t\tif ((j < count - 1 || !shortline) && spaces)\n\t\t{\n\t\t    vim_memset(ptr, ' ', (size_t)spaces);\n\t\t    ptr += spaces;\n\t\t}\n\t\telse\n\t\t    totlen -= spaces;  // didn't use these spaces\n\t    }\n\n\t    // may insert some spaces after the new text\n\t    vim_memset(ptr, ' ', (size_t)bd.endspaces);\n\t    ptr += bd.endspaces;\n\n\t    // move the text after the cursor to the end of the line.\n\t    mch_memmove(ptr, oldp + bd.textcol + delcount,\n\t\t\t\t(size_t)(oldlen - bd.textcol - delcount + 1));\n\t    ml_replace(curwin->w_cursor.lnum, newp, FALSE);\n\n\t    ++curwin->w_cursor.lnum;\n\t    if (i == 0)\n\t\tcurwin->w_cursor.col += bd.startspaces;\n\t}\n\n\tchanged_lines(lnum, 0, curwin->w_cursor.lnum, nr_lines);\n\n\t// Set '[ mark.\n\tcurbuf->b_op_start = curwin->w_cursor;\n\tcurbuf->b_op_start.lnum = lnum;\n\n\t// adjust '] mark\n\tcurbuf->b_op_end.lnum = curwin->w_cursor.lnum - 1;\n\tcurbuf->b_op_end.col = bd.textcol + totlen - 1;\n\tcurbuf->b_op_end.coladd = 0;\n\tif (flags & PUT_CURSEND)\n\t{\n\t    colnr_T len;\n\n\t    curwin->w_cursor = curbuf->b_op_end;\n\t    curwin->w_cursor.col++;\n\n\t    // in Insert mode we might be after the NUL, correct for that\n\t    len = (colnr_T)STRLEN(ml_get_curline());\n\t    if (curwin->w_cursor.col > len)\n\t\tcurwin->w_cursor.col = len;\n\t}\n\telse\n\t    curwin->w_cursor.lnum = lnum;\n    }\n    else\n    {\n\t// Character or Line mode\n\tif (y_type == MCHAR)\n\t{\n\t    // if type is MCHAR, FORWARD is the same as BACKWARD on the next\n\t    // char\n\t    if (dir == FORWARD && gchar_cursor() != NUL)\n\t    {\n\t\tif (has_mbyte)\n\t\t{\n\t\t    int bytelen = (*mb_ptr2len)(ml_get_cursor());\n\n\t\t    // put it on the next of the multi-byte character.\n\t\t    col += bytelen;\n\t\t    if (yanklen)\n\t\t    {\n\t\t\tcurwin->w_cursor.col += bytelen;\n\t\t\tcurbuf->b_op_end.col += bytelen;\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    ++col;\n\t\t    if (yanklen)\n\t\t    {\n\t\t\t++curwin->w_cursor.col;\n\t\t\t++curbuf->b_op_end.col;\n\t\t    }\n\t\t}\n\t    }\n\t    curbuf->b_op_start = curwin->w_cursor;\n\t}\n\t// Line mode: BACKWARD is the same as FORWARD on the previous line\n\telse if (dir == BACKWARD)\n\t    --lnum;\n\tnew_cursor = curwin->w_cursor;\n\n\t// simple case: insert into one line at a time\n\tif (y_type == MCHAR && y_size == 1)\n\t{\n\t    linenr_T\tend_lnum = 0; // init for gcc\n\t    linenr_T\tstart_lnum = lnum;\n\t    int\t\tfirst_byte_off = 0;\n\n\t    if (VIsual_active)\n\t    {\n\t\tend_lnum = curbuf->b_visual.vi_end.lnum;\n\t\tif (end_lnum < curbuf->b_visual.vi_start.lnum)\n\t\t    end_lnum = curbuf->b_visual.vi_start.lnum;\n\t\tif (end_lnum > start_lnum)\n\t\t{\n\t\t    pos_T   pos;\n\n\t\t    // \"col\" is valid for the first line, in following lines\n\t\t    // the virtual column needs to be used.  Matters for\n\t\t    // multi-byte characters.\n\t\t    pos.lnum = lnum;\n\t\t    pos.col = col;\n\t\t    pos.coladd = 0;\n\t\t    getvcol(curwin, &pos, NULL, &vcol, NULL);\n\t\t}\n\t    }\n\n\t    if (count == 0 || yanklen == 0)\n\t    {\n\t\tif (VIsual_active)\n\t\t    lnum = end_lnum;\n\t    }\n\t    else if (count > INT_MAX / yanklen)\n\t\t// multiplication overflow\n\t\temsg(_(e_resulting_text_too_long));\n\t    else\n\t    {\n\t\ttotlen = count * yanklen;\n\t\tdo {\n\t\t    oldp = ml_get(lnum);\n\t\t    oldlen = (int)STRLEN(oldp);\n\t\t    if (lnum > start_lnum)\n\t\t    {\n\t\t\tpos_T   pos;\n\n\t\t\tpos.lnum = lnum;\n\t\t\tif (getvpos(&pos, vcol) == OK)\n\t\t\t    col = pos.col;\n\t\t\telse\n\t\t\t    col = MAXCOL;\n\t\t    }\n\t\t    if (VIsual_active && col > oldlen)\n\t\t    {\n\t\t\tlnum++;\n\t\t\tcontinue;\n\t\t    }\n\t\t    newp = alloc(totlen + oldlen + 1);\n\t\t    if (newp == NULL)\n\t\t\tgoto end;\t// alloc() gave an error message\n\t\t    mch_memmove(newp, oldp, (size_t)col);\n\t\t    ptr = newp + col;\n\t\t    for (i = 0; i < count; ++i)\n\t\t    {\n\t\t\tmch_memmove(ptr, y_array[0], (size_t)yanklen);\n\t\t\tptr += yanklen;\n\t\t    }\n\t\t    STRMOVE(ptr, oldp + col);\n\t\t    ml_replace(lnum, newp, FALSE);\n\n\t\t    // compute the byte offset for the last character\n\t\t    first_byte_off = mb_head_off(newp, ptr - 1);\n\n\t\t    // Place cursor on last putted char.\n\t\t    if (lnum == curwin->w_cursor.lnum)\n\t\t    {\n\t\t\t// make sure curwin->w_virtcol is updated\n\t\t\tchanged_cline_bef_curs();\n\t\t\tcurwin->w_cursor.col += (colnr_T)(totlen - 1);\n\t\t    }\n\t\t    if (VIsual_active)\n\t\t\tlnum++;\n\t\t} while (VIsual_active && lnum <= end_lnum);\n\n\t\tif (VIsual_active) // reset lnum to the last visual line\n\t\t    lnum--;\n\t    }\n\n\t    // put '] at the first byte of the last character\n\t    curbuf->b_op_end = curwin->w_cursor;\n\t    curbuf->b_op_end.col -= first_byte_off;\n\n\t    // For \"CTRL-O p\" in Insert mode, put cursor after last char\n\t    if (totlen && (restart_edit != 0 || (flags & PUT_CURSEND)))\n\t\t++curwin->w_cursor.col;\n\t    else\n\t\tcurwin->w_cursor.col -= first_byte_off;\n\t    changed_bytes(lnum, col);\n\t}\n\telse\n\t{\n\t    linenr_T\tnew_lnum = new_cursor.lnum;\n\t    size_t\tlen;\n\n\t    // Insert at least one line.  When y_type is MCHAR, break the first\n\t    // line in two.\n\t    for (cnt = 1; cnt <= count; ++cnt)\n\t    {\n\t\ti = 0;\n\t\tif (y_type == MCHAR)\n\t\t{\n\t\t    // Split the current line in two at the insert position.\n\t\t    // First insert y_array[size - 1] in front of second line.\n\t\t    // Then append y_array[0] to first line.\n\t\t    lnum = new_cursor.lnum;\n\t\t    ptr = ml_get(lnum) + col;\n\t\t    totlen = (int)STRLEN(y_array[y_size - 1]);\n\t\t    newp = alloc(STRLEN(ptr) + totlen + 1);\n\t\t    if (newp == NULL)\n\t\t\tgoto error;\n\t\t    STRCPY(newp, y_array[y_size - 1]);\n\t\t    STRCAT(newp, ptr);\n\t\t    // insert second line\n\t\t    ml_append(lnum, newp, (colnr_T)0, FALSE);\n\t\t    ++new_lnum;\n\t\t    vim_free(newp);\n\n\t\t    oldp = ml_get(lnum);\n\t\t    newp = alloc(col + yanklen + 1);\n\t\t    if (newp == NULL)\n\t\t\tgoto error;\n\t\t\t\t\t    // copy first part of line\n\t\t    mch_memmove(newp, oldp, (size_t)col);\n\t\t\t\t\t    // append to first line\n\t\t    mch_memmove(newp + col, y_array[0], (size_t)(yanklen + 1));\n\t\t    ml_replace(lnum, newp, FALSE);\n\n\t\t    curwin->w_cursor.lnum = lnum;\n\t\t    i = 1;\n\t\t}\n\n\t\tfor (; i < y_size; ++i)\n\t\t{\n\t\t    if (y_type != MCHAR || i < y_size - 1)\n\t\t    {\n\t\t\tif (ml_append(lnum, y_array[i], (colnr_T)0, FALSE)\n\t\t\t\t\t\t\t\t      == FAIL)\n\t\t\t    goto error;\n\t\t\tnew_lnum++;\n\t\t    }\n\t\t    lnum++;\n\t\t    ++nr_lines;\n\t\t    if (flags & PUT_FIXINDENT)\n\t\t    {\n\t\t\told_pos = curwin->w_cursor;\n\t\t\tcurwin->w_cursor.lnum = lnum;\n\t\t\tptr = ml_get(lnum);\n\t\t\tif (cnt == count && i == y_size - 1)\n\t\t\t    lendiff = (int)STRLEN(ptr);\n\t\t\tif (*ptr == '#' && preprocs_left())\n\t\t\t    indent = 0;     // Leave # lines at start\n\t\t\telse\n\t\t\t     if (*ptr == NUL)\n\t\t\t    indent = 0;     // Ignore empty lines\n\t\t\telse if (first_indent)\n\t\t\t{\n\t\t\t    indent_diff = orig_indent - get_indent();\n\t\t\t    indent = orig_indent;\n\t\t\t    first_indent = FALSE;\n\t\t\t}\n\t\t\telse if ((indent = get_indent() + indent_diff) < 0)\n\t\t\t    indent = 0;\n\t\t\t(void)set_indent(indent, 0);\n\t\t\tcurwin->w_cursor = old_pos;\n\t\t\t// remember how many chars were removed\n\t\t\tif (cnt == count && i == y_size - 1)\n\t\t\t    lendiff -= (int)STRLEN(ml_get(lnum));\n\t\t    }\n\t\t}\n\t\tif (cnt == 1)\n\t\t    new_lnum = lnum;\n\t    }\n\nerror:\n\t    // Adjust marks.\n\t    if (y_type == MLINE)\n\t    {\n\t\tcurbuf->b_op_start.col = 0;\n\t\tif (dir == FORWARD)\n\t\t    curbuf->b_op_start.lnum++;\n\t    }\n\t    // Skip mark_adjust when adding lines after the last one, there\n\t    // can't be marks there. But still needed in diff mode.\n\t    if (curbuf->b_op_start.lnum + (y_type == MCHAR) - 1 + nr_lines\n\t\t\t\t\t\t < curbuf->b_ml.ml_line_count\n#ifdef FEAT_DIFF\n\t\t\t\t\t\t || curwin->w_p_diff\n#endif\n\t\t\t\t\t\t )\n\t\tmark_adjust(curbuf->b_op_start.lnum + (y_type == MCHAR),\n\t\t\t\t\t     (linenr_T)MAXLNUM, nr_lines, 0L);\n\n\t    // note changed text for displaying and folding\n\t    if (y_type == MCHAR)\n\t\tchanged_lines(curwin->w_cursor.lnum, col,\n\t\t\t\t\t curwin->w_cursor.lnum + 1, nr_lines);\n\t    else\n\t\tchanged_lines(curbuf->b_op_start.lnum, 0,\n\t\t\t\t\t   curbuf->b_op_start.lnum, nr_lines);\n\t    if (y_current_used != NULL && (y_current_used != y_current\n\t\t\t\t\t     || y_current->y_array != y_array))\n\t    {\n\t\t// Something invoked through changed_lines() has changed the\n\t\t// yank buffer, e.g. a GUI clipboard callback.\n\t\temsg(_(e_yank_register_changed_while_using_it));\n\t\tgoto end;\n\t    }\n\n\t    // Put the '] mark on the first byte of the last inserted character.\n\t    // Correct the length for change in indent.\n\t    curbuf->b_op_end.lnum = new_lnum;\n\t    len = STRLEN(y_array[y_size - 1]);\n\t    col = (colnr_T)len - lendiff;\n\t    if (col > 1)\n\t    {\n\t\tcurbuf->b_op_end.col = col - 1;\n\t\tif (len > 0)\n\t\t    curbuf->b_op_end.col -= mb_head_off(y_array[y_size - 1],\n\t\t\t\t\t\ty_array[y_size - 1] + len - 1);\n\t    }\n\t    else\n\t\tcurbuf->b_op_end.col = 0;\n\n\t    if (flags & PUT_CURSLINE)\n\t    {\n\t\t// \":put\": put cursor on last inserted line\n\t\tcurwin->w_cursor.lnum = lnum;\n\t\tbeginline(BL_WHITE | BL_FIX);\n\t    }\n\t    else if (flags & PUT_CURSEND)\n\t    {\n\t\t// put cursor after inserted text\n\t\tif (y_type == MLINE)\n\t\t{\n\t\t    if (lnum >= curbuf->b_ml.ml_line_count)\n\t\t\tcurwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;\n\t\t    else\n\t\t\tcurwin->w_cursor.lnum = lnum + 1;\n\t\t    curwin->w_cursor.col = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t    curwin->w_cursor.lnum = new_lnum;\n\t\t    curwin->w_cursor.col = col;\n\t\t    curbuf->b_op_end = curwin->w_cursor;\n\t\t    if (col > 1)\n\t\t\tcurbuf->b_op_end.col = col - 1;\n\t\t}\n\t    }\n\t    else if (y_type == MLINE)\n\t    {\n\t\t// put cursor on first non-blank in first inserted line\n\t\tcurwin->w_cursor.col = 0;\n\t\tif (dir == FORWARD)\n\t\t    ++curwin->w_cursor.lnum;\n\t\tbeginline(BL_WHITE | BL_FIX);\n\t    }\n\t    else\t// put cursor on first inserted character\n\t\tcurwin->w_cursor = new_cursor;\n\t}\n    }\n\n    msgmore(nr_lines);\n    curwin->w_set_curswant = TRUE;\n\nend:\n    if (cmdmod.cmod_flags & CMOD_LOCKMARKS)\n    {\n\tcurbuf->b_op_start = orig_start;\n\tcurbuf->b_op_end = orig_end;\n    }\n    if (allocated)\n\tvim_free(insert_string);\n    if (regname == '=')\n\tvim_free(y_array);\n\n    VIsual_active = FALSE;\n\n    // If the cursor is past the end of the line put it at the end.\n    adjust_cursor_eol();\n}", "func_hash": 133908805751953919427107952660215245985, "file_name": "register.c", "file_hash": 165298981279959476687221469555741136053, "cwe": ["CWE-787"], "cve": "CVE-2022-2264", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2264"}
{"idx": 202082, "project": "radare2", "commit_id": "ecc44b6a2f18ee70ac133365de0e509d26d5e168", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/ecc44b6a2f18ee70ac133365de0e509d26d5e168", "commit_message": "Fix oobread in java parser ##crash\n\n* Reported by @bet4it via @huntrdev\n* BountyID c8f4c2de-7d96-4ad4-857a-c099effca2d6\n* Reproducer: bootstrap.class", "target": 1, "func": "R_API RBinJavaAttrInfo *r_bin_java_bootstrap_methods_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tRBinJavaBootStrapMethod *bsm = NULL;\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (attr) {\n\t\tattr->type = R_BIN_JAVA_ATTR_TYPE_BOOTSTRAP_METHODS_ATTR;\n\t\tattr->info.bootstrap_methods_attr.num_bootstrap_methods = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tattr->info.bootstrap_methods_attr.bootstrap_methods = r_list_newf (r_bin_java_bootstrap_method_free);\n\t\tfor (i = 0; i < attr->info.bootstrap_methods_attr.num_bootstrap_methods; i++) {\n\t\t\t// bsm = r_bin_java_bootstrap_method_new (bin, bin->b->cur);\n\t\t\tif (offset >= sz) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbsm = r_bin_java_bootstrap_method_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\t\tif (bsm) {\n\t\t\t\toffset += bsm->size;\n\t\t\t\tr_list_append (attr->info.bootstrap_methods_attr.bootstrap_methods, (void *) bsm);\n\t\t\t} else {\n\t\t\t\t// TODO eprintf Failed to read the %d boot strap method.\n\t\t\t}\n\t\t}\n\t\tattr->size = offset;\n\t}\n\treturn attr;\n}", "func_hash": 121022317607075696066263684863636152093, "file_name": "class.c", "file_hash": 47177688403428674570419012647523968387, "cwe": ["CWE-125"], "cve": "CVE-2022-1452", "cve_desc": "Out-of-bounds Read in r_bin_java_bootstrap_methods_attr_new function in GitHub repository radareorg/radare2 prior to 5.7.0. The bug causes the program reads data past the end 2f the intented buffer. Typically, this can allow attackers to read sensitive information from other memory locations or cause a crash. More details see [CWE-125: Out-of-bounds read](https://cwe.mitre.org/data/definitions/125.html).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1452"}
{"idx": 328836, "project": "radare2", "commit_id": "ecc44b6a2f18ee70ac133365de0e509d26d5e168", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/ecc44b6a2f18ee70ac133365de0e509d26d5e168", "commit_message": "Fix oobread in java parser ##crash\n\n* Reported by @bet4it via @huntrdev\n* BountyID c8f4c2de-7d96-4ad4-857a-c099effca2d6\n* Reproducer: bootstrap.class", "target": 0, "func": "R_API RBinJavaAttrInfo *r_bin_java_bootstrap_methods_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tRBinJavaBootStrapMethod *bsm = NULL;\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (attr) {\n\t\tattr->type = R_BIN_JAVA_ATTR_TYPE_BOOTSTRAP_METHODS_ATTR;\n\t\tif (offset + 8 > sz)  {\n\t\t\tfree (attr);\n\t\t\treturn NULL;\n\t\t}\n\t\tattr->info.bootstrap_methods_attr.num_bootstrap_methods = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tattr->info.bootstrap_methods_attr.bootstrap_methods = r_list_newf (r_bin_java_bootstrap_method_free);\n\t\tfor (i = 0; i < attr->info.bootstrap_methods_attr.num_bootstrap_methods; i++) {\n\t\t\t// bsm = r_bin_java_bootstrap_method_new (bin, bin->b->cur);\n\t\t\tif (offset >= sz) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbsm = r_bin_java_bootstrap_method_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\t\tif (bsm) {\n\t\t\t\toffset += bsm->size;\n\t\t\t\tr_list_append (attr->info.bootstrap_methods_attr.bootstrap_methods, (void *) bsm);\n\t\t\t} else {\n\t\t\t\t// TODO eprintf Failed to read the %d boot strap method.\n\t\t\t}\n\t\t}\n\t\tattr->size = offset;\n\t}\n\treturn attr;\n}", "func_hash": 161704709334478835269694958839919177798, "file_name": "class.c", "file_hash": 14172744137787125285025549785651095579, "cwe": ["CWE-125"], "cve": "CVE-2022-1452", "cve_desc": "Out-of-bounds Read in r_bin_java_bootstrap_methods_attr_new function in GitHub repository radareorg/radare2 prior to 5.7.0. The bug causes the program reads data past the end 2f the intented buffer. Typically, this can allow attackers to read sensitive information from other memory locations or cause a crash. More details see [CWE-125: Out-of-bounds read](https://cwe.mitre.org/data/definitions/125.html).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1452"}
{"idx": 202125, "project": "cairo", "commit_id": "03a820b173ed1fdef6ff14b4468f5dbc02ff59be", "project_url": "https://gitlab.freedesktop.org/cairo/cairo", "commit_url": "https://gitlab.freedesktop.org/cairo/cairo/-/merge_requests/85/diffs?commit_id=03a820b173ed1fdef6ff14b4468f5dbc02ff59be", "commit_message": "Fix mask usage in image-compositor", "target": 1, "func": "_inplace_src_spans (void *abstract_renderer, int y, int h,\n\t\t    const cairo_half_open_span_t *spans,\n\t\t    unsigned num_spans)\n{\n    cairo_image_span_renderer_t *r = abstract_renderer;\n    uint8_t *m;\n    int x0;\n\n    if (num_spans == 0)\n\treturn CAIRO_STATUS_SUCCESS;\n\n    x0 = spans[0].x;\n    m = r->_buf;\n    do {\n\tint len = spans[1].x - spans[0].x;\n\tif (len >= r->u.composite.run_length && spans[0].coverage == 0xff) {\n\t    if (spans[0].x != x0) {\n#if PIXMAN_HAS_OP_LERP\n\t\tpixman_image_composite32 (PIXMAN_OP_LERP_SRC,\n\t\t\t\t\t  r->src, r->mask, r->u.composite.dst,\n\t\t\t\t\t  x0 + r->u.composite.src_x,\n\t\t\t\t\t  y + r->u.composite.src_y,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  x0, y,\n\t\t\t\t\t  spans[0].x - x0, h);\n#else\n\t\tpixman_image_composite32 (PIXMAN_OP_OUT_REVERSE,\n\t\t\t\t\t  r->mask, NULL, r->u.composite.dst,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  x0, y,\n\t\t\t\t\t  spans[0].x - x0, h);\n\t\tpixman_image_composite32 (PIXMAN_OP_ADD,\n\t\t\t\t\t  r->src, r->mask, r->u.composite.dst,\n\t\t\t\t\t  x0 + r->u.composite.src_x,\n\t\t\t\t\t  y + r->u.composite.src_y,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  x0, y,\n\t\t\t\t\t  spans[0].x - x0, h);\n#endif\n\t    }\n\n\t    pixman_image_composite32 (PIXMAN_OP_SRC,\n\t\t\t\t      r->src, NULL, r->u.composite.dst,\n\t\t\t\t      spans[0].x + r->u.composite.src_x,\n\t\t\t\t      y + r->u.composite.src_y,\n\t\t\t\t      0, 0,\n\t\t\t\t      spans[0].x, y,\n\t\t\t\t      spans[1].x - spans[0].x, h);\n\n\t    m = r->_buf;\n\t    x0 = spans[1].x;\n\t} else if (spans[0].coverage == 0x0) {\n\t    if (spans[0].x != x0) {\n#if PIXMAN_HAS_OP_LERP\n\t\tpixman_image_composite32 (PIXMAN_OP_LERP_SRC,\n\t\t\t\t\t  r->src, r->mask, r->u.composite.dst,\n\t\t\t\t\t  x0 + r->u.composite.src_x,\n\t\t\t\t\t  y + r->u.composite.src_y,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  x0, y,\n\t\t\t\t\t  spans[0].x - x0, h);\n#else\n\t\tpixman_image_composite32 (PIXMAN_OP_OUT_REVERSE,\n\t\t\t\t\t  r->mask, NULL, r->u.composite.dst,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  x0, y,\n\t\t\t\t\t  spans[0].x - x0, h);\n\t\tpixman_image_composite32 (PIXMAN_OP_ADD,\n\t\t\t\t\t  r->src, r->mask, r->u.composite.dst,\n\t\t\t\t\t  x0 + r->u.composite.src_x,\n\t\t\t\t\t  y + r->u.composite.src_y,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  x0, y,\n\t\t\t\t\t  spans[0].x - x0, h);\n#endif\n\t    }\n\n\t    m = r->_buf;\n\t    x0 = spans[1].x;\n\t} else {\n\t    *m++ = spans[0].coverage;\n\t    if (len > 1) {\n\t\tmemset (m, spans[0].coverage, --len);\n\t\tm += len;\n\t    }\n\t}\n\tspans++;\n    } while (--num_spans > 1);\n\n    if (spans[0].x != x0) {\n#if PIXMAN_HAS_OP_LERP\n\tpixman_image_composite32 (PIXMAN_OP_LERP_SRC,\n\t\t\t\t  r->src, r->mask, r->u.composite.dst,\n\t\t\t\t  x0 + r->u.composite.src_x,\n\t\t\t\t  y + r->u.composite.src_y,\n\t\t\t\t  0, 0,\n\t\t\t\t  x0, y,\n\t\t\t\t  spans[0].x - x0, h);\n#else\n\tpixman_image_composite32 (PIXMAN_OP_OUT_REVERSE,\n\t\t\t\t  r->mask, NULL, r->u.composite.dst,\n\t\t\t\t  0, 0,\n\t\t\t\t  0, 0,\n\t\t\t\t  x0, y,\n\t\t\t\t  spans[0].x - x0, h);\n\tpixman_image_composite32 (PIXMAN_OP_ADD,\n\t\t\t\t  r->src, r->mask, r->u.composite.dst,\n\t\t\t\t  x0 + r->u.composite.src_x,\n\t\t\t\t  y + r->u.composite.src_y,\n\t\t\t\t  0, 0,\n\t\t\t\t  x0, y,\n\t\t\t\t  spans[0].x - x0, h);\n#endif\n    }\n\n    return CAIRO_STATUS_SUCCESS;\n}", "func_hash": 284944114374640076378159892516757654917, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2020-35492", "cve_desc": "A flaw was found in cairo's image-compositor.c in all versions prior to 1.17.4. This flaw allows an attacker who can provide a crafted input file to cairo's image-compositor (for example, by convincing a user to open a file in an application using cairo, or if an application uses cairo on untrusted input) to cause a stack buffer overflow -> out-of-bounds WRITE. The highest impact from this vulnerability is to confidentiality, integrity, as well as system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35492"}
{"idx": 329925, "project": "cairo", "commit_id": "03a820b173ed1fdef6ff14b4468f5dbc02ff59be", "project_url": "https://gitlab.freedesktop.org/cairo/cairo", "commit_url": "https://gitlab.freedesktop.org/cairo/cairo/-/merge_requests/85/diffs?commit_id=03a820b173ed1fdef6ff14b4468f5dbc02ff59be", "commit_message": "Fix mask usage in image-compositor", "target": 0, "func": "_inplace_src_spans (void *abstract_renderer, int y, int h,\n\t\t    const cairo_half_open_span_t *spans,\n\t\t    unsigned num_spans)\n{\n    cairo_image_span_renderer_t *r = abstract_renderer;\n    uint8_t *m, *base = (uint8_t*)pixman_image_get_data(r->mask);\n    int x0;\n\n    if (num_spans == 0)\n\treturn CAIRO_STATUS_SUCCESS;\n\n    x0 = spans[0].x;\n    m = base;\n    do {\n\tint len = spans[1].x - spans[0].x;\n\tif (len >= r->u.composite.run_length && spans[0].coverage == 0xff) {\n\t    if (spans[0].x != x0) {\n#if PIXMAN_HAS_OP_LERP\n\t\tpixman_image_composite32 (PIXMAN_OP_LERP_SRC,\n\t\t\t\t\t  r->src, r->mask, r->u.composite.dst,\n\t\t\t\t\t  x0 + r->u.composite.src_x,\n\t\t\t\t\t  y + r->u.composite.src_y,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  x0, y,\n\t\t\t\t\t  spans[0].x - x0, h);\n#else\n\t\tpixman_image_composite32 (PIXMAN_OP_OUT_REVERSE,\n\t\t\t\t\t  r->mask, NULL, r->u.composite.dst,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  x0, y,\n\t\t\t\t\t  spans[0].x - x0, h);\n\t\tpixman_image_composite32 (PIXMAN_OP_ADD,\n\t\t\t\t\t  r->src, r->mask, r->u.composite.dst,\n\t\t\t\t\t  x0 + r->u.composite.src_x,\n\t\t\t\t\t  y + r->u.composite.src_y,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  x0, y,\n\t\t\t\t\t  spans[0].x - x0, h);\n#endif\n\t    }\n\n\t    pixman_image_composite32 (PIXMAN_OP_SRC,\n\t\t\t\t      r->src, NULL, r->u.composite.dst,\n\t\t\t\t      spans[0].x + r->u.composite.src_x,\n\t\t\t\t      y + r->u.composite.src_y,\n\t\t\t\t      0, 0,\n\t\t\t\t      spans[0].x, y,\n\t\t\t\t      spans[1].x - spans[0].x, h);\n\n\t    m = base;\n\t    x0 = spans[1].x;\n\t} else if (spans[0].coverage == 0x0) {\n\t    if (spans[0].x != x0) {\n#if PIXMAN_HAS_OP_LERP\n\t\tpixman_image_composite32 (PIXMAN_OP_LERP_SRC,\n\t\t\t\t\t  r->src, r->mask, r->u.composite.dst,\n\t\t\t\t\t  x0 + r->u.composite.src_x,\n\t\t\t\t\t  y + r->u.composite.src_y,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  x0, y,\n\t\t\t\t\t  spans[0].x - x0, h);\n#else\n\t\tpixman_image_composite32 (PIXMAN_OP_OUT_REVERSE,\n\t\t\t\t\t  r->mask, NULL, r->u.composite.dst,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  x0, y,\n\t\t\t\t\t  spans[0].x - x0, h);\n\t\tpixman_image_composite32 (PIXMAN_OP_ADD,\n\t\t\t\t\t  r->src, r->mask, r->u.composite.dst,\n\t\t\t\t\t  x0 + r->u.composite.src_x,\n\t\t\t\t\t  y + r->u.composite.src_y,\n\t\t\t\t\t  0, 0,\n\t\t\t\t\t  x0, y,\n\t\t\t\t\t  spans[0].x - x0, h);\n#endif\n\t    }\n\n\t    m = base;\n\t    x0 = spans[1].x;\n\t} else {\n\t    *m++ = spans[0].coverage;\n\t    if (len > 1) {\n\t\tmemset (m, spans[0].coverage, --len);\n\t\tm += len;\n\t    }\n\t}\n\tspans++;\n    } while (--num_spans > 1);\n\n    if (spans[0].x != x0) {\n#if PIXMAN_HAS_OP_LERP\n\tpixman_image_composite32 (PIXMAN_OP_LERP_SRC,\n\t\t\t\t  r->src, r->mask, r->u.composite.dst,\n\t\t\t\t  x0 + r->u.composite.src_x,\n\t\t\t\t  y + r->u.composite.src_y,\n\t\t\t\t  0, 0,\n\t\t\t\t  x0, y,\n\t\t\t\t  spans[0].x - x0, h);\n#else\n\tpixman_image_composite32 (PIXMAN_OP_OUT_REVERSE,\n\t\t\t\t  r->mask, NULL, r->u.composite.dst,\n\t\t\t\t  0, 0,\n\t\t\t\t  0, 0,\n\t\t\t\t  x0, y,\n\t\t\t\t  spans[0].x - x0, h);\n\tpixman_image_composite32 (PIXMAN_OP_ADD,\n\t\t\t\t  r->src, r->mask, r->u.composite.dst,\n\t\t\t\t  x0 + r->u.composite.src_x,\n\t\t\t\t  y + r->u.composite.src_y,\n\t\t\t\t  0, 0,\n\t\t\t\t  x0, y,\n\t\t\t\t  spans[0].x - x0, h);\n#endif\n    }\n\n    return CAIRO_STATUS_SUCCESS;\n}", "func_hash": 297166780528255828865202210898036623430, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2020-35492", "cve_desc": "A flaw was found in cairo's image-compositor.c in all versions prior to 1.17.4. This flaw allows an attacker who can provide a crafted input file to cairo's image-compositor (for example, by convincing a user to open a file in an application using cairo, or if an application uses cairo on untrusted input) to cause a stack buffer overflow -> out-of-bounds WRITE. The highest impact from this vulnerability is to confidentiality, integrity, as well as system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35492"}
{"idx": 202256, "project": "qtbase", "commit_id": "6b400e3147dcfd8cc3a393ace1bd118c93762e0c", "project_url": "https://github.com/qt/qtbase", "commit_url": "https://github.com/qt/qtbase/commit/6b400e3147dcfd8cc3a393ace1bd118c93762e0c", "commit_message": "Improve fix for avoiding huge number of tiny dashes\n\nSome pathological cases were not caught by the previous fix.\n\nFixes: QTBUG-95239\nPick-to: 6.2 6.1 5.15\nChange-Id: I0337ee3923ff93ccb36c4d7b810a9c0667354cc5\nReviewed-by: Robert L\u00f6hning ", "target": 1, "func": "void QPaintEngineEx::stroke(const QVectorPath &path, const QPen &inPen)\n{\n#ifdef QT_DEBUG_DRAW\n    qDebug() << \"QPaintEngineEx::stroke()\" << pen;\n#endif\n\n    Q_D(QPaintEngineEx);\n\n    if (path.isEmpty())\n        return;\n\n    if (!d->strokeHandler) {\n        d->strokeHandler = new StrokeHandler(path.elementCount()+4);\n        d->stroker.setMoveToHook(qpaintengineex_moveTo);\n        d->stroker.setLineToHook(qpaintengineex_lineTo);\n        d->stroker.setCubicToHook(qpaintengineex_cubicTo);\n    }\n\n    QRectF clipRect;\n    QPen pen = inPen;\n    if (pen.style() > Qt::SolidLine) {\n        QRectF cpRect = path.controlPointRect();\n        const QTransform &xf = state()->matrix;\n        if (pen.isCosmetic()) {\n            clipRect = d->exDeviceRect;\n            cpRect.translate(xf.dx(), xf.dy());\n        } else {\n            clipRect = xf.inverted().mapRect(QRectF(d->exDeviceRect));\n        }\n        // Check to avoid generating unwieldy amount of dashes that will not be visible anyway\n        QRectF extentRect = cpRect & clipRect;\n        qreal extent = qMax(extentRect.width(), extentRect.height());\n        qreal patternLength = 0;\n        const QList pattern = pen.dashPattern();\n        const int patternSize = qMin(pattern.size(), 32);\n        for (int i = 0; i < patternSize; i++)\n            patternLength += qMax(pattern.at(i), qreal(0));\n        if (pen.widthF())\n            patternLength *= pen.widthF();\n        if (qFuzzyIsNull(patternLength)) {\n            pen.setStyle(Qt::NoPen);\n        } else if (extent / patternLength > 10000) {\n            // approximate stream of tiny dashes with semi-transparent solid line\n            pen.setStyle(Qt::SolidLine);\n            QColor color(pen.color());\n            color.setAlpha(color.alpha() / 2);\n            pen.setColor(color);\n        }\n    }\n\n    if (!qpen_fast_equals(pen, d->strokerPen)) {\n        d->strokerPen = pen;\n        d->stroker.setJoinStyle(pen.joinStyle());\n        d->stroker.setCapStyle(pen.capStyle());\n        d->stroker.setMiterLimit(pen.miterLimit());\n        qreal penWidth = pen.widthF();\n        if (penWidth == 0)\n            d->stroker.setStrokeWidth(1);\n        else\n            d->stroker.setStrokeWidth(penWidth);\n\n        Qt::PenStyle style = pen.style();\n        if (style == Qt::SolidLine) {\n            d->activeStroker = &d->stroker;\n        } else if (style == Qt::NoPen) {\n            d->activeStroker = nullptr;\n        } else {\n            d->dasher.setDashPattern(pen.dashPattern());\n            d->dasher.setDashOffset(pen.dashOffset());\n            d->activeStroker = &d->dasher;\n        }\n    }\n\n    if (!d->activeStroker) {\n        return;\n    }\n\n    if (!clipRect.isNull())\n        d->activeStroker->setClipRect(clipRect);\n\n    if (d->activeStroker == &d->stroker)\n        d->stroker.setForceOpen(path.hasExplicitOpen());\n\n    const QPainterPath::ElementType *types = path.elements();\n    const qreal *points = path.points();\n    int pointCount = path.elementCount();\n\n    const qreal *lastPoint = points + (pointCount<<1);\n\n    d->strokeHandler->types.reset();\n    d->strokeHandler->pts.reset();\n\n    // Some engines might decide to optimize for the non-shape hint later on...\n    uint flags = QVectorPath::WindingFill;\n\n    if (path.elementCount() > 2)\n        flags |= QVectorPath::NonConvexShapeMask;\n\n    if (d->stroker.capStyle() == Qt::RoundCap || d->stroker.joinStyle() == Qt::RoundJoin)\n        flags |= QVectorPath::CurvedShapeMask;\n\n    // ### Perspective Xforms are currently not supported...\n    if (!pen.isCosmetic()) {\n        // We include cosmetic pens in this case to avoid having to\n        // change the current transform. Normal transformed,\n        // non-cosmetic pens will be transformed as part of fill\n        // later, so they are also covered here..\n        d->activeStroker->setCurveThresholdFromTransform(state()->matrix);\n        d->activeStroker->begin(d->strokeHandler);\n        if (types) {\n            while (points < lastPoint) {\n                switch (*types) {\n                case QPainterPath::MoveToElement:\n                    d->activeStroker->moveTo(points[0], points[1]);\n                    points += 2;\n                    ++types;\n                    break;\n                case QPainterPath::LineToElement:\n                    d->activeStroker->lineTo(points[0], points[1]);\n                    points += 2;\n                    ++types;\n                    break;\n                case QPainterPath::CurveToElement:\n                    d->activeStroker->cubicTo(points[0], points[1],\n                                              points[2], points[3],\n                                              points[4], points[5]);\n                    points += 6;\n                    types += 3;\n                    flags |= QVectorPath::CurvedShapeMask;\n                    break;\n                default:\n                    break;\n                }\n            }\n            if (path.hasImplicitClose())\n                d->activeStroker->lineTo(path.points()[0], path.points()[1]);\n\n        } else {\n            d->activeStroker->moveTo(points[0], points[1]);\n            points += 2;\n            while (points < lastPoint) {\n                d->activeStroker->lineTo(points[0], points[1]);\n                points += 2;\n            }\n            if (path.hasImplicitClose())\n                d->activeStroker->lineTo(path.points()[0], path.points()[1]);\n        }\n        d->activeStroker->end();\n\n        if (!d->strokeHandler->types.size()) // an empty path...\n            return;\n\n        QVectorPath strokePath(d->strokeHandler->pts.data(),\n                               d->strokeHandler->types.size(),\n                               d->strokeHandler->types.data(),\n                               flags);\n        fill(strokePath, pen.brush());\n    } else {\n        // For cosmetic pens we need a bit of trickery... We to process xform the input points\n        if (state()->matrix.type() >= QTransform::TxProject) {\n            QPainterPath painterPath = state()->matrix.map(path.convertToPainterPath());\n            d->activeStroker->strokePath(painterPath, d->strokeHandler, QTransform());\n        } else {\n            d->activeStroker->setCurveThresholdFromTransform(QTransform());\n            d->activeStroker->begin(d->strokeHandler);\n            if (types) {\n                while (points < lastPoint) {\n                    switch (*types) {\n                    case QPainterPath::MoveToElement: {\n                        QPointF pt = (*(const QPointF *) points) * state()->matrix;\n                        d->activeStroker->moveTo(pt.x(), pt.y());\n                        points += 2;\n                        ++types;\n                        break;\n                    }\n                    case QPainterPath::LineToElement: {\n                        QPointF pt = (*(const QPointF *) points) * state()->matrix;\n                        d->activeStroker->lineTo(pt.x(), pt.y());\n                        points += 2;\n                        ++types;\n                        break;\n                    }\n                    case QPainterPath::CurveToElement: {\n                        QPointF c1 = ((const QPointF *) points)[0] * state()->matrix;\n                        QPointF c2 = ((const QPointF *) points)[1] * state()->matrix;\n                        QPointF e =  ((const QPointF *) points)[2] * state()->matrix;\n                        d->activeStroker->cubicTo(c1.x(), c1.y(), c2.x(), c2.y(), e.x(), e.y());\n                        points += 6;\n                        types += 3;\n                        flags |= QVectorPath::CurvedShapeMask;\n                        break;\n                    }\n                    default:\n                        break;\n                    }\n                }\n                if (path.hasImplicitClose()) {\n                    QPointF pt = * ((const QPointF *) path.points()) * state()->matrix;\n                    d->activeStroker->lineTo(pt.x(), pt.y());\n                }\n\n            } else {\n                QPointF p = ((const QPointF *)points)[0] * state()->matrix;\n                d->activeStroker->moveTo(p.x(), p.y());\n                points += 2;\n                while (points < lastPoint) {\n                    QPointF p = ((const QPointF *)points)[0] * state()->matrix;\n                    d->activeStroker->lineTo(p.x(), p.y());\n                    points += 2;\n                }\n                if (path.hasImplicitClose())\n                    d->activeStroker->lineTo(p.x(), p.y());\n            }\n            d->activeStroker->end();\n        }\n\n        QVectorPath strokePath(d->strokeHandler->pts.data(),\n                               d->strokeHandler->types.size(),\n                               d->strokeHandler->types.data(),\n                               flags);\n\n        QTransform xform = state()->matrix;\n        state()->matrix = QTransform();\n        transformChanged();\n\n        QBrush brush = pen.brush();\n        if (qbrush_style(brush) != Qt::SolidPattern)\n            brush.setTransform(brush.transform() * xform);\n\n        fill(strokePath, brush);\n\n        state()->matrix = xform;\n        transformChanged();\n    }\n}", "func_hash": 209191742971544690982165605152005956873, "file_name": "qpaintengineex.cpp", "file_hash": 121502439456016918324891600204397406142, "cwe": ["CWE-787"], "cve": "CVE-2021-38593", "cve_desc": "Qt 5.x before 5.15.6 and 6.x through 6.1.2 has an out-of-bounds write in QOutlineMapper::convertPath (called from QRasterPaintEngine::fill and QPaintEngineEx::stroke).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-38593"}
{"idx": 331760, "project": "qtbase", "commit_id": "6b400e3147dcfd8cc3a393ace1bd118c93762e0c", "project_url": "https://github.com/qt/qtbase", "commit_url": "https://github.com/qt/qtbase/commit/6b400e3147dcfd8cc3a393ace1bd118c93762e0c", "commit_message": "Improve fix for avoiding huge number of tiny dashes\n\nSome pathological cases were not caught by the previous fix.\n\nFixes: QTBUG-95239\nPick-to: 6.2 6.1 5.15\nChange-Id: I0337ee3923ff93ccb36c4d7b810a9c0667354cc5\nReviewed-by: Robert L\u00f6hning ", "target": 0, "func": "void QPaintEngineEx::stroke(const QVectorPath &path, const QPen &inPen)\n{\n#ifdef QT_DEBUG_DRAW\n    qDebug() << \"QPaintEngineEx::stroke()\" << pen;\n#endif\n\n    Q_D(QPaintEngineEx);\n\n    if (path.isEmpty())\n        return;\n\n    if (!d->strokeHandler) {\n        d->strokeHandler = new StrokeHandler(path.elementCount()+4);\n        d->stroker.setMoveToHook(qpaintengineex_moveTo);\n        d->stroker.setLineToHook(qpaintengineex_lineTo);\n        d->stroker.setCubicToHook(qpaintengineex_cubicTo);\n    }\n\n    QRectF clipRect;\n    QPen pen = inPen;\n    if (pen.style() > Qt::SolidLine) {\n        QRectF cpRect = path.controlPointRect();\n        const QTransform &xf = state()->matrix;\n        if (pen.isCosmetic()) {\n            clipRect = d->exDeviceRect;\n            cpRect.translate(xf.dx(), xf.dy());\n        } else {\n            clipRect = xf.inverted().mapRect(QRectF(d->exDeviceRect));\n        }\n        // Check to avoid generating unwieldy amount of dashes that will not be visible anyway\n        QRectF extentRect = cpRect & clipRect;\n        qreal extent = qMax(extentRect.width(), extentRect.height());\n        qreal patternLength = 0;\n        const QList pattern = pen.dashPattern();\n        const int patternSize = qMin(pattern.size(), 32);\n        for (int i = 0; i < patternSize; i++)\n            patternLength += qMax(pattern.at(i), qreal(0));\n        if (pen.widthF())\n            patternLength *= pen.widthF();\n        if (qFuzzyIsNull(patternLength)) {\n            pen.setStyle(Qt::NoPen);\n        } else if (qFuzzyIsNull(extent) || extent / patternLength > 10000) {\n            // approximate stream of tiny dashes with semi-transparent solid line\n            pen.setStyle(Qt::SolidLine);\n            QColor color(pen.color());\n            color.setAlpha(color.alpha() / 2);\n            pen.setColor(color);\n        }\n    }\n\n    if (!qpen_fast_equals(pen, d->strokerPen)) {\n        d->strokerPen = pen;\n        d->stroker.setJoinStyle(pen.joinStyle());\n        d->stroker.setCapStyle(pen.capStyle());\n        d->stroker.setMiterLimit(pen.miterLimit());\n        qreal penWidth = pen.widthF();\n        if (penWidth == 0)\n            d->stroker.setStrokeWidth(1);\n        else\n            d->stroker.setStrokeWidth(penWidth);\n\n        Qt::PenStyle style = pen.style();\n        if (style == Qt::SolidLine) {\n            d->activeStroker = &d->stroker;\n        } else if (style == Qt::NoPen) {\n            d->activeStroker = nullptr;\n        } else {\n            d->dasher.setDashPattern(pen.dashPattern());\n            d->dasher.setDashOffset(pen.dashOffset());\n            d->activeStroker = &d->dasher;\n        }\n    }\n\n    if (!d->activeStroker) {\n        return;\n    }\n\n    if (!clipRect.isNull())\n        d->activeStroker->setClipRect(clipRect);\n\n    if (d->activeStroker == &d->stroker)\n        d->stroker.setForceOpen(path.hasExplicitOpen());\n\n    const QPainterPath::ElementType *types = path.elements();\n    const qreal *points = path.points();\n    int pointCount = path.elementCount();\n\n    const qreal *lastPoint = points + (pointCount<<1);\n\n    d->strokeHandler->types.reset();\n    d->strokeHandler->pts.reset();\n\n    // Some engines might decide to optimize for the non-shape hint later on...\n    uint flags = QVectorPath::WindingFill;\n\n    if (path.elementCount() > 2)\n        flags |= QVectorPath::NonConvexShapeMask;\n\n    if (d->stroker.capStyle() == Qt::RoundCap || d->stroker.joinStyle() == Qt::RoundJoin)\n        flags |= QVectorPath::CurvedShapeMask;\n\n    // ### Perspective Xforms are currently not supported...\n    if (!pen.isCosmetic()) {\n        // We include cosmetic pens in this case to avoid having to\n        // change the current transform. Normal transformed,\n        // non-cosmetic pens will be transformed as part of fill\n        // later, so they are also covered here..\n        d->activeStroker->setCurveThresholdFromTransform(state()->matrix);\n        d->activeStroker->begin(d->strokeHandler);\n        if (types) {\n            while (points < lastPoint) {\n                switch (*types) {\n                case QPainterPath::MoveToElement:\n                    d->activeStroker->moveTo(points[0], points[1]);\n                    points += 2;\n                    ++types;\n                    break;\n                case QPainterPath::LineToElement:\n                    d->activeStroker->lineTo(points[0], points[1]);\n                    points += 2;\n                    ++types;\n                    break;\n                case QPainterPath::CurveToElement:\n                    d->activeStroker->cubicTo(points[0], points[1],\n                                              points[2], points[3],\n                                              points[4], points[5]);\n                    points += 6;\n                    types += 3;\n                    flags |= QVectorPath::CurvedShapeMask;\n                    break;\n                default:\n                    break;\n                }\n            }\n            if (path.hasImplicitClose())\n                d->activeStroker->lineTo(path.points()[0], path.points()[1]);\n\n        } else {\n            d->activeStroker->moveTo(points[0], points[1]);\n            points += 2;\n            while (points < lastPoint) {\n                d->activeStroker->lineTo(points[0], points[1]);\n                points += 2;\n            }\n            if (path.hasImplicitClose())\n                d->activeStroker->lineTo(path.points()[0], path.points()[1]);\n        }\n        d->activeStroker->end();\n\n        if (!d->strokeHandler->types.size()) // an empty path...\n            return;\n\n        QVectorPath strokePath(d->strokeHandler->pts.data(),\n                               d->strokeHandler->types.size(),\n                               d->strokeHandler->types.data(),\n                               flags);\n        fill(strokePath, pen.brush());\n    } else {\n        // For cosmetic pens we need a bit of trickery... We to process xform the input points\n        if (state()->matrix.type() >= QTransform::TxProject) {\n            QPainterPath painterPath = state()->matrix.map(path.convertToPainterPath());\n            d->activeStroker->strokePath(painterPath, d->strokeHandler, QTransform());\n        } else {\n            d->activeStroker->setCurveThresholdFromTransform(QTransform());\n            d->activeStroker->begin(d->strokeHandler);\n            if (types) {\n                while (points < lastPoint) {\n                    switch (*types) {\n                    case QPainterPath::MoveToElement: {\n                        QPointF pt = (*(const QPointF *) points) * state()->matrix;\n                        d->activeStroker->moveTo(pt.x(), pt.y());\n                        points += 2;\n                        ++types;\n                        break;\n                    }\n                    case QPainterPath::LineToElement: {\n                        QPointF pt = (*(const QPointF *) points) * state()->matrix;\n                        d->activeStroker->lineTo(pt.x(), pt.y());\n                        points += 2;\n                        ++types;\n                        break;\n                    }\n                    case QPainterPath::CurveToElement: {\n                        QPointF c1 = ((const QPointF *) points)[0] * state()->matrix;\n                        QPointF c2 = ((const QPointF *) points)[1] * state()->matrix;\n                        QPointF e =  ((const QPointF *) points)[2] * state()->matrix;\n                        d->activeStroker->cubicTo(c1.x(), c1.y(), c2.x(), c2.y(), e.x(), e.y());\n                        points += 6;\n                        types += 3;\n                        flags |= QVectorPath::CurvedShapeMask;\n                        break;\n                    }\n                    default:\n                        break;\n                    }\n                }\n                if (path.hasImplicitClose()) {\n                    QPointF pt = * ((const QPointF *) path.points()) * state()->matrix;\n                    d->activeStroker->lineTo(pt.x(), pt.y());\n                }\n\n            } else {\n                QPointF p = ((const QPointF *)points)[0] * state()->matrix;\n                d->activeStroker->moveTo(p.x(), p.y());\n                points += 2;\n                while (points < lastPoint) {\n                    QPointF p = ((const QPointF *)points)[0] * state()->matrix;\n                    d->activeStroker->lineTo(p.x(), p.y());\n                    points += 2;\n                }\n                if (path.hasImplicitClose())\n                    d->activeStroker->lineTo(p.x(), p.y());\n            }\n            d->activeStroker->end();\n        }\n\n        QVectorPath strokePath(d->strokeHandler->pts.data(),\n                               d->strokeHandler->types.size(),\n                               d->strokeHandler->types.data(),\n                               flags);\n\n        QTransform xform = state()->matrix;\n        state()->matrix = QTransform();\n        transformChanged();\n\n        QBrush brush = pen.brush();\n        if (qbrush_style(brush) != Qt::SolidPattern)\n            brush.setTransform(brush.transform() * xform);\n\n        fill(strokePath, brush);\n\n        state()->matrix = xform;\n        transformChanged();\n    }\n}", "func_hash": 262258193863623717012890974299984432074, "file_name": "qpaintengineex.cpp", "file_hash": 220664880987933761772605675716001859723, "cwe": ["CWE-787"], "cve": "CVE-2021-38593", "cve_desc": "Qt 5.x before 5.15.6 and 6.x through 6.1.2 has an out-of-bounds write in QOutlineMapper::convertPath (called from QRasterPaintEngine::fill and QPaintEngineEx::stroke).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-38593"}
{"idx": 202276, "project": "vim", "commit_id": "57df9e8a9f9ae1aafdde9b86b10ad907627a87dc", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/57df9e8a9f9ae1aafdde9b86b10ad907627a87dc", "commit_message": "patch 8.2.4151: reading beyond the end of a line\n\nProblem:    Reading beyond the end of a line.\nSolution:   For block insert only use the offset for correcting the length.", "target": 1, "func": "block_insert(\n    oparg_T\t\t*oap,\n    char_u\t\t*s,\n    int\t\t\tb_insert,\n    struct block_def\t*bdp)\n{\n    int\t\tts_val;\n    int\t\tcount = 0;\t// extra spaces to replace a cut TAB\n    int\t\tspaces = 0;\t// non-zero if cutting a TAB\n    colnr_T\toffset;\t\t// pointer along new line\n    colnr_T\tstartcol;\t// column where insert starts\n    unsigned\ts_len;\t\t// STRLEN(s)\n    char_u\t*newp, *oldp;\t// new, old lines\n    linenr_T\tlnum;\t\t// loop var\n    int\t\toldstate = State;\n\n    State = INSERT;\t\t// don't want REPLACE for State\n    s_len = (unsigned)STRLEN(s);\n\n    for (lnum = oap->start.lnum + 1; lnum <= oap->end.lnum; lnum++)\n    {\n\tblock_prep(oap, bdp, lnum, TRUE);\n\tif (bdp->is_short && b_insert)\n\t    continue;\t// OP_INSERT, line ends before block start\n\n\toldp = ml_get(lnum);\n\n\tif (b_insert)\n\t{\n\t    ts_val = bdp->start_char_vcols;\n\t    spaces = bdp->startspaces;\n\t    if (spaces != 0)\n\t\tcount = ts_val - 1; // we're cutting a TAB\n\t    offset = bdp->textcol;\n\t}\n\telse // append\n\t{\n\t    ts_val = bdp->end_char_vcols;\n\t    if (!bdp->is_short) // spaces = padding after block\n\t    {\n\t\tspaces = (bdp->endspaces ? ts_val - bdp->endspaces : 0);\n\t\tif (spaces != 0)\n\t\t    count = ts_val - 1; // we're cutting a TAB\n\t\toffset = bdp->textcol + bdp->textlen - (spaces != 0);\n\t    }\n\t    else // spaces = padding to block edge\n\t    {\n\t\t// if $ used, just append to EOL (ie spaces==0)\n\t\tif (!bdp->is_MAX)\n\t\t    spaces = (oap->end_vcol - bdp->end_vcol) + 1;\n\t\tcount = spaces;\n\t\toffset = bdp->textcol + bdp->textlen;\n\t    }\n\t}\n\n\tif (has_mbyte && spaces > 0)\n\t{\n\t    int off;\n\n\t    // Avoid starting halfway a multi-byte character.\n\t    if (b_insert)\n\t    {\n\t\toff = (*mb_head_off)(oldp, oldp + offset + spaces);\n\t\tspaces -= off;\n\t\tcount -= off;\n\t    }\n\t    else\n\t    {\n\t\t// spaces fill the gap, the character that's at the edge moves\n\t\t// right\n\t\toff = (*mb_head_off)(oldp, oldp + offset);\n\t\toffset -= off;\n\t    }\n\t}\n\tif (spaces < 0)  // can happen when the cursor was moved\n\t    spaces = 0;\n\n\t// Make sure the allocated size matches what is actually copied below.\n\tnewp = alloc(STRLEN(oldp) + spaces + s_len\n\t\t    + (spaces > 0 && !bdp->is_short ? ts_val - spaces : 0)\n\t\t\t\t\t\t\t\t  + count + 1);\n\tif (newp == NULL)\n\t    continue;\n\n\t// copy up to shifted part\n\tmch_memmove(newp, oldp, (size_t)offset);\n\toldp += offset;\n\n\t// insert pre-padding\n\tvim_memset(newp + offset, ' ', (size_t)spaces);\n\tstartcol = offset + spaces;\n\n\t// copy the new text\n\tmch_memmove(newp + startcol, s, (size_t)s_len);\n\toffset += s_len;\n\n\tif (spaces > 0 && !bdp->is_short)\n\t{\n\t    if (*oldp == TAB)\n\t    {\n\t\t// insert post-padding\n\t\tvim_memset(newp + offset + spaces, ' ',\n\t\t\t\t\t\t    (size_t)(ts_val - spaces));\n\t\t// we're splitting a TAB, don't copy it\n\t\toldp++;\n\t\t// We allowed for that TAB, remember this now\n\t\tcount++;\n\t    }\n\t    else\n\t\t// Not a TAB, no extra spaces\n\t\tcount = spaces;\n\t}\n\n\tif (spaces > 0)\n\t    offset += count;\n\tSTRMOVE(newp + offset, oldp);\n\n\tml_replace(lnum, newp, FALSE);\n\n\tif (b_insert)\n\t    // correct any text properties\n\t    inserted_bytes(lnum, startcol, s_len);\n\n\tif (lnum == oap->end.lnum)\n\t{\n\t    // Set \"']\" mark to the end of the block instead of the end of\n\t    // the insert in the first line.\n\t    curbuf->b_op_end.lnum = oap->end.lnum;\n\t    curbuf->b_op_end.col = offset;\n\t}\n    } // for all lnum\n\n    changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L);\n\n    State = oldstate;\n}", "func_hash": 183841044104193466999010248328275139619, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-0318", "cve_desc": "Heap-based Buffer Overflow in vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0318"}
{"idx": 332375, "project": "vim", "commit_id": "57df9e8a9f9ae1aafdde9b86b10ad907627a87dc", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/57df9e8a9f9ae1aafdde9b86b10ad907627a87dc", "commit_message": "patch 8.2.4151: reading beyond the end of a line\n\nProblem:    Reading beyond the end of a line.\nSolution:   For block insert only use the offset for correcting the length.", "target": 0, "func": "block_insert(\n    oparg_T\t\t*oap,\n    char_u\t\t*s,\n    int\t\t\tb_insert,\n    struct block_def\t*bdp)\n{\n    int\t\tts_val;\n    int\t\tcount = 0;\t// extra spaces to replace a cut TAB\n    int\t\tspaces = 0;\t// non-zero if cutting a TAB\n    colnr_T\toffset;\t\t// pointer along new line\n    colnr_T\tstartcol;\t// column where insert starts\n    unsigned\ts_len;\t\t// STRLEN(s)\n    char_u\t*newp, *oldp;\t// new, old lines\n    linenr_T\tlnum;\t\t// loop var\n    int\t\toldstate = State;\n\n    State = INSERT;\t\t// don't want REPLACE for State\n    s_len = (unsigned)STRLEN(s);\n\n    for (lnum = oap->start.lnum + 1; lnum <= oap->end.lnum; lnum++)\n    {\n\tblock_prep(oap, bdp, lnum, TRUE);\n\tif (bdp->is_short && b_insert)\n\t    continue;\t// OP_INSERT, line ends before block start\n\n\toldp = ml_get(lnum);\n\n\tif (b_insert)\n\t{\n\t    ts_val = bdp->start_char_vcols;\n\t    spaces = bdp->startspaces;\n\t    if (spaces != 0)\n\t\tcount = ts_val - 1; // we're cutting a TAB\n\t    offset = bdp->textcol;\n\t}\n\telse // append\n\t{\n\t    ts_val = bdp->end_char_vcols;\n\t    if (!bdp->is_short) // spaces = padding after block\n\t    {\n\t\tspaces = (bdp->endspaces ? ts_val - bdp->endspaces : 0);\n\t\tif (spaces != 0)\n\t\t    count = ts_val - 1; // we're cutting a TAB\n\t\toffset = bdp->textcol + bdp->textlen - (spaces != 0);\n\t    }\n\t    else // spaces = padding to block edge\n\t    {\n\t\t// if $ used, just append to EOL (ie spaces==0)\n\t\tif (!bdp->is_MAX)\n\t\t    spaces = (oap->end_vcol - bdp->end_vcol) + 1;\n\t\tcount = spaces;\n\t\toffset = bdp->textcol + bdp->textlen;\n\t    }\n\t}\n\n\tif (has_mbyte && spaces > 0)\n\t    // avoid copying part of a multi-byte character\n\t    offset -= (*mb_head_off)(oldp, oldp + offset);\n\n\tif (spaces < 0)  // can happen when the cursor was moved\n\t    spaces = 0;\n\n\t// Make sure the allocated size matches what is actually copied below.\n\tnewp = alloc(STRLEN(oldp) + spaces + s_len\n\t\t    + (spaces > 0 && !bdp->is_short ? ts_val - spaces : 0)\n\t\t\t\t\t\t\t\t  + count + 1);\n\tif (newp == NULL)\n\t    continue;\n\n\t// copy up to shifted part\n\tmch_memmove(newp, oldp, (size_t)offset);\n\toldp += offset;\n\n\t// insert pre-padding\n\tvim_memset(newp + offset, ' ', (size_t)spaces);\n\tstartcol = offset + spaces;\n\n\t// copy the new text\n\tmch_memmove(newp + startcol, s, (size_t)s_len);\n\toffset += s_len;\n\n\tif (spaces > 0 && !bdp->is_short)\n\t{\n\t    if (*oldp == TAB)\n\t    {\n\t\t// insert post-padding\n\t\tvim_memset(newp + offset + spaces, ' ',\n\t\t\t\t\t\t    (size_t)(ts_val - spaces));\n\t\t// we're splitting a TAB, don't copy it\n\t\toldp++;\n\t\t// We allowed for that TAB, remember this now\n\t\tcount++;\n\t    }\n\t    else\n\t\t// Not a TAB, no extra spaces\n\t\tcount = spaces;\n\t}\n\n\tif (spaces > 0)\n\t    offset += count;\n\tSTRMOVE(newp + offset, oldp);\n\n\tml_replace(lnum, newp, FALSE);\n\n\tif (b_insert)\n\t    // correct any text properties\n\t    inserted_bytes(lnum, startcol, s_len);\n\n\tif (lnum == oap->end.lnum)\n\t{\n\t    // Set \"']\" mark to the end of the block instead of the end of\n\t    // the insert in the first line.\n\t    curbuf->b_op_end.lnum = oap->end.lnum;\n\t    curbuf->b_op_end.col = offset;\n\t}\n    } // for all lnum\n\n    changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L);\n\n    State = oldstate;\n}", "func_hash": 7107013452158908965442250951300434750, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-0318", "cve_desc": "Heap-based Buffer Overflow in vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0318"}
{"idx": 202304, "project": "vim", "commit_id": "65b605665997fad54ef39a93199e305af2fe4d7f", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/65b605665997fad54ef39a93199e305af2fe4d7f", "commit_message": "patch 8.2.3409: reading beyond end of line with invalid utf-8 character\n\nProblem:    Reading beyond end of line with invalid utf-8 character.\nSolution:   Check for NUL when advancing.", "target": 1, "func": "find_match_text(colnr_T startcol, int regstart, char_u *match_text)\n{\n    colnr_T col = startcol;\n    int\t    c1, c2;\n    int\t    len1, len2;\n    int\t    match;\n\n    for (;;)\n    {\n\tmatch = TRUE;\n\tlen2 = MB_CHAR2LEN(regstart); // skip regstart\n\tfor (len1 = 0; match_text[len1] != NUL; len1 += MB_CHAR2LEN(c1))\n\t{\n\t    c1 = PTR2CHAR(match_text + len1);\n\t    c2 = PTR2CHAR(rex.line + col + len2);\n\t    if (c1 != c2 && (!rex.reg_ic || MB_CASEFOLD(c1) != MB_CASEFOLD(c2)))\n\t    {\n\t\tmatch = FALSE;\n\t\tbreak;\n\t    }\n\t    len2 += MB_CHAR2LEN(c2);\n\t}\n\tif (match\n\t\t// check that no composing char follows\n\t\t&& !(enc_utf8\n\t\t\t  && utf_iscomposing(PTR2CHAR(rex.line + col + len2))))\n\t{\n\t    cleanup_subexpr();\n\t    if (REG_MULTI)\n\t    {\n\t\trex.reg_startpos[0].lnum = rex.lnum;\n\t\trex.reg_startpos[0].col = col;\n\t\trex.reg_endpos[0].lnum = rex.lnum;\n\t\trex.reg_endpos[0].col = col + len2;\n\t    }\n\t    else\n\t    {\n\t\trex.reg_startp[0] = rex.line + col;\n\t\trex.reg_endp[0] = rex.line + col + len2;\n\t    }\n\t    return 1L;\n\t}\n\n\t// Try finding regstart after the current match.\n\tcol += MB_CHAR2LEN(regstart); // skip regstart\n\tif (skip_to_start(regstart, &col) == FAIL)\n\t    break;\n    }\n    return 0L;\n}", "func_hash": 167741715836576091847644361250163558580, "file_name": "None", "file_hash": null, "cwe": ["CWE-122"], "cve": "CVE-2021-3778", "cve_desc": "vim is vulnerable to Heap-based Buffer Overflow", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3778"}
{"idx": 333041, "project": "vim", "commit_id": "65b605665997fad54ef39a93199e305af2fe4d7f", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/65b605665997fad54ef39a93199e305af2fe4d7f", "commit_message": "patch 8.2.3409: reading beyond end of line with invalid utf-8 character\n\nProblem:    Reading beyond end of line with invalid utf-8 character.\nSolution:   Check for NUL when advancing.", "target": 0, "func": "find_match_text(colnr_T startcol, int regstart, char_u *match_text)\n{\n    colnr_T col = startcol;\n    int\t    c1, c2;\n    int\t    len1, len2;\n    int\t    match;\n\n    for (;;)\n    {\n\tmatch = TRUE;\n\tlen2 = MB_CHAR2LEN(regstart); // skip regstart\n\tfor (len1 = 0; match_text[len1] != NUL; len1 += MB_CHAR2LEN(c1))\n\t{\n\t    c1 = PTR2CHAR(match_text + len1);\n\t    c2 = PTR2CHAR(rex.line + col + len2);\n\t    if (c1 != c2 && (!rex.reg_ic || MB_CASEFOLD(c1) != MB_CASEFOLD(c2)))\n\t    {\n\t\tmatch = FALSE;\n\t\tbreak;\n\t    }\n\t    len2 += enc_utf8 ? utf_ptr2len(rex.line + col + len2)\n\t\t\t\t\t\t\t     : MB_CHAR2LEN(c2);\n\t}\n\tif (match\n\t\t// check that no composing char follows\n\t\t&& !(enc_utf8\n\t\t\t  && utf_iscomposing(PTR2CHAR(rex.line + col + len2))))\n\t{\n\t    cleanup_subexpr();\n\t    if (REG_MULTI)\n\t    {\n\t\trex.reg_startpos[0].lnum = rex.lnum;\n\t\trex.reg_startpos[0].col = col;\n\t\trex.reg_endpos[0].lnum = rex.lnum;\n\t\trex.reg_endpos[0].col = col + len2;\n\t    }\n\t    else\n\t    {\n\t\trex.reg_startp[0] = rex.line + col;\n\t\trex.reg_endp[0] = rex.line + col + len2;\n\t    }\n\t    return 1L;\n\t}\n\n\t// Try finding regstart after the current match.\n\tcol += MB_CHAR2LEN(regstart); // skip regstart\n\tif (skip_to_start(regstart, &col) == FAIL)\n\t    break;\n    }\n    return 0L;\n}", "func_hash": 187278234885415513203260954810277689325, "file_name": "None", "file_hash": null, "cwe": ["CWE-122"], "cve": "CVE-2021-3778", "cve_desc": "vim is vulnerable to Heap-based Buffer Overflow", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3778"}
{"idx": 202392, "project": "php-src", "commit_id": "8fa9d1ce28f3a894b104979df30d0b65e0f21107", "project_url": "https://github.com/php/php-src", "commit_url": "https://git.php.net/?p=php-src.git;a=commit;h=8fa9d1ce28f3a894b104979df30d0b65e0f21107", "commit_message": "improve fix #72558, while (u>=0) with unsigned int will always be true", "target": 1, "func": "static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size)\n{\n\tunsigned int u = 0;\n\tLineContribType *res;\n\tint overflow_error = 0;\n\n\tres = (LineContribType *) gdMalloc(sizeof(LineContribType));\n\tif (!res) {\n\t\treturn NULL;\n\t}\n\tres->WindowSize = windows_size;\n\tres->LineLength = line_length;\n\tif (overflow2(line_length, sizeof(ContributionType))) {\n\t\tgdFree(res);\n\t\treturn NULL;\n\t}\n\tres->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType));\n\tif (res->ContribRow == NULL) {\n\t\tgdFree(res);\n\t\treturn NULL;\n\t}\n\tfor (u = 0 ; u < line_length ; u++) {\n\t\tif (overflow2(windows_size, sizeof(double))) {\n\t\t\toverflow_error = 1;\n\t\t} else {\n\t\t\tres->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double));\n\t\t}\n\t\tif (overflow_error == 1 || res->ContribRow[u].Weights == NULL) {\n\t\t\tu--;\n\t\t\twhile (u >= 0) {\n\t\t\t\tgdFree(res->ContribRow[u].Weights);\n\t\t\t\tu--;\n\t\t\t}\n\t\t\treturn NULL;\n\t\t}\n\t}\n\treturn res;\n}", "func_hash": 194329029953977312970767834657292140797, "file_name": "gd_interpolation.c", "file_hash": 48112947254685040097740151772508640024, "cwe": ["CWE-119"], "cve": "CVE-2016-6207", "cve_desc": "Integer overflow in the _gdContributionsAlloc function in gd_interpolation.c in GD Graphics Library (aka libgd) before 2.2.3 allows remote attackers to cause a denial of service (out-of-bounds memory write or memory consumption) via unspecified vectors.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-6207"}
{"idx": 333503, "project": "php-src", "commit_id": "8fa9d1ce28f3a894b104979df30d0b65e0f21107", "project_url": "https://github.com/php/php-src", "commit_url": "https://git.php.net/?p=php-src.git;a=commit;h=8fa9d1ce28f3a894b104979df30d0b65e0f21107", "commit_message": "improve fix #72558, while (u>=0) with unsigned int will always be true", "target": 0, "func": "static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size)\n{\n\tunsigned int u = 0;\n\tLineContribType *res;\n\tint overflow_error = 0;\n\n\tres = (LineContribType *) gdMalloc(sizeof(LineContribType));\n\tif (!res) {\n\t\treturn NULL;\n\t}\n\tres->WindowSize = windows_size;\n\tres->LineLength = line_length;\n\tif (overflow2(line_length, sizeof(ContributionType))) {\n\t\tgdFree(res);\n\t\treturn NULL;\n\t}\n\tres->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType));\n\tif (res->ContribRow == NULL) {\n\t\tgdFree(res);\n\t\treturn NULL;\n\t}\n\tfor (u = 0 ; u < line_length ; u++) {\n\t\tif (overflow2(windows_size, sizeof(double))) {\n\t\t\toverflow_error = 1;\n\t\t} else {\n\t\t\tres->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double));\n\t\t}\n\t\tif (overflow_error == 1 || res->ContribRow[u].Weights == NULL) {\n\t\t\tunsigned int i;\n\t\t\tu--;\n\t\t\tfor (i=0;i<=u;i++) {\n\t\t\t\tgdFree(res->ContribRow[i].Weights);\n\t\t\t}\n\t\t\tgdFree(res);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\treturn res;\n}", "func_hash": 144028133167446566795171831954194871613, "file_name": "gd_interpolation.c", "file_hash": 190827623618557315538392680975816018804, "cwe": ["CWE-119"], "cve": "CVE-2016-6207", "cve_desc": "Integer overflow in the _gdContributionsAlloc function in gd_interpolation.c in GD Graphics Library (aka libgd) before 2.2.3 allows remote attackers to cause a denial of service (out-of-bounds memory write or memory consumption) via unspecified vectors.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-6207"}
{"idx": 202659, "project": "net", "commit_id": "7892032cfe67f4bde6fc2ee967e45a8fbaf33756", "project_url": "https://git.kernel.org/cgit/linux/kernel/git/davem/net", "commit_url": "https://git.kernel.org/cgit/linux/kernel/git/davem/net.git/commit/?id=7892032cfe67f4bde6fc2ee967e45a8fbaf33756", "commit_message": "ip6_gre: fix ip6gre_err() invalid reads\n\nAndrey Konovalov reported out of bound accesses in ip6gre_err()\n\nIf GRE flags contains GRE_KEY, the following expression\n*(((__be32 *)p) + (grehlen / 4) - 1)\n\naccesses data ~40 bytes after the expected point, since\ngrehlen includes the size of IPv6 headers.\n\nLet's use a \"struct gre_base_hdr *greh\" pointer to make this\ncode more readable.\n\np[1] becomes greh->protocol.\ngrhlen is the GRE header length.\n\nFixes: c12b395a4664 (\"gre: Support GRE over IPv6\")\nSigned-off-by: Eric Dumazet \nReported-by: Andrey Konovalov \nSigned-off-by: David S. Miller ", "target": 1, "func": "static void ip6gre_err(struct sk_buff *skb, struct inet6_skb_parm *opt,\n\t\tu8 type, u8 code, int offset, __be32 info)\n{\n\tconst struct ipv6hdr *ipv6h = (const struct ipv6hdr *)skb->data;\n\t__be16 *p = (__be16 *)(skb->data + offset);\n\tint grehlen = offset + 4;\n\tstruct ip6_tnl *t;\n\t__be16 flags;\n\n\tflags = p[0];\n\tif (flags&(GRE_CSUM|GRE_KEY|GRE_SEQ|GRE_ROUTING|GRE_VERSION)) {\n\t\tif (flags&(GRE_VERSION|GRE_ROUTING))\n\t\t\treturn;\n\t\tif (flags&GRE_KEY) {\n\t\t\tgrehlen += 4;\n\t\t\tif (flags&GRE_CSUM)\n\t\t\t\tgrehlen += 4;\n\t\t}\n\t}\n\n\t/* If only 8 bytes returned, keyed message will be dropped here */\n\tif (!pskb_may_pull(skb, grehlen))\n\t\treturn;\n\tipv6h = (const struct ipv6hdr *)skb->data;\n\tp = (__be16 *)(skb->data + offset);\n\n\tt = ip6gre_tunnel_lookup(skb->dev, &ipv6h->daddr, &ipv6h->saddr,\n\t\t\t\tflags & GRE_KEY ?\n\t\t\t\t*(((__be32 *)p) + (grehlen / 4) - 1) : 0,\n\t\t\t\tp[1]);\n\tif (!t)\n\t\treturn;\n\n\tswitch (type) {\n\t\t__u32 teli;\n\t\tstruct ipv6_tlv_tnl_enc_lim *tel;\n\t\t__u32 mtu;\n\tcase ICMPV6_DEST_UNREACH:\n\t\tnet_dbg_ratelimited(\"%s: Path to destination invalid or inactive!\\n\",\n\t\t\t\t    t->parms.name);\n\t\tbreak;\n\tcase ICMPV6_TIME_EXCEED:\n\t\tif (code == ICMPV6_EXC_HOPLIMIT) {\n\t\t\tnet_dbg_ratelimited(\"%s: Too small hop limit or routing loop in tunnel!\\n\",\n\t\t\t\t\t    t->parms.name);\n\t\t}\n\t\tbreak;\n\tcase ICMPV6_PARAMPROB:\n\t\tteli = 0;\n\t\tif (code == ICMPV6_HDR_FIELD)\n\t\t\tteli = ip6_tnl_parse_tlv_enc_lim(skb, skb->data);\n\n\t\tif (teli && teli == be32_to_cpu(info) - 2) {\n\t\t\ttel = (struct ipv6_tlv_tnl_enc_lim *) &skb->data[teli];\n\t\t\tif (tel->encap_limit == 0) {\n\t\t\t\tnet_dbg_ratelimited(\"%s: Too small encapsulation limit or routing loop in tunnel!\\n\",\n\t\t\t\t\t\t    t->parms.name);\n\t\t\t}\n\t\t} else {\n\t\t\tnet_dbg_ratelimited(\"%s: Recipient unable to parse tunneled packet!\\n\",\n\t\t\t\t\t    t->parms.name);\n\t\t}\n\t\tbreak;\n\tcase ICMPV6_PKT_TOOBIG:\n\t\tmtu = be32_to_cpu(info) - offset;\n\t\tif (mtu < IPV6_MIN_MTU)\n\t\t\tmtu = IPV6_MIN_MTU;\n\t\tt->dev->mtu = mtu;\n\t\tbreak;\n\t}\n\n\tif (time_before(jiffies, t->err_time + IP6TUNNEL_ERR_TIMEO))\n\t\tt->err_count++;\n\telse\n\t\tt->err_count = 1;\n\tt->err_time = jiffies;\n}", "func_hash": 14483423650343594705979392035761356983, "file_name": "ip6_gre.c", "file_hash": 117967096098363699106311326917896397499, "cwe": ["CWE-125"], "cve": "CVE-2017-5897", "cve_desc": "The ip6gre_err function in net/ipv6/ip6_gre.c in the Linux kernel allows remote attackers to have unspecified impact via vectors involving GRE flags in an IPv6 packet, which trigger an out-of-bounds access.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-5897"}
{"idx": 336106, "project": "net", "commit_id": "7892032cfe67f4bde6fc2ee967e45a8fbaf33756", "project_url": "https://git.kernel.org/cgit/linux/kernel/git/davem/net", "commit_url": "https://git.kernel.org/cgit/linux/kernel/git/davem/net.git/commit/?id=7892032cfe67f4bde6fc2ee967e45a8fbaf33756", "commit_message": "ip6_gre: fix ip6gre_err() invalid reads\n\nAndrey Konovalov reported out of bound accesses in ip6gre_err()\n\nIf GRE flags contains GRE_KEY, the following expression\n*(((__be32 *)p) + (grehlen / 4) - 1)\n\naccesses data ~40 bytes after the expected point, since\ngrehlen includes the size of IPv6 headers.\n\nLet's use a \"struct gre_base_hdr *greh\" pointer to make this\ncode more readable.\n\np[1] becomes greh->protocol.\ngrhlen is the GRE header length.\n\nFixes: c12b395a4664 (\"gre: Support GRE over IPv6\")\nSigned-off-by: Eric Dumazet \nReported-by: Andrey Konovalov \nSigned-off-by: David S. Miller ", "target": 0, "func": "static void ip6gre_err(struct sk_buff *skb, struct inet6_skb_parm *opt,\n\t\t       u8 type, u8 code, int offset, __be32 info)\n{\n\tconst struct gre_base_hdr *greh;\n\tconst struct ipv6hdr *ipv6h;\n\tint grehlen = sizeof(*greh);\n\tstruct ip6_tnl *t;\n\tint key_off = 0;\n\t__be16 flags;\n\t__be32 key;\n\n\tif (!pskb_may_pull(skb, offset + grehlen))\n\t\treturn;\n\tgreh = (const struct gre_base_hdr *)(skb->data + offset);\n\tflags = greh->flags;\n\tif (flags & (GRE_VERSION | GRE_ROUTING))\n\t\treturn;\n\tif (flags & GRE_CSUM)\n\t\tgrehlen += 4;\n\tif (flags & GRE_KEY) {\n\t\tkey_off = grehlen + offset;\n\t\tgrehlen += 4;\n\t}\n\n\tif (!pskb_may_pull(skb, offset + grehlen))\n\t\treturn;\n\tipv6h = (const struct ipv6hdr *)skb->data;\n\tgreh = (const struct gre_base_hdr *)(skb->data + offset);\n\tkey = key_off ? *(__be32 *)(skb->data + key_off) : 0;\n\n\tt = ip6gre_tunnel_lookup(skb->dev, &ipv6h->daddr, &ipv6h->saddr,\n\t\t\t\t key, greh->protocol);\n\tif (!t)\n\t\treturn;\n\n\tswitch (type) {\n\t\t__u32 teli;\n\t\tstruct ipv6_tlv_tnl_enc_lim *tel;\n\t\t__u32 mtu;\n\tcase ICMPV6_DEST_UNREACH:\n\t\tnet_dbg_ratelimited(\"%s: Path to destination invalid or inactive!\\n\",\n\t\t\t\t    t->parms.name);\n\t\tbreak;\n\tcase ICMPV6_TIME_EXCEED:\n\t\tif (code == ICMPV6_EXC_HOPLIMIT) {\n\t\t\tnet_dbg_ratelimited(\"%s: Too small hop limit or routing loop in tunnel!\\n\",\n\t\t\t\t\t    t->parms.name);\n\t\t}\n\t\tbreak;\n\tcase ICMPV6_PARAMPROB:\n\t\tteli = 0;\n\t\tif (code == ICMPV6_HDR_FIELD)\n\t\t\tteli = ip6_tnl_parse_tlv_enc_lim(skb, skb->data);\n\n\t\tif (teli && teli == be32_to_cpu(info) - 2) {\n\t\t\ttel = (struct ipv6_tlv_tnl_enc_lim *) &skb->data[teli];\n\t\t\tif (tel->encap_limit == 0) {\n\t\t\t\tnet_dbg_ratelimited(\"%s: Too small encapsulation limit or routing loop in tunnel!\\n\",\n\t\t\t\t\t\t    t->parms.name);\n\t\t\t}\n\t\t} else {\n\t\t\tnet_dbg_ratelimited(\"%s: Recipient unable to parse tunneled packet!\\n\",\n\t\t\t\t\t    t->parms.name);\n\t\t}\n\t\tbreak;\n\tcase ICMPV6_PKT_TOOBIG:\n\t\tmtu = be32_to_cpu(info) - offset;\n\t\tif (mtu < IPV6_MIN_MTU)\n\t\t\tmtu = IPV6_MIN_MTU;\n\t\tt->dev->mtu = mtu;\n\t\tbreak;\n\t}\n\n\tif (time_before(jiffies, t->err_time + IP6TUNNEL_ERR_TIMEO))\n\t\tt->err_count++;\n\telse\n\t\tt->err_count = 1;\n\tt->err_time = jiffies;\n}", "func_hash": 275651998275867668694727636706080952271, "file_name": "ip6_gre.c", "file_hash": 12117188675970598231582084849956564114, "cwe": ["CWE-125"], "cve": "CVE-2017-5897", "cve_desc": "The ip6gre_err function in net/ipv6/ip6_gre.c in the Linux kernel allows remote attackers to have unspecified impact via vectors involving GRE flags in an IPv6 packet, which trigger an out-of-bounds access.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-5897"}
{"idx": 202677, "project": "qemu", "commit_id": "9302e863aa8baa5d932fc078967050c055fa1a7f", "project_url": "https://github.com/bonzini/qemu", "commit_url": "http://git.qemu.org/?p=qemu.git;a=commit;h=9302e863aa8baa5d932fc078967050c055fa1a7f", "commit_message": "parallels: Sanity check for s->tracks (CVE-2014-0142)\n\nThis avoids a possible division by zero.\n\nConvert s->tracks to unsigned as well because it feels better than\nsurviving just because the results of calculations with s->tracks are\nconverted to unsigned anyway.\n\nSigned-off-by: Kevin Wolf \nReviewed-by: Max Reitz \nSigned-off-by: Stefan Hajnoczi ", "target": 1, "func": "static int parallels_open(BlockDriverState *bs, QDict *options, int flags,\n                          Error **errp)\n{\n    BDRVParallelsState *s = bs->opaque;\n    int i;\n    struct parallels_header ph;\n    int ret;\n\n    bs->read_only = 1; // no write support yet\n\n    ret = bdrv_pread(bs->file, 0, &ph, sizeof(ph));\n    if (ret < 0) {\n        goto fail;\n    }\n\n    if (memcmp(ph.magic, HEADER_MAGIC, 16) ||\n        (le32_to_cpu(ph.version) != HEADER_VERSION)) {\n        error_setg(errp, \"Image not in Parallels format\");\n        ret = -EINVAL;\n        goto fail;\n    }\n\n    bs->total_sectors = le32_to_cpu(ph.nb_sectors);\n\n    s->tracks = le32_to_cpu(ph.tracks);\n\n    s->catalog_size = le32_to_cpu(ph.catalog_entries);\n    if (s->catalog_size > INT_MAX / 4) {\n        error_setg(errp, \"Catalog too large\");\n        ret = -EFBIG;\n        goto fail;\n    }\n    s->catalog_bitmap = g_malloc(s->catalog_size * 4);\n\n    ret = bdrv_pread(bs->file, 64, s->catalog_bitmap, s->catalog_size * 4);\n    if (ret < 0) {\n        goto fail;\n    }\n\n    for (i = 0; i < s->catalog_size; i++)\n\tle32_to_cpus(&s->catalog_bitmap[i]);\n\n    qemu_co_mutex_init(&s->lock);\n    return 0;\n\nfail:\n    g_free(s->catalog_bitmap);\n    return ret;\n}", "func_hash": 337127974960403546779692670017681638774, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2014-0142", "cve_desc": "QEMU, possibly before 2.0.0, allows local users to cause a denial of service (divide-by-zero error and crash) via a zero value in the (1) tracks field to the seek_to_sector function in block/parallels.c or (2) extent_size field in the bochs function in block/bochs.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-0142"}
{"idx": 336484, "project": "qemu", "commit_id": "9302e863aa8baa5d932fc078967050c055fa1a7f", "project_url": "https://github.com/bonzini/qemu", "commit_url": "http://git.qemu.org/?p=qemu.git;a=commit;h=9302e863aa8baa5d932fc078967050c055fa1a7f", "commit_message": "parallels: Sanity check for s->tracks (CVE-2014-0142)\n\nThis avoids a possible division by zero.\n\nConvert s->tracks to unsigned as well because it feels better than\nsurviving just because the results of calculations with s->tracks are\nconverted to unsigned anyway.\n\nSigned-off-by: Kevin Wolf \nReviewed-by: Max Reitz \nSigned-off-by: Stefan Hajnoczi ", "target": 0, "func": "static int parallels_open(BlockDriverState *bs, QDict *options, int flags,\n                          Error **errp)\n{\n    BDRVParallelsState *s = bs->opaque;\n    int i;\n    struct parallels_header ph;\n    int ret;\n\n    bs->read_only = 1; // no write support yet\n\n    ret = bdrv_pread(bs->file, 0, &ph, sizeof(ph));\n    if (ret < 0) {\n        goto fail;\n    }\n\n    if (memcmp(ph.magic, HEADER_MAGIC, 16) ||\n        (le32_to_cpu(ph.version) != HEADER_VERSION)) {\n        error_setg(errp, \"Image not in Parallels format\");\n        ret = -EINVAL;\n        goto fail;\n    }\n\n    bs->total_sectors = le32_to_cpu(ph.nb_sectors);\n\n    s->tracks = le32_to_cpu(ph.tracks);\n    if (s->tracks == 0) {\n        error_setg(errp, \"Invalid image: Zero sectors per track\");\n        ret = -EINVAL;\n        goto fail;\n    }\n\n    s->catalog_size = le32_to_cpu(ph.catalog_entries);\n    if (s->catalog_size > INT_MAX / 4) {\n        error_setg(errp, \"Catalog too large\");\n        ret = -EFBIG;\n        goto fail;\n    }\n    s->catalog_bitmap = g_malloc(s->catalog_size * 4);\n\n    ret = bdrv_pread(bs->file, 64, s->catalog_bitmap, s->catalog_size * 4);\n    if (ret < 0) {\n        goto fail;\n    }\n\n    for (i = 0; i < s->catalog_size; i++)\n\tle32_to_cpus(&s->catalog_bitmap[i]);\n\n    qemu_co_mutex_init(&s->lock);\n    return 0;\n\nfail:\n    g_free(s->catalog_bitmap);\n    return ret;\n}", "func_hash": 85532877697804718298733270367705862714, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2014-0142", "cve_desc": "QEMU, possibly before 2.0.0, allows local users to cause a denial of service (divide-by-zero error and crash) via a zero value in the (1) tracks field to the seek_to_sector function in block/parallels.c or (2) extent_size field in the bochs function in block/bochs.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-0142"}
{"idx": 202688, "project": "ghostpdl", "commit_id": "450da26a76286a8342ec0864b3d113856709f8f6", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "https://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=450da26a76286a8342ec0864b3d113856709f8f6", "commit_message": "Bug 701785: fixed sanitizer heap-buffer-overflow in lprn_is_black().\n\nIn contrib/lips4/gdevlprn.c:lprn_is_black(), it seems that bpl is not\nnecessarily a multiple of lprn->nBw, so we need to explicitly avoid straying\ninto the next line's data.\n\nThis also avoids accessing beyond our buffer if we are already on the last\nline, and so fixes the sanitizer error.\n\nFixes:\n    ./sanbin/gs -sOutputFile=tmp -sDEVICE=lips2p ../bug-701785.pdf", "target": 1, "func": "lprn_is_black(gx_device_printer * pdev, int r, int h, int bx)\n{\n    gx_device_lprn *const lprn = (gx_device_lprn *) pdev;\n\n    int bh = lprn->nBh;\n    int bpl = gdev_mem_bytes_per_scan_line(pdev);\n    int x, y, y0;\n    byte *p;\n    int maxY = lprn->BlockLine / lprn->nBh * lprn->nBh;\n\n    y0 = (r + h - bh) % maxY;\n    for (y = 0; y < bh; y++) {\n        p = &lprn->ImageBuf[(y0 + y) * bpl + bx * lprn->nBw];\n        for (x = 0; x < lprn->nBw; x++)\n            if (p[x] != 0)\n                return 1;\n    }\n    return 0;\n}", "func_hash": 276235081077601818208956388725727672709, "file_name": "gdevlprn.c", "file_hash": 146789313062349427560159100335401323936, "cwe": ["CWE-787"], "cve": "CVE-2020-16287", "cve_desc": "A buffer overflow vulnerability in lprn_is_black() in contrib/lips4/gdevlprn.c of Artifex Software GhostScript v9.50 allows a remote attacker to cause a denial of service via a crafted PDF file. This is fixed in v9.51.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16287"}
{"idx": 336807, "project": "ghostpdl", "commit_id": "450da26a76286a8342ec0864b3d113856709f8f6", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "https://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=450da26a76286a8342ec0864b3d113856709f8f6", "commit_message": "Bug 701785: fixed sanitizer heap-buffer-overflow in lprn_is_black().\n\nIn contrib/lips4/gdevlprn.c:lprn_is_black(), it seems that bpl is not\nnecessarily a multiple of lprn->nBw, so we need to explicitly avoid straying\ninto the next line's data.\n\nThis also avoids accessing beyond our buffer if we are already on the last\nline, and so fixes the sanitizer error.\n\nFixes:\n    ./sanbin/gs -sOutputFile=tmp -sDEVICE=lips2p ../bug-701785.pdf", "target": 0, "func": "lprn_is_black(gx_device_printer * pdev, int r, int h, int bx)\n{\n    gx_device_lprn *const lprn = (gx_device_lprn *) pdev;\n\n    int bh = lprn->nBh;\n    int bpl = gdev_mem_bytes_per_scan_line(pdev);\n    int x, y, y0;\n    byte *p;\n    int maxY = lprn->BlockLine / lprn->nBh * lprn->nBh;\n\n    y0 = (r + h - bh) % maxY;\n    for (y = 0; y < bh; y++) {\n        p = &lprn->ImageBuf[(y0 + y) * bpl + bx * lprn->nBw];\n        for (x = 0; x < lprn->nBw; x++) {\n            /* bpl isn't necessarily a multiple of lprn->nBw, so\n            we need to explicitly stop after the last byte in this\n            line to avoid accessing either the next line's data or\n            going off the end of our buffer completely. This avoids\n            https://bugs.ghostscript.com/show_bug.cgi?id=701785. */\n            if (bx * lprn->nBw + x >= bpl)  break;\n            if (p[x] != 0)\n                return 1;\n        }\n    }\n    return 0;\n}", "func_hash": 150670636989365509549221893772046699987, "file_name": "gdevlprn.c", "file_hash": 90759681637200263840236208606383547324, "cwe": ["CWE-787"], "cve": "CVE-2020-16287", "cve_desc": "A buffer overflow vulnerability in lprn_is_black() in contrib/lips4/gdevlprn.c of Artifex Software GhostScript v9.50 allows a remote attacker to cause a denial of service via a crafted PDF file. This is fixed in v9.51.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16287"}
{"idx": 202708, "project": "vim", "commit_id": "8e4b76da1d7e987d43ca960dfbc372d1c617466f", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/8e4b76da1d7e987d43ca960dfbc372d1c617466f", "commit_message": "patch 8.2.4901: NULL pointer access when using invalid pattern\n\nProblem:    NULL pointer access when using invalid pattern.\nSolution:   Check for failed regexp program.", "target": 1, "func": "fname_match(\n    regmatch_T\t*rmp,\n    char_u\t*name,\n    int\t\tignore_case)  // when TRUE ignore case, when FALSE use 'fic'\n{\n    char_u\t*match = NULL;\n    char_u\t*p;\n\n    if (name != NULL)\n    {\n\t// Ignore case when 'fileignorecase' or the argument is set.\n\trmp->rm_ic = p_fic || ignore_case;\n\tif (vim_regexec(rmp, name, (colnr_T)0))\n\t    match = name;\n\telse\n\t{\n\t    // Replace $(HOME) with '~' and try matching again.\n\t    p = home_replace_save(NULL, name);\n\t    if (p != NULL && vim_regexec(rmp, p, (colnr_T)0))\n\t\tmatch = name;\n\t    vim_free(p);\n\t}\n    }\n\n    return match;\n}", "func_hash": 10065855190174385623233460326166538906, "file_name": "buffer.c", "file_hash": 293823123124136567259918164990957667329, "cwe": ["CWE-476"], "cve": "CVE-2022-1620", "cve_desc": "NULL Pointer Dereference in function vim_regexec_string at regexp.c:2729 in GitHub repository vim/vim prior to 8.2.4901. NULL Pointer Dereference in function vim_regexec_string at regexp.c:2729 allows attackers to cause a denial of service (application crash) via a crafted input.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1620"}
{"idx": 337374, "project": "vim", "commit_id": "8e4b76da1d7e987d43ca960dfbc372d1c617466f", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/8e4b76da1d7e987d43ca960dfbc372d1c617466f", "commit_message": "patch 8.2.4901: NULL pointer access when using invalid pattern\n\nProblem:    NULL pointer access when using invalid pattern.\nSolution:   Check for failed regexp program.", "target": 0, "func": "fname_match(\n    regmatch_T\t*rmp,\n    char_u\t*name,\n    int\t\tignore_case)  // when TRUE ignore case, when FALSE use 'fic'\n{\n    char_u\t*match = NULL;\n    char_u\t*p;\n\n    if (name != NULL)\n    {\n\t// Ignore case when 'fileignorecase' or the argument is set.\n\trmp->rm_ic = p_fic || ignore_case;\n\tif (vim_regexec(rmp, name, (colnr_T)0))\n\t    match = name;\n\telse if (rmp->regprog != NULL)\n\t{\n\t    // Replace $(HOME) with '~' and try matching again.\n\t    p = home_replace_save(NULL, name);\n\t    if (p != NULL && vim_regexec(rmp, p, (colnr_T)0))\n\t\tmatch = name;\n\t    vim_free(p);\n\t}\n    }\n\n    return match;\n}", "func_hash": 197882423023027832397527147027813452758, "file_name": "buffer.c", "file_hash": 116246354520267882741601792511100691040, "cwe": ["CWE-476"], "cve": "CVE-2022-1620", "cve_desc": "NULL Pointer Dereference in function vim_regexec_string at regexp.c:2729 in GitHub repository vim/vim prior to 8.2.4901. NULL Pointer Dereference in function vim_regexec_string at regexp.c:2729 allows attackers to cause a denial of service (application crash) via a crafted input.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1620"}
{"idx": 202719, "project": "linux", "commit_id": "a2d859e3fc97e79d907761550dbc03ff1b36479c", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=a2d859e3fc97e79d907761550dbc03ff1b36479c", "commit_message": "sctp: account stream padding length for reconf chunk\n\nsctp_make_strreset_req() makes repeated calls to sctp_addto_chunk()\nwhich will automatically account for padding on each call. inreq and\noutreq are already 4 bytes aligned, but the payload is not and doing\nSCTP_PAD4(a + b) (which _sctp_make_chunk() did implicitly here) is\ndifferent from SCTP_PAD4(a) + SCTP_PAD4(b) and not enough. It led to\npossible attempt to use more buffer than it was allocated and triggered\na BUG_ON.\n\nCc: Vlad Yasevich \nCc: Neil Horman \nCc: Greg KH \nFixes: cc16f00f6529 (\"sctp: add support for generating stream reconf ssn reset request chunk\")\nReported-by: Eiichi Tsukata \nSigned-off-by: Eiichi Tsukata \nSigned-off-by: Marcelo Ricardo Leitner \nSigned-off-by: Marcelo Ricardo Leitner \nReviewed-by: Xin Long \nLink: https://lore.kernel.org/r/b97c1f8b0c7ff79ac4ed206fc2c49d3612e0850c.1634156849.git.mleitner@redhat.com\nSigned-off-by: Jakub Kicinski ", "target": 1, "func": "struct sctp_chunk *sctp_make_strreset_req(\n\t\t\t\t\tconst struct sctp_association *asoc,\n\t\t\t\t\t__u16 stream_num, __be16 *stream_list,\n\t\t\t\t\tbool out, bool in)\n{\n\t__u16 stream_len = stream_num * sizeof(__u16);\n\tstruct sctp_strreset_outreq outreq;\n\tstruct sctp_strreset_inreq inreq;\n\tstruct sctp_chunk *retval;\n\t__u16 outlen, inlen;\n\n\toutlen = (sizeof(outreq) + stream_len) * out;\n\tinlen = (sizeof(inreq) + stream_len) * in;\n\n\tretval = sctp_make_reconf(asoc, outlen + inlen);\n\tif (!retval)\n\t\treturn NULL;\n\n\tif (outlen) {\n\t\toutreq.param_hdr.type = SCTP_PARAM_RESET_OUT_REQUEST;\n\t\toutreq.param_hdr.length = htons(outlen);\n\t\toutreq.request_seq = htonl(asoc->strreset_outseq);\n\t\toutreq.response_seq = htonl(asoc->strreset_inseq - 1);\n\t\toutreq.send_reset_at_tsn = htonl(asoc->next_tsn - 1);\n\n\t\tsctp_addto_chunk(retval, sizeof(outreq), &outreq);\n\n\t\tif (stream_len)\n\t\t\tsctp_addto_chunk(retval, stream_len, stream_list);\n\t}\n\n\tif (inlen) {\n\t\tinreq.param_hdr.type = SCTP_PARAM_RESET_IN_REQUEST;\n\t\tinreq.param_hdr.length = htons(inlen);\n\t\tinreq.request_seq = htonl(asoc->strreset_outseq + out);\n\n\t\tsctp_addto_chunk(retval, sizeof(inreq), &inreq);\n\n\t\tif (stream_len)\n\t\t\tsctp_addto_chunk(retval, stream_len, stream_list);\n\t}\n\n\treturn retval;\n}", "func_hash": 215335113411495657240056321729109595636, "file_name": "sm_make_chunk.c", "file_hash": 110519816461895113606911923370921219323, "cwe": ["CWE-704"], "cve": "CVE-2022-0322", "cve_desc": "A flaw was found in the sctp_make_strreset_req function in net/sctp/sm_make_chunk.c in the SCTP network protocol in the Linux kernel with a local user privilege access. In this flaw, an attempt to use more buffer than is allocated triggers a BUG_ON issue, leading to a denial of service (DOS).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0322"}
{"idx": 337848, "project": "linux", "commit_id": "a2d859e3fc97e79d907761550dbc03ff1b36479c", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=a2d859e3fc97e79d907761550dbc03ff1b36479c", "commit_message": "sctp: account stream padding length for reconf chunk\n\nsctp_make_strreset_req() makes repeated calls to sctp_addto_chunk()\nwhich will automatically account for padding on each call. inreq and\noutreq are already 4 bytes aligned, but the payload is not and doing\nSCTP_PAD4(a + b) (which _sctp_make_chunk() did implicitly here) is\ndifferent from SCTP_PAD4(a) + SCTP_PAD4(b) and not enough. It led to\npossible attempt to use more buffer than it was allocated and triggered\na BUG_ON.\n\nCc: Vlad Yasevich \nCc: Neil Horman \nCc: Greg KH \nFixes: cc16f00f6529 (\"sctp: add support for generating stream reconf ssn reset request chunk\")\nReported-by: Eiichi Tsukata \nSigned-off-by: Eiichi Tsukata \nSigned-off-by: Marcelo Ricardo Leitner \nSigned-off-by: Marcelo Ricardo Leitner \nReviewed-by: Xin Long \nLink: https://lore.kernel.org/r/b97c1f8b0c7ff79ac4ed206fc2c49d3612e0850c.1634156849.git.mleitner@redhat.com\nSigned-off-by: Jakub Kicinski ", "target": 0, "func": "struct sctp_chunk *sctp_make_strreset_req(\n\t\t\t\t\tconst struct sctp_association *asoc,\n\t\t\t\t\t__u16 stream_num, __be16 *stream_list,\n\t\t\t\t\tbool out, bool in)\n{\n\t__u16 stream_len = stream_num * sizeof(__u16);\n\tstruct sctp_strreset_outreq outreq;\n\tstruct sctp_strreset_inreq inreq;\n\tstruct sctp_chunk *retval;\n\t__u16 outlen, inlen;\n\n\toutlen = (sizeof(outreq) + stream_len) * out;\n\tinlen = (sizeof(inreq) + stream_len) * in;\n\n\tretval = sctp_make_reconf(asoc, SCTP_PAD4(outlen) + SCTP_PAD4(inlen));\n\tif (!retval)\n\t\treturn NULL;\n\n\tif (outlen) {\n\t\toutreq.param_hdr.type = SCTP_PARAM_RESET_OUT_REQUEST;\n\t\toutreq.param_hdr.length = htons(outlen);\n\t\toutreq.request_seq = htonl(asoc->strreset_outseq);\n\t\toutreq.response_seq = htonl(asoc->strreset_inseq - 1);\n\t\toutreq.send_reset_at_tsn = htonl(asoc->next_tsn - 1);\n\n\t\tsctp_addto_chunk(retval, sizeof(outreq), &outreq);\n\n\t\tif (stream_len)\n\t\t\tsctp_addto_chunk(retval, stream_len, stream_list);\n\t}\n\n\tif (inlen) {\n\t\tinreq.param_hdr.type = SCTP_PARAM_RESET_IN_REQUEST;\n\t\tinreq.param_hdr.length = htons(inlen);\n\t\tinreq.request_seq = htonl(asoc->strreset_outseq + out);\n\n\t\tsctp_addto_chunk(retval, sizeof(inreq), &inreq);\n\n\t\tif (stream_len)\n\t\t\tsctp_addto_chunk(retval, stream_len, stream_list);\n\t}\n\n\treturn retval;\n}", "func_hash": 175020260748921031996578395052444557756, "file_name": "sm_make_chunk.c", "file_hash": 72489321105602052766082993841220689495, "cwe": ["CWE-704"], "cve": "CVE-2022-0322", "cve_desc": "A flaw was found in the sctp_make_strreset_req function in net/sctp/sm_make_chunk.c in the SCTP network protocol in the Linux kernel with a local user privilege access. In this flaw, an attempt to use more buffer than is allocated triggers a BUG_ON issue, leading to a denial of service (DOS).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0322"}
{"idx": 202748, "project": "ImageMagick", "commit_id": "fbb5e1c8211c4e88ecc367e784b79d457c300d6d", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/fbb5e1c8211c4e88ecc367e784b79d457c300d6d", "commit_message": "...", "target": 1, "func": "static Image *ReadTGAImage(const ImageInfo *image_info,\n  ExceptionInfo *exception)\n{\n  Image\n    *image;\n\n  MagickBooleanType\n    status;\n\n  PixelInfo\n    pixel;\n\n  Quantum\n    index;\n\n  register Quantum\n    *q;\n\n  register ssize_t\n    i,\n    x;\n\n  size_t\n    base,\n    flag,\n    offset,\n    real,\n    skip;\n\n  ssize_t\n    count,\n    y;\n\n  TGAInfo\n    tga_info;\n\n  unsigned char\n    j,\n    k,\n    pixels[4],\n    runlength;\n\n  unsigned int\n    alpha_bits;\n\n  /*\n    Open image file.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  image=AcquireImage(image_info,exception);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n    Read TGA header information.\n  */\n  count=ReadBlob(image,1,&tga_info.id_length);\n  tga_info.colormap_type=(unsigned char) ReadBlobByte(image);\n  tga_info.image_type=(TGAImageType) ReadBlobByte(image);\n  if ((count != 1) ||\n      ((tga_info.image_type != TGAColormap) &&\n       (tga_info.image_type != TGARGB) &&\n       (tga_info.image_type != TGAMonochrome) &&\n       (tga_info.image_type != TGARLEColormap) &&\n       (tga_info.image_type != TGARLERGB) &&\n       (tga_info.image_type != TGARLEMonochrome)) ||\n      (((tga_info.image_type == TGAColormap) ||\n       (tga_info.image_type == TGARLEColormap)) &&\n       (tga_info.colormap_type == 0)))\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  tga_info.colormap_index=ReadBlobLSBShort(image);\n  tga_info.colormap_length=ReadBlobLSBShort(image);\n  tga_info.colormap_size=(unsigned char) ReadBlobByte(image);\n  tga_info.x_origin=ReadBlobLSBShort(image);\n  tga_info.y_origin=ReadBlobLSBShort(image);\n  tga_info.width=(unsigned short) ReadBlobLSBShort(image);\n  tga_info.height=(unsigned short) ReadBlobLSBShort(image);\n  tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image);\n  tga_info.attributes=(unsigned char) ReadBlobByte(image);\n  if (EOFBlob(image) != MagickFalse)\n    ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n  if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) &&\n       (tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32)))\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  /*\n    Initialize image structure.\n  */\n  image->columns=tga_info.width;\n  image->rows=tga_info.height;\n  alpha_bits=(tga_info.attributes & 0x0FU);\n  image->alpha_trait=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) ||\n    (tga_info.colormap_size == 32) ?  BlendPixelTrait : UndefinedPixelTrait;\n  if ((tga_info.image_type != TGAColormap) &&\n      (tga_info.image_type != TGARLEColormap))\n    image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 :\n      (tga_info.bits_per_pixel <= 16) ? 5 : 8);\n  else\n    image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 :\n      (tga_info.colormap_size <= 16) ? 5 : 8);\n  if ((tga_info.image_type == TGAColormap) ||\n      (tga_info.image_type == TGAMonochrome) ||\n      (tga_info.image_type == TGARLEColormap) ||\n      (tga_info.image_type == TGARLEMonochrome))\n    image->storage_class=PseudoClass;\n  image->compression=NoCompression;\n  if ((tga_info.image_type == TGARLEColormap) ||\n      (tga_info.image_type == TGARLEMonochrome) ||\n      (tga_info.image_type == TGARLERGB))\n    image->compression=RLECompression;\n  if (image->storage_class == PseudoClass)\n    {\n      if (tga_info.colormap_type != 0)\n        image->colors=tga_info.colormap_index+tga_info.colormap_length;\n      else\n        {\n          size_t\n            one;\n\n          one=1;\n          image->colors=one << tga_info.bits_per_pixel;\n          if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n            ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        }\n    }\n  if (tga_info.id_length != 0)\n    {\n      char\n        *comment;\n\n      size_t\n        length;\n\n      /*\n        TGA image comment.\n      */\n      length=(size_t) tga_info.id_length;\n      comment=(char *) NULL;\n      if (~length >= (MagickPathExtent-1))\n        comment=(char *) AcquireQuantumMemory(length+MagickPathExtent,\n          sizeof(*comment));\n      if (comment == (char *) NULL)\n        ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n      count=ReadBlob(image,tga_info.id_length,(unsigned char *) comment);\n      comment[tga_info.id_length]='\\0';\n      (void) SetImageProperty(image,\"comment\",comment,exception);\n      comment=DestroyString(comment);\n    }\n  if (tga_info.attributes & (1UL << 4))\n    {\n      if (tga_info.attributes & (1UL << 5))\n        SetImageArtifact(image,\"tga:image-origin\",\"TopRight\");\n      else\n        SetImageArtifact(image,\"tga:image-origin\",\"BottomRight\");\n    }\n  else\n    {\n      if (tga_info.attributes & (1UL << 5))\n        SetImageArtifact(image,\"tga:image-origin\",\"TopLeft\");\n      else\n        SetImageArtifact(image,\"tga:image-origin\",\"BottomLeft\");\n    }\n  if (image_info->ping != MagickFalse)\n    {\n      (void) CloseBlob(image);\n      return(image);\n    }\n  status=SetImageExtent(image,image->columns,image->rows,exception);\n  if (status == MagickFalse)\n    return(DestroyImageList(image));\n  (void) ResetMagickMemory(&pixel,0,sizeof(pixel));\n  pixel.alpha=(MagickRealType) OpaqueAlpha;\n  if (tga_info.colormap_type != 0)\n    {\n      /*\n        Read TGA raster colormap.\n      */\n      if (image->colors < tga_info.colormap_index)\n        image->colors=tga_info.colormap_index;\n      if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n        ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n      for (i=0; i < (ssize_t) tga_info.colormap_index; i++)\n        image->colormap[i]=pixel;\n      for ( ; i < (ssize_t) image->colors; i++)\n      {\n        switch (tga_info.colormap_size)\n        {\n          case 8:\n          default:\n          {\n            /*\n              Gray scale.\n            */\n            pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            pixel.green=pixel.red;\n            pixel.blue=pixel.red;\n            break;\n          }\n          case 15:\n          case 16:\n          {\n            QuantumAny\n              range;\n\n            /*\n              5 bits each of red green and blue.\n            */\n            j=(unsigned char) ReadBlobByte(image);\n            k=(unsigned char) ReadBlobByte(image);\n            range=GetQuantumRange(5UL);\n            pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,\n              range);\n            pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*(k & 0x03)\n              << 3)+(1UL*(j & 0xe0) >> 5),range);\n            pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);\n            break;\n          }\n          case 24:\n          {\n            /*\n              8 bits each of blue, green and red.\n            */\n            pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            break;\n          }\n          case 32:\n          {\n            /*\n              8 bits each of blue, green, red, and alpha.\n            */\n            pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            pixel.alpha=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            break;\n          }\n        }\n        image->colormap[i]=pixel;\n      }\n    }\n  /*\n    Convert TGA pixels to pixel packets.\n  */\n  base=0;\n  flag=0;\n  skip=MagickFalse;\n  real=0;\n  index=0;\n  runlength=0;\n  offset=0;\n  for (y=0; y < (ssize_t) image->rows; y++)\n  {\n    real=offset;\n    if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0)\n      real=image->rows-real-1;\n    q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception);\n    if (q == (Quantum *) NULL)\n      break;\n    for (x=0; x < (ssize_t) image->columns; x++)\n    {\n      if ((tga_info.image_type == TGARLEColormap) ||\n          (tga_info.image_type == TGARLERGB) ||\n          (tga_info.image_type == TGARLEMonochrome))\n        {\n          if (runlength != 0)\n            {\n              runlength--;\n              skip=flag != 0;\n            }\n          else\n            {\n              count=ReadBlob(image,1,&runlength);\n              if (count != 1)\n                ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n              flag=runlength & 0x80;\n              if (flag != 0)\n                runlength-=128;\n              skip=MagickFalse;\n            }\n        }\n      if (skip == MagickFalse)\n        switch (tga_info.bits_per_pixel)\n        {\n          case 8:\n          default:\n          {\n            /*\n              Gray scale.\n            */\n            index=(Quantum) ReadBlobByte(image);\n            if (tga_info.colormap_type != 0)\n              pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image,\n                (ssize_t) index,exception)];\n            else\n              {\n                pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)\n                  index);\n                pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)\n                  index);\n                pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)\n                  index);\n              }\n            break;\n          }\n          case 15:\n          case 16:\n          {\n            QuantumAny\n              range;\n\n            /*\n              5 bits each of RGB.\n            */\n            if (ReadBlob(image,2,pixels) != 2)\n              ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n            j=pixels[0];\n            k=pixels[1];\n            range=GetQuantumRange(5UL);\n            pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,\n              range);\n            pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*\n              (k & 0x03) << 3)+(1UL*(j & 0xe0) >> 5),range);\n            pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);\n            if (image->alpha_trait != UndefinedPixelTrait)\n              pixel.alpha=(MagickRealType) ((k & 0x80) == 0 ? (Quantum)\n                TransparentAlpha : (Quantum) OpaqueAlpha);\n            if (image->storage_class == PseudoClass)\n              index=(Quantum) ConstrainColormapIndex(image,((ssize_t) (k << 8))+\n                j,exception);\n            break;\n          }\n          case 24:\n          {\n            /*\n              BGR pixels.\n            */\n            if (ReadBlob(image,3,pixels) != 3)\n              ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n            pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);\n            pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);\n            pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);\n            break;\n          }\n          case 32:\n          {\n            /*\n              BGRA pixels.\n            */\n            if (ReadBlob(image,4,pixels) != 4)\n              ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n            pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);\n            pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);\n            pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);\n            pixel.alpha=(MagickRealType) ScaleCharToQuantum(pixels[3]);\n            break;\n          }\n        }\n      if (status == MagickFalse)\n        ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n      if (image->storage_class == PseudoClass)\n        SetPixelIndex(image,index,q);\n      SetPixelRed(image,ClampToQuantum(pixel.red),q);\n      SetPixelGreen(image,ClampToQuantum(pixel.green),q);\n      SetPixelBlue(image,ClampToQuantum(pixel.blue),q);\n      if (image->alpha_trait != UndefinedPixelTrait)\n        SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n      q+=GetPixelChannels(image);\n    }\n    /*\n      if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 4)\n        offset+=4;\n      else\n    */\n      if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 2)\n        offset+=2;\n      else\n        offset++;\n    if (offset >= image->rows)\n      {\n        base++;\n        offset=base;\n      }\n    if (SyncAuthenticPixels(image,exception) == MagickFalse)\n      break;\n    if (image->previous == (Image *) NULL)\n      {\n        status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n          image->rows);\n        if (status == MagickFalse)\n          break;\n      }\n  }\n  if (EOFBlob(image) != MagickFalse)\n    ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n      image->filename);\n  (void) CloseBlob(image);\n  return(GetFirstImageInList(image));\n}", "func_hash": 95115433929731884744054008378657506459, "file_name": "tga.c", "file_hash": 229955351147198147579545037524450823231, "cwe": ["CWE-772"], "cve": "CVE-2017-11170", "cve_desc": "The ReadTGAImage function in coders\\tga.c in ImageMagick 7.0.5-6 has a memory leak vulnerability that can cause memory exhaustion via invalid colors data in the header of a TGA or VST file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-11170"}
{"idx": 338747, "project": "ImageMagick", "commit_id": "fbb5e1c8211c4e88ecc367e784b79d457c300d6d", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/fbb5e1c8211c4e88ecc367e784b79d457c300d6d", "commit_message": "...", "target": 0, "func": "static Image *ReadTGAImage(const ImageInfo *image_info,\n  ExceptionInfo *exception)\n{\n  Image\n    *image;\n\n  MagickBooleanType\n    status;\n\n  PixelInfo\n    pixel;\n\n  Quantum\n    index;\n\n  register Quantum\n    *q;\n\n  register ssize_t\n    i,\n    x;\n\n  size_t\n    base,\n    flag,\n    offset,\n    real,\n    skip;\n\n  ssize_t\n    count,\n    y;\n\n  TGAInfo\n    tga_info;\n\n  unsigned char\n    j,\n    k,\n    pixels[4],\n    runlength;\n\n  unsigned int\n    alpha_bits;\n\n  /*\n    Open image file.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  image=AcquireImage(image_info,exception);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n    Read TGA header information.\n  */\n  count=ReadBlob(image,1,&tga_info.id_length);\n  tga_info.colormap_type=(unsigned char) ReadBlobByte(image);\n  tga_info.image_type=(TGAImageType) ReadBlobByte(image);\n  if ((count != 1) ||\n      ((tga_info.image_type != TGAColormap) &&\n       (tga_info.image_type != TGARGB) &&\n       (tga_info.image_type != TGAMonochrome) &&\n       (tga_info.image_type != TGARLEColormap) &&\n       (tga_info.image_type != TGARLERGB) &&\n       (tga_info.image_type != TGARLEMonochrome)) ||\n      (((tga_info.image_type == TGAColormap) ||\n       (tga_info.image_type == TGARLEColormap)) &&\n       (tga_info.colormap_type == 0)))\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  tga_info.colormap_index=ReadBlobLSBShort(image);\n  tga_info.colormap_length=ReadBlobLSBShort(image);\n  tga_info.colormap_size=(unsigned char) ReadBlobByte(image);\n  tga_info.x_origin=ReadBlobLSBShort(image);\n  tga_info.y_origin=ReadBlobLSBShort(image);\n  tga_info.width=(unsigned short) ReadBlobLSBShort(image);\n  tga_info.height=(unsigned short) ReadBlobLSBShort(image);\n  tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image);\n  tga_info.attributes=(unsigned char) ReadBlobByte(image);\n  if (EOFBlob(image) != MagickFalse)\n    ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n  if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) &&\n       (tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32)))\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  /*\n    Initialize image structure.\n  */\n  image->columns=tga_info.width;\n  image->rows=tga_info.height;\n  alpha_bits=(tga_info.attributes & 0x0FU);\n  image->alpha_trait=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) ||\n    (tga_info.colormap_size == 32) ?  BlendPixelTrait : UndefinedPixelTrait;\n  if ((tga_info.image_type != TGAColormap) &&\n      (tga_info.image_type != TGARLEColormap))\n    image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 :\n      (tga_info.bits_per_pixel <= 16) ? 5 : 8);\n  else\n    image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 :\n      (tga_info.colormap_size <= 16) ? 5 : 8);\n  if ((tga_info.image_type == TGAColormap) ||\n      (tga_info.image_type == TGAMonochrome) ||\n      (tga_info.image_type == TGARLEColormap) ||\n      (tga_info.image_type == TGARLEMonochrome))\n    image->storage_class=PseudoClass;\n  image->compression=NoCompression;\n  if ((tga_info.image_type == TGARLEColormap) ||\n      (tga_info.image_type == TGARLEMonochrome) ||\n      (tga_info.image_type == TGARLERGB))\n    image->compression=RLECompression;\n  if (image->storage_class == PseudoClass)\n    {\n      if (tga_info.colormap_type != 0)\n        image->colors=tga_info.colormap_index+tga_info.colormap_length;\n      else\n        {\n          size_t\n            one;\n\n          one=1;\n          image->colors=one << tga_info.bits_per_pixel;\n          if (image->colors > ((~0UL)/sizeof(*image->colormap)))\n            ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n          if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n            ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        }\n    }\n  if (tga_info.id_length != 0)\n    {\n      char\n        *comment;\n\n      size_t\n        length;\n\n      /*\n        TGA image comment.\n      */\n      length=(size_t) tga_info.id_length;\n      comment=(char *) NULL;\n      if (~length >= (MagickPathExtent-1))\n        comment=(char *) AcquireQuantumMemory(length+MagickPathExtent,\n          sizeof(*comment));\n      if (comment == (char *) NULL)\n        ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n      count=ReadBlob(image,tga_info.id_length,(unsigned char *) comment);\n      comment[tga_info.id_length]='\\0';\n      (void) SetImageProperty(image,\"comment\",comment,exception);\n      comment=DestroyString(comment);\n    }\n  if (tga_info.attributes & (1UL << 4))\n    {\n      if (tga_info.attributes & (1UL << 5))\n        SetImageArtifact(image,\"tga:image-origin\",\"TopRight\");\n      else\n        SetImageArtifact(image,\"tga:image-origin\",\"BottomRight\");\n    }\n  else\n    {\n      if (tga_info.attributes & (1UL << 5))\n        SetImageArtifact(image,\"tga:image-origin\",\"TopLeft\");\n      else\n        SetImageArtifact(image,\"tga:image-origin\",\"BottomLeft\");\n    }\n  if (image_info->ping != MagickFalse)\n    {\n      (void) CloseBlob(image);\n      return(image);\n    }\n  status=SetImageExtent(image,image->columns,image->rows,exception);\n  if (status == MagickFalse)\n    return(DestroyImageList(image));\n  (void) ResetMagickMemory(&pixel,0,sizeof(pixel));\n  pixel.alpha=(MagickRealType) OpaqueAlpha;\n  if (tga_info.colormap_type != 0)\n    {\n      /*\n        Read TGA raster colormap.\n      */\n      if (image->colors < tga_info.colormap_index)\n        image->colors=tga_info.colormap_index;\n      if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n        ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n      for (i=0; i < (ssize_t) tga_info.colormap_index; i++)\n        image->colormap[i]=pixel;\n      for ( ; i < (ssize_t) image->colors; i++)\n      {\n        switch (tga_info.colormap_size)\n        {\n          case 8:\n          default:\n          {\n            /*\n              Gray scale.\n            */\n            pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            pixel.green=pixel.red;\n            pixel.blue=pixel.red;\n            break;\n          }\n          case 15:\n          case 16:\n          {\n            QuantumAny\n              range;\n\n            /*\n              5 bits each of red green and blue.\n            */\n            j=(unsigned char) ReadBlobByte(image);\n            k=(unsigned char) ReadBlobByte(image);\n            range=GetQuantumRange(5UL);\n            pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,\n              range);\n            pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*(k & 0x03)\n              << 3)+(1UL*(j & 0xe0) >> 5),range);\n            pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);\n            break;\n          }\n          case 24:\n          {\n            /*\n              8 bits each of blue, green and red.\n            */\n            pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            break;\n          }\n          case 32:\n          {\n            /*\n              8 bits each of blue, green, red, and alpha.\n            */\n            pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            pixel.alpha=(MagickRealType) ScaleCharToQuantum((unsigned char)\n              ReadBlobByte(image));\n            break;\n          }\n        }\n        image->colormap[i]=pixel;\n      }\n    }\n  /*\n    Convert TGA pixels to pixel packets.\n  */\n  base=0;\n  flag=0;\n  skip=MagickFalse;\n  real=0;\n  index=0;\n  runlength=0;\n  offset=0;\n  for (y=0; y < (ssize_t) image->rows; y++)\n  {\n    real=offset;\n    if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0)\n      real=image->rows-real-1;\n    q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception);\n    if (q == (Quantum *) NULL)\n      break;\n    for (x=0; x < (ssize_t) image->columns; x++)\n    {\n      if ((tga_info.image_type == TGARLEColormap) ||\n          (tga_info.image_type == TGARLERGB) ||\n          (tga_info.image_type == TGARLEMonochrome))\n        {\n          if (runlength != 0)\n            {\n              runlength--;\n              skip=flag != 0;\n            }\n          else\n            {\n              count=ReadBlob(image,1,&runlength);\n              if (count != 1)\n                ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n              flag=runlength & 0x80;\n              if (flag != 0)\n                runlength-=128;\n              skip=MagickFalse;\n            }\n        }\n      if (skip == MagickFalse)\n        switch (tga_info.bits_per_pixel)\n        {\n          case 8:\n          default:\n          {\n            /*\n              Gray scale.\n            */\n            index=(Quantum) ReadBlobByte(image);\n            if (tga_info.colormap_type != 0)\n              pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image,\n                (ssize_t) index,exception)];\n            else\n              {\n                pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)\n                  index);\n                pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)\n                  index);\n                pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)\n                  index);\n              }\n            break;\n          }\n          case 15:\n          case 16:\n          {\n            QuantumAny\n              range;\n\n            /*\n              5 bits each of RGB.\n            */\n            if (ReadBlob(image,2,pixels) != 2)\n              ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n            j=pixels[0];\n            k=pixels[1];\n            range=GetQuantumRange(5UL);\n            pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,\n              range);\n            pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*\n              (k & 0x03) << 3)+(1UL*(j & 0xe0) >> 5),range);\n            pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);\n            if (image->alpha_trait != UndefinedPixelTrait)\n              pixel.alpha=(MagickRealType) ((k & 0x80) == 0 ? (Quantum)\n                TransparentAlpha : (Quantum) OpaqueAlpha);\n            if (image->storage_class == PseudoClass)\n              index=(Quantum) ConstrainColormapIndex(image,((ssize_t) (k << 8))+\n                j,exception);\n            break;\n          }\n          case 24:\n          {\n            /*\n              BGR pixels.\n            */\n            if (ReadBlob(image,3,pixels) != 3)\n              ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n            pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);\n            pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);\n            pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);\n            break;\n          }\n          case 32:\n          {\n            /*\n              BGRA pixels.\n            */\n            if (ReadBlob(image,4,pixels) != 4)\n              ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n            pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);\n            pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);\n            pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);\n            pixel.alpha=(MagickRealType) ScaleCharToQuantum(pixels[3]);\n            break;\n          }\n        }\n      if (status == MagickFalse)\n        ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n      if (image->storage_class == PseudoClass)\n        SetPixelIndex(image,index,q);\n      SetPixelRed(image,ClampToQuantum(pixel.red),q);\n      SetPixelGreen(image,ClampToQuantum(pixel.green),q);\n      SetPixelBlue(image,ClampToQuantum(pixel.blue),q);\n      if (image->alpha_trait != UndefinedPixelTrait)\n        SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n      q+=GetPixelChannels(image);\n    }\n    /*\n      if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 4)\n        offset+=4;\n      else\n    */\n      if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 2)\n        offset+=2;\n      else\n        offset++;\n    if (offset >= image->rows)\n      {\n        base++;\n        offset=base;\n      }\n    if (SyncAuthenticPixels(image,exception) == MagickFalse)\n      break;\n    if (image->previous == (Image *) NULL)\n      {\n        status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n          image->rows);\n        if (status == MagickFalse)\n          break;\n      }\n  }\n  if (EOFBlob(image) != MagickFalse)\n    ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n      image->filename);\n  (void) CloseBlob(image);\n  return(GetFirstImageInList(image));\n}", "func_hash": 175791113381074585644433899536597352981, "file_name": "tga.c", "file_hash": 184535518978867885654371830775021710506, "cwe": ["CWE-772"], "cve": "CVE-2017-11170", "cve_desc": "The ReadTGAImage function in coders\\tga.c in ImageMagick 7.0.5-6 has a memory leak vulnerability that can cause memory exhaustion via invalid colors data in the header of a TGA or VST file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-11170"}
{"idx": 202783, "project": "php-src", "commit_id": "37da90248deb2188e8ee50e4753ad6340679b425", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commitdiff;h=37da90248deb2188e8ee50e4753ad6340679b425", "commit_message": "Added missing allocation checks", "target": 1, "func": "static Bigint * Balloc(int k)\n{\n\tint x;\n\tBigint *rv;\n\n\t_THREAD_PRIVATE_MUTEX_LOCK(dtoa_mutex);\n\tif ((rv = freelist[k])) {\n\t\tfreelist[k] = rv->next;\n\t} else {\n\t\tx = 1 << k;\n\t\trv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(Long));\n\t\trv->k = k;\n\t\trv->maxwds = x;\n\t}\n\t_THREAD_PRIVATE_MUTEX_UNLOCK(dtoa_mutex);\n\trv->sign = rv->wds = 0;\n\treturn rv;\n}", "func_hash": 233883423838019694196347564918158945680, "file_name": "zend_strtod.c", "file_hash": 162225586697792700551271623353891886066, "cwe": ["CWE-119"], "cve": "CVE-2009-0689", "cve_desc": "Array index error in the (1) dtoa implementation in dtoa.c (aka pdtoa.c) and the (2) gdtoa (aka new dtoa) implementation in gdtoa/misc.c in libc, as used in multiple operating systems and products including in FreeBSD 6.4 and 7.2, NetBSD 5.0, OpenBSD 4.5, Mozilla Firefox 3.0.x before 3.0.15 and 3.5.x before 3.5.4, K-Meleon 1.5.3, SeaMonkey 1.1.8, and other products, allows context-dependent attackers to cause a denial of service (application crash) and possibly execute arbitrary code via a large precision value in the format argument to a printf function, which triggers incorrect memory allocation and a heap-based buffer overflow during conversion to a floating-point number.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2009-0689"}
{"idx": 339712, "project": "php-src", "commit_id": "37da90248deb2188e8ee50e4753ad6340679b425", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commitdiff;h=37da90248deb2188e8ee50e4753ad6340679b425", "commit_message": "Added missing allocation checks", "target": 0, "func": "static Bigint * Balloc(int k)\n{\n\tint x;\n\tBigint *rv;\n\n\tif (k > Kmax) {\n\t\tzend_error(E_ERROR, \"Balloc() allocation exceeds list boundary\");\n\t}\n\n\t_THREAD_PRIVATE_MUTEX_LOCK(dtoa_mutex);\n\tif ((rv = freelist[k])) {\n\t\tfreelist[k] = rv->next;\n\t} else {\n\t\tx = 1 << k;\n\t\trv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(Long));\n\t\tif (!rv) {\n\t\t\t_THREAD_PRIVATE_MUTEX_UNLOCK(dtoa_mutex);\n\t\t\tzend_error(E_ERROR, \"Balloc() failed to allocate memory\");\n\t\t}\n\t\trv->k = k;\n\t\trv->maxwds = x;\n\t}\n\t_THREAD_PRIVATE_MUTEX_UNLOCK(dtoa_mutex);\n\trv->sign = rv->wds = 0;\n\treturn rv;\n}", "func_hash": 126877960775748554954774287335252576908, "file_name": "zend_strtod.c", "file_hash": 330178516637592595167149550690737234647, "cwe": ["CWE-119"], "cve": "CVE-2009-0689", "cve_desc": "Array index error in the (1) dtoa implementation in dtoa.c (aka pdtoa.c) and the (2) gdtoa (aka new dtoa) implementation in gdtoa/misc.c in libc, as used in multiple operating systems and products including in FreeBSD 6.4 and 7.2, NetBSD 5.0, OpenBSD 4.5, Mozilla Firefox 3.0.x before 3.0.15 and 3.5.x before 3.5.4, K-Meleon 1.5.3, SeaMonkey 1.1.8, and other products, allows context-dependent attackers to cause a denial of service (application crash) and possibly execute arbitrary code via a large precision value in the format argument to a printf function, which triggers incorrect memory allocation and a heap-based buffer overflow during conversion to a floating-point number.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2009-0689"}
{"idx": 202822, "project": "ghostpdl", "commit_id": "5d499272b95a6b890a1397e11d20937de000d31b", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "https://github.com/ArtifexSoftware/ghostpdl/commit/5d499272b95a6b890a1397e11d20937de000d31b", "commit_message": "Bug 702582, CVE 2020-15900 Memory Corruption in Ghostscript 9.52\n\nFix the 'rsearch' calculation for the 'post' size to give the correct\nsize.  Previous calculation would result in a size that was too large,\nand could underflow to max uint32_t. Also fix 'rsearch' to return the\ncorrect 'pre' string with empty string match.\n\nA future change may 'undefine' this undocumented, non-standard operator\nduring initialization as we do with the many other non-standard internal\nPostScript operators and procedures.", "target": 1, "func": "search_impl(i_ctx_t *i_ctx_p, bool forward)\n{\n    os_ptr op = osp;\n    os_ptr op1 = op - 1;\n    uint size = r_size(op);\n    uint count;\n    byte *pat;\n    byte *ptr;\n    byte ch;\n    int incr = forward ? 1 : -1;\n\n    check_read_type(*op1, t_string);\n    check_read_type(*op, t_string);\n    if (size > r_size(op1)) {\t/* can't match */\n        make_false(op);\n        return 0;\n    }\n    count = r_size(op1) - size;\n    ptr = op1->value.bytes;\n    if (size == 0)\n        goto found;\n    if (!forward)\n        ptr += count;\n    pat = op->value.bytes;\n    ch = pat[0];\n    do {\n        if (*ptr == ch && (size == 1 || !memcmp(ptr, pat, size)))\n            goto found;\n        ptr += incr;\n    }\n    while (count--);\n    /* No match */\n    make_false(op);\n    return 0;\nfound:\n    op->tas.type_attrs = op1->tas.type_attrs;\n    op->value.bytes = ptr;\n    r_set_size(op, size);\n    push(2);\n    op[-1] = *op1;\n    r_set_size(op - 1, ptr - op[-1].value.bytes);\n    op1->value.bytes = ptr + size;\n    r_set_size(op1, count + (!forward ? (size - 1) : 0));\n    make_true(op);\n    return 0;\n}", "func_hash": 86939516891110967185620104740052162316, "file_name": "zstring.c", "file_hash": 72939855407215089106002168079796587202, "cwe": ["CWE-787"], "cve": "CVE-2020-15900", "cve_desc": "A memory corruption issue was found in Artifex Ghostscript 9.50 and 9.52. Use of a non-standard PostScript operator can allow overriding of file access controls. The 'rsearch' calculation for the 'post' size resulted in a size that was too large, and could underflow to max uint32_t. This was fixed in commit 5d499272b95a6b890a1397e11d20937de000d31b.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15900"}
{"idx": 341817, "project": "ghostpdl", "commit_id": "5d499272b95a6b890a1397e11d20937de000d31b", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "https://github.com/ArtifexSoftware/ghostpdl/commit/5d499272b95a6b890a1397e11d20937de000d31b", "commit_message": "Bug 702582, CVE 2020-15900 Memory Corruption in Ghostscript 9.52\n\nFix the 'rsearch' calculation for the 'post' size to give the correct\nsize.  Previous calculation would result in a size that was too large,\nand could underflow to max uint32_t. Also fix 'rsearch' to return the\ncorrect 'pre' string with empty string match.\n\nA future change may 'undefine' this undocumented, non-standard operator\nduring initialization as we do with the many other non-standard internal\nPostScript operators and procedures.", "target": 0, "func": "search_impl(i_ctx_t *i_ctx_p, bool forward)\n{\n    os_ptr op = osp;\n    os_ptr op1 = op - 1;\n    uint size = r_size(op);\n    uint count;\n    byte *pat;\n    byte *ptr;\n    byte ch;\n    int incr = forward ? 1 : -1;\n\n    check_read_type(*op1, t_string);\n    check_read_type(*op, t_string);\n    if (size > r_size(op1)) {\t/* can't match */\n        make_false(op);\n        return 0;\n    }\n    count = r_size(op1) - size;\n    ptr = op1->value.bytes;\n    if (size == 0)\n        goto found;\n    if (!forward)\n        ptr += count;\n    pat = op->value.bytes;\n    ch = pat[0];\n    do {\n        if (*ptr == ch && (size == 1 || !memcmp(ptr, pat, size)))\n            goto found;\n        ptr += incr;\n    }\n    while (count--);\n    /* No match */\n    make_false(op);\n    return 0;\nfound:\n    op->tas.type_attrs = op1->tas.type_attrs;\n    op->value.bytes = ptr;\t\t\t\t/* match */\n    op->tas.rsize = size;\t\t\t\t/* match */\n    push(2);\n    op[-1] = *op1;\t\t\t\t\t/* pre */\n    op[-3].value.bytes = ptr + size;\t\t\t/* post */\n    if (forward) {\n        op[-1].tas.rsize = ptr - op[-1].value.bytes;\t/* pre */\n        op[-3].tas.rsize = count;\t\t\t/* post */\n    } else {\n        op[-1].tas.rsize = count;\t\t\t/* pre */\n        op[-3].tas.rsize -= count + size;\t\t/* post */\n    }\n    make_true(op);\n    return 0;\n}", "func_hash": 122691468476432977214258761853397783174, "file_name": "zstring.c", "file_hash": 242560896359670915428991047058679210834, "cwe": ["CWE-787"], "cve": "CVE-2020-15900", "cve_desc": "A memory corruption issue was found in Artifex Ghostscript 9.50 and 9.52. Use of a non-standard PostScript operator can allow overriding of file access controls. The 'rsearch' calculation for the 'post' size resulted in a size that was too large, and could underflow to max uint32_t. This was fixed in commit 5d499272b95a6b890a1397e11d20937de000d31b.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15900"}
{"idx": 202888, "project": "linux", "commit_id": "ebe48d368e97d007bfeb76fcb065d6cfc4c96645", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/ebe48d368e97d007bfeb76fcb065d6cfc4c96645", "commit_message": "esp: Fix possible buffer overflow in ESP transformation\n\nThe maximum message size that can be send is bigger than\nthe  maximum site that skb_page_frag_refill can allocate.\nSo it is possible to write beyond the allocated buffer.\n\nFix this by doing a fallback to COW in that case.\n\nv2:\n\nAvoid get get_order() costs as suggested by Linus Torvalds.\n\nFixes: cac2661c53f3 (\"esp4: Avoid skb_cow_data whenever possible\")\nFixes: 03e2a30f6a27 (\"esp6: Avoid skb_cow_data whenever possible\")\nReported-by: valis \nSigned-off-by: Steffen Klassert ", "target": 1, "func": "int esp_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *esp)\n{\n\tu8 *tail;\n\tint nfrags;\n\tint esph_offset;\n\tstruct page *page;\n\tstruct sk_buff *trailer;\n\tint tailen = esp->tailen;\n\n\t/* this is non-NULL only with TCP/UDP Encapsulation */\n\tif (x->encap) {\n\t\tint err = esp_output_encap(x, skb, esp);\n\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tif (!skb_cloned(skb)) {\n\t\tif (tailen <= skb_tailroom(skb)) {\n\t\t\tnfrags = 1;\n\t\t\ttrailer = skb;\n\t\t\ttail = skb_tail_pointer(trailer);\n\n\t\t\tgoto skip_cow;\n\t\t} else if ((skb_shinfo(skb)->nr_frags < MAX_SKB_FRAGS)\n\t\t\t   && !skb_has_frag_list(skb)) {\n\t\t\tint allocsize;\n\t\t\tstruct sock *sk = skb->sk;\n\t\t\tstruct page_frag *pfrag = &x->xfrag;\n\n\t\t\tesp->inplace = false;\n\n\t\t\tallocsize = ALIGN(tailen, L1_CACHE_BYTES);\n\n\t\t\tspin_lock_bh(&x->lock);\n\n\t\t\tif (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {\n\t\t\t\tspin_unlock_bh(&x->lock);\n\t\t\t\tgoto cow;\n\t\t\t}\n\n\t\t\tpage = pfrag->page;\n\t\t\tget_page(page);\n\n\t\t\ttail = page_address(page) + pfrag->offset;\n\n\t\t\tesp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);\n\n\t\t\tnfrags = skb_shinfo(skb)->nr_frags;\n\n\t\t\t__skb_fill_page_desc(skb, nfrags, page, pfrag->offset,\n\t\t\t\t\t     tailen);\n\t\t\tskb_shinfo(skb)->nr_frags = ++nfrags;\n\n\t\t\tpfrag->offset = pfrag->offset + allocsize;\n\n\t\t\tspin_unlock_bh(&x->lock);\n\n\t\t\tnfrags++;\n\n\t\t\tskb->len += tailen;\n\t\t\tskb->data_len += tailen;\n\t\t\tskb->truesize += tailen;\n\t\t\tif (sk && sk_fullsock(sk))\n\t\t\t\trefcount_add(tailen, &sk->sk_wmem_alloc);\n\n\t\t\tgoto out;\n\t\t}\n\t}\n\ncow:\n\tesph_offset = (unsigned char *)esp->esph - skb_transport_header(skb);\n\n\tnfrags = skb_cow_data(skb, tailen, &trailer);\n\tif (nfrags < 0)\n\t\tgoto out;\n\ttail = skb_tail_pointer(trailer);\n\tesp->esph = (struct ip_esp_hdr *)(skb_transport_header(skb) + esph_offset);\n\nskip_cow:\n\tesp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);\n\tpskb_put(skb, trailer, tailen);\n\nout:\n\treturn nfrags;\n}", "func_hash": 111996591465481135953474754686135159337, "file_name": "esp4.c", "file_hash": 169926453254442983322582759592161291384, "cwe": ["CWE-787"], "cve": "CVE-2022-27666", "cve_desc": "A heap buffer overflow flaw was found in IPsec ESP transformation code in net/ipv4/esp4.c and net/ipv6/esp6.c. This flaw allows a local attacker with a normal user privilege to overwrite kernel heap objects and may cause a local privilege escalation threat.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27666"}
{"idx": 343175, "project": "linux", "commit_id": "ebe48d368e97d007bfeb76fcb065d6cfc4c96645", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/ebe48d368e97d007bfeb76fcb065d6cfc4c96645", "commit_message": "esp: Fix possible buffer overflow in ESP transformation\n\nThe maximum message size that can be send is bigger than\nthe  maximum site that skb_page_frag_refill can allocate.\nSo it is possible to write beyond the allocated buffer.\n\nFix this by doing a fallback to COW in that case.\n\nv2:\n\nAvoid get get_order() costs as suggested by Linus Torvalds.\n\nFixes: cac2661c53f3 (\"esp4: Avoid skb_cow_data whenever possible\")\nFixes: 03e2a30f6a27 (\"esp6: Avoid skb_cow_data whenever possible\")\nReported-by: valis \nSigned-off-by: Steffen Klassert ", "target": 0, "func": "int esp_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *esp)\n{\n\tu8 *tail;\n\tint nfrags;\n\tint esph_offset;\n\tstruct page *page;\n\tstruct sk_buff *trailer;\n\tint tailen = esp->tailen;\n\tunsigned int allocsz;\n\n\t/* this is non-NULL only with TCP/UDP Encapsulation */\n\tif (x->encap) {\n\t\tint err = esp_output_encap(x, skb, esp);\n\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tallocsz = ALIGN(skb->data_len + tailen, L1_CACHE_BYTES);\n\tif (allocsz > ESP_SKB_FRAG_MAXSIZE)\n\t\tgoto cow;\n\n\tif (!skb_cloned(skb)) {\n\t\tif (tailen <= skb_tailroom(skb)) {\n\t\t\tnfrags = 1;\n\t\t\ttrailer = skb;\n\t\t\ttail = skb_tail_pointer(trailer);\n\n\t\t\tgoto skip_cow;\n\t\t} else if ((skb_shinfo(skb)->nr_frags < MAX_SKB_FRAGS)\n\t\t\t   && !skb_has_frag_list(skb)) {\n\t\t\tint allocsize;\n\t\t\tstruct sock *sk = skb->sk;\n\t\t\tstruct page_frag *pfrag = &x->xfrag;\n\n\t\t\tesp->inplace = false;\n\n\t\t\tallocsize = ALIGN(tailen, L1_CACHE_BYTES);\n\n\t\t\tspin_lock_bh(&x->lock);\n\n\t\t\tif (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {\n\t\t\t\tspin_unlock_bh(&x->lock);\n\t\t\t\tgoto cow;\n\t\t\t}\n\n\t\t\tpage = pfrag->page;\n\t\t\tget_page(page);\n\n\t\t\ttail = page_address(page) + pfrag->offset;\n\n\t\t\tesp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);\n\n\t\t\tnfrags = skb_shinfo(skb)->nr_frags;\n\n\t\t\t__skb_fill_page_desc(skb, nfrags, page, pfrag->offset,\n\t\t\t\t\t     tailen);\n\t\t\tskb_shinfo(skb)->nr_frags = ++nfrags;\n\n\t\t\tpfrag->offset = pfrag->offset + allocsize;\n\n\t\t\tspin_unlock_bh(&x->lock);\n\n\t\t\tnfrags++;\n\n\t\t\tskb->len += tailen;\n\t\t\tskb->data_len += tailen;\n\t\t\tskb->truesize += tailen;\n\t\t\tif (sk && sk_fullsock(sk))\n\t\t\t\trefcount_add(tailen, &sk->sk_wmem_alloc);\n\n\t\t\tgoto out;\n\t\t}\n\t}\n\ncow:\n\tesph_offset = (unsigned char *)esp->esph - skb_transport_header(skb);\n\n\tnfrags = skb_cow_data(skb, tailen, &trailer);\n\tif (nfrags < 0)\n\t\tgoto out;\n\ttail = skb_tail_pointer(trailer);\n\tesp->esph = (struct ip_esp_hdr *)(skb_transport_header(skb) + esph_offset);\n\nskip_cow:\n\tesp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);\n\tpskb_put(skb, trailer, tailen);\n\nout:\n\treturn nfrags;\n}", "func_hash": 32635591870999159240037878048744247169, "file_name": "esp4.c", "file_hash": 243441935638352226599130061922041332693, "cwe": ["CWE-787"], "cve": "CVE-2022-27666", "cve_desc": "A heap buffer overflow flaw was found in IPsec ESP transformation code in net/ipv4/esp4.c and net/ipv6/esp6.c. This flaw allows a local attacker with a normal user privilege to overwrite kernel heap objects and may cause a local privilege escalation threat.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27666"}
{"idx": 202889, "project": "linux", "commit_id": "ebe48d368e97d007bfeb76fcb065d6cfc4c96645", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/ebe48d368e97d007bfeb76fcb065d6cfc4c96645", "commit_message": "esp: Fix possible buffer overflow in ESP transformation\n\nThe maximum message size that can be send is bigger than\nthe  maximum site that skb_page_frag_refill can allocate.\nSo it is possible to write beyond the allocated buffer.\n\nFix this by doing a fallback to COW in that case.\n\nv2:\n\nAvoid get get_order() costs as suggested by Linus Torvalds.\n\nFixes: cac2661c53f3 (\"esp4: Avoid skb_cow_data whenever possible\")\nFixes: 03e2a30f6a27 (\"esp6: Avoid skb_cow_data whenever possible\")\nReported-by: valis \nSigned-off-by: Steffen Klassert ", "target": 1, "func": "int esp6_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *esp)\n{\n\tu8 *tail;\n\tint nfrags;\n\tint esph_offset;\n\tstruct page *page;\n\tstruct sk_buff *trailer;\n\tint tailen = esp->tailen;\n\n\tif (x->encap) {\n\t\tint err = esp6_output_encap(x, skb, esp);\n\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tif (!skb_cloned(skb)) {\n\t\tif (tailen <= skb_tailroom(skb)) {\n\t\t\tnfrags = 1;\n\t\t\ttrailer = skb;\n\t\t\ttail = skb_tail_pointer(trailer);\n\n\t\t\tgoto skip_cow;\n\t\t} else if ((skb_shinfo(skb)->nr_frags < MAX_SKB_FRAGS)\n\t\t\t   && !skb_has_frag_list(skb)) {\n\t\t\tint allocsize;\n\t\t\tstruct sock *sk = skb->sk;\n\t\t\tstruct page_frag *pfrag = &x->xfrag;\n\n\t\t\tesp->inplace = false;\n\n\t\t\tallocsize = ALIGN(tailen, L1_CACHE_BYTES);\n\n\t\t\tspin_lock_bh(&x->lock);\n\n\t\t\tif (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {\n\t\t\t\tspin_unlock_bh(&x->lock);\n\t\t\t\tgoto cow;\n\t\t\t}\n\n\t\t\tpage = pfrag->page;\n\t\t\tget_page(page);\n\n\t\t\ttail = page_address(page) + pfrag->offset;\n\n\t\t\tesp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);\n\n\t\t\tnfrags = skb_shinfo(skb)->nr_frags;\n\n\t\t\t__skb_fill_page_desc(skb, nfrags, page, pfrag->offset,\n\t\t\t\t\t     tailen);\n\t\t\tskb_shinfo(skb)->nr_frags = ++nfrags;\n\n\t\t\tpfrag->offset = pfrag->offset + allocsize;\n\n\t\t\tspin_unlock_bh(&x->lock);\n\n\t\t\tnfrags++;\n\n\t\t\tskb->len += tailen;\n\t\t\tskb->data_len += tailen;\n\t\t\tskb->truesize += tailen;\n\t\t\tif (sk && sk_fullsock(sk))\n\t\t\t\trefcount_add(tailen, &sk->sk_wmem_alloc);\n\n\t\t\tgoto out;\n\t\t}\n\t}\n\ncow:\n\tesph_offset = (unsigned char *)esp->esph - skb_transport_header(skb);\n\n\tnfrags = skb_cow_data(skb, tailen, &trailer);\n\tif (nfrags < 0)\n\t\tgoto out;\n\ttail = skb_tail_pointer(trailer);\n\tesp->esph = (struct ip_esp_hdr *)(skb_transport_header(skb) + esph_offset);\n\nskip_cow:\n\tesp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);\n\tpskb_put(skb, trailer, tailen);\n\nout:\n\treturn nfrags;\n}", "func_hash": 288301041182247062764395753908590668676, "file_name": "esp6.c", "file_hash": 297879342136766332467148715516497305667, "cwe": ["CWE-787"], "cve": "CVE-2022-27666", "cve_desc": "A heap buffer overflow flaw was found in IPsec ESP transformation code in net/ipv4/esp4.c and net/ipv6/esp6.c. This flaw allows a local attacker with a normal user privilege to overwrite kernel heap objects and may cause a local privilege escalation threat.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27666"}
{"idx": 343158, "project": "linux", "commit_id": "ebe48d368e97d007bfeb76fcb065d6cfc4c96645", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/ebe48d368e97d007bfeb76fcb065d6cfc4c96645", "commit_message": "esp: Fix possible buffer overflow in ESP transformation\n\nThe maximum message size that can be send is bigger than\nthe  maximum site that skb_page_frag_refill can allocate.\nSo it is possible to write beyond the allocated buffer.\n\nFix this by doing a fallback to COW in that case.\n\nv2:\n\nAvoid get get_order() costs as suggested by Linus Torvalds.\n\nFixes: cac2661c53f3 (\"esp4: Avoid skb_cow_data whenever possible\")\nFixes: 03e2a30f6a27 (\"esp6: Avoid skb_cow_data whenever possible\")\nReported-by: valis \nSigned-off-by: Steffen Klassert ", "target": 0, "func": "int esp6_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *esp)\n{\n\tu8 *tail;\n\tint nfrags;\n\tint esph_offset;\n\tstruct page *page;\n\tstruct sk_buff *trailer;\n\tint tailen = esp->tailen;\n\tunsigned int allocsz;\n\n\tif (x->encap) {\n\t\tint err = esp6_output_encap(x, skb, esp);\n\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tallocsz = ALIGN(skb->data_len + tailen, L1_CACHE_BYTES);\n\tif (allocsz > ESP_SKB_FRAG_MAXSIZE)\n\t\tgoto cow;\n\n\tif (!skb_cloned(skb)) {\n\t\tif (tailen <= skb_tailroom(skb)) {\n\t\t\tnfrags = 1;\n\t\t\ttrailer = skb;\n\t\t\ttail = skb_tail_pointer(trailer);\n\n\t\t\tgoto skip_cow;\n\t\t} else if ((skb_shinfo(skb)->nr_frags < MAX_SKB_FRAGS)\n\t\t\t   && !skb_has_frag_list(skb)) {\n\t\t\tint allocsize;\n\t\t\tstruct sock *sk = skb->sk;\n\t\t\tstruct page_frag *pfrag = &x->xfrag;\n\n\t\t\tesp->inplace = false;\n\n\t\t\tallocsize = ALIGN(tailen, L1_CACHE_BYTES);\n\n\t\t\tspin_lock_bh(&x->lock);\n\n\t\t\tif (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {\n\t\t\t\tspin_unlock_bh(&x->lock);\n\t\t\t\tgoto cow;\n\t\t\t}\n\n\t\t\tpage = pfrag->page;\n\t\t\tget_page(page);\n\n\t\t\ttail = page_address(page) + pfrag->offset;\n\n\t\t\tesp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);\n\n\t\t\tnfrags = skb_shinfo(skb)->nr_frags;\n\n\t\t\t__skb_fill_page_desc(skb, nfrags, page, pfrag->offset,\n\t\t\t\t\t     tailen);\n\t\t\tskb_shinfo(skb)->nr_frags = ++nfrags;\n\n\t\t\tpfrag->offset = pfrag->offset + allocsize;\n\n\t\t\tspin_unlock_bh(&x->lock);\n\n\t\t\tnfrags++;\n\n\t\t\tskb->len += tailen;\n\t\t\tskb->data_len += tailen;\n\t\t\tskb->truesize += tailen;\n\t\t\tif (sk && sk_fullsock(sk))\n\t\t\t\trefcount_add(tailen, &sk->sk_wmem_alloc);\n\n\t\t\tgoto out;\n\t\t}\n\t}\n\ncow:\n\tesph_offset = (unsigned char *)esp->esph - skb_transport_header(skb);\n\n\tnfrags = skb_cow_data(skb, tailen, &trailer);\n\tif (nfrags < 0)\n\t\tgoto out;\n\ttail = skb_tail_pointer(trailer);\n\tesp->esph = (struct ip_esp_hdr *)(skb_transport_header(skb) + esph_offset);\n\nskip_cow:\n\tesp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);\n\tpskb_put(skb, trailer, tailen);\n\nout:\n\treturn nfrags;\n}", "func_hash": 5299017131743026733431501074283607591, "file_name": "esp6.c", "file_hash": 272053559916260151312940536238291966334, "cwe": ["CWE-787"], "cve": "CVE-2022-27666", "cve_desc": "A heap buffer overflow flaw was found in IPsec ESP transformation code in net/ipv4/esp4.c and net/ipv6/esp6.c. This flaw allows a local attacker with a normal user privilege to overwrite kernel heap objects and may cause a local privilege escalation threat.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27666"}
{"idx": 202892, "project": "pure-ftpd", "commit_id": "37ad222868e52271905b94afea4fc780d83294b4", "project_url": "https://github.com/jedisct1/pure-ftpd", "commit_url": "https://github.com/jedisct1/pure-ftpd/commit/37ad222868e52271905b94afea4fc780d83294b4", "commit_message": "Initialize the max upload file size when quotas are enabled\n\nDue to an unwanted check, files causing the quota to be exceeded\nwere deleted after the upload, but not during the upload.\n\nThe bug was introduced in 2009 in version 1.0.23\n\nSpotted by @DroidTest, thanks!", "target": 1, "func": "void dostor(char *name, const int append, const int autorename)\n{\n    ULHandler ulhandler;\n    int f;\n    const char *ul_name = NULL;\n    const char *atomic_file = NULL;\n    off_t filesize = (off_t) 0U;\n    struct stat st;\n    double started = 0.0;\n    signed char overwrite = 0;\n    int overflow = 0;\n    int ret = -1;\n    off_t max_filesize = (off_t) -1;\n#ifdef QUOTAS\n    Quota quota;\n#endif\n    const char *name2 = NULL;\n\n    if (type < 1 || (type == 1 && restartat > (off_t) 1)) {\n        addreply_noformat(503, MSG_NO_ASCII_RESUME);\n        goto end;\n    }\n#ifndef ANON_CAN_RESUME\n    if (guest != 0 && anon_noupload != 0) {\n        addreply_noformat(550, MSG_ANON_CANT_OVERWRITE);\n        goto end;\n    }\n#endif\n    if (ul_check_free_space(name, -1.0) == 0) {\n        addreply_noformat(552, MSG_NO_DISK_SPACE);\n        goto end;\n    }\n    if (checknamesanity(name, dot_write_ok) != 0) {\n        addreply(553, MSG_SANITY_FILE_FAILURE, name);\n        goto end;\n    }\n    if (autorename != 0) {\n        no_truncate = 1;\n    }\n    if (restartat > (off_t) 0 || no_truncate != 0) {\n        if ((atomic_file = get_atomic_file(name)) == NULL) {\n            addreply(553, MSG_SANITY_FILE_FAILURE, name);\n            goto end;\n        }\n        if (restartat > (off_t) 0 &&\n            rename(name, atomic_file) != 0 && errno != ENOENT) {\n            error(553, MSG_RENAME_FAILURE);\n            atomic_file = NULL;\n            goto end;\n        }\n    }\n    if (atomic_file != NULL) {\n        ul_name = atomic_file;\n    } else {\n        ul_name = name;\n    }\n    if (atomic_file == NULL &&\n        (f = open(ul_name, O_WRONLY | O_NOFOLLOW)) != -1) {\n        overwrite++;\n    } else if ((f = open(ul_name, O_CREAT | O_WRONLY | O_NOFOLLOW,\n                         (mode_t) 0777 & ~u_mask)) == -1) {\n        error(553, MSG_OPEN_FAILURE2);\n        goto end;\n    }\n    if (fstat(f, &st) < 0) {\n        (void) close(f);\n        error(553, MSG_STAT_FAILURE2);\n        goto end;\n    }\n    if (!S_ISREG(st.st_mode)) {\n        (void) close(f);\n        addreply_noformat(550, MSG_NOT_REGULAR_FILE);\n        goto end;\n    }\n    alarm(MAX_SESSION_XFER_IDLE);\n\n    /* Anonymous users *CAN* overwrite 0-bytes files - This is the right behavior */\n    if (st.st_size > (off_t) 0) {\n#ifndef ANON_CAN_RESUME\n        if (guest != 0) {\n            addreply_noformat(550, MSG_ANON_CANT_OVERWRITE);\n            (void) close(f);\n            goto end;\n        }\n#endif\n        if (append != 0) {\n            restartat = st.st_size;\n        }\n    } else {\n        restartat = (off_t) 0;\n    }\n    if (restartat > st.st_size) {\n        restartat = st.st_size;\n    }\n    if (restartat > (off_t) 0 && lseek(f, restartat, SEEK_SET) < (off_t) 0) {\n        (void) close(f);\n        error(451, \"seek\");\n        goto end;\n    }\n    if (restartat < st.st_size) {\n        if (ftruncate(f, restartat) < 0) {\n            (void) close(f);\n            error(451, \"ftruncate\");\n            goto end;\n        }\n#ifdef QUOTAS\n        if (restartat != st.st_size) {\n            (void) quota_update(NULL, 0LL,\n                                (long long) (restartat - st.st_size),\n                                &overflow);\n        }\n#endif\n    }\n#ifdef QUOTAS\n    if (quota_update("a, 0LL, 0LL, &overflow) == 0 &&\n        (overflow > 0 || quota.files >= user_quota_files ||\n         quota.size > user_quota_size ||\n         (max_filesize >= (off_t) 0 &&\n          (max_filesize = user_quota_size - quota.size) < (off_t) 0))) {\n        overflow = 1;\n        (void) close(f);\n        goto afterquota;\n    }\n#endif\n    opendata();\n    if (xferfd == -1) {\n        (void) close(f);\n        goto end;\n    }\n    doreply();\n# ifdef WITH_TLS\n    if (data_protection_level == CPL_PRIVATE) {\n        tls_init_data_session(xferfd, passive);\n    }\n# endif\n    state_needs_update = 1;\n    setprocessname(\"pure-ftpd (UPLOAD)\");\n    filesize = restartat;\n\n#ifdef FTPWHO\n    if (shm_data_cur != NULL) {\n        const size_t sl = strlen(name);\n\n        ftpwho_lock();\n        shm_data_cur->state = FTPWHO_STATE_UPLOAD;\n        shm_data_cur->download_total_size = (off_t) 0U;\n        shm_data_cur->download_current_size = (off_t) filesize;\n        shm_data_cur->restartat = restartat;\n        (void) time(&shm_data_cur->xfer_date);\n        if (sl < sizeof shm_data_cur->filename) {\n            memcpy(shm_data_cur->filename, name, sl);\n            shm_data_cur->filename[sl] = 0;\n        } else {\n            memcpy(shm_data_cur->filename,\n                   &name[sl - sizeof shm_data_cur->filename - 1U],\n                   sizeof shm_data_cur->filename);\n        }\n        ftpwho_unlock();\n    }\n#endif\n\n    /* Here starts the real upload code */\n\n    started = get_usec_time();\n\n    if (ul_init(&ulhandler, clientfd, tls_cnx, xferfd, name, f, tls_data_cnx,\n                restartat, type == 1, throttling_bandwidth_ul,\n                max_filesize) == 0) {\n        ret = ul_send(&ulhandler);\n        ul_exit(&ulhandler);\n    } else {\n        ret = -1;\n    }\n    (void) close(f);\n    closedata();\n\n    /* Here ends the real upload code */\n\n#ifdef SHOW_REAL_DISK_SPACE\n    if (FSTATFS(f, &statfsbuf) == 0) {\n        double space;\n\n        space = (double) STATFS_BAVAIL(statfsbuf) *\n            (double) STATFS_FRSIZE(statfsbuf);\n        if (space > 524288.0) {\n            addreply(0, MSG_SPACE_FREE_M, space / 1048576.0);\n        } else {\n            addreply(0, MSG_SPACE_FREE_K, space / 1024.0);\n        }\n    }\n#endif\n\n    uploaded += (unsigned long long) ulhandler.total_uploaded;\n    {\n        off_t atomic_file_size;\n        off_t original_file_size;\n        int files_count;\n\n        if (overwrite == 0) {\n            files_count = 1;\n        } else {\n            files_count = 0;\n        }\n        if (autorename != 0 && restartat == (off_t) 0) {\n            if ((atomic_file_size = get_file_size(atomic_file)) < (off_t) 0) {\n                goto afterquota;\n            }\n            if (tryautorename(atomic_file, name, &name2) != 0) {\n                error(553, MSG_RENAME_FAILURE);\n                goto afterquota;\n            } else {\n#ifdef QUOTAS\n                ul_quota_update(name2 ? name2 : name, 1, atomic_file_size);\n#endif\n                atomic_file = NULL;\n            }\n        } else if (atomic_file != NULL) {\n            if ((atomic_file_size = get_file_size(atomic_file)) < (off_t) 0) {\n                goto afterquota;\n            }\n            if ((original_file_size = get_file_size(name)) < (off_t) 0 ||\n                restartat > original_file_size) {\n                original_file_size = restartat;\n            }\n            if (rename(atomic_file, name) != 0) {\n                error(553, MSG_RENAME_FAILURE);\n                goto afterquota;\n            } else {\n#ifdef QUOTAS\n                overflow = ul_quota_update\n                    (name, files_count, atomic_file_size - original_file_size);\n#endif\n                atomic_file = NULL;\n            }\n        } else {\n#ifdef QUOTAS\n            overflow = ul_quota_update\n                (name, files_count, ulhandler.total_uploaded);\n#endif\n        }\n    }\n    afterquota:\n    if (overflow > 0) {\n        addreply(552, MSG_QUOTA_EXCEEDED, name);\n    } else {\n        if (ret == 0) {\n            addreply_noformat(226, MSG_TRANSFER_SUCCESSFUL);\n        } else {\n            addreply_noformat(451, MSG_ABORTED);\n        }\n        displayrate(MSG_UPLOADED, ulhandler.total_uploaded, started,\n                    name2 ? name2 : name, 1);\n    }\n    end:\n    restartat = (off_t) 0;\n    if (atomic_file != NULL) {\n        unlink(atomic_file);\n        atomic_file = NULL;\n    }\n}", "func_hash": 206214968854253605299556693579818029977, "file_name": "ftpd.c", "file_hash": 235084351397611292950237183012549023004, "cwe": ["CWE-434"], "cve": "CVE-2021-40524", "cve_desc": "In Pure-FTPd before 1.0.50, an incorrect max_filesize quota mechanism in the server allows attackers to upload files of unbounded size, which may lead to denial of service or a server hang. This occurs because a certain greater-than-zero test does not anticipate an initial -1 value. (Versions 1.0.23 through 1.0.49 are affected.)", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40524"}
{"idx": 343298, "project": "pure-ftpd", "commit_id": "37ad222868e52271905b94afea4fc780d83294b4", "project_url": "https://github.com/jedisct1/pure-ftpd", "commit_url": "https://github.com/jedisct1/pure-ftpd/commit/37ad222868e52271905b94afea4fc780d83294b4", "commit_message": "Initialize the max upload file size when quotas are enabled\n\nDue to an unwanted check, files causing the quota to be exceeded\nwere deleted after the upload, but not during the upload.\n\nThe bug was introduced in 2009 in version 1.0.23\n\nSpotted by @DroidTest, thanks!", "target": 0, "func": "void dostor(char *name, const int append, const int autorename)\n{\n    ULHandler ulhandler;\n    int f;\n    const char *ul_name = NULL;\n    const char *atomic_file = NULL;\n    off_t filesize = (off_t) 0U;\n    struct stat st;\n    double started = 0.0;\n    signed char overwrite = 0;\n    int overflow = 0;\n    int ret = -1;\n    off_t max_filesize = (off_t) -1;\n#ifdef QUOTAS\n    Quota quota;\n#endif\n    const char *name2 = NULL;\n\n    if (type < 1 || (type == 1 && restartat > (off_t) 1)) {\n        addreply_noformat(503, MSG_NO_ASCII_RESUME);\n        goto end;\n    }\n#ifndef ANON_CAN_RESUME\n    if (guest != 0 && anon_noupload != 0) {\n        addreply_noformat(550, MSG_ANON_CANT_OVERWRITE);\n        goto end;\n    }\n#endif\n    if (ul_check_free_space(name, -1.0) == 0) {\n        addreply_noformat(552, MSG_NO_DISK_SPACE);\n        goto end;\n    }\n    if (checknamesanity(name, dot_write_ok) != 0) {\n        addreply(553, MSG_SANITY_FILE_FAILURE, name);\n        goto end;\n    }\n    if (autorename != 0) {\n        no_truncate = 1;\n    }\n    if (restartat > (off_t) 0 || no_truncate != 0) {\n        if ((atomic_file = get_atomic_file(name)) == NULL) {\n            addreply(553, MSG_SANITY_FILE_FAILURE, name);\n            goto end;\n        }\n        if (restartat > (off_t) 0 &&\n            rename(name, atomic_file) != 0 && errno != ENOENT) {\n            error(553, MSG_RENAME_FAILURE);\n            atomic_file = NULL;\n            goto end;\n        }\n    }\n    if (atomic_file != NULL) {\n        ul_name = atomic_file;\n    } else {\n        ul_name = name;\n    }\n    if (atomic_file == NULL &&\n        (f = open(ul_name, O_WRONLY | O_NOFOLLOW)) != -1) {\n        overwrite++;\n    } else if ((f = open(ul_name, O_CREAT | O_WRONLY | O_NOFOLLOW,\n                         (mode_t) 0777 & ~u_mask)) == -1) {\n        error(553, MSG_OPEN_FAILURE2);\n        goto end;\n    }\n    if (fstat(f, &st) < 0) {\n        (void) close(f);\n        error(553, MSG_STAT_FAILURE2);\n        goto end;\n    }\n    if (!S_ISREG(st.st_mode)) {\n        (void) close(f);\n        addreply_noformat(550, MSG_NOT_REGULAR_FILE);\n        goto end;\n    }\n    alarm(MAX_SESSION_XFER_IDLE);\n\n    /* Anonymous users *CAN* overwrite 0-bytes files - This is the right behavior */\n    if (st.st_size > (off_t) 0) {\n#ifndef ANON_CAN_RESUME\n        if (guest != 0) {\n            addreply_noformat(550, MSG_ANON_CANT_OVERWRITE);\n            (void) close(f);\n            goto end;\n        }\n#endif\n        if (append != 0) {\n            restartat = st.st_size;\n        }\n    } else {\n        restartat = (off_t) 0;\n    }\n    if (restartat > st.st_size) {\n        restartat = st.st_size;\n    }\n    if (restartat > (off_t) 0 && lseek(f, restartat, SEEK_SET) < (off_t) 0) {\n        (void) close(f);\n        error(451, \"seek\");\n        goto end;\n    }\n    if (restartat < st.st_size) {\n        if (ftruncate(f, restartat) < 0) {\n            (void) close(f);\n            error(451, \"ftruncate\");\n            goto end;\n        }\n#ifdef QUOTAS\n        if (restartat != st.st_size) {\n            (void) quota_update(NULL, 0LL,\n                                (long long) (restartat - st.st_size),\n                                &overflow);\n        }\n#endif\n    }\n#ifdef QUOTAS\n    if (quota_update("a, 0LL, 0LL, &overflow) == 0 &&\n        (overflow > 0 || quota.files >= user_quota_files ||\n         quota.size > user_quota_size ||\n         (max_filesize = user_quota_size - quota.size) < (off_t) 0)) {\n        overflow = 1;\n        (void) close(f);\n        goto afterquota;\n    }\n#endif\n    opendata();\n    if (xferfd == -1) {\n        (void) close(f);\n        goto end;\n    }\n    doreply();\n# ifdef WITH_TLS\n    if (data_protection_level == CPL_PRIVATE) {\n        tls_init_data_session(xferfd, passive);\n    }\n# endif\n    state_needs_update = 1;\n    setprocessname(\"pure-ftpd (UPLOAD)\");\n    filesize = restartat;\n\n#ifdef FTPWHO\n    if (shm_data_cur != NULL) {\n        const size_t sl = strlen(name);\n\n        ftpwho_lock();\n        shm_data_cur->state = FTPWHO_STATE_UPLOAD;\n        shm_data_cur->download_total_size = (off_t) 0U;\n        shm_data_cur->download_current_size = (off_t) filesize;\n        shm_data_cur->restartat = restartat;\n        (void) time(&shm_data_cur->xfer_date);\n        if (sl < sizeof shm_data_cur->filename) {\n            memcpy(shm_data_cur->filename, name, sl);\n            shm_data_cur->filename[sl] = 0;\n        } else {\n            memcpy(shm_data_cur->filename,\n                   &name[sl - sizeof shm_data_cur->filename - 1U],\n                   sizeof shm_data_cur->filename);\n        }\n        ftpwho_unlock();\n    }\n#endif\n\n    /* Here starts the real upload code */\n\n    started = get_usec_time();\n\n    if (ul_init(&ulhandler, clientfd, tls_cnx, xferfd, name, f, tls_data_cnx,\n                restartat, type == 1, throttling_bandwidth_ul,\n                max_filesize) == 0) {\n        ret = ul_send(&ulhandler);\n        ul_exit(&ulhandler);\n    } else {\n        ret = -1;\n    }\n    (void) close(f);\n    closedata();\n\n    /* Here ends the real upload code */\n\n#ifdef SHOW_REAL_DISK_SPACE\n    if (FSTATFS(f, &statfsbuf) == 0) {\n        double space;\n\n        space = (double) STATFS_BAVAIL(statfsbuf) *\n            (double) STATFS_FRSIZE(statfsbuf);\n        if (space > 524288.0) {\n            addreply(0, MSG_SPACE_FREE_M, space / 1048576.0);\n        } else {\n            addreply(0, MSG_SPACE_FREE_K, space / 1024.0);\n        }\n    }\n#endif\n\n    uploaded += (unsigned long long) ulhandler.total_uploaded;\n    {\n        off_t atomic_file_size;\n        off_t original_file_size;\n        int files_count;\n\n        if (overwrite == 0) {\n            files_count = 1;\n        } else {\n            files_count = 0;\n        }\n        if (autorename != 0 && restartat == (off_t) 0) {\n            if ((atomic_file_size = get_file_size(atomic_file)) < (off_t) 0) {\n                goto afterquota;\n            }\n            if (tryautorename(atomic_file, name, &name2) != 0) {\n                error(553, MSG_RENAME_FAILURE);\n                goto afterquota;\n            } else {\n#ifdef QUOTAS\n                ul_quota_update(name2 ? name2 : name, 1, atomic_file_size);\n#endif\n                atomic_file = NULL;\n            }\n        } else if (atomic_file != NULL) {\n            if ((atomic_file_size = get_file_size(atomic_file)) < (off_t) 0) {\n                goto afterquota;\n            }\n            if ((original_file_size = get_file_size(name)) < (off_t) 0 ||\n                restartat > original_file_size) {\n                original_file_size = restartat;\n            }\n            if (rename(atomic_file, name) != 0) {\n                error(553, MSG_RENAME_FAILURE);\n                goto afterquota;\n            } else {\n#ifdef QUOTAS\n                overflow = ul_quota_update\n                    (name, files_count, atomic_file_size - original_file_size);\n#endif\n                atomic_file = NULL;\n            }\n        } else {\n#ifdef QUOTAS\n            overflow = ul_quota_update\n                (name, files_count, ulhandler.total_uploaded);\n#endif\n        }\n    }\n    afterquota:\n    if (overflow > 0) {\n        addreply(552, MSG_QUOTA_EXCEEDED, name);\n    } else {\n        if (ret == 0) {\n            addreply_noformat(226, MSG_TRANSFER_SUCCESSFUL);\n        } else {\n            addreply_noformat(451, MSG_ABORTED);\n        }\n        displayrate(MSG_UPLOADED, ulhandler.total_uploaded, started,\n                    name2 ? name2 : name, 1);\n    }\n    end:\n    restartat = (off_t) 0;\n    if (atomic_file != NULL) {\n        unlink(atomic_file);\n        atomic_file = NULL;\n    }\n}", "func_hash": 189507601171684383524883387321805614234, "file_name": "ftpd.c", "file_hash": 102895278505023286855651896148239525136, "cwe": ["CWE-434"], "cve": "CVE-2021-40524", "cve_desc": "In Pure-FTPd before 1.0.50, an incorrect max_filesize quota mechanism in the server allows attackers to upload files of unbounded size, which may lead to denial of service or a server hang. This occurs because a certain greater-than-zero test does not anticipate an initial -1 value. (Versions 1.0.23 through 1.0.49 are affected.)", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40524"}
{"idx": 202943, "project": "lua", "commit_id": "42d40581dd919fb134c07027ca1ce0844c670daf", "project_url": "https://github.com/lua/lua", "commit_url": "https://github.com/lua/lua/commit/42d40581dd919fb134c07027ca1ce0844c670daf", "commit_message": "Save stack space while handling errors\n\nBecause error handling (luaG_errormsg) uses slots from EXTRA_STACK,\nand some errors can recur (e.g., string overflow while creating an\nerror message in 'luaG_runerror', or a C-stack overflow before calling\nthe message handler), the code should use stack slots with parsimony.\n\nThis commit fixes the bug \"Lua-stack overflow when C stack overflows\nwhile handling an error\".", "target": 1, "func": "l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {\n  CallInfo *ci = L->ci;\n  const char *msg;\n  va_list argp;\n  luaC_checkGC(L);  /* error message uses memory */\n  va_start(argp, fmt);\n  msg = luaO_pushvfstring(L, fmt, argp);  /* format message */\n  va_end(argp);\n  if (isLua(ci))  /* if Lua function, add source:line information */\n    luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));\n  luaG_errormsg(L);\n}", "func_hash": 326823398637399129975364476390386969104, "file_name": "ldebug.c", "file_hash": 317295124781077525458993227148135997551, "cwe": ["CWE-787"], "cve": "CVE-2022-33099", "cve_desc": "An issue in the component luaG_runerror of Lua v5.4.4 and below leads to a heap-buffer overflow when a recursive error occurs.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-33099"}
{"idx": 344242, "project": "lua", "commit_id": "42d40581dd919fb134c07027ca1ce0844c670daf", "project_url": "https://github.com/lua/lua", "commit_url": "https://github.com/lua/lua/commit/42d40581dd919fb134c07027ca1ce0844c670daf", "commit_message": "Save stack space while handling errors\n\nBecause error handling (luaG_errormsg) uses slots from EXTRA_STACK,\nand some errors can recur (e.g., string overflow while creating an\nerror message in 'luaG_runerror', or a C-stack overflow before calling\nthe message handler), the code should use stack slots with parsimony.\n\nThis commit fixes the bug \"Lua-stack overflow when C stack overflows\nwhile handling an error\".", "target": 0, "func": "l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {\n  CallInfo *ci = L->ci;\n  const char *msg;\n  va_list argp;\n  luaC_checkGC(L);  /* error message uses memory */\n  va_start(argp, fmt);\n  msg = luaO_pushvfstring(L, fmt, argp);  /* format message */\n  va_end(argp);\n  if (isLua(ci)) {  /* if Lua function, add source:line information */\n    luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));\n    setobjs2s(L, L->top - 2, L->top - 1);  /* remove 'msg' from the stack */\n    L->top--;\n  }\n  luaG_errormsg(L);\n}", "func_hash": 213182302759646008213936194965010984301, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-33099", "cve_desc": "An issue in the component luaG_runerror of Lua v5.4.4 and below leads to a heap-buffer overflow when a recursive error occurs.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-33099"}
{"idx": 203614, "project": "linux", "commit_id": "a09d2d00af53b43c6f11e6ab3cb58443c2cac8a7", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/a09d2d00af53b43c6f11e6ab3cb58443c2cac8a7", "commit_message": "video: fbdev: pxa3xx-gcu: Fix integer overflow in pxa3xx_gcu_write\n\nIn pxa3xx_gcu_write, a count parameter of type size_t is passed to words of\ntype int.  Then, copy_from_user() may cause a heap overflow because it is used\nas the third argument of copy_from_user().\n\nSigned-off-by: Hyunwoo Kim \nSigned-off-by: Helge Deller ", "target": 1, "func": "pxa3xx_gcu_write(struct file *file, const char *buff,\n\t\t size_t count, loff_t *offp)\n{\n\tint ret;\n\tunsigned long flags;\n\tstruct pxa3xx_gcu_batch\t*buffer;\n\tstruct pxa3xx_gcu_priv *priv = to_pxa3xx_gcu_priv(file);\n\n\tint words = count / 4;\n\n\t/* Does not need to be atomic. There's a lock in user space,\n\t * but anyhow, this is just for statistics. */\n\tpriv->shared->num_writes++;\n\tpriv->shared->num_words += words;\n\n\t/* Last word reserved for batch buffer end command */\n\tif (words >= PXA3XX_GCU_BATCH_WORDS)\n\t\treturn -E2BIG;\n\n\t/* Wait for a free buffer */\n\tif (!priv->free) {\n\t\tret = pxa3xx_gcu_wait_free(priv);\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t}\n\n\t/*\n\t * Get buffer from free list\n\t */\n\tspin_lock_irqsave(&priv->spinlock, flags);\n\tbuffer = priv->free;\n\tpriv->free = buffer->next;\n\tspin_unlock_irqrestore(&priv->spinlock, flags);\n\n\n\t/* Copy data from user into buffer */\n\tret = copy_from_user(buffer->ptr, buff, words * 4);\n\tif (ret) {\n\t\tspin_lock_irqsave(&priv->spinlock, flags);\n\t\tbuffer->next = priv->free;\n\t\tpriv->free = buffer;\n\t\tspin_unlock_irqrestore(&priv->spinlock, flags);\n\t\treturn -EFAULT;\n\t}\n\n\tbuffer->length = words;\n\n\t/* Append batch buffer end command */\n\tbuffer->ptr[words] = 0x01000000;\n\n\t/*\n\t * Add buffer to ready list\n\t */\n\tspin_lock_irqsave(&priv->spinlock, flags);\n\n\tbuffer->next = NULL;\n\n\tif (priv->ready) {\n\t\tBUG_ON(priv->ready_last == NULL);\n\n\t\tpriv->ready_last->next = buffer;\n\t} else\n\t\tpriv->ready = buffer;\n\n\tpriv->ready_last = buffer;\n\n\tif (!priv->shared->hw_running)\n\t\trun_ready(priv);\n\n\tspin_unlock_irqrestore(&priv->spinlock, flags);\n\n\treturn words * 4;\n}", "func_hash": 295091935056220827099180820590433673308, "file_name": "pxa3xx-gcu.c", "file_hash": 328263488920768374085149640831046958332, "cwe": ["CWE-703"], "cve": "CVE-2022-39842", "cve_desc": "An issue was discovered in the Linux kernel before 5.19. In pxa3xx_gcu_write in drivers/video/fbdev/pxa3xx-gcu.c, the count parameter has a type conflict of size_t versus int, causing an integer overflow and bypassing the size check. After that, because it is used as the third argument to copy_from_user(), a heap overflow may occur. NOTE: the original discoverer disputes that the overflow can actually happen.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-39842"}
{"idx": 345131, "project": "linux", "commit_id": "a09d2d00af53b43c6f11e6ab3cb58443c2cac8a7", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/a09d2d00af53b43c6f11e6ab3cb58443c2cac8a7", "commit_message": "video: fbdev: pxa3xx-gcu: Fix integer overflow in pxa3xx_gcu_write\n\nIn pxa3xx_gcu_write, a count parameter of type size_t is passed to words of\ntype int.  Then, copy_from_user() may cause a heap overflow because it is used\nas the third argument of copy_from_user().\n\nSigned-off-by: Hyunwoo Kim \nSigned-off-by: Helge Deller ", "target": 0, "func": "pxa3xx_gcu_write(struct file *file, const char *buff,\n\t\t size_t count, loff_t *offp)\n{\n\tint ret;\n\tunsigned long flags;\n\tstruct pxa3xx_gcu_batch\t*buffer;\n\tstruct pxa3xx_gcu_priv *priv = to_pxa3xx_gcu_priv(file);\n\n\tsize_t words = count / 4;\n\n\t/* Does not need to be atomic. There's a lock in user space,\n\t * but anyhow, this is just for statistics. */\n\tpriv->shared->num_writes++;\n\tpriv->shared->num_words += words;\n\n\t/* Last word reserved for batch buffer end command */\n\tif (words >= PXA3XX_GCU_BATCH_WORDS)\n\t\treturn -E2BIG;\n\n\t/* Wait for a free buffer */\n\tif (!priv->free) {\n\t\tret = pxa3xx_gcu_wait_free(priv);\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t}\n\n\t/*\n\t * Get buffer from free list\n\t */\n\tspin_lock_irqsave(&priv->spinlock, flags);\n\tbuffer = priv->free;\n\tpriv->free = buffer->next;\n\tspin_unlock_irqrestore(&priv->spinlock, flags);\n\n\n\t/* Copy data from user into buffer */\n\tret = copy_from_user(buffer->ptr, buff, words * 4);\n\tif (ret) {\n\t\tspin_lock_irqsave(&priv->spinlock, flags);\n\t\tbuffer->next = priv->free;\n\t\tpriv->free = buffer;\n\t\tspin_unlock_irqrestore(&priv->spinlock, flags);\n\t\treturn -EFAULT;\n\t}\n\n\tbuffer->length = words;\n\n\t/* Append batch buffer end command */\n\tbuffer->ptr[words] = 0x01000000;\n\n\t/*\n\t * Add buffer to ready list\n\t */\n\tspin_lock_irqsave(&priv->spinlock, flags);\n\n\tbuffer->next = NULL;\n\n\tif (priv->ready) {\n\t\tBUG_ON(priv->ready_last == NULL);\n\n\t\tpriv->ready_last->next = buffer;\n\t} else\n\t\tpriv->ready = buffer;\n\n\tpriv->ready_last = buffer;\n\n\tif (!priv->shared->hw_running)\n\t\trun_ready(priv);\n\n\tspin_unlock_irqrestore(&priv->spinlock, flags);\n\n\treturn words * 4;\n}", "func_hash": 130082292833953650664570449389673394925, "file_name": "pxa3xx-gcu.c", "file_hash": 198658222992962284307702769824081313722, "cwe": ["CWE-703"], "cve": "CVE-2022-39842", "cve_desc": "An issue was discovered in the Linux kernel before 5.19. In pxa3xx_gcu_write in drivers/video/fbdev/pxa3xx-gcu.c, the count parameter has a type conflict of size_t versus int, causing an integer overflow and bypassing the size check. After that, because it is used as the third argument to copy_from_user(), a heap overflow may occur. NOTE: the original discoverer disputes that the overflow can actually happen.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-39842"}
{"idx": 203902, "project": "vim", "commit_id": "4748c4bd64610cf943a431d215bb1aad51f8d0b4", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/4748c4bd64610cf943a431d215bb1aad51f8d0b4", "commit_message": "patch 8.2.4974: \":so\" command may read after end of buffer\n\nProblem:    \":so\" command may read after end of buffer.\nSolution:   Compute length of text properly.", "target": 1, "func": "get_one_sourceline(source_cookie_T *sp)\n{\n    garray_T\t\tga;\n    int\t\t\tlen;\n    int\t\t\tc;\n    char_u\t\t*buf;\n#ifdef USE_CRNL\n    int\t\t\thas_cr;\t\t// CR-LF found\n#endif\n    int\t\t\thave_read = FALSE;\n\n    // use a growarray to store the sourced line\n    ga_init2(&ga, 1, 250);\n\n    // Loop until there is a finished line (or end-of-file).\n    ++sp->sourcing_lnum;\n    for (;;)\n    {\n\t// make room to read at least 120 (more) characters\n\tif (ga_grow(&ga, 120) == FAIL)\n\t    break;\n\tif (sp->source_from_buf)\n\t{\n\t    if (sp->buf_lnum >= sp->buflines.ga_len)\n\t\tbreak;\t\t    // all the lines are processed\n\t    ga_concat(&ga, ((char_u **)sp->buflines.ga_data)[sp->buf_lnum]);\n\t    sp->buf_lnum++;\n\t    if (ga_grow(&ga, 1) == FAIL)\n\t\tbreak;\n\t    buf = (char_u *)ga.ga_data;\n\t    buf[ga.ga_len++] = NUL;\n\t}\n\telse\n\t{\n\t    buf = (char_u *)ga.ga_data;\n\t    if (fgets((char *)buf + ga.ga_len, ga.ga_maxlen - ga.ga_len,\n\t\t\tsp->fp) == NULL)\n\t\tbreak;\n\t}\n\tlen = ga.ga_len + (int)STRLEN(buf + ga.ga_len);\n#ifdef USE_CRNL\n\t// Ignore a trailing CTRL-Z, when in Dos mode.\tOnly recognize the\n\t// CTRL-Z by its own, or after a NL.\n\tif (\t   (len == 1 || (len >= 2 && buf[len - 2] == '\\n'))\n\t\t&& sp->fileformat == EOL_DOS\n\t\t&& buf[len - 1] == Ctrl_Z)\n\t{\n\t    buf[len - 1] = NUL;\n\t    break;\n\t}\n#endif\n\n\thave_read = TRUE;\n\tga.ga_len = len;\n\n\t// If the line was longer than the buffer, read more.\n\tif (ga.ga_maxlen - ga.ga_len == 1 && buf[len - 1] != '\\n')\n\t    continue;\n\n\tif (len >= 1 && buf[len - 1] == '\\n')\t// remove trailing NL\n\t{\n#ifdef USE_CRNL\n\t    has_cr = (len >= 2 && buf[len - 2] == '\\r');\n\t    if (sp->fileformat == EOL_UNKNOWN)\n\t    {\n\t\tif (has_cr)\n\t\t    sp->fileformat = EOL_DOS;\n\t\telse\n\t\t    sp->fileformat = EOL_UNIX;\n\t    }\n\n\t    if (sp->fileformat == EOL_DOS)\n\t    {\n\t\tif (has_cr)\t    // replace trailing CR\n\t\t{\n\t\t    buf[len - 2] = '\\n';\n\t\t    --len;\n\t\t    --ga.ga_len;\n\t\t}\n\t\telse\t    // lines like \":map xx yy^M\" will have failed\n\t\t{\n\t\t    if (!sp->error)\n\t\t    {\n\t\t\tmsg_source(HL_ATTR(HLF_W));\n\t\t\temsg(_(\"W15: Warning: Wrong line separator, ^M may be missing\"));\n\t\t    }\n\t\t    sp->error = TRUE;\n\t\t    sp->fileformat = EOL_UNIX;\n\t\t}\n\t    }\n#endif\n\t    // The '\\n' is escaped if there is an odd number of ^V's just\n\t    // before it, first set \"c\" just before the 'V's and then check\n\t    // len&c parities (is faster than ((len-c)%2 == 0)) -- Acevedo\n\t    for (c = len - 2; c >= 0 && buf[c] == Ctrl_V; c--)\n\t\t;\n\t    if ((len & 1) != (c & 1))\t// escaped NL, read more\n\t    {\n\t\t++sp->sourcing_lnum;\n\t\tcontinue;\n\t    }\n\n\t    buf[len - 1] = NUL;\t\t// remove the NL\n\t}\n\n\t// Check for ^C here now and then, so recursive :so can be broken.\n\tline_breakcheck();\n\tbreak;\n    }\n\n    if (have_read)\n\treturn (char_u *)ga.ga_data;\n\n    vim_free(ga.ga_data);\n    return NULL;\n}", "func_hash": 227828882376561631125996314087212654807, "file_name": "scriptfile.c", "file_hash": 113985695348083727862524217442557990815, "cwe": ["CWE-703"], "cve": "CVE-2022-1769", "cve_desc": "Buffer Over-read in GitHub repository vim/vim prior to 8.2.4974.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1769"}
{"idx": 346415, "project": "vim", "commit_id": "4748c4bd64610cf943a431d215bb1aad51f8d0b4", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/4748c4bd64610cf943a431d215bb1aad51f8d0b4", "commit_message": "patch 8.2.4974: \":so\" command may read after end of buffer\n\nProblem:    \":so\" command may read after end of buffer.\nSolution:   Compute length of text properly.", "target": 0, "func": "get_one_sourceline(source_cookie_T *sp)\n{\n    garray_T\t\tga;\n    int\t\t\tlen;\n    int\t\t\tc;\n    char_u\t\t*buf;\n#ifdef USE_CRNL\n    int\t\t\thas_cr;\t\t// CR-LF found\n#endif\n    int\t\t\thave_read = FALSE;\n\n    // use a growarray to store the sourced line\n    ga_init2(&ga, 1, 250);\n\n    // Loop until there is a finished line (or end-of-file).\n    ++sp->sourcing_lnum;\n    for (;;)\n    {\n\t// make room to read at least 120 (more) characters\n\tif (ga_grow(&ga, 120) == FAIL)\n\t    break;\n\tif (sp->source_from_buf)\n\t{\n\t    if (sp->buf_lnum >= sp->buflines.ga_len)\n\t\tbreak;\t\t    // all the lines are processed\n\t    ga_concat(&ga, ((char_u **)sp->buflines.ga_data)[sp->buf_lnum]);\n\t    sp->buf_lnum++;\n\t    if (ga_grow(&ga, 1) == FAIL)\n\t\tbreak;\n\t    buf = (char_u *)ga.ga_data;\n\t    buf[ga.ga_len++] = NUL;\n\t    len = ga.ga_len;\n\t}\n\telse\n\t{\n\t    buf = (char_u *)ga.ga_data;\n\t    if (fgets((char *)buf + ga.ga_len, ga.ga_maxlen - ga.ga_len,\n\t\t\tsp->fp) == NULL)\n\t\tbreak;\n\t    len = ga.ga_len + (int)STRLEN(buf + ga.ga_len);\n\t}\n#ifdef USE_CRNL\n\t// Ignore a trailing CTRL-Z, when in Dos mode.\tOnly recognize the\n\t// CTRL-Z by its own, or after a NL.\n\tif (\t   (len == 1 || (len >= 2 && buf[len - 2] == '\\n'))\n\t\t&& sp->fileformat == EOL_DOS\n\t\t&& buf[len - 1] == Ctrl_Z)\n\t{\n\t    buf[len - 1] = NUL;\n\t    break;\n\t}\n#endif\n\n\thave_read = TRUE;\n\tga.ga_len = len;\n\n\t// If the line was longer than the buffer, read more.\n\tif (ga.ga_maxlen - ga.ga_len == 1 && buf[len - 1] != '\\n')\n\t    continue;\n\n\tif (len >= 1 && buf[len - 1] == '\\n')\t// remove trailing NL\n\t{\n#ifdef USE_CRNL\n\t    has_cr = (len >= 2 && buf[len - 2] == '\\r');\n\t    if (sp->fileformat == EOL_UNKNOWN)\n\t    {\n\t\tif (has_cr)\n\t\t    sp->fileformat = EOL_DOS;\n\t\telse\n\t\t    sp->fileformat = EOL_UNIX;\n\t    }\n\n\t    if (sp->fileformat == EOL_DOS)\n\t    {\n\t\tif (has_cr)\t    // replace trailing CR\n\t\t{\n\t\t    buf[len - 2] = '\\n';\n\t\t    --len;\n\t\t    --ga.ga_len;\n\t\t}\n\t\telse\t    // lines like \":map xx yy^M\" will have failed\n\t\t{\n\t\t    if (!sp->error)\n\t\t    {\n\t\t\tmsg_source(HL_ATTR(HLF_W));\n\t\t\temsg(_(\"W15: Warning: Wrong line separator, ^M may be missing\"));\n\t\t    }\n\t\t    sp->error = TRUE;\n\t\t    sp->fileformat = EOL_UNIX;\n\t\t}\n\t    }\n#endif\n\t    // The '\\n' is escaped if there is an odd number of ^V's just\n\t    // before it, first set \"c\" just before the 'V's and then check\n\t    // len&c parities (is faster than ((len-c)%2 == 0)) -- Acevedo\n\t    for (c = len - 2; c >= 0 && buf[c] == Ctrl_V; c--)\n\t\t;\n\t    if ((len & 1) != (c & 1))\t// escaped NL, read more\n\t    {\n\t\t++sp->sourcing_lnum;\n\t\tcontinue;\n\t    }\n\n\t    buf[len - 1] = NUL;\t\t// remove the NL\n\t}\n\n\t// Check for ^C here now and then, so recursive :so can be broken.\n\tline_breakcheck();\n\tbreak;\n    }\n\n    if (have_read)\n\treturn (char_u *)ga.ga_data;\n\n    vim_free(ga.ga_data);\n    return NULL;\n}", "func_hash": 178235949916864624695352217723493381575, "file_name": "scriptfile.c", "file_hash": 185541822912914842655555626416100401533, "cwe": ["CWE-703"], "cve": "CVE-2022-1769", "cve_desc": "Buffer Over-read in GitHub repository vim/vim prior to 8.2.4974.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1769"}
{"idx": 204016, "project": "squashfs-tools", "commit_id": "e0485802ec72996c20026da320650d8362f555bd", "project_url": "https://github.com/plougher/squashfs-tools", "commit_url": "https://github.com/plougher/squashfs-tools/commit/e0485802ec72996c20026da320650d8362f555bd", "commit_message": "Unsquashfs: additional write outside destination directory exploit fix\n\nAn issue on github (https://github.com/plougher/squashfs-tools/issues/72)\nshowed how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and '..') can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nSince then it has been shown that specially crafted Squashfs filesystems\nthat contain a symbolic link pointing outside of the destination directory,\ncoupled with an identically named file within the same directory, can\ncause Unsquashfs to write files outside of the destination directory.\n\nSpecifically the symbolic link produces a pathname pointing outside\nof the destination directory, which is then followed when writing the\nduplicate identically named file within the directory.\n\nThis commit fixes this exploit by explictly checking for duplicate\nfilenames within a directory.  As directories in v2.1, v3.x, and v4.0\nfilesystems are sorted, this is achieved by checking for consecutively\nidentical filenames.  Additionally directories are checked to\nensure they are sorted, to avoid attempts to evade the duplicate\ncheck.\n\nVersion 1.x and 2.0 filesystems (where the directories were unsorted)\nare sorted and then the above duplicate filename check is applied.\n\nSigned-off-by: Phillip Lougher ", "target": 1, "func": "static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tsquashfs_dir_header_2 dirh;\n\tchar buffer[sizeof(squashfs_dir_entry_2) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tsquashfs_dir_entry_2 *dire = (squashfs_dir_entry_2 *) buffer;\n\tlong long start;\n\tint bytes = 0;\n\tint dir_count, size, res;\n\tstruct dir_ent *ent, *cur_ent = NULL;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tMEM_ERROR();\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = NULL;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 0)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\toffset = (*i)->offset;\n\tsize = (*i)->data + bytes;\n\n\twhile(bytes < size) {\n\t\tif(swap) {\n\t\t\tsquashfs_dir_header_2 sdirh;\n\t\t\tres = read_directory_data(&sdirh, &start, &offset, sizeof(sdirh));\n\t\t\tif(res)\n\t\t\t\tSQUASHFS_SWAP_DIR_HEADER_2(&dirh, &sdirh);\n\t\t} else\n\t\t\tres = read_directory_data(&dirh, &start, &offset, sizeof(dirh));\n\n\t\tif(res == FALSE)\n\t\t\tgoto corrupted;\n\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tif(swap) {\n\t\t\t\tsquashfs_dir_entry_2 sdire;\n\t\t\t\tres = read_directory_data(&sdire, &start,\n\t\t\t\t\t&offset, sizeof(sdire));\n\t\t\t\tif(res)\n\t\t\t\t\tSQUASHFS_SWAP_DIR_ENTRY_2(dire, &sdire);\n\t\t\t} else\n\t\t\t\tres = read_directory_data(dire, &start,\n\t\t\t\t\t&offset, sizeof(*dire));\n\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tres = read_directory_data(dire->name, &start, &offset,\n\t\t\t\t\t\t\t\tdire->size + 1);\n\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\n\t\t\t/* check name for invalid characters (i.e /, ., ..) */\n\t\t\tif(check_name(dire->name, dire->size + 1) == FALSE) {\n\t\t\t\tERROR(\"File system corrupted: invalid characters in name\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\n\t\t\tent = malloc(sizeof(struct dir_ent));\n\t\t\tif(ent == NULL)\n\t\t\t\tMEM_ERROR();\n\n\t\t\tent->name = strdup(dire->name);\n\t\t\tent->start_block = dirh.start_block;\n\t\t\tent->offset = dire->offset;\n\t\t\tent->type = dire->type;\n\t\t\tent->next = NULL;\n\t\t\tif(cur_ent == NULL)\n\t\t\t\tdir->dirs = ent;\n\t\t\telse\n\t\t\t\tcur_ent->next = ent;\n\t\t\tcur_ent = ent;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tsquashfs_closedir(dir);\n\treturn NULL;\n}", "func_hash": 285801527234841078419372065290976958053, "file_name": "None", "file_hash": null, "cwe": ["CWE-200"], "cve": "CVE-2021-41072", "cve_desc": "squashfs_opendir in unsquash-2.c in Squashfs-Tools 4.5 allows Directory Traversal, a different vulnerability than CVE-2021-40153. A squashfs filesystem that has been crafted to include a symbolic link and then contents under the same filename in a filesystem can cause unsquashfs to first create the symbolic link pointing outside the expected directory, and then the subsequent write operation will cause the unsquashfs process to write through the symbolic link elsewhere in the filesystem.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41072"}
{"idx": 349259, "project": "squashfs-tools", "commit_id": "e0485802ec72996c20026da320650d8362f555bd", "project_url": "https://github.com/plougher/squashfs-tools", "commit_url": "https://github.com/plougher/squashfs-tools/commit/e0485802ec72996c20026da320650d8362f555bd", "commit_message": "Unsquashfs: additional write outside destination directory exploit fix\n\nAn issue on github (https://github.com/plougher/squashfs-tools/issues/72)\nshowed how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and '..') can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nSince then it has been shown that specially crafted Squashfs filesystems\nthat contain a symbolic link pointing outside of the destination directory,\ncoupled with an identically named file within the same directory, can\ncause Unsquashfs to write files outside of the destination directory.\n\nSpecifically the symbolic link produces a pathname pointing outside\nof the destination directory, which is then followed when writing the\nduplicate identically named file within the directory.\n\nThis commit fixes this exploit by explictly checking for duplicate\nfilenames within a directory.  As directories in v2.1, v3.x, and v4.0\nfilesystems are sorted, this is achieved by checking for consecutively\nidentical filenames.  Additionally directories are checked to\nensure they are sorted, to avoid attempts to evade the duplicate\ncheck.\n\nVersion 1.x and 2.0 filesystems (where the directories were unsorted)\nare sorted and then the above duplicate filename check is applied.\n\nSigned-off-by: Phillip Lougher ", "target": 0, "func": "static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tsquashfs_dir_header_3 dirh;\n\tchar buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tsquashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer;\n\tlong long start;\n\tint bytes = 0;\n\tint dir_count, size, res;\n\tstruct dir_ent *ent, *cur_ent = NULL;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tMEM_ERROR();\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = NULL;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 3)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\toffset = (*i)->offset;\n\tsize = (*i)->data + bytes - 3;\n\n\twhile(bytes < size) {\t\t\t\n\t\tif(swap) {\n\t\t\tsquashfs_dir_header_3 sdirh;\n\t\t\tres = read_directory_data(&sdirh, &start, &offset, sizeof(sdirh));\n\t\t\tif(res)\n\t\t\t\tSQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh);\n\t\t} else\n\t\t\tres = read_directory_data(&dirh, &start, &offset, sizeof(dirh));\n\t\n\t\tif(res == FALSE)\n\t\t\tgoto corrupted;\n\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tif(swap) {\n\t\t\t\tsquashfs_dir_entry_3 sdire;\n\t\t\t\tres = read_directory_data(&sdire, &start,\n\t\t\t\t\t&offset, sizeof(sdire));\n\t\t\t\tif(res)\n\t\t\t\t\tSQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire);\n\t\t\t} else\n\t\t\t\tres = read_directory_data(dire, &start,\n\t\t\t\t\t&offset, sizeof(*dire));\n\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tres = read_directory_data(dire->name, &start, &offset,\n\t\t\t\t\t\t\t\tdire->size + 1);\n\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\n\t\t\t/* check name for invalid characters (i.e /, ., ..) */\n\t\t\tif(check_name(dire->name, dire->size + 1) == FALSE) {\n\t\t\t\tERROR(\"File system corrupted: invalid characters in name\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\n\t\t\tent = malloc(sizeof(struct dir_ent));\n\t\t\tif(ent == NULL)\n\t\t\t\tMEM_ERROR();\n\n\t\t\tent->name = strdup(dire->name);\n\t\t\tent->start_block = dirh.start_block;\n\t\t\tent->offset = dire->offset;\n\t\t\tent->type = dire->type;\n\t\t\tent->next = NULL;\n\t\t\tif(cur_ent == NULL)\n\t\t\t\tdir->dirs = ent;\n\t\t\telse\n\t\t\t\tcur_ent->next = ent;\n\t\t\tcur_ent = ent;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\t/* check directory for duplicate names and sorting */\n\tif(check_directory(dir) == FALSE) {\n\t\tERROR(\"File system corrupted: directory has duplicate names or is unsorted\\n\");\n\t\tgoto corrupted;\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tsquashfs_closedir(dir);\n\treturn NULL;\n}", "func_hash": 329567721656130311991352890320471862864, "file_name": "None", "file_hash": null, "cwe": ["CWE-200"], "cve": "CVE-2021-41072", "cve_desc": "squashfs_opendir in unsquash-2.c in Squashfs-Tools 4.5 allows Directory Traversal, a different vulnerability than CVE-2021-40153. A squashfs filesystem that has been crafted to include a symbolic link and then contents under the same filename in a filesystem can cause unsquashfs to first create the symbolic link pointing outside the expected directory, and then the subsequent write operation will cause the unsquashfs process to write through the symbolic link elsewhere in the filesystem.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41072"}
{"idx": 204017, "project": "squashfs-tools", "commit_id": "e0485802ec72996c20026da320650d8362f555bd", "project_url": "https://github.com/plougher/squashfs-tools", "commit_url": "https://github.com/plougher/squashfs-tools/commit/e0485802ec72996c20026da320650d8362f555bd", "commit_message": "Unsquashfs: additional write outside destination directory exploit fix\n\nAn issue on github (https://github.com/plougher/squashfs-tools/issues/72)\nshowed how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and '..') can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nSince then it has been shown that specially crafted Squashfs filesystems\nthat contain a symbolic link pointing outside of the destination directory,\ncoupled with an identically named file within the same directory, can\ncause Unsquashfs to write files outside of the destination directory.\n\nSpecifically the symbolic link produces a pathname pointing outside\nof the destination directory, which is then followed when writing the\nduplicate identically named file within the directory.\n\nThis commit fixes this exploit by explictly checking for duplicate\nfilenames within a directory.  As directories in v2.1, v3.x, and v4.0\nfilesystems are sorted, this is achieved by checking for consecutively\nidentical filenames.  Additionally directories are checked to\nensure they are sorted, to avoid attempts to evade the duplicate\ncheck.\n\nVersion 1.x and 2.0 filesystems (where the directories were unsorted)\nare sorted and then the above duplicate filename check is applied.\n\nSigned-off-by: Phillip Lougher ", "target": 1, "func": "static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tsquashfs_dir_header_3 dirh;\n\tchar buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tsquashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer;\n\tlong long start;\n\tint bytes = 0;\n\tint dir_count, size, res;\n\tstruct dir_ent *ent, *cur_ent = NULL;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tMEM_ERROR();\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = NULL;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 3)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\toffset = (*i)->offset;\n\tsize = (*i)->data + bytes - 3;\n\n\twhile(bytes < size) {\t\t\t\n\t\tif(swap) {\n\t\t\tsquashfs_dir_header_3 sdirh;\n\t\t\tres = read_directory_data(&sdirh, &start, &offset, sizeof(sdirh));\n\t\t\tif(res)\n\t\t\t\tSQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh);\n\t\t} else\n\t\t\tres = read_directory_data(&dirh, &start, &offset, sizeof(dirh));\n\t\n\t\tif(res == FALSE)\n\t\t\tgoto corrupted;\n\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tif(swap) {\n\t\t\t\tsquashfs_dir_entry_3 sdire;\n\t\t\t\tres = read_directory_data(&sdire, &start,\n\t\t\t\t\t&offset, sizeof(sdire));\n\t\t\t\tif(res)\n\t\t\t\t\tSQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire);\n\t\t\t} else\n\t\t\t\tres = read_directory_data(dire, &start,\n\t\t\t\t\t&offset, sizeof(*dire));\n\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tres = read_directory_data(dire->name, &start, &offset,\n\t\t\t\t\t\t\t\tdire->size + 1);\n\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\n\t\t\t/* check name for invalid characters (i.e /, ., ..) */\n\t\t\tif(check_name(dire->name, dire->size + 1) == FALSE) {\n\t\t\t\tERROR(\"File system corrupted: invalid characters in name\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\n\t\t\tent = malloc(sizeof(struct dir_ent));\n\t\t\tif(ent == NULL)\n\t\t\t\tMEM_ERROR();\n\n\t\t\tent->name = strdup(dire->name);\n\t\t\tent->start_block = dirh.start_block;\n\t\t\tent->offset = dire->offset;\n\t\t\tent->type = dire->type;\n\t\t\tent->next = NULL;\n\t\t\tif(cur_ent == NULL)\n\t\t\t\tdir->dirs = ent;\n\t\t\telse\n\t\t\t\tcur_ent->next = ent;\n\t\t\tcur_ent = ent;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tsquashfs_closedir(dir);\n\treturn NULL;\n}", "func_hash": 255918777018822290262253660606481852296, "file_name": "None", "file_hash": null, "cwe": ["CWE-200"], "cve": "CVE-2021-41072", "cve_desc": "squashfs_opendir in unsquash-2.c in Squashfs-Tools 4.5 allows Directory Traversal, a different vulnerability than CVE-2021-40153. A squashfs filesystem that has been crafted to include a symbolic link and then contents under the same filename in a filesystem can cause unsquashfs to first create the symbolic link pointing outside the expected directory, and then the subsequent write operation will cause the unsquashfs process to write through the symbolic link elsewhere in the filesystem.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41072"}
{"idx": 349259, "project": "squashfs-tools", "commit_id": "e0485802ec72996c20026da320650d8362f555bd", "project_url": "https://github.com/plougher/squashfs-tools", "commit_url": "https://github.com/plougher/squashfs-tools/commit/e0485802ec72996c20026da320650d8362f555bd", "commit_message": "Unsquashfs: additional write outside destination directory exploit fix\n\nAn issue on github (https://github.com/plougher/squashfs-tools/issues/72)\nshowed how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and '..') can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nSince then it has been shown that specially crafted Squashfs filesystems\nthat contain a symbolic link pointing outside of the destination directory,\ncoupled with an identically named file within the same directory, can\ncause Unsquashfs to write files outside of the destination directory.\n\nSpecifically the symbolic link produces a pathname pointing outside\nof the destination directory, which is then followed when writing the\nduplicate identically named file within the directory.\n\nThis commit fixes this exploit by explictly checking for duplicate\nfilenames within a directory.  As directories in v2.1, v3.x, and v4.0\nfilesystems are sorted, this is achieved by checking for consecutively\nidentical filenames.  Additionally directories are checked to\nensure they are sorted, to avoid attempts to evade the duplicate\ncheck.\n\nVersion 1.x and 2.0 filesystems (where the directories were unsorted)\nare sorted and then the above duplicate filename check is applied.\n\nSigned-off-by: Phillip Lougher ", "target": 0, "func": "static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tsquashfs_dir_header_3 dirh;\n\tchar buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tsquashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer;\n\tlong long start;\n\tint bytes = 0;\n\tint dir_count, size, res;\n\tstruct dir_ent *ent, *cur_ent = NULL;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tMEM_ERROR();\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = NULL;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 3)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\toffset = (*i)->offset;\n\tsize = (*i)->data + bytes - 3;\n\n\twhile(bytes < size) {\t\t\t\n\t\tif(swap) {\n\t\t\tsquashfs_dir_header_3 sdirh;\n\t\t\tres = read_directory_data(&sdirh, &start, &offset, sizeof(sdirh));\n\t\t\tif(res)\n\t\t\t\tSQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh);\n\t\t} else\n\t\t\tres = read_directory_data(&dirh, &start, &offset, sizeof(dirh));\n\t\n\t\tif(res == FALSE)\n\t\t\tgoto corrupted;\n\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tif(swap) {\n\t\t\t\tsquashfs_dir_entry_3 sdire;\n\t\t\t\tres = read_directory_data(&sdire, &start,\n\t\t\t\t\t&offset, sizeof(sdire));\n\t\t\t\tif(res)\n\t\t\t\t\tSQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire);\n\t\t\t} else\n\t\t\t\tres = read_directory_data(dire, &start,\n\t\t\t\t\t&offset, sizeof(*dire));\n\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tres = read_directory_data(dire->name, &start, &offset,\n\t\t\t\t\t\t\t\tdire->size + 1);\n\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\n\t\t\t/* check name for invalid characters (i.e /, ., ..) */\n\t\t\tif(check_name(dire->name, dire->size + 1) == FALSE) {\n\t\t\t\tERROR(\"File system corrupted: invalid characters in name\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\n\t\t\tent = malloc(sizeof(struct dir_ent));\n\t\t\tif(ent == NULL)\n\t\t\t\tMEM_ERROR();\n\n\t\t\tent->name = strdup(dire->name);\n\t\t\tent->start_block = dirh.start_block;\n\t\t\tent->offset = dire->offset;\n\t\t\tent->type = dire->type;\n\t\t\tent->next = NULL;\n\t\t\tif(cur_ent == NULL)\n\t\t\t\tdir->dirs = ent;\n\t\t\telse\n\t\t\t\tcur_ent->next = ent;\n\t\t\tcur_ent = ent;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\t/* check directory for duplicate names and sorting */\n\tif(check_directory(dir) == FALSE) {\n\t\tERROR(\"File system corrupted: directory has duplicate names or is unsorted\\n\");\n\t\tgoto corrupted;\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tsquashfs_closedir(dir);\n\treturn NULL;\n}", "func_hash": 329567721656130311991352890320471862864, "file_name": "None", "file_hash": null, "cwe": ["CWE-200"], "cve": "CVE-2021-41072", "cve_desc": "squashfs_opendir in unsquash-2.c in Squashfs-Tools 4.5 allows Directory Traversal, a different vulnerability than CVE-2021-40153. A squashfs filesystem that has been crafted to include a symbolic link and then contents under the same filename in a filesystem can cause unsquashfs to first create the symbolic link pointing outside the expected directory, and then the subsequent write operation will cause the unsquashfs process to write through the symbolic link elsewhere in the filesystem.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41072"}
{"idx": 204019, "project": "squashfs-tools", "commit_id": "e0485802ec72996c20026da320650d8362f555bd", "project_url": "https://github.com/plougher/squashfs-tools", "commit_url": "https://github.com/plougher/squashfs-tools/commit/e0485802ec72996c20026da320650d8362f555bd", "commit_message": "Unsquashfs: additional write outside destination directory exploit fix\n\nAn issue on github (https://github.com/plougher/squashfs-tools/issues/72)\nshowed how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and '..') can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nSince then it has been shown that specially crafted Squashfs filesystems\nthat contain a symbolic link pointing outside of the destination directory,\ncoupled with an identically named file within the same directory, can\ncause Unsquashfs to write files outside of the destination directory.\n\nSpecifically the symbolic link produces a pathname pointing outside\nof the destination directory, which is then followed when writing the\nduplicate identically named file within the directory.\n\nThis commit fixes this exploit by explictly checking for duplicate\nfilenames within a directory.  As directories in v2.1, v3.x, and v4.0\nfilesystems are sorted, this is achieved by checking for consecutively\nidentical filenames.  Additionally directories are checked to\nensure they are sorted, to avoid attempts to evade the duplicate\ncheck.\n\nVersion 1.x and 2.0 filesystems (where the directories were unsorted)\nare sorted and then the above duplicate filename check is applied.\n\nSigned-off-by: Phillip Lougher ", "target": 1, "func": "static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tstruct squashfs_dir_header dirh;\n\tchar buffer[sizeof(struct squashfs_dir_entry) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tstruct squashfs_dir_entry *dire = (struct squashfs_dir_entry *) buffer;\n\tlong long start;\n\tint bytes = 0, dir_count, size, res;\n\tstruct dir_ent *ent, *cur_ent = NULL;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tMEM_ERROR();\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = NULL;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 3)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\toffset = (*i)->offset;\n\tsize = (*i)->data + bytes - 3;\n\n\twhile(bytes < size) {\t\t\t\n\t\tres = read_directory_data(&dirh, &start, &offset, sizeof(dirh));\n\t\tif(res == FALSE)\n\t\t\tgoto corrupted;\n\n\t\tSQUASHFS_INSWAP_DIR_HEADER(&dirh);\n\t\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tres = read_directory_data(dire, &start, &offset, sizeof(*dire));\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tSQUASHFS_INSWAP_DIR_ENTRY(dire);\n\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tres = read_directory_data(dire->name, &start, &offset,\n\t\t\t\t\t\t\t\tdire->size + 1);\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\n\t\t\t/* check name for invalid characters (i.e /, ., ..) */\n\t\t\tif(check_name(dire->name, dire->size + 1) == FALSE) {\n\t\t\t\tERROR(\"File system corrupted: invalid characters in name\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\n\t\t\tent = malloc(sizeof(struct dir_ent));\n\t\t\tif(ent == NULL)\n\t\t\t\tMEM_ERROR();\n\n\t\t\tent->name = strdup(dire->name);\n\t\t\tent->start_block = dirh.start_block;\n\t\t\tent->offset = dire->offset;\n\t\t\tent->type = dire->type;\n\t\t\tent->next = NULL;\n\t\t\tif(cur_ent == NULL)\n\t\t\t\tdir->dirs = ent;\n\t\t\telse\n\t\t\t\tcur_ent->next = ent;\n\t\t\tcur_ent = ent;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tsquashfs_closedir(dir);\n\treturn NULL;\n}", "func_hash": 201112194066190404081281072830763464085, "file_name": "None", "file_hash": null, "cwe": ["CWE-200"], "cve": "CVE-2021-41072", "cve_desc": "squashfs_opendir in unsquash-2.c in Squashfs-Tools 4.5 allows Directory Traversal, a different vulnerability than CVE-2021-40153. A squashfs filesystem that has been crafted to include a symbolic link and then contents under the same filename in a filesystem can cause unsquashfs to first create the symbolic link pointing outside the expected directory, and then the subsequent write operation will cause the unsquashfs process to write through the symbolic link elsewhere in the filesystem.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41072"}
{"idx": 349251, "project": "squashfs-tools", "commit_id": "e0485802ec72996c20026da320650d8362f555bd", "project_url": "https://github.com/plougher/squashfs-tools", "commit_url": "https://github.com/plougher/squashfs-tools/commit/e0485802ec72996c20026da320650d8362f555bd", "commit_message": "Unsquashfs: additional write outside destination directory exploit fix\n\nAn issue on github (https://github.com/plougher/squashfs-tools/issues/72)\nshowed how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and '..') can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nSince then it has been shown that specially crafted Squashfs filesystems\nthat contain a symbolic link pointing outside of the destination directory,\ncoupled with an identically named file within the same directory, can\ncause Unsquashfs to write files outside of the destination directory.\n\nSpecifically the symbolic link produces a pathname pointing outside\nof the destination directory, which is then followed when writing the\nduplicate identically named file within the directory.\n\nThis commit fixes this exploit by explictly checking for duplicate\nfilenames within a directory.  As directories in v2.1, v3.x, and v4.0\nfilesystems are sorted, this is achieved by checking for consecutively\nidentical filenames.  Additionally directories are checked to\nensure they are sorted, to avoid attempts to evade the duplicate\ncheck.\n\nVersion 1.x and 2.0 filesystems (where the directories were unsorted)\nare sorted and then the above duplicate filename check is applied.\n\nSigned-off-by: Phillip Lougher ", "target": 0, "func": "static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tstruct squashfs_dir_header dirh;\n\tchar buffer[sizeof(struct squashfs_dir_entry) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tstruct squashfs_dir_entry *dire = (struct squashfs_dir_entry *) buffer;\n\tlong long start;\n\tint bytes = 0, dir_count, size, res;\n\tstruct dir_ent *ent, *cur_ent = NULL;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tMEM_ERROR();\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = NULL;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 3)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\toffset = (*i)->offset;\n\tsize = (*i)->data + bytes - 3;\n\n\twhile(bytes < size) {\t\t\t\n\t\tres = read_directory_data(&dirh, &start, &offset, sizeof(dirh));\n\t\tif(res == FALSE)\n\t\t\tgoto corrupted;\n\n\t\tSQUASHFS_INSWAP_DIR_HEADER(&dirh);\n\t\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tres = read_directory_data(dire, &start, &offset, sizeof(*dire));\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tSQUASHFS_INSWAP_DIR_ENTRY(dire);\n\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tres = read_directory_data(dire->name, &start, &offset,\n\t\t\t\t\t\t\t\tdire->size + 1);\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\n\t\t\t/* check name for invalid characters (i.e /, ., ..) */\n\t\t\tif(check_name(dire->name, dire->size + 1) == FALSE) {\n\t\t\t\tERROR(\"File system corrupted: invalid characters in name\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\n\t\t\tent = malloc(sizeof(struct dir_ent));\n\t\t\tif(ent == NULL)\n\t\t\t\tMEM_ERROR();\n\n\t\t\tent->name = strdup(dire->name);\n\t\t\tent->start_block = dirh.start_block;\n\t\t\tent->offset = dire->offset;\n\t\t\tent->type = dire->type;\n\t\t\tent->next = NULL;\n\t\t\tif(cur_ent == NULL)\n\t\t\t\tdir->dirs = ent;\n\t\t\telse\n\t\t\t\tcur_ent->next = ent;\n\t\t\tcur_ent = ent;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\t/* check directory for duplicate names and sorting */\n\tif(check_directory(dir) == FALSE) {\n\t\tERROR(\"File system corrupted: directory has duplicate names or is unsorted\\n\");\n\t\tgoto corrupted;\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tsquashfs_closedir(dir);\n\treturn NULL;\n}", "func_hash": 101994300630246920373110387154385179099, "file_name": "None", "file_hash": null, "cwe": ["CWE-200"], "cve": "CVE-2021-41072", "cve_desc": "squashfs_opendir in unsquash-2.c in Squashfs-Tools 4.5 allows Directory Traversal, a different vulnerability than CVE-2021-40153. A squashfs filesystem that has been crafted to include a symbolic link and then contents under the same filename in a filesystem can cause unsquashfs to first create the symbolic link pointing outside the expected directory, and then the subsequent write operation will cause the unsquashfs process to write through the symbolic link elsewhere in the filesystem.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41072"}
{"idx": 204032, "project": "linux", "commit_id": "1d0688421449718c6c5f46e458a378c9b530ba18", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=1d0688421449718c6c5f46e458a378c9b530ba18", "commit_message": "Bluetooth: virtio_bt: fix memory leak in virtbt_rx_handle()\n\nOn the reception of packets with an invalid packet type, the memory of\nthe allocated socket buffers is never freed. Add a default case that frees\nthese to avoid a memory leak.\n\nFixes: afd2daa26c7a (\"Bluetooth: Add support for virtio transport driver\")\nSigned-off-by: Soenke Huster \nSigned-off-by: Marcel Holtmann ", "target": 1, "func": "static void virtbt_rx_handle(struct virtio_bluetooth *vbt, struct sk_buff *skb)\n{\n\t__u8 pkt_type;\n\n\tpkt_type = *((__u8 *) skb->data);\n\tskb_pull(skb, 1);\n\n\tswitch (pkt_type) {\n\tcase HCI_EVENT_PKT:\n\tcase HCI_ACLDATA_PKT:\n\tcase HCI_SCODATA_PKT:\n\tcase HCI_ISODATA_PKT:\n\t\thci_skb_pkt_type(skb) = pkt_type;\n\t\thci_recv_frame(vbt->hdev, skb);\n\t\tbreak;\n\t}\n}", "func_hash": 317953678093244017346219057450366042536, "file_name": "virtio_bt.c", "file_hash": 236732335469257962390870321221153262680, "cwe": ["CWE-772"], "cve": "CVE-2022-26878", "cve_desc": "drivers/bluetooth/virtio_bt.c in the Linux kernel before 5.16.3 has a memory leak (socket buffers have memory allocated but not freed).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-26878"}
{"idx": 349528, "project": "linux", "commit_id": "1d0688421449718c6c5f46e458a378c9b530ba18", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=1d0688421449718c6c5f46e458a378c9b530ba18", "commit_message": "Bluetooth: virtio_bt: fix memory leak in virtbt_rx_handle()\n\nOn the reception of packets with an invalid packet type, the memory of\nthe allocated socket buffers is never freed. Add a default case that frees\nthese to avoid a memory leak.\n\nFixes: afd2daa26c7a (\"Bluetooth: Add support for virtio transport driver\")\nSigned-off-by: Soenke Huster \nSigned-off-by: Marcel Holtmann ", "target": 0, "func": "static void virtbt_rx_handle(struct virtio_bluetooth *vbt, struct sk_buff *skb)\n{\n\t__u8 pkt_type;\n\n\tpkt_type = *((__u8 *) skb->data);\n\tskb_pull(skb, 1);\n\n\tswitch (pkt_type) {\n\tcase HCI_EVENT_PKT:\n\tcase HCI_ACLDATA_PKT:\n\tcase HCI_SCODATA_PKT:\n\tcase HCI_ISODATA_PKT:\n\t\thci_skb_pkt_type(skb) = pkt_type;\n\t\thci_recv_frame(vbt->hdev, skb);\n\t\tbreak;\n\tdefault:\n\t\tkfree_skb(skb);\n\t\tbreak;\n\t}\n}", "func_hash": 158789804082007954716918629696286112823, "file_name": "virtio_bt.c", "file_hash": 116955738040617915933180365116033475903, "cwe": ["CWE-772"], "cve": "CVE-2022-26878", "cve_desc": "drivers/bluetooth/virtio_bt.c in the Linux kernel before 5.16.3 has a memory leak (socket buffers have memory allocated but not freed).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-26878"}
{"idx": 204036, "project": "net", "commit_id": "b922f622592af76b57cbc566eaeccda0b31a3496", "project_url": "https://git.kernel.org/cgit/linux/kernel/git/davem/net", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/netdev/net.git/commit/?id=b922f622592af76b57cbc566eaeccda0b31a3496", "commit_message": "atlantic: Fix OOB read and write in hw_atl_utils_fw_rpc_wait\n\nThis bug report shows up when running our research tools. The\nreports is SOOB read, but it seems SOOB write is also possible\na few lines below.\n\nIn details, fw.len and sw.len are inputs coming from io. A len\nover the size of self->rpc triggers SOOB. The patch fixes the\nbugs by adding sanity checks.\n\nThe bugs are triggerable with compromised/malfunctioning devices.\nThey are potentially exploitable given they first leak up to\n0xffff bytes and able to overwrite the region later.\n\nThe patch is tested with QEMU emulater.\nThis is NOT tested with a real device.\n\nAttached is the log we found by fuzzing.\n\nBUG: KASAN: slab-out-of-bounds in\n\thw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]\nRead of size 4 at addr ffff888016260b08 by task modprobe/213\nCPU: 0 PID: 213 Comm: modprobe Not tainted 5.6.0 #1\nCall Trace:\n dump_stack+0x76/0xa0\n print_address_description.constprop.0+0x16/0x200\n ? hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]\n ? hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]\n __kasan_report.cold+0x37/0x7c\n ? aq_hw_read_reg_bit+0x60/0x70 [atlantic]\n ? hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]\n kasan_report+0xe/0x20\n hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]\n hw_atl_utils_fw_rpc_call+0x95/0x130 [atlantic]\n hw_atl_utils_fw_rpc_wait+0x176/0x210 [atlantic]\n hw_atl_utils_mpi_create+0x229/0x2e0 [atlantic]\n ? hw_atl_utils_fw_rpc_wait+0x210/0x210 [atlantic]\n ? hw_atl_utils_initfw+0x9f/0x1c8 [atlantic]\n hw_atl_utils_initfw+0x12a/0x1c8 [atlantic]\n aq_nic_ndev_register+0x88/0x650 [atlantic]\n ? aq_nic_ndev_init+0x235/0x3c0 [atlantic]\n aq_pci_probe+0x731/0x9b0 [atlantic]\n ? aq_pci_func_init+0xc0/0xc0 [atlantic]\n local_pci_probe+0xd3/0x160\n pci_device_probe+0x23f/0x3e0\n\nReported-by: Brendan Dolan-Gavitt \nSigned-off-by: Zekun Shen \nSigned-off-by: David S. Miller ", "target": 1, "func": "int hw_atl_utils_fw_rpc_wait(struct aq_hw_s *self,\n\t\t\t     struct hw_atl_utils_fw_rpc **rpc)\n{\n\tstruct aq_hw_atl_utils_fw_rpc_tid_s sw;\n\tstruct aq_hw_atl_utils_fw_rpc_tid_s fw;\n\tint err = 0;\n\n\tdo {\n\t\tsw.val = aq_hw_read_reg(self, HW_ATL_RPC_CONTROL_ADR);\n\n\t\tself->rpc_tid = sw.tid;\n\n\t\terr = readx_poll_timeout_atomic(hw_atl_utils_rpc_state_get,\n\t\t\t\t\t\tself, fw.val,\n\t\t\t\t\t\tsw.tid == fw.tid,\n\t\t\t\t\t\t1000U, 100000U);\n\t\tif (err < 0)\n\t\t\tgoto err_exit;\n\n\t\terr = aq_hw_err_from_flags(self);\n\t\tif (err < 0)\n\t\t\tgoto err_exit;\n\n\t\tif (fw.len == 0xFFFFU) {\n\t\t\terr = hw_atl_utils_fw_rpc_call(self, sw.len);\n\t\t\tif (err < 0)\n\t\t\t\tgoto err_exit;\n\t\t}\n\t} while (sw.tid != fw.tid || 0xFFFFU == fw.len);\n\n\tif (rpc) {\n\t\tif (fw.len) {\n\t\t\terr =\n\t\t\thw_atl_utils_fw_downld_dwords(self,\n\t\t\t\t\t\t      self->rpc_addr,\n\t\t\t\t\t\t      (u32 *)(void *)\n\t\t\t\t\t\t      &self->rpc,\n\t\t\t\t\t\t      (fw.len + sizeof(u32) -\n\t\t\t\t\t\t       sizeof(u8)) /\n\t\t\t\t\t\t      sizeof(u32));\n\t\t\tif (err < 0)\n\t\t\t\tgoto err_exit;\n\t\t}\n\n\t\t*rpc = &self->rpc;\n\t}\n\nerr_exit:\n\treturn err;\n}", "func_hash": 172267235624297887549936176387558671779, "file_name": "hw_atl_utils.c", "file_hash": 44971629265501342494525008338833784195, "cwe": ["CWE-787"], "cve": "CVE-2021-43975", "cve_desc": "In the Linux kernel through 5.15.2, hw_atl_utils_fw_rpc_wait in drivers/net/ethernet/aquantia/atlantic/hw_atl/hw_atl_utils.c allows an attacker (who can introduce a crafted device) to trigger an out-of-bounds write via a crafted length value.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43975"}
{"idx": 349888, "project": "net", "commit_id": "b922f622592af76b57cbc566eaeccda0b31a3496", "project_url": "https://git.kernel.org/cgit/linux/kernel/git/davem/net", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/netdev/net.git/commit/?id=b922f622592af76b57cbc566eaeccda0b31a3496", "commit_message": "atlantic: Fix OOB read and write in hw_atl_utils_fw_rpc_wait\n\nThis bug report shows up when running our research tools. The\nreports is SOOB read, but it seems SOOB write is also possible\na few lines below.\n\nIn details, fw.len and sw.len are inputs coming from io. A len\nover the size of self->rpc triggers SOOB. The patch fixes the\nbugs by adding sanity checks.\n\nThe bugs are triggerable with compromised/malfunctioning devices.\nThey are potentially exploitable given they first leak up to\n0xffff bytes and able to overwrite the region later.\n\nThe patch is tested with QEMU emulater.\nThis is NOT tested with a real device.\n\nAttached is the log we found by fuzzing.\n\nBUG: KASAN: slab-out-of-bounds in\n\thw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]\nRead of size 4 at addr ffff888016260b08 by task modprobe/213\nCPU: 0 PID: 213 Comm: modprobe Not tainted 5.6.0 #1\nCall Trace:\n dump_stack+0x76/0xa0\n print_address_description.constprop.0+0x16/0x200\n ? hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]\n ? hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]\n __kasan_report.cold+0x37/0x7c\n ? aq_hw_read_reg_bit+0x60/0x70 [atlantic]\n ? hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]\n kasan_report+0xe/0x20\n hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]\n hw_atl_utils_fw_rpc_call+0x95/0x130 [atlantic]\n hw_atl_utils_fw_rpc_wait+0x176/0x210 [atlantic]\n hw_atl_utils_mpi_create+0x229/0x2e0 [atlantic]\n ? hw_atl_utils_fw_rpc_wait+0x210/0x210 [atlantic]\n ? hw_atl_utils_initfw+0x9f/0x1c8 [atlantic]\n hw_atl_utils_initfw+0x12a/0x1c8 [atlantic]\n aq_nic_ndev_register+0x88/0x650 [atlantic]\n ? aq_nic_ndev_init+0x235/0x3c0 [atlantic]\n aq_pci_probe+0x731/0x9b0 [atlantic]\n ? aq_pci_func_init+0xc0/0xc0 [atlantic]\n local_pci_probe+0xd3/0x160\n pci_device_probe+0x23f/0x3e0\n\nReported-by: Brendan Dolan-Gavitt \nSigned-off-by: Zekun Shen \nSigned-off-by: David S. Miller ", "target": 0, "func": "int hw_atl_utils_fw_rpc_wait(struct aq_hw_s *self,\n\t\t\t     struct hw_atl_utils_fw_rpc **rpc)\n{\n\tstruct aq_hw_atl_utils_fw_rpc_tid_s sw;\n\tstruct aq_hw_atl_utils_fw_rpc_tid_s fw;\n\tint err = 0;\n\n\tdo {\n\t\tsw.val = aq_hw_read_reg(self, HW_ATL_RPC_CONTROL_ADR);\n\n\t\tself->rpc_tid = sw.tid;\n\n\t\terr = readx_poll_timeout_atomic(hw_atl_utils_rpc_state_get,\n\t\t\t\t\t\tself, fw.val,\n\t\t\t\t\t\tsw.tid == fw.tid,\n\t\t\t\t\t\t1000U, 100000U);\n\t\tif (err < 0)\n\t\t\tgoto err_exit;\n\n\t\terr = aq_hw_err_from_flags(self);\n\t\tif (err < 0)\n\t\t\tgoto err_exit;\n\n\t\tif (fw.len == 0xFFFFU) {\n\t\t\tif (sw.len > sizeof(self->rpc)) {\n\t\t\t\tprintk(KERN_INFO \"Invalid sw len: %x\\n\", sw.len);\n\t\t\t\terr = -EINVAL;\n\t\t\t\tgoto err_exit;\n\t\t\t}\n\t\t\terr = hw_atl_utils_fw_rpc_call(self, sw.len);\n\t\t\tif (err < 0)\n\t\t\t\tgoto err_exit;\n\t\t}\n\t} while (sw.tid != fw.tid || 0xFFFFU == fw.len);\n\n\tif (rpc) {\n\t\tif (fw.len) {\n\t\t\tif (fw.len > sizeof(self->rpc)) {\n\t\t\t\tprintk(KERN_INFO \"Invalid fw len: %x\\n\", fw.len);\n\t\t\t\terr = -EINVAL;\n\t\t\t\tgoto err_exit;\n\t\t\t}\n\t\t\terr =\n\t\t\thw_atl_utils_fw_downld_dwords(self,\n\t\t\t\t\t\t      self->rpc_addr,\n\t\t\t\t\t\t      (u32 *)(void *)\n\t\t\t\t\t\t      &self->rpc,\n\t\t\t\t\t\t      (fw.len + sizeof(u32) -\n\t\t\t\t\t\t       sizeof(u8)) /\n\t\t\t\t\t\t      sizeof(u32));\n\t\t\tif (err < 0)\n\t\t\t\tgoto err_exit;\n\t\t}\n\n\t\t*rpc = &self->rpc;\n\t}\n\nerr_exit:\n\treturn err;\n}", "func_hash": 78874513261411721250229563927367854833, "file_name": "hw_atl_utils.c", "file_hash": 98512152350108532243910999144686301920, "cwe": ["CWE-787"], "cve": "CVE-2021-43975", "cve_desc": "In the Linux kernel through 5.15.2, hw_atl_utils_fw_rpc_wait in drivers/net/ethernet/aquantia/atlantic/hw_atl/hw_atl_utils.c allows an attacker (who can introduce a crafted device) to trigger an out-of-bounds write via a crafted length value.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43975"}
{"idx": 204073, "project": "shapelib", "commit_id": "c75b9281a5b9452d92e1682bdfe6019a13ed819f", "project_url": "https://github.com/OSGeo/shapelib", "commit_url": "https://github.com/OSGeo/shapelib/commit/c75b9281a5b9452d92e1682bdfe6019a13ed819f", "commit_message": "Remove double free() in contrib/shpsrt, issue #39\n\nThis fixes issue #39", "target": 1, "func": "static char ** split(const char *arg, const char *delim) {\n  char *copy = dupstr(arg);\n  char **result = NULL;\n  int i = 0;\n\n  for (char *cptr = strtok(copy, delim); cptr; cptr = strtok(NULL, delim)) {\n    char **tmp = realloc (result, sizeof *result * (i + 1));\n    if (!tmp && result) {\n      while (i > 0) {\n\tfree(result[--i]);\n      }\n      free(result);\n      free(copy);\n      return NULL;\n    }\n    result = tmp;\n    result[i++] = dupstr(cptr);\n  }\n\n  free(copy);\n\n  if (i) {\n    char **tmp = realloc(result, sizeof *result * (i + 1));\n    if (!tmp) {\n      while (i > 0) {\n\tfree(result[--i]);\n      }\n      free(result);\n      free(copy);\n      return NULL;\n    }\n    result = tmp;\n    result[i++] = NULL;\n  }\n\n  return result;\n}", "func_hash": 154440466975385336432510777562091378708, "file_name": "shpsort.c", "file_hash": 43221346953143953382565106661243368341, "cwe": ["CWE-415"], "cve": "CVE-2022-0699", "cve_desc": "A double-free condition exists in contrib/shpsort.c of shapelib 1.5.0 and older releases. This issue may allow an attacker to cause a denial of service or have other unspecified impact via control over malloc.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0699"}
{"idx": 351182, "project": "shapelib", "commit_id": "c75b9281a5b9452d92e1682bdfe6019a13ed819f", "project_url": "https://github.com/OSGeo/shapelib", "commit_url": "https://github.com/OSGeo/shapelib/commit/c75b9281a5b9452d92e1682bdfe6019a13ed819f", "commit_message": "Remove double free() in contrib/shpsrt, issue #39\n\nThis fixes issue #39", "target": 0, "func": "static char ** split(const char *arg, const char *delim) {\n  char *copy = dupstr(arg);\n  char **result = NULL;\n  int i = 0;\n\n  for (char *cptr = strtok(copy, delim); cptr; cptr = strtok(NULL, delim)) {\n    char **tmp = realloc (result, sizeof *result * (i + 1));\n    if (!tmp && result) {\n      while (i > 0) {\n\tfree(result[--i]);\n      }\n      free(result);\n      free(copy);\n      return NULL;\n    }\n    result = tmp;\n    result[i++] = dupstr(cptr);\n  }\n\n  free(copy);\n\n  if (i) {\n    char **tmp = realloc(result, sizeof *result * (i + 1));\n    if (!tmp) {\n      while (i > 0) {\n\tfree(result[--i]);\n      }\n      free(result);\n      return NULL;\n    }\n    result = tmp;\n    result[i++] = NULL;\n  }\n\n  return result;\n}", "func_hash": 106488258740944380908337679488455743324, "file_name": "shpsort.c", "file_hash": 120261673171922757461559370561018380783, "cwe": ["CWE-415"], "cve": "CVE-2022-0699", "cve_desc": "A double-free condition exists in contrib/shpsort.c of shapelib 1.5.0 and older releases. This issue may allow an attacker to cause a denial of service or have other unspecified impact via control over malloc.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0699"}
{"idx": 204115, "project": "openldap", "commit_id": "3539fc33212b528c56b716584f2c2994af7c30b0", "project_url": "https://github.com/openldap/openldap", "commit_url": "https://git.openldap.org/openldap/openldap/-/commit/3539fc33212b528c56b716584f2c2994af7c30b0", "commit_message": "ITS#9454 fix issuerAndThisUpdateCheck", "target": 1, "func": "issuerAndThisUpdateCheck(\n\tstruct berval *in,\n\tstruct berval *is,\n\tstruct berval *tu,\n\tvoid *ctx )\n{\n\tint numdquotes = 0;\n\tstruct berval x = *in;\n\tstruct berval ni = BER_BVNULL;\n\t/* Parse GSER format */ \n\tenum {\n\t\tHAVE_NONE = 0x0,\n\t\tHAVE_ISSUER = 0x1,\n\t\tHAVE_THISUPDATE = 0x2,\n\t\tHAVE_ALL = ( HAVE_ISSUER | HAVE_THISUPDATE )\n\t} have = HAVE_NONE;\n\n\n\tif ( in->bv_len < STRLENOF( \"{issuer \\\"\\\",thisUpdate \\\"YYMMDDhhmmssZ\\\"}\" ) ) return LDAP_INVALID_SYNTAX;\n\n\tif ( in->bv_val[0] != '{' || in->bv_val[in->bv_len-1] != '}' ) {\n\t\treturn LDAP_INVALID_SYNTAX;\n\t}\n\n\tx.bv_val++;\n\tx.bv_len -= STRLENOF(\"{}\");\n\n\tdo {\n\t\t/* eat leading spaces */\n\t\tfor ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {\n\t\t\t/* empty */;\n\t\t}\n\n\t\t/* should be at issuer or thisUpdate */\n\t\tif ( strncasecmp( x.bv_val, \"issuer\", STRLENOF(\"issuer\") ) == 0 ) {\n\t\t\tif ( have & HAVE_ISSUER ) return LDAP_INVALID_SYNTAX;\n\n\t\t\t/* parse issuer */\n\t\t\tx.bv_val += STRLENOF(\"issuer\");\n\t\t\tx.bv_len -= STRLENOF(\"issuer\");\n\n\t\t\tif ( x.bv_val[0] != ' ' ) return LDAP_INVALID_SYNTAX;\n\t\t\tx.bv_val++;\n\t\t\tx.bv_len--;\n\n\t\t\t/* eat leading spaces */\n\t\t\tfor ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {\n\t\t\t\t/* empty */;\n\t\t\t}\n\n\t\t\t/* For backward compatibility, this part is optional */\n\t\t\tif ( strncasecmp( x.bv_val, \"rdnSequence:\", STRLENOF(\"rdnSequence:\") ) != 0 ) {\n\t\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t\t}\n\t\t\tx.bv_val += STRLENOF(\"rdnSequence:\");\n\t\t\tx.bv_len -= STRLENOF(\"rdnSequence:\");\n\n\t\t\tif ( x.bv_val[0] != '\"' ) return LDAP_INVALID_SYNTAX;\n\t\t\tx.bv_val++;\n\t\t\tx.bv_len--;\n\n\t\t\tis->bv_val = x.bv_val;\n\t\t\tis->bv_len = 0;\n\n\t\t\tfor ( ; is->bv_len < x.bv_len; ) {\n\t\t\t\tif ( is->bv_val[is->bv_len] != '\"' ) {\n\t\t\t\t\tis->bv_len++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif ( is->bv_val[is->bv_len+1] == '\"' ) {\n\t\t\t\t\t/* double dquote */\n\t\t\t\t\tnumdquotes++;\n\t\t\t\t\tis->bv_len += 2;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tx.bv_val += is->bv_len + 1;\n\t\t\tx.bv_len -= is->bv_len + 1;\n\n\t\t\thave |= HAVE_ISSUER;\n\n\t\t} else if ( strncasecmp( x.bv_val, \"thisUpdate\", STRLENOF(\"thisUpdate\") ) == 0 )\n\t\t{\n\t\t\tif ( have & HAVE_THISUPDATE ) return LDAP_INVALID_SYNTAX;\n\n\t\t\t/* parse thisUpdate */\n\t\t\tx.bv_val += STRLENOF(\"thisUpdate\");\n\t\t\tx.bv_len -= STRLENOF(\"thisUpdate\");\n\n\t\t\tif ( x.bv_val[0] != ' ' ) return LDAP_INVALID_SYNTAX;\n\t\t\tx.bv_val++;\n\t\t\tx.bv_len--;\n\n\t\t\t/* eat leading spaces */\n\t\t\tfor ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {\n\t\t\t\t/* empty */;\n\t\t\t}\n\n\t\t\tif ( !x.bv_len || x.bv_val[0] != '\"' ) return LDAP_INVALID_SYNTAX;\n\t\t\tx.bv_val++;\n\t\t\tx.bv_len--;\n\n\t\t\ttu->bv_val = x.bv_val;\n\t\t\ttu->bv_len = 0;\n\n\t\t\tfor ( ; tu->bv_len < x.bv_len; tu->bv_len++ ) {\n\t\t\t\tif ( tu->bv_val[tu->bv_len] == '\"' ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tx.bv_val += tu->bv_len + 1;\n\t\t\tx.bv_len -= tu->bv_len + 1;\n\n\t\t\thave |= HAVE_THISUPDATE;\n\n\t\t} else {\n\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t}\n\n\t\t/* eat leading spaces */\n\t\tfor ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {\n\t\t\t/* empty */;\n\t\t}\n\n\t\tif ( have == HAVE_ALL ) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif ( x.bv_val[0] != ',' ) {\n\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t}\n\n\t\tx.bv_val++;\n\t\tx.bv_len--;\n\t} while ( 1 );\n\n\t/* should have no characters left... */\n\tif ( x.bv_len ) return LDAP_INVALID_SYNTAX;\n\n\tif ( numdquotes == 0 ) {\n\t\tber_dupbv_x( &ni, is, ctx );\n\n\t} else {\n\t\tber_len_t src, dst;\n\n\t\tni.bv_len = is->bv_len - numdquotes;\n\t\tni.bv_val = slap_sl_malloc( ni.bv_len + 1, ctx );\n\t\tfor ( src = 0, dst = 0; src < is->bv_len; src++, dst++ ) {\n\t\t\tif ( is->bv_val[src] == '\"' ) {\n\t\t\t\tsrc++;\n\t\t\t}\n\t\t\tni.bv_val[dst] = is->bv_val[src];\n\t\t}\n\t\tni.bv_val[dst] = '\\0';\n\t}\n\t\t\n\t*is = ni;\n\n\treturn 0;\n}", "func_hash": 320953270427993363171410441809926002124, "file_name": "schema_init.c", "file_hash": 177224706623297221858931327325567866275, "cwe": ["CWE-617"], "cve": "CVE-2021-27212", "cve_desc": "In OpenLDAP through 2.4.57 and 2.5.x through 2.5.1alpha, an assertion failure in slapd can occur in the issuerAndThisUpdateCheck function via a crafted packet, resulting in a denial of service (daemon exit) via a short timestamp. This is related to schema_init.c and checkTime.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-27212"}
{"idx": 353015, "project": "openldap", "commit_id": "3539fc33212b528c56b716584f2c2994af7c30b0", "project_url": "https://github.com/openldap/openldap", "commit_url": "https://git.openldap.org/openldap/openldap/-/commit/3539fc33212b528c56b716584f2c2994af7c30b0", "commit_message": "ITS#9454 fix issuerAndThisUpdateCheck", "target": 0, "func": "issuerAndThisUpdateCheck(\n\tstruct berval *in,\n\tstruct berval *is,\n\tstruct berval *tu,\n\tvoid *ctx )\n{\n\tint numdquotes = 0;\n\tstruct berval x = *in;\n\tstruct berval ni = BER_BVNULL;\n\t/* Parse GSER format */ \n\tenum {\n\t\tHAVE_NONE = 0x0,\n\t\tHAVE_ISSUER = 0x1,\n\t\tHAVE_THISUPDATE = 0x2,\n\t\tHAVE_ALL = ( HAVE_ISSUER | HAVE_THISUPDATE )\n\t} have = HAVE_NONE;\n\n\n\tif ( in->bv_len < STRLENOF( \"{issuer \\\"\\\",thisUpdate \\\"YYMMDDhhmmssZ\\\"}\" ) ) return LDAP_INVALID_SYNTAX;\n\n\tif ( in->bv_val[0] != '{' || in->bv_val[in->bv_len-1] != '}' ) {\n\t\treturn LDAP_INVALID_SYNTAX;\n\t}\n\n\tx.bv_val++;\n\tx.bv_len -= STRLENOF(\"{}\");\n\n\tdo {\n\t\t/* eat leading spaces */\n\t\tfor ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {\n\t\t\t/* empty */;\n\t\t}\n\n\t\t/* should be at issuer or thisUpdate */\n\t\tif ( strncasecmp( x.bv_val, \"issuer\", STRLENOF(\"issuer\") ) == 0 ) {\n\t\t\tif ( have & HAVE_ISSUER ) return LDAP_INVALID_SYNTAX;\n\n\t\t\t/* parse issuer */\n\t\t\tx.bv_val += STRLENOF(\"issuer\");\n\t\t\tx.bv_len -= STRLENOF(\"issuer\");\n\n\t\t\tif ( x.bv_val[0] != ' ' ) return LDAP_INVALID_SYNTAX;\n\t\t\tx.bv_val++;\n\t\t\tx.bv_len--;\n\n\t\t\t/* eat leading spaces */\n\t\t\tfor ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {\n\t\t\t\t/* empty */;\n\t\t\t}\n\n\t\t\t/* For backward compatibility, this part is optional */\n\t\t\tif ( strncasecmp( x.bv_val, \"rdnSequence:\", STRLENOF(\"rdnSequence:\") ) != 0 ) {\n\t\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t\t}\n\t\t\tx.bv_val += STRLENOF(\"rdnSequence:\");\n\t\t\tx.bv_len -= STRLENOF(\"rdnSequence:\");\n\n\t\t\tif ( x.bv_val[0] != '\"' ) return LDAP_INVALID_SYNTAX;\n\t\t\tx.bv_val++;\n\t\t\tx.bv_len--;\n\n\t\t\tis->bv_val = x.bv_val;\n\t\t\tis->bv_len = 0;\n\n\t\t\tfor ( ; is->bv_len < x.bv_len; ) {\n\t\t\t\tif ( is->bv_val[is->bv_len] != '\"' ) {\n\t\t\t\t\tis->bv_len++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif ( is->bv_val[is->bv_len+1] == '\"' ) {\n\t\t\t\t\t/* double dquote */\n\t\t\t\t\tnumdquotes++;\n\t\t\t\t\tis->bv_len += 2;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tx.bv_val += is->bv_len + 1;\n\t\t\tx.bv_len -= is->bv_len + 1;\n\n\t\t\thave |= HAVE_ISSUER;\n\n\t\t} else if ( strncasecmp( x.bv_val, \"thisUpdate\", STRLENOF(\"thisUpdate\") ) == 0 )\n\t\t{\n\t\t\tif ( have & HAVE_THISUPDATE ) return LDAP_INVALID_SYNTAX;\n\n\t\t\t/* parse thisUpdate */\n\t\t\tx.bv_val += STRLENOF(\"thisUpdate\");\n\t\t\tx.bv_len -= STRLENOF(\"thisUpdate\");\n\n\t\t\tif ( x.bv_val[0] != ' ' ) return LDAP_INVALID_SYNTAX;\n\t\t\tx.bv_val++;\n\t\t\tx.bv_len--;\n\n\t\t\t/* eat leading spaces */\n\t\t\tfor ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {\n\t\t\t\t/* empty */;\n\t\t\t}\n\n\t\t\tif ( !x.bv_len || x.bv_val[0] != '\"' ) return LDAP_INVALID_SYNTAX;\n\t\t\tx.bv_val++;\n\t\t\tx.bv_len--;\n\n\t\t\ttu->bv_val = x.bv_val;\n\t\t\ttu->bv_len = 0;\n\n\t\t\tfor ( ; tu->bv_len < x.bv_len; tu->bv_len++ ) {\n\t\t\t\tif ( tu->bv_val[tu->bv_len] == '\"' ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( tu->bv_len < STRLENOF(\"YYYYmmddHHmmssZ\") ) return LDAP_INVALID_SYNTAX;\n\n\t\t\tx.bv_val += tu->bv_len + 1;\n\t\t\tx.bv_len -= tu->bv_len + 1;\n\n\t\t\thave |= HAVE_THISUPDATE;\n\n\t\t} else {\n\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t}\n\n\t\t/* eat leading spaces */\n\t\tfor ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {\n\t\t\t/* empty */;\n\t\t}\n\n\t\tif ( have == HAVE_ALL ) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif ( x.bv_val[0] != ',' ) {\n\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t}\n\n\t\tx.bv_val++;\n\t\tx.bv_len--;\n\t} while ( 1 );\n\n\t/* should have no characters left... */\n\tif ( x.bv_len ) return LDAP_INVALID_SYNTAX;\n\n\tif ( numdquotes == 0 ) {\n\t\tber_dupbv_x( &ni, is, ctx );\n\n\t} else {\n\t\tber_len_t src, dst;\n\n\t\tni.bv_len = is->bv_len - numdquotes;\n\t\tni.bv_val = slap_sl_malloc( ni.bv_len + 1, ctx );\n\t\tfor ( src = 0, dst = 0; src < is->bv_len; src++, dst++ ) {\n\t\t\tif ( is->bv_val[src] == '\"' ) {\n\t\t\t\tsrc++;\n\t\t\t}\n\t\t\tni.bv_val[dst] = is->bv_val[src];\n\t\t}\n\t\tni.bv_val[dst] = '\\0';\n\t}\n\t\t\n\t*is = ni;\n\n\treturn 0;\n}", "func_hash": 298149048073642841250394521193700631288, "file_name": "schema_init.c", "file_hash": 127214091536244192150172242805699646468, "cwe": ["CWE-617"], "cve": "CVE-2021-27212", "cve_desc": "In OpenLDAP through 2.4.57 and 2.5.x through 2.5.1alpha, an assertion failure in slapd can occur in the issuerAndThisUpdateCheck function via a crafted packet, resulting in a denial of service (daemon exit) via a short timestamp. This is related to schema_init.c and checkTime.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-27212"}
{"idx": 204137, "project": "poppler", "commit_id": "b224e2f5739fe61de9fa69955d016725b2a4b78d", "project_url": "https://github.com/freedesktop/poppler", "commit_url": "https://gitlab.freedesktop.org/poppler/poppler/commit/b224e2f5739fe61de9fa69955d016725b2a4b78d", "commit_message": "SplashOutputDev::tilingPatternFill: Fix crash on broken file\n\nIssue #802", "target": 1, "func": "bool SplashOutputDev::tilingPatternFill(GfxState *state, Gfx *gfxA, Catalog *catalog, Object *str,\n\t\t\t\t\tconst double *ptm, int paintType, int /*tilingType*/, Dict *resDict,\n\t\t\t\t\tconst double *mat, const double *bbox,\n\t\t\t\t\tint x0, int y0, int x1, int y1,\n\t\t\t\t\tdouble xStep, double yStep)\n{\n  PDFRectangle box;\n  Gfx *gfx;\n  Splash *formerSplash = splash;\n  SplashBitmap *formerBitmap = bitmap;\n  double width, height;\n  int surface_width, surface_height, result_width, result_height, i;\n  int repeatX, repeatY;\n  SplashCoord matc[6];\n  Matrix m1;\n  const double *ctm;\n  double savedCTM[6];\n  double kx, ky, sx, sy;\n  bool retValue = false;\n\n  width = bbox[2] - bbox[0];\n  height = bbox[3] - bbox[1];\n\n  if (xStep != width || yStep != height)\n    return false;\n\n  // calculate offsets\n  ctm = state->getCTM();\n  for (i = 0; i < 6; ++i) {\n    savedCTM[i] = ctm[i];\n  }\n  state->concatCTM(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);\n  state->concatCTM(1, 0, 0, 1, bbox[0], bbox[1]);\n  ctm = state->getCTM();\n  for (i = 0; i < 6; ++i) {\n    if (!std::isfinite(ctm[i])) {\n      state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n      return false;\n    }\n  }\n  matc[4] = x0 * xStep * ctm[0] + y0 * yStep * ctm[2] + ctm[4];\n  matc[5] = x0 * xStep * ctm[1] + y0 * yStep * ctm[3] + ctm[5];\n  if (splashAbs(ctm[1]) > splashAbs(ctm[0])) {\n    kx = -ctm[1];\n    ky = ctm[2] - (ctm[0] * ctm[3]) / ctm[1];\n  } else {\n    kx = ctm[0];\n    ky = ctm[3] - (ctm[1] * ctm[2]) / ctm[0];\n  }\n  result_width = (int) ceil(fabs(kx * width * (x1 - x0)));\n  result_height = (int) ceil(fabs(ky * height * (y1 - y0)));\n  kx = state->getHDPI() / 72.0;\n  ky = state->getVDPI() / 72.0;\n  m1.m[0] = (ptm[0] == 0) ? fabs(ptm[2]) * kx : fabs(ptm[0]) * kx;\n  m1.m[1] = 0;\n  m1.m[2] = 0;\n  m1.m[3] = (ptm[3] == 0) ? fabs(ptm[1]) * ky : fabs(ptm[3]) * ky;\n  m1.m[4] = 0;\n  m1.m[5] = 0;\n  m1.transform(width, height, &kx, &ky);\n  surface_width = (int) ceil (fabs(kx));\n  surface_height = (int) ceil (fabs(ky));\n\n  sx = (double) result_width / (surface_width * (x1 - x0));\n  sy = (double) result_height / (surface_height * (y1 - y0));\n  m1.m[0] *= sx;\n  m1.m[3] *= sy;\n  m1.transform(width, height, &kx, &ky);\n\n  if(fabs(kx) < 1 && fabs(ky) < 1) {\n    kx = std::min(kx, ky);\n    ky = 2 / kx;\n    m1.m[0] *= ky;\n    m1.m[3] *= ky;\n    m1.transform(width, height, &kx, &ky);\n    surface_width = (int) ceil (fabs(kx));\n    surface_height = (int) ceil (fabs(ky));\n    repeatX = x1 - x0;\n    repeatY = y1 - y0;\n  } else {\n    if ((unsigned long) surface_width * surface_height > 0x800000L) {\n      state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n      return false;\n    }\n    while(fabs(kx) > 16384 || fabs(ky) > 16384) {\n      // limit pattern bitmap size\n      m1.m[0] /= 2;\n      m1.m[3] /= 2;\n      m1.transform(width, height, &kx, &ky);\n    }\n    surface_width = (int) ceil (fabs(kx));\n    surface_height = (int) ceil (fabs(ky));\n    // adjust repeat values to completely fill region\n    repeatX = result_width / surface_width;\n    repeatY = result_height / surface_height;\n    if (surface_width * repeatX < result_width)\n      repeatX++;\n    if (surface_height * repeatY < result_height)\n      repeatY++;\n    if (x1 - x0 > repeatX)\n      repeatX = x1 - x0;\n    if (y1 - y0 > repeatY)\n      repeatY = y1 - y0;\n  }\n  // restore CTM and calculate rotate and scale with rounded matrix\n  state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n  state->concatCTM(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);\n  state->concatCTM(width * repeatX, 0, 0, height * repeatY, bbox[0], bbox[1]);\n  ctm = state->getCTM();\n  matc[0] = ctm[0];\n  matc[1] = ctm[1];\n  matc[2] = ctm[2];\n  matc[3] = ctm[3];\n\n  if (surface_width == 0 || surface_height == 0 || repeatX * repeatY <= 4) {\n    state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n    return false;\n  }\n  m1.transform(bbox[0], bbox[1], &kx, &ky);\n  m1.m[4] = -kx;\n  m1.m[5] = -ky;\n\n  bitmap = new SplashBitmap(surface_width, surface_height, 1,\n                            (paintType == 1) ? colorMode : splashModeMono8, true);\n  if (bitmap->getDataPtr() == nullptr) {\n    SplashBitmap *tBitmap = bitmap;\n    bitmap = formerBitmap;\n    delete tBitmap;\n    state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n    return false;\n  }\n  splash = new Splash(bitmap, true);\n  if (paintType == 2) {\n    SplashColor clearColor;\n#ifdef SPLASH_CMYK\n    clearColor[0] = (colorMode == splashModeCMYK8 || colorMode == splashModeDeviceN8) ? 0x00 : 0xFF;\n#else\n    clearColor[0] = 0xFF;\n#endif\n    splash->clear(clearColor, 0);\n  } else {\n    splash->clear(paperColor, 0);\n  }\n  splash->setThinLineMode(formerSplash->getThinLineMode());\n  splash->setMinLineWidth(s_minLineWidth);\n\n  box.x1 = bbox[0]; box.y1 = bbox[1];\n  box.x2 = bbox[2]; box.y2 = bbox[3];\n  gfx = new Gfx(doc, this, resDict, &box, nullptr, nullptr, nullptr, gfxA);\n  // set pattern transformation matrix\n  gfx->getState()->setCTM(m1.m[0], m1.m[1], m1.m[2], m1.m[3], m1.m[4], m1.m[5]);\n  updateCTM(gfx->getState(), m1.m[0], m1.m[1], m1.m[2], m1.m[3], m1.m[4], m1.m[5]);\n  gfx->display(str);\n  delete splash;\n  splash = formerSplash;\n  TilingSplashOutBitmap imgData;\n  imgData.bitmap = bitmap;\n  imgData.paintType = paintType;\n  imgData.pattern = splash->getFillPattern();\n  imgData.colorMode = colorMode;\n  imgData.y = 0;\n  imgData.repeatX = repeatX;\n  imgData.repeatY = repeatY;\n  SplashBitmap *tBitmap = bitmap;\n  bitmap = formerBitmap;\n  result_width = tBitmap->getWidth() * imgData.repeatX;\n  result_height = tBitmap->getHeight() * imgData.repeatY;\n\n  if (splashAbs(matc[1]) > splashAbs(matc[0])) {\n    kx = -matc[1];\n    ky = matc[2] - (matc[0] * matc[3]) / matc[1];\n  } else {\n    kx = matc[0];\n    ky = matc[3] - (matc[1] * matc[2]) / matc[0];\n  }\n  kx = result_width / (fabs(kx) + 1);\n  ky = result_height / (fabs(ky) + 1);\n  state->concatCTM(kx, 0, 0, ky, 0, 0);\n  ctm = state->getCTM();\n  matc[0] = ctm[0];\n  matc[1] = ctm[1];\n  matc[2] = ctm[2];\n  matc[3] = ctm[3];\n  bool minorAxisZero = matc[1] == 0 && matc[2] == 0;\n  if (matc[0] > 0 && minorAxisZero && matc[3] > 0) {\n    // draw the tiles\n    for (int y = 0; y < imgData.repeatY; ++y) {\n      for (int x = 0; x < imgData.repeatX; ++x) {\n        x0 = splashFloor(matc[4]) + x * tBitmap->getWidth();\n        y0 = splashFloor(matc[5]) + y * tBitmap->getHeight();\n        splash->blitImage(tBitmap, true, x0, y0);\n      }\n    }\n    retValue = true;\n  } else {\n    retValue = splash->drawImage(&tilingBitmapSrc, nullptr, &imgData, colorMode, true, result_width, result_height, matc, false, true) == splashOk;\n  }\n  delete tBitmap;\n  delete gfx;\n  return retValue;\n}", "func_hash": 185397419658299701437950097682121552321, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2019-14494", "cve_desc": "An issue was discovered in Poppler through 0.78.0. There is a divide-by-zero error in the function SplashOutputDev::tilingPatternFill at SplashOutputDev.cc.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-14494"}
{"idx": 353124, "project": "poppler", "commit_id": "b224e2f5739fe61de9fa69955d016725b2a4b78d", "project_url": "https://github.com/freedesktop/poppler", "commit_url": "https://gitlab.freedesktop.org/poppler/poppler/commit/b224e2f5739fe61de9fa69955d016725b2a4b78d", "commit_message": "SplashOutputDev::tilingPatternFill: Fix crash on broken file\n\nIssue #802", "target": 0, "func": "bool SplashOutputDev::tilingPatternFill(GfxState *state, Gfx *gfxA, Catalog *catalog, Object *str,\n\t\t\t\t\tconst double *ptm, int paintType, int /*tilingType*/, Dict *resDict,\n\t\t\t\t\tconst double *mat, const double *bbox,\n\t\t\t\t\tint x0, int y0, int x1, int y1,\n\t\t\t\t\tdouble xStep, double yStep)\n{\n  PDFRectangle box;\n  Gfx *gfx;\n  Splash *formerSplash = splash;\n  SplashBitmap *formerBitmap = bitmap;\n  double width, height;\n  int surface_width, surface_height, result_width, result_height, i;\n  int repeatX, repeatY;\n  SplashCoord matc[6];\n  Matrix m1;\n  const double *ctm;\n  double savedCTM[6];\n  double kx, ky, sx, sy;\n  bool retValue = false;\n\n  width = bbox[2] - bbox[0];\n  height = bbox[3] - bbox[1];\n\n  if (xStep != width || yStep != height)\n    return false;\n\n  // calculate offsets\n  ctm = state->getCTM();\n  for (i = 0; i < 6; ++i) {\n    savedCTM[i] = ctm[i];\n  }\n  state->concatCTM(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);\n  state->concatCTM(1, 0, 0, 1, bbox[0], bbox[1]);\n  ctm = state->getCTM();\n  for (i = 0; i < 6; ++i) {\n    if (!std::isfinite(ctm[i])) {\n      state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n      return false;\n    }\n  }\n  matc[4] = x0 * xStep * ctm[0] + y0 * yStep * ctm[2] + ctm[4];\n  matc[5] = x0 * xStep * ctm[1] + y0 * yStep * ctm[3] + ctm[5];\n  if (splashAbs(ctm[1]) > splashAbs(ctm[0])) {\n    kx = -ctm[1];\n    ky = ctm[2] - (ctm[0] * ctm[3]) / ctm[1];\n  } else {\n    kx = ctm[0];\n    ky = ctm[3] - (ctm[1] * ctm[2]) / ctm[0];\n  }\n  result_width = (int) ceil(fabs(kx * width * (x1 - x0)));\n  result_height = (int) ceil(fabs(ky * height * (y1 - y0)));\n  kx = state->getHDPI() / 72.0;\n  ky = state->getVDPI() / 72.0;\n  m1.m[0] = (ptm[0] == 0) ? fabs(ptm[2]) * kx : fabs(ptm[0]) * kx;\n  m1.m[1] = 0;\n  m1.m[2] = 0;\n  m1.m[3] = (ptm[3] == 0) ? fabs(ptm[1]) * ky : fabs(ptm[3]) * ky;\n  m1.m[4] = 0;\n  m1.m[5] = 0;\n  m1.transform(width, height, &kx, &ky);\n  surface_width = (int) ceil (fabs(kx));\n  surface_height = (int) ceil (fabs(ky));\n\n  sx = (double) result_width / (surface_width * (x1 - x0));\n  sy = (double) result_height / (surface_height * (y1 - y0));\n  m1.m[0] *= sx;\n  m1.m[3] *= sy;\n  m1.transform(width, height, &kx, &ky);\n\n  if(fabs(kx) < 1 && fabs(ky) < 1) {\n    kx = std::min(kx, ky);\n    ky = 2 / kx;\n    m1.m[0] *= ky;\n    m1.m[3] *= ky;\n    m1.transform(width, height, &kx, &ky);\n    surface_width = (int) ceil (fabs(kx));\n    surface_height = (int) ceil (fabs(ky));\n    repeatX = x1 - x0;\n    repeatY = y1 - y0;\n  } else {\n    if ((unsigned long) surface_width * surface_height > 0x800000L) {\n      state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n      return false;\n    }\n    while(fabs(kx) > 16384 || fabs(ky) > 16384) {\n      // limit pattern bitmap size\n      m1.m[0] /= 2;\n      m1.m[3] /= 2;\n      m1.transform(width, height, &kx, &ky);\n    }\n    surface_width = (int) ceil (fabs(kx));\n    surface_height = (int) ceil (fabs(ky));\n    // adjust repeat values to completely fill region\n    if (unlikely(surface_width == 0 || surface_height == 0)) {\n        state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n        return false;\n    }\n    repeatX = result_width / surface_width;\n    repeatY = result_height / surface_height;\n    if (surface_width * repeatX < result_width)\n      repeatX++;\n    if (surface_height * repeatY < result_height)\n      repeatY++;\n    if (x1 - x0 > repeatX)\n      repeatX = x1 - x0;\n    if (y1 - y0 > repeatY)\n      repeatY = y1 - y0;\n  }\n  // restore CTM and calculate rotate and scale with rounded matrix\n  state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n  state->concatCTM(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);\n  state->concatCTM(width * repeatX, 0, 0, height * repeatY, bbox[0], bbox[1]);\n  ctm = state->getCTM();\n  matc[0] = ctm[0];\n  matc[1] = ctm[1];\n  matc[2] = ctm[2];\n  matc[3] = ctm[3];\n\n  if (surface_width == 0 || surface_height == 0 || repeatX * repeatY <= 4) {\n    state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n    return false;\n  }\n  m1.transform(bbox[0], bbox[1], &kx, &ky);\n  m1.m[4] = -kx;\n  m1.m[5] = -ky;\n\n  bitmap = new SplashBitmap(surface_width, surface_height, 1,\n                            (paintType == 1) ? colorMode : splashModeMono8, true);\n  if (bitmap->getDataPtr() == nullptr) {\n    SplashBitmap *tBitmap = bitmap;\n    bitmap = formerBitmap;\n    delete tBitmap;\n    state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n    return false;\n  }\n  splash = new Splash(bitmap, true);\n  if (paintType == 2) {\n    SplashColor clearColor;\n#ifdef SPLASH_CMYK\n    clearColor[0] = (colorMode == splashModeCMYK8 || colorMode == splashModeDeviceN8) ? 0x00 : 0xFF;\n#else\n    clearColor[0] = 0xFF;\n#endif\n    splash->clear(clearColor, 0);\n  } else {\n    splash->clear(paperColor, 0);\n  }\n  splash->setThinLineMode(formerSplash->getThinLineMode());\n  splash->setMinLineWidth(s_minLineWidth);\n\n  box.x1 = bbox[0]; box.y1 = bbox[1];\n  box.x2 = bbox[2]; box.y2 = bbox[3];\n  gfx = new Gfx(doc, this, resDict, &box, nullptr, nullptr, nullptr, gfxA);\n  // set pattern transformation matrix\n  gfx->getState()->setCTM(m1.m[0], m1.m[1], m1.m[2], m1.m[3], m1.m[4], m1.m[5]);\n  updateCTM(gfx->getState(), m1.m[0], m1.m[1], m1.m[2], m1.m[3], m1.m[4], m1.m[5]);\n  gfx->display(str);\n  delete splash;\n  splash = formerSplash;\n  TilingSplashOutBitmap imgData;\n  imgData.bitmap = bitmap;\n  imgData.paintType = paintType;\n  imgData.pattern = splash->getFillPattern();\n  imgData.colorMode = colorMode;\n  imgData.y = 0;\n  imgData.repeatX = repeatX;\n  imgData.repeatY = repeatY;\n  SplashBitmap *tBitmap = bitmap;\n  bitmap = formerBitmap;\n  result_width = tBitmap->getWidth() * imgData.repeatX;\n  result_height = tBitmap->getHeight() * imgData.repeatY;\n\n  if (splashAbs(matc[1]) > splashAbs(matc[0])) {\n    kx = -matc[1];\n    ky = matc[2] - (matc[0] * matc[3]) / matc[1];\n  } else {\n    kx = matc[0];\n    ky = matc[3] - (matc[1] * matc[2]) / matc[0];\n  }\n  kx = result_width / (fabs(kx) + 1);\n  ky = result_height / (fabs(ky) + 1);\n  state->concatCTM(kx, 0, 0, ky, 0, 0);\n  ctm = state->getCTM();\n  matc[0] = ctm[0];\n  matc[1] = ctm[1];\n  matc[2] = ctm[2];\n  matc[3] = ctm[3];\n  bool minorAxisZero = matc[1] == 0 && matc[2] == 0;\n  if (matc[0] > 0 && minorAxisZero && matc[3] > 0) {\n    // draw the tiles\n    for (int y = 0; y < imgData.repeatY; ++y) {\n      for (int x = 0; x < imgData.repeatX; ++x) {\n        x0 = splashFloor(matc[4]) + x * tBitmap->getWidth();\n        y0 = splashFloor(matc[5]) + y * tBitmap->getHeight();\n        splash->blitImage(tBitmap, true, x0, y0);\n      }\n    }\n    retValue = true;\n  } else {\n    retValue = splash->drawImage(&tilingBitmapSrc, nullptr, &imgData, colorMode, true, result_width, result_height, matc, false, true) == splashOk;\n  }\n  delete tBitmap;\n  delete gfx;\n  return retValue;\n}", "func_hash": 66158581333655074861214413743208531440, "file_name": "None", "file_hash": null, "cwe": ["CWE-369"], "cve": "CVE-2019-14494", "cve_desc": "An issue was discovered in Poppler through 0.78.0. There is a divide-by-zero error in the function SplashOutputDev::tilingPatternFill at SplashOutputDev.cc.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-14494"}
{"idx": 204195, "project": "pjproject", "commit_id": "8b621f192cae14456ee0b0ade52ce6c6f258af1e", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/8b621f192cae14456ee0b0ade52ce6c6f258af1e", "commit_message": "Merge pull request from GHSA-3qx3-cg72-wrh9", "target": 1, "func": "static void parse_rtcp_bye(pjmedia_rtcp_session *sess,\n\t\t\t   const void *pkt,\n\t\t\t   pj_size_t size)\n{\n    pj_str_t reason = {\"-\", 1};\n\n    /* Check and get BYE reason */\n    if (size > 8) {\n\treason.slen = PJ_MIN(sizeof(sess->stat.peer_sdes_buf_),\n                             *((pj_uint8_t*)pkt+8));\n\tpj_memcpy(sess->stat.peer_sdes_buf_, ((pj_uint8_t*)pkt+9),\n\t\t  reason.slen);\n\treason.ptr = sess->stat.peer_sdes_buf_;\n    }\n\n    /* Just print RTCP BYE log */\n    PJ_LOG(5, (sess->name, \"Received RTCP BYE, reason: %.*s\",\n\t       reason.slen, reason.ptr));\n}", "func_hash": 95691820477494011989494034307855997524, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2021-43804", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In affected versions if the incoming RTCP BYE message contains a reason's length, this declared length is not checked against the actual received packet size, potentially resulting in an out-of-bound read access. This issue affects all users that use PJMEDIA and RTCP. A malicious actor can send a RTCP BYE message with an invalid reason length. Users are advised to upgrade as soon as possible. There are no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43804"}
{"idx": 355014, "project": "pjproject", "commit_id": "8b621f192cae14456ee0b0ade52ce6c6f258af1e", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/8b621f192cae14456ee0b0ade52ce6c6f258af1e", "commit_message": "Merge pull request from GHSA-3qx3-cg72-wrh9", "target": 0, "func": "static void parse_rtcp_bye(pjmedia_rtcp_session *sess,\n\t\t\t   const void *pkt,\n\t\t\t   pj_size_t size)\n{\n    pj_str_t reason = {\"-\", 1};\n\n    /* Check and get BYE reason */\n    if (size > 8) {\n    \t/* Make sure the BYE reason does not exceed:\n    \t * - the size of the available buffer\n    \t * - the declared reason's length\n    \t * - the actual packet size\n    \t */\n\treason.slen = PJ_MIN(sizeof(sess->stat.peer_sdes_buf_),\n                             *((pj_uint8_t*)pkt+8));\n        reason.slen = PJ_MIN(reason.slen, size-9);\n\n\tpj_memcpy(sess->stat.peer_sdes_buf_, ((pj_uint8_t*)pkt+9),\n\t\t  reason.slen);\n\treason.ptr = sess->stat.peer_sdes_buf_;\n    }\n\n    /* Just print RTCP BYE log */\n    PJ_LOG(5, (sess->name, \"Received RTCP BYE, reason: %.*s\",\n\t       reason.slen, reason.ptr));\n}", "func_hash": 57940868666737291177801775704260101315, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2021-43804", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In affected versions if the incoming RTCP BYE message contains a reason's length, this declared length is not checked against the actual received packet size, potentially resulting in an out-of-bound read access. This issue affects all users that use PJMEDIA and RTCP. A malicious actor can send a RTCP BYE message with an invalid reason length. Users are advised to upgrade as soon as possible. There are no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43804"}
{"idx": 204243, "project": "vim", "commit_id": "fe6fb267e6ee5c5da2f41889e4e0e0ac5bf4b89d", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/fe6fb267e6ee5c5da2f41889e4e0e0ac5bf4b89d", "commit_message": "patch 8.2.4206: condition with many \"(\" causes a crash\n\nProblem:    Condition with many \"(\" causes a crash.\nSolution:   Limit recursion to 1000.", "target": 1, "func": "eval7(\n    char_u\t**arg,\n    typval_T\t*rettv,\n    evalarg_T\t*evalarg,\n    int\t\twant_string)\t// after \".\" operator\n{\n    int\t\tevaluate = evalarg != NULL\n\t\t\t\t      && (evalarg->eval_flags & EVAL_EVALUATE);\n    int\t\tlen;\n    char_u\t*s;\n    char_u\t*name_start = NULL;\n    char_u\t*start_leader, *end_leader;\n    int\t\tret = OK;\n    char_u\t*alias;\n\n    /*\n     * Initialise variable so that clear_tv() can't mistake this for a\n     * string and free a string that isn't there.\n     */\n    rettv->v_type = VAR_UNKNOWN;\n\n    /*\n     * Skip '!', '-' and '+' characters.  They are handled later.\n     */\n    start_leader = *arg;\n    if (eval_leader(arg, in_vim9script()) == FAIL)\n\treturn FAIL;\n    end_leader = *arg;\n\n    if (**arg == '.' && (!isdigit(*(*arg + 1))\n#ifdef FEAT_FLOAT\n\t    || in_old_script(2)\n#endif\n\t    ))\n    {\n\tsemsg(_(e_invalid_expression_str), *arg);\n\t++*arg;\n\treturn FAIL;\n    }\n\n    switch (**arg)\n    {\n    /*\n     * Number constant.\n     */\n    case '0':\n    case '1':\n    case '2':\n    case '3':\n    case '4':\n    case '5':\n    case '6':\n    case '7':\n    case '8':\n    case '9':\n    case '.':\tret = eval_number(arg, rettv, evaluate, want_string);\n\n\t\t// Apply prefixed \"-\" and \"+\" now.  Matters especially when\n\t\t// \"->\" follows.\n\t\tif (ret == OK && evaluate && end_leader > start_leader\n\t\t\t\t\t\t  && rettv->v_type != VAR_BLOB)\n\t\t    ret = eval7_leader(rettv, TRUE, start_leader, &end_leader);\n\t\tbreak;\n\n    /*\n     * String constant: \"string\".\n     */\n    case '\"':\tret = eval_string(arg, rettv, evaluate);\n\t\tbreak;\n\n    /*\n     * Literal string constant: 'str''ing'.\n     */\n    case '\\'':\tret = eval_lit_string(arg, rettv, evaluate);\n\t\tbreak;\n\n    /*\n     * List: [expr, expr]\n     */\n    case '[':\tret = eval_list(arg, rettv, evalarg, TRUE);\n\t\tbreak;\n\n    /*\n     * Dictionary: #{key: val, key: val}\n     */\n    case '#':\tif (in_vim9script())\n\t\t{\n\t\t    ret = vim9_bad_comment(*arg) ? FAIL : NOTDONE;\n\t\t}\n\t\telse if ((*arg)[1] == '{')\n\t\t{\n\t\t    ++*arg;\n\t\t    ret = eval_dict(arg, rettv, evalarg, TRUE);\n\t\t}\n\t\telse\n\t\t    ret = NOTDONE;\n\t\tbreak;\n\n    /*\n     * Lambda: {arg, arg -> expr}\n     * Dictionary: {'key': val, 'key': val}\n     */\n    case '{':\tif (in_vim9script())\n\t\t    ret = NOTDONE;\n\t\telse\n\t\t    ret = get_lambda_tv(arg, rettv, in_vim9script(), evalarg);\n\t\tif (ret == NOTDONE)\n\t\t    ret = eval_dict(arg, rettv, evalarg, FALSE);\n\t\tbreak;\n\n    /*\n     * Option value: &name\n     */\n    case '&':\tret = eval_option(arg, rettv, evaluate);\n\t\tbreak;\n\n    /*\n     * Environment variable: $VAR.\n     */\n    case '$':\tret = eval_env_var(arg, rettv, evaluate);\n\t\tbreak;\n\n    /*\n     * Register contents: @r.\n     */\n    case '@':\t++*arg;\n\t\tif (evaluate)\n\t\t{\n\t\t    if (in_vim9script() && IS_WHITE_OR_NUL(**arg))\n\t\t\tsemsg(_(e_syntax_error_at_str), *arg);\n\t\t    else if (in_vim9script() && !valid_yank_reg(**arg, FALSE))\n\t\t\temsg_invreg(**arg);\n\t\t    else\n\t\t    {\n\t\t\trettv->v_type = VAR_STRING;\n\t\t\trettv->vval.v_string = get_reg_contents(**arg,\n\t\t\t\t\t\t\t\tGREG_EXPR_SRC);\n\t\t    }\n\t\t}\n\t\tif (**arg != NUL)\n\t\t    ++*arg;\n\t\tbreak;\n\n    /*\n     * nested expression: (expression).\n     * or lambda: (arg) => expr\n     */\n    case '(':\tret = NOTDONE;\n\t\tif (in_vim9script())\n\t\t{\n\t\t    ret = get_lambda_tv(arg, rettv, TRUE, evalarg);\n\t\t    if (ret == OK && evaluate)\n\t\t    {\n\t\t\tufunc_T *ufunc = rettv->vval.v_partial->pt_func;\n\n\t\t\t// Compile it here to get the return type.  The return\n\t\t\t// type is optional, when it's missing use t_unknown.\n\t\t\t// This is recognized in compile_return().\n\t\t\tif (ufunc->uf_ret_type->tt_type == VAR_VOID)\n\t\t\t    ufunc->uf_ret_type = &t_unknown;\n\t\t\tif (compile_def_function(ufunc,\n\t\t\t\t     FALSE, COMPILE_TYPE(ufunc), NULL) == FAIL)\n\t\t\t{\n\t\t\t    clear_tv(rettv);\n\t\t\t    ret = FAIL;\n\t\t\t}\n\t\t    }\n\t\t}\n\t\tif (ret == NOTDONE)\n\t\t{\n\t\t    *arg = skipwhite_and_linebreak(*arg + 1, evalarg);\n\t\t    ret = eval1(arg, rettv, evalarg);\t// recursive!\n\n\t\t    *arg = skipwhite_and_linebreak(*arg, evalarg);\n\t\t    if (**arg == ')')\n\t\t\t++*arg;\n\t\t    else if (ret == OK)\n\t\t    {\n\t\t\temsg(_(e_missing_closing_paren));\n\t\t\tclear_tv(rettv);\n\t\t\tret = FAIL;\n\t\t    }\n\t\t}\n\t\tbreak;\n\n    default:\tret = NOTDONE;\n\t\tbreak;\n    }\n\n    if (ret == NOTDONE)\n    {\n\t/*\n\t * Must be a variable or function name.\n\t * Can also be a curly-braces kind of name: {expr}.\n\t */\n\ts = *arg;\n\tlen = get_name_len(arg, &alias, evaluate, TRUE);\n\tif (alias != NULL)\n\t    s = alias;\n\n\tif (len <= 0)\n\t    ret = FAIL;\n\telse\n\t{\n\t    int\t    flags = evalarg == NULL ? 0 : evalarg->eval_flags;\n\n\t    if (evaluate && in_vim9script() && len == 1 && *s == '_')\n\t    {\n\t\temsg(_(e_cannot_use_underscore_here));\n\t\tret = FAIL;\n\t    }\n\t    else if ((in_vim9script() ? **arg : *skipwhite(*arg)) == '(')\n\t    {\n\t\t// \"name(...\"  recursive!\n\t\t*arg = skipwhite(*arg);\n\t\tret = eval_func(arg, evalarg, s, len, rettv, flags, NULL);\n\t    }\n\t    else if (flags & EVAL_CONSTANT)\n\t\tret = FAIL;\n\t    else if (evaluate)\n\t    {\n\t\t// get the value of \"true\", \"false\" or a variable\n\t\tif (len == 4 && in_vim9script() && STRNCMP(s, \"true\", 4) == 0)\n\t\t{\n\t\t    rettv->v_type = VAR_BOOL;\n\t\t    rettv->vval.v_number = VVAL_TRUE;\n\t\t    ret = OK;\n\t\t}\n\t\telse if (len == 5 && in_vim9script()\n\t\t\t\t\t\t&& STRNCMP(s, \"false\", 5) == 0)\n\t\t{\n\t\t    rettv->v_type = VAR_BOOL;\n\t\t    rettv->vval.v_number = VVAL_FALSE;\n\t\t    ret = OK;\n\t\t}\n\t\telse if (len == 4 && in_vim9script()\n\t\t\t\t\t\t&& STRNCMP(s, \"null\", 4) == 0)\n\t\t{\n\t\t    rettv->v_type = VAR_SPECIAL;\n\t\t    rettv->vval.v_number = VVAL_NULL;\n\t\t    ret = OK;\n\t\t}\n\t\telse\n\t\t{\n\t\t    name_start = s;\n\t\t    ret = eval_variable(s, len, 0, rettv, NULL,\n\t\t\t\t\t   EVAL_VAR_VERBOSE + EVAL_VAR_IMPORT);\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\t// skip the name\n\t\tcheck_vars(s, len);\n\t\tret = OK;\n\t    }\n\t}\n\tvim_free(alias);\n    }\n\n    // Handle following '[', '(' and '.' for expr[expr], expr.name,\n    // expr(expr), expr->name(expr)\n    if (ret == OK)\n\tret = handle_subscript(arg, name_start, rettv, evalarg, TRUE);\n\n    /*\n     * Apply logical NOT and unary '-', from right to left, ignore '+'.\n     */\n    if (ret == OK && evaluate && end_leader > start_leader)\n\tret = eval7_leader(rettv, FALSE, start_leader, &end_leader);\n    return ret;\n}", "func_hash": 36727009233023880586835574908835910206, "file_name": "eval.c", "file_hash": 215532001349875821306945607465028796767, "cwe": ["CWE-787"], "cve": "CVE-2022-0351", "cve_desc": "Access of Memory Location Before Start of Buffer in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0351"}
{"idx": 355649, "project": "vim", "commit_id": "fe6fb267e6ee5c5da2f41889e4e0e0ac5bf4b89d", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/fe6fb267e6ee5c5da2f41889e4e0e0ac5bf4b89d", "commit_message": "patch 8.2.4206: condition with many \"(\" causes a crash\n\nProblem:    Condition with many \"(\" causes a crash.\nSolution:   Limit recursion to 1000.", "target": 0, "func": "eval7(\n    char_u\t**arg,\n    typval_T\t*rettv,\n    evalarg_T\t*evalarg,\n    int\t\twant_string)\t// after \".\" operator\n{\n    int\t\tevaluate = evalarg != NULL\n\t\t\t\t      && (evalarg->eval_flags & EVAL_EVALUATE);\n    int\t\tlen;\n    char_u\t*s;\n    char_u\t*name_start = NULL;\n    char_u\t*start_leader, *end_leader;\n    int\t\tret = OK;\n    char_u\t*alias;\n    static\tint recurse = 0;\n\n    /*\n     * Initialise variable so that clear_tv() can't mistake this for a\n     * string and free a string that isn't there.\n     */\n    rettv->v_type = VAR_UNKNOWN;\n\n    /*\n     * Skip '!', '-' and '+' characters.  They are handled later.\n     */\n    start_leader = *arg;\n    if (eval_leader(arg, in_vim9script()) == FAIL)\n\treturn FAIL;\n    end_leader = *arg;\n\n    if (**arg == '.' && (!isdigit(*(*arg + 1))\n#ifdef FEAT_FLOAT\n\t    || in_old_script(2)\n#endif\n\t    ))\n    {\n\tsemsg(_(e_invalid_expression_str), *arg);\n\t++*arg;\n\treturn FAIL;\n    }\n\n    // Limit recursion to 1000 levels.  At least at 10000 we run out of stack\n    // and crash.\n    if (recurse == 1000)\n    {\n\tsemsg(_(e_expression_too_recursive_str), *arg);\n\treturn FAIL;\n    }\n    ++recurse;\n\n    switch (**arg)\n    {\n    /*\n     * Number constant.\n     */\n    case '0':\n    case '1':\n    case '2':\n    case '3':\n    case '4':\n    case '5':\n    case '6':\n    case '7':\n    case '8':\n    case '9':\n    case '.':\tret = eval_number(arg, rettv, evaluate, want_string);\n\n\t\t// Apply prefixed \"-\" and \"+\" now.  Matters especially when\n\t\t// \"->\" follows.\n\t\tif (ret == OK && evaluate && end_leader > start_leader\n\t\t\t\t\t\t  && rettv->v_type != VAR_BLOB)\n\t\t    ret = eval7_leader(rettv, TRUE, start_leader, &end_leader);\n\t\tbreak;\n\n    /*\n     * String constant: \"string\".\n     */\n    case '\"':\tret = eval_string(arg, rettv, evaluate);\n\t\tbreak;\n\n    /*\n     * Literal string constant: 'str''ing'.\n     */\n    case '\\'':\tret = eval_lit_string(arg, rettv, evaluate);\n\t\tbreak;\n\n    /*\n     * List: [expr, expr]\n     */\n    case '[':\tret = eval_list(arg, rettv, evalarg, TRUE);\n\t\tbreak;\n\n    /*\n     * Dictionary: #{key: val, key: val}\n     */\n    case '#':\tif (in_vim9script())\n\t\t{\n\t\t    ret = vim9_bad_comment(*arg) ? FAIL : NOTDONE;\n\t\t}\n\t\telse if ((*arg)[1] == '{')\n\t\t{\n\t\t    ++*arg;\n\t\t    ret = eval_dict(arg, rettv, evalarg, TRUE);\n\t\t}\n\t\telse\n\t\t    ret = NOTDONE;\n\t\tbreak;\n\n    /*\n     * Lambda: {arg, arg -> expr}\n     * Dictionary: {'key': val, 'key': val}\n     */\n    case '{':\tif (in_vim9script())\n\t\t    ret = NOTDONE;\n\t\telse\n\t\t    ret = get_lambda_tv(arg, rettv, in_vim9script(), evalarg);\n\t\tif (ret == NOTDONE)\n\t\t    ret = eval_dict(arg, rettv, evalarg, FALSE);\n\t\tbreak;\n\n    /*\n     * Option value: &name\n     */\n    case '&':\tret = eval_option(arg, rettv, evaluate);\n\t\tbreak;\n\n    /*\n     * Environment variable: $VAR.\n     */\n    case '$':\tret = eval_env_var(arg, rettv, evaluate);\n\t\tbreak;\n\n    /*\n     * Register contents: @r.\n     */\n    case '@':\t++*arg;\n\t\tif (evaluate)\n\t\t{\n\t\t    if (in_vim9script() && IS_WHITE_OR_NUL(**arg))\n\t\t\tsemsg(_(e_syntax_error_at_str), *arg);\n\t\t    else if (in_vim9script() && !valid_yank_reg(**arg, FALSE))\n\t\t\temsg_invreg(**arg);\n\t\t    else\n\t\t    {\n\t\t\trettv->v_type = VAR_STRING;\n\t\t\trettv->vval.v_string = get_reg_contents(**arg,\n\t\t\t\t\t\t\t\tGREG_EXPR_SRC);\n\t\t    }\n\t\t}\n\t\tif (**arg != NUL)\n\t\t    ++*arg;\n\t\tbreak;\n\n    /*\n     * nested expression: (expression).\n     * or lambda: (arg) => expr\n     */\n    case '(':\tret = NOTDONE;\n\t\tif (in_vim9script())\n\t\t{\n\t\t    ret = get_lambda_tv(arg, rettv, TRUE, evalarg);\n\t\t    if (ret == OK && evaluate)\n\t\t    {\n\t\t\tufunc_T *ufunc = rettv->vval.v_partial->pt_func;\n\n\t\t\t// Compile it here to get the return type.  The return\n\t\t\t// type is optional, when it's missing use t_unknown.\n\t\t\t// This is recognized in compile_return().\n\t\t\tif (ufunc->uf_ret_type->tt_type == VAR_VOID)\n\t\t\t    ufunc->uf_ret_type = &t_unknown;\n\t\t\tif (compile_def_function(ufunc,\n\t\t\t\t     FALSE, COMPILE_TYPE(ufunc), NULL) == FAIL)\n\t\t\t{\n\t\t\t    clear_tv(rettv);\n\t\t\t    ret = FAIL;\n\t\t\t}\n\t\t    }\n\t\t}\n\t\tif (ret == NOTDONE)\n\t\t{\n\t\t    *arg = skipwhite_and_linebreak(*arg + 1, evalarg);\n\t\t    ret = eval1(arg, rettv, evalarg);\t// recursive!\n\n\t\t    *arg = skipwhite_and_linebreak(*arg, evalarg);\n\t\t    if (**arg == ')')\n\t\t\t++*arg;\n\t\t    else if (ret == OK)\n\t\t    {\n\t\t\temsg(_(e_missing_closing_paren));\n\t\t\tclear_tv(rettv);\n\t\t\tret = FAIL;\n\t\t    }\n\t\t}\n\t\tbreak;\n\n    default:\tret = NOTDONE;\n\t\tbreak;\n    }\n\n    if (ret == NOTDONE)\n    {\n\t/*\n\t * Must be a variable or function name.\n\t * Can also be a curly-braces kind of name: {expr}.\n\t */\n\ts = *arg;\n\tlen = get_name_len(arg, &alias, evaluate, TRUE);\n\tif (alias != NULL)\n\t    s = alias;\n\n\tif (len <= 0)\n\t    ret = FAIL;\n\telse\n\t{\n\t    int\t    flags = evalarg == NULL ? 0 : evalarg->eval_flags;\n\n\t    if (evaluate && in_vim9script() && len == 1 && *s == '_')\n\t    {\n\t\temsg(_(e_cannot_use_underscore_here));\n\t\tret = FAIL;\n\t    }\n\t    else if ((in_vim9script() ? **arg : *skipwhite(*arg)) == '(')\n\t    {\n\t\t// \"name(...\"  recursive!\n\t\t*arg = skipwhite(*arg);\n\t\tret = eval_func(arg, evalarg, s, len, rettv, flags, NULL);\n\t    }\n\t    else if (flags & EVAL_CONSTANT)\n\t\tret = FAIL;\n\t    else if (evaluate)\n\t    {\n\t\t// get the value of \"true\", \"false\" or a variable\n\t\tif (len == 4 && in_vim9script() && STRNCMP(s, \"true\", 4) == 0)\n\t\t{\n\t\t    rettv->v_type = VAR_BOOL;\n\t\t    rettv->vval.v_number = VVAL_TRUE;\n\t\t    ret = OK;\n\t\t}\n\t\telse if (len == 5 && in_vim9script()\n\t\t\t\t\t\t&& STRNCMP(s, \"false\", 5) == 0)\n\t\t{\n\t\t    rettv->v_type = VAR_BOOL;\n\t\t    rettv->vval.v_number = VVAL_FALSE;\n\t\t    ret = OK;\n\t\t}\n\t\telse if (len == 4 && in_vim9script()\n\t\t\t\t\t\t&& STRNCMP(s, \"null\", 4) == 0)\n\t\t{\n\t\t    rettv->v_type = VAR_SPECIAL;\n\t\t    rettv->vval.v_number = VVAL_NULL;\n\t\t    ret = OK;\n\t\t}\n\t\telse\n\t\t{\n\t\t    name_start = s;\n\t\t    ret = eval_variable(s, len, 0, rettv, NULL,\n\t\t\t\t\t   EVAL_VAR_VERBOSE + EVAL_VAR_IMPORT);\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\t// skip the name\n\t\tcheck_vars(s, len);\n\t\tret = OK;\n\t    }\n\t}\n\tvim_free(alias);\n    }\n\n    // Handle following '[', '(' and '.' for expr[expr], expr.name,\n    // expr(expr), expr->name(expr)\n    if (ret == OK)\n\tret = handle_subscript(arg, name_start, rettv, evalarg, TRUE);\n\n    /*\n     * Apply logical NOT and unary '-', from right to left, ignore '+'.\n     */\n    if (ret == OK && evaluate && end_leader > start_leader)\n\tret = eval7_leader(rettv, FALSE, start_leader, &end_leader);\n\n    --recurse;\n    return ret;\n}", "func_hash": 324139368658301016034800923930937563014, "file_name": "eval.c", "file_hash": 208824404078014502397565483410500490043, "cwe": ["CWE-787"], "cve": "CVE-2022-0351", "cve_desc": "Access of Memory Location Before Start of Buffer in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0351"}
{"idx": 204278, "project": "firejail", "commit_id": "1884ea22a90d225950d81c804f1771b42ae55f54", "project_url": "https://github.com/netblue30/firejail", "commit_url": "https://github.com/netblue30/firejail/commit/1884ea22a90d225950d81c804f1771b42ae55f54", "commit_message": "CVE-2022-31214: fixing the fix, one more time\n\nthe previous commit \"CVE-2022-31214: fixing the fix\"\nmade private-etc=fonts,fonts and similar commands\nfail with an error\n\nfix that regression by tolerating already existing\ndirectories", "target": 1, "func": "static void build_dirs(char *src, char *dst, size_t src_prefix_len, size_t dst_prefix_len) {\n\tchar *p = src + src_prefix_len + 1;\n\tchar *q = dst + dst_prefix_len + 1;\n\tchar *r = dst + dst_prefix_len;\n\tstruct stat s;\n\tbool last = false;\n\t*r = '\\0';\n\tfor (; !last; p++, q++) {\n\t\tif (*p == '\\0') {\n\t\t\tlast = true;\n\t\t}\n\t\tif (*p == '\\0' || (*p == '/' && *(p - 1) != '/')) {\n\t\t\t// We found a new component of our src path.\n\t\t\t// Null-terminate it temporarily here so that we can work\n\t\t\t// with it.\n\t\t\t*p = '\\0';\n\t\t\tif (stat(src, &s) == 0 && S_ISDIR(s.st_mode)) {\n\t\t\t\t// Null-terminate the dst path and undo its previous\n\t\t\t\t// termination.\n\t\t\t\t*q = '\\0';\n\t\t\t\t*r = '/';\n\t\t\t\tr = q;\n\t\t\t\tmkdir_attr(dst, s.st_mode, 0, 0);\n\t\t\t}\n\t\t\tif (!last) {\n\t\t\t\t// If we're not at the final terminating null, restore\n\t\t\t\t// the slash so that we can continue our traversal.\n\t\t\t\t*p = '/';\n\t\t\t}\n\t\t}\n\t}\n}", "func_hash": 306665336163416948713995999483700256340, "file_name": "None", "file_hash": null, "cwe": ["CWE-94"], "cve": "CVE-2022-31214", "cve_desc": "A Privilege Context Switching issue was discovered in join.c in Firejail 0.9.68. By crafting a bogus Firejail container that is accepted by the Firejail setuid-root program as a join target, a local attacker can enter an environment in which the Linux user namespace is still the initial user namespace, the NO_NEW_PRIVS prctl is not activated, and the entered mount namespace is under the attacker's control. In this way, the filesystem layout can be adjusted to gain root privileges through execution of available setuid-root binaries such as su or sudo.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31214"}
{"idx": 356170, "project": "firejail", "commit_id": "1884ea22a90d225950d81c804f1771b42ae55f54", "project_url": "https://github.com/netblue30/firejail", "commit_url": "https://github.com/netblue30/firejail/commit/1884ea22a90d225950d81c804f1771b42ae55f54", "commit_message": "CVE-2022-31214: fixing the fix, one more time\n\nthe previous commit \"CVE-2022-31214: fixing the fix\"\nmade private-etc=fonts,fonts and similar commands\nfail with an error\n\nfix that regression by tolerating already existing\ndirectories", "target": 0, "func": "static void build_dirs(char *src, char *dst, size_t src_prefix_len, size_t dst_prefix_len) {\n\tchar *p = src + src_prefix_len + 1;\n\tchar *q = dst + dst_prefix_len + 1;\n\tchar *r = dst + dst_prefix_len;\n\tstruct stat s;\n\tbool last = false;\n\t*r = '\\0';\n\tfor (; !last; p++, q++) {\n\t\tif (*p == '\\0') {\n\t\t\tlast = true;\n\t\t}\n\t\tif (*p == '\\0' || (*p == '/' && *(p - 1) != '/')) {\n\t\t\t// We found a new component of our src path.\n\t\t\t// Null-terminate it temporarily here so that we can work\n\t\t\t// with it.\n\t\t\t*p = '\\0';\n\t\t\tif (stat(src, &s) == 0 && S_ISDIR(s.st_mode)) {\n\t\t\t\t// Null-terminate the dst path and undo its previous\n\t\t\t\t// termination.\n\t\t\t\t*q = '\\0';\n\t\t\t\t*r = '/';\n\t\t\t\tr = q;\n\t\t\t\tif (mkdir(dst, 0700) != 0 && errno != EEXIST)\n\t\t\t\t\terrExit(\"mkdir\");\n\t\t\t\tif (chmod(dst, s.st_mode) != 0)\n\t\t\t\t\terrExit(\"chmod\");\n\t\t\t}\n\t\t\tif (!last) {\n\t\t\t\t// If we're not at the final terminating null, restore\n\t\t\t\t// the slash so that we can continue our traversal.\n\t\t\t\t*p = '/';\n\t\t\t}\n\t\t}\n\t}\n}", "func_hash": 189578159776607937045956887346946926481, "file_name": "None", "file_hash": null, "cwe": ["CWE-94"], "cve": "CVE-2022-31214", "cve_desc": "A Privilege Context Switching issue was discovered in join.c in Firejail 0.9.68. By crafting a bogus Firejail container that is accepted by the Firejail setuid-root program as a join target, a local attacker can enter an environment in which the Linux user namespace is still the initial user namespace, the NO_NEW_PRIVS prctl is not activated, and the entered mount namespace is under the attacker's control. In this way, the filesystem layout can be adjusted to gain root privileges through execution of available setuid-root binaries such as su or sudo.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31214"}
{"idx": 204351, "project": "squirrel", "commit_id": "23a0620658714b996d20da3d4dd1a0dcf9b0bd98", "project_url": "https://github.com/albertodemichelis/squirrel", "commit_url": "https://github.com/albertodemichelis/squirrel/commit/23a0620658714b996d20da3d4dd1a0dcf9b0bd98", "commit_message": "check max member count in class", "target": 1, "func": "bool SQClass::NewSlot(SQSharedState *ss,const SQObjectPtr &key,const SQObjectPtr &val,bool bstatic)\n{\n    SQObjectPtr temp;\n    bool belongs_to_static_table = sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE || bstatic;\n    if(_locked && !belongs_to_static_table)\n        return false; //the class already has an instance so cannot be modified\n    if(_members->Get(key,temp) && _isfield(temp)) //overrides the default value\n    {\n        _defaultvalues[_member_idx(temp)].val = val;\n        return true;\n    }\n    if(belongs_to_static_table) {\n        SQInteger mmidx;\n        if((sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE) &&\n            (mmidx = ss->GetMetaMethodIdxByName(key)) != -1) {\n            _metamethods[mmidx] = val;\n        }\n        else {\n            SQObjectPtr theval = val;\n            if(_base && sq_type(val) == OT_CLOSURE) {\n                theval = _closure(val)->Clone();\n                _closure(theval)->_base = _base;\n                __ObjAddRef(_base); //ref for the closure\n            }\n            if(sq_type(temp) == OT_NULL) {\n                bool isconstructor;\n                SQVM::IsEqual(ss->_constructoridx, key, isconstructor);\n                if(isconstructor) {\n                    _constructoridx = (SQInteger)_methods.size();\n                }\n                SQClassMember m;\n                m.val = theval;\n                _members->NewSlot(key,SQObjectPtr(_make_method_idx(_methods.size())));\n                _methods.push_back(m);\n            }\n            else {\n                _methods[_member_idx(temp)].val = theval;\n            }\n        }\n        return true;\n    }\n    SQClassMember m;\n    m.val = val;\n    _members->NewSlot(key,SQObjectPtr(_make_field_idx(_defaultvalues.size())));\n    _defaultvalues.push_back(m);\n    return true;\n}", "func_hash": 269872855469648419079058130898644045027, "file_name": "sqclass.cpp", "file_hash": 75131817582394814638781750834830258905, "cwe": ["CWE-125"], "cve": "CVE-2021-41556", "cve_desc": "sqclass.cpp in Squirrel through 2.2.5 and 3.x through 3.1 allows an out-of-bounds read (in the core interpreter) that can lead to Code Execution. If a victim executes an attacker-controlled squirrel script, it is possible for the attacker to break out of the squirrel script sandbox even if all dangerous functionality such as File System functions has been disabled. An attacker might abuse this bug to target (for example) Cloud services that allow customization via SquirrelScripts, or distribute malware through video games that embed a Squirrel Engine.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41556"}
{"idx": 357668, "project": "squirrel", "commit_id": "23a0620658714b996d20da3d4dd1a0dcf9b0bd98", "project_url": "https://github.com/albertodemichelis/squirrel", "commit_url": "https://github.com/albertodemichelis/squirrel/commit/23a0620658714b996d20da3d4dd1a0dcf9b0bd98", "commit_message": "check max member count in class", "target": 0, "func": "bool SQClass::NewSlot(SQSharedState *ss,const SQObjectPtr &key,const SQObjectPtr &val,bool bstatic)\n{\n    SQObjectPtr temp;\n    bool belongs_to_static_table = sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE || bstatic;\n    if(_locked && !belongs_to_static_table)\n        return false; //the class already has an instance so cannot be modified\n    if(_members->Get(key,temp) && _isfield(temp)) //overrides the default value\n    {\n        _defaultvalues[_member_idx(temp)].val = val;\n        return true;\n    }\n\tif (_members->CountUsed() >= MEMBER_MAX_COUNT) {\n\t\treturn false;\n\t}\n    if(belongs_to_static_table) {\n        SQInteger mmidx;\n        if((sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE) &&\n            (mmidx = ss->GetMetaMethodIdxByName(key)) != -1) {\n            _metamethods[mmidx] = val;\n        }\n        else {\n            SQObjectPtr theval = val;\n            if(_base && sq_type(val) == OT_CLOSURE) {\n                theval = _closure(val)->Clone();\n                _closure(theval)->_base = _base;\n                __ObjAddRef(_base); //ref for the closure\n            }\n            if(sq_type(temp) == OT_NULL) {\n                bool isconstructor;\n                SQVM::IsEqual(ss->_constructoridx, key, isconstructor);\n                if(isconstructor) {\n                    _constructoridx = (SQInteger)_methods.size();\n                }\n                SQClassMember m;\n                m.val = theval;\n                _members->NewSlot(key,SQObjectPtr(_make_method_idx(_methods.size())));\n                _methods.push_back(m);\n            }\n            else {\n                _methods[_member_idx(temp)].val = theval;\n            }\n        }\n        return true;\n    }\n    SQClassMember m;\n    m.val = val;\n    _members->NewSlot(key,SQObjectPtr(_make_field_idx(_defaultvalues.size())));\n    _defaultvalues.push_back(m);\n    return true;\n}", "func_hash": 114176109037888032181151333197990654093, "file_name": "sqclass.cpp", "file_hash": 129356662613675265537572681929065618991, "cwe": ["CWE-125"], "cve": "CVE-2021-41556", "cve_desc": "sqclass.cpp in Squirrel through 2.2.5 and 3.x through 3.1 allows an out-of-bounds read (in the core interpreter) that can lead to Code Execution. If a victim executes an attacker-controlled squirrel script, it is possible for the attacker to break out of the squirrel script sandbox even if all dangerous functionality such as File System functions has been disabled. An attacker might abuse this bug to target (for example) Cloud services that allow customization via SquirrelScripts, or distribute malware through video games that embed a Squirrel Engine.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41556"}
{"idx": 204412, "project": "bpf", "commit_id": "4b81ccebaeee885ab1aa1438133f2991e3a2b6ea", "project_url": "https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf.git/commit/?id=4b81ccebaeee885ab1aa1438133f2991e3a2b6ea", "commit_message": "bpf, ringbuf: Deny reserve of buffers larger than ringbuf\n\nA BPF program might try to reserve a buffer larger than the ringbuf size.\nIf the consumer pointer is way ahead of the producer, that would be\nsuccessfully reserved, allowing the BPF program to read or write out of\nthe ringbuf allocated area.\n\nReported-by: Ryota Shiga (Flatt Security)\nFixes: 457f44363a88 (\"bpf: Implement BPF ring buffer and verifier support for it\")\nSigned-off-by: Thadeu Lima de Souza Cascardo \nSigned-off-by: Daniel Borkmann \nAcked-by: Andrii Nakryiko \nAcked-by: Alexei Starovoitov ", "target": 1, "func": "static void *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size)\n{\n\tunsigned long cons_pos, prod_pos, new_prod_pos, flags;\n\tu32 len, pg_off;\n\tstruct bpf_ringbuf_hdr *hdr;\n\n\tif (unlikely(size > RINGBUF_MAX_RECORD_SZ))\n\t\treturn NULL;\n\n\tlen = round_up(size + BPF_RINGBUF_HDR_SZ, 8);\n\tcons_pos = smp_load_acquire(&rb->consumer_pos);\n\n\tif (in_nmi()) {\n\t\tif (!spin_trylock_irqsave(&rb->spinlock, flags))\n\t\t\treturn NULL;\n\t} else {\n\t\tspin_lock_irqsave(&rb->spinlock, flags);\n\t}\n\n\tprod_pos = rb->producer_pos;\n\tnew_prod_pos = prod_pos + len;\n\n\t/* check for out of ringbuf space by ensuring producer position\n\t * doesn't advance more than (ringbuf_size - 1) ahead\n\t */\n\tif (new_prod_pos - cons_pos > rb->mask) {\n\t\tspin_unlock_irqrestore(&rb->spinlock, flags);\n\t\treturn NULL;\n\t}\n\n\thdr = (void *)rb->data + (prod_pos & rb->mask);\n\tpg_off = bpf_ringbuf_rec_pg_off(rb, hdr);\n\thdr->len = size | BPF_RINGBUF_BUSY_BIT;\n\thdr->pg_off = pg_off;\n\n\t/* pairs with consumer's smp_load_acquire() */\n\tsmp_store_release(&rb->producer_pos, new_prod_pos);\n\n\tspin_unlock_irqrestore(&rb->spinlock, flags);\n\n\treturn (void *)hdr + BPF_RINGBUF_HDR_SZ;\n}", "func_hash": 305878074800514937766892583405358065403, "file_name": "ringbuf.c", "file_hash": 6876939472683174674440151046802738508, "cwe": ["CWE-787"], "cve": "CVE-2021-3489", "cve_desc": "The eBPF RINGBUF bpf_ringbuf_reserve() function in the Linux kernel did not check that the allocated size was smaller than the ringbuf size, allowing an attacker to perform out-of-bounds writes within the kernel and therefore, arbitrary code execution. This issue was fixed via commit 4b81ccebaeee (\"bpf, ringbuf: Deny reserve of buffers larger than ringbuf\") (v5.13-rc4) and backported to the stable kernels in v5.12.4, v5.11.21, and v5.10.37. It was introduced via 457f44363a88 (\"bpf: Implement BPF ring buffer and verifier support for it\") (v5.8-rc1).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3489"}
{"idx": 359206, "project": "bpf", "commit_id": "4b81ccebaeee885ab1aa1438133f2991e3a2b6ea", "project_url": "https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf.git/commit/?id=4b81ccebaeee885ab1aa1438133f2991e3a2b6ea", "commit_message": "bpf, ringbuf: Deny reserve of buffers larger than ringbuf\n\nA BPF program might try to reserve a buffer larger than the ringbuf size.\nIf the consumer pointer is way ahead of the producer, that would be\nsuccessfully reserved, allowing the BPF program to read or write out of\nthe ringbuf allocated area.\n\nReported-by: Ryota Shiga (Flatt Security)\nFixes: 457f44363a88 (\"bpf: Implement BPF ring buffer and verifier support for it\")\nSigned-off-by: Thadeu Lima de Souza Cascardo \nSigned-off-by: Daniel Borkmann \nAcked-by: Andrii Nakryiko \nAcked-by: Alexei Starovoitov ", "target": 0, "func": "static void *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size)\n{\n\tunsigned long cons_pos, prod_pos, new_prod_pos, flags;\n\tu32 len, pg_off;\n\tstruct bpf_ringbuf_hdr *hdr;\n\n\tif (unlikely(size > RINGBUF_MAX_RECORD_SZ))\n\t\treturn NULL;\n\n\tlen = round_up(size + BPF_RINGBUF_HDR_SZ, 8);\n\tif (len > rb->mask + 1)\n\t\treturn NULL;\n\n\tcons_pos = smp_load_acquire(&rb->consumer_pos);\n\n\tif (in_nmi()) {\n\t\tif (!spin_trylock_irqsave(&rb->spinlock, flags))\n\t\t\treturn NULL;\n\t} else {\n\t\tspin_lock_irqsave(&rb->spinlock, flags);\n\t}\n\n\tprod_pos = rb->producer_pos;\n\tnew_prod_pos = prod_pos + len;\n\n\t/* check for out of ringbuf space by ensuring producer position\n\t * doesn't advance more than (ringbuf_size - 1) ahead\n\t */\n\tif (new_prod_pos - cons_pos > rb->mask) {\n\t\tspin_unlock_irqrestore(&rb->spinlock, flags);\n\t\treturn NULL;\n\t}\n\n\thdr = (void *)rb->data + (prod_pos & rb->mask);\n\tpg_off = bpf_ringbuf_rec_pg_off(rb, hdr);\n\thdr->len = size | BPF_RINGBUF_BUSY_BIT;\n\thdr->pg_off = pg_off;\n\n\t/* pairs with consumer's smp_load_acquire() */\n\tsmp_store_release(&rb->producer_pos, new_prod_pos);\n\n\tspin_unlock_irqrestore(&rb->spinlock, flags);\n\n\treturn (void *)hdr + BPF_RINGBUF_HDR_SZ;\n}", "func_hash": 233821322614692863219886146117009832812, "file_name": "ringbuf.c", "file_hash": 3063228527898556498340075998394929987, "cwe": ["CWE-787"], "cve": "CVE-2021-3489", "cve_desc": "The eBPF RINGBUF bpf_ringbuf_reserve() function in the Linux kernel did not check that the allocated size was smaller than the ringbuf size, allowing an attacker to perform out-of-bounds writes within the kernel and therefore, arbitrary code execution. This issue was fixed via commit 4b81ccebaeee (\"bpf, ringbuf: Deny reserve of buffers larger than ringbuf\") (v5.13-rc4) and backported to the stable kernels in v5.12.4, v5.11.21, and v5.10.37. It was introduced via 457f44363a88 (\"bpf: Implement BPF ring buffer and verifier support for it\") (v5.8-rc1).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3489"}
{"idx": 204425, "project": "frr", "commit_id": "6d58272b4cf96f0daa846210dd2104877900f921", "project_url": "https://github.com/FRRouting/frr", "commit_url": "https://github.com/FRRouting/frr/commit/6d58272b4cf96f0daa846210dd2104877900f921", "commit_message": "[bgpd] cleanup, compact and consolidate capability parsing code\n\n2007-07-26 Paul Jakma \n\n\t* (general) Clean up and compact capability parsing slightly.\n\t  Consolidate validation of length and logging of generic TLV, and\n\t  memcpy of capability data, thus removing such from cap specifc\n\t  code (not always present or correct).\n\t* bgp_open.h: Add structures for the generic capability TLV header\n\t  and for the data formats of the various specific capabilities we\n\t  support.  Hence remove the badly named, or else misdefined, struct\n\t  capability.\n\t* bgp_open.c: (bgp_capability_vty_out) Use struct capability_mp_data.\n\t  Do the length checks *before* memcpy()'ing based on that length\n\t  (stored capability - should have been validated anyway on input,\n\t  but..).\n\t  (bgp_afi_safi_valid_indices) new function to validate (afi,safi)\n\t  which is about to be used as index into arrays, consolidates\n\t  several instances of same, at least one of which appeared to be\n\t  incomplete..\n\t  (bgp_capability_mp) Much condensed.\n\t  (bgp_capability_orf_entry) New, process one ORF entry\n\t  (bgp_capability_orf) Condensed. Fixed to process all ORF entries.\n\t  (bgp_capability_restart) Condensed, and fixed to use a\n\t  cap-specific type, rather than abusing capability_mp.\n\t  (struct message capcode_str) added to aid generic logging.\n\t  (size_t cap_minsizes[]) added to aid generic validation of\n\t  capability length field.\n\t  (bgp_capability_parse) Generic logging and validation of TLV\n\t  consolidated here. Code compacted as much as possible.\n\t* bgp_packet.c: (bgp_open_receive) Capability parsers now use\n\t  streams, so no more need here to manually fudge the input stream\n\t  getp.\n\t  (bgp_capability_msg_parse) use struct capability_mp_data. Validate\n\t  lengths /before/ memcpy. Use bgp_afi_safi_valid_indices.\n\t  (bgp_capability_receive) Exported for use by test harness.\n\t* bgp_vty.c: (bgp_show_summary) fix conversion warning\n\t  (bgp_show_peer) ditto\n\t* bgp_debug.h: Fix storage 'extern' after type 'const'.\n        * lib/log.c: (mes_lookup) warning about code not being in\n          same-number array slot should be debug, not warning. E.g. BGP\n          has several discontigious number spaces, allocating from\n          different parts of a space is not uncommon (e.g. IANA\n          assigned versus vendor-assigned code points in some number\n          space).", "target": 1, "func": "bgp_capability_msg_parse (struct peer *peer, u_char *pnt, bgp_size_t length)\n{\n  u_char *end;\n  struct capability cap;\n  u_char action;\n  struct bgp *bgp;\n  afi_t afi;\n  safi_t safi;\n\n  bgp = peer->bgp;\n  end = pnt + length;\n\n  while (pnt < end)\n    {\n      /* We need at least action, capability code and capability length. */\n      if (pnt + 3 > end)\n        {\n          zlog_info (\"%s Capability length error\", peer->host);\n          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);\n          return -1;\n        }\n\n      action = *pnt;\n\n      /* Fetch structure to the byte stream. */\n      memcpy (&cap, pnt + 1, sizeof (struct capability));\n\n      /* Action value check.  */\n      if (action != CAPABILITY_ACTION_SET\n\t  && action != CAPABILITY_ACTION_UNSET)\n        {\n          zlog_info (\"%s Capability Action Value error %d\",\n\t\t     peer->host, action);\n          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);\n          return -1;\n        }\n\n      if (BGP_DEBUG (normal, NORMAL))\n\tzlog_debug (\"%s CAPABILITY has action: %d, code: %u, length %u\",\n\t\t   peer->host, action, cap.code, cap.length);\n\n      /* Capability length check. */\n      if (pnt + (cap.length + 3) > end)\n        {\n          zlog_info (\"%s Capability length error\", peer->host);\n          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);\n          return -1;\n        }\n\n      /* We know MP Capability Code. */\n      if (cap.code == CAPABILITY_CODE_MP)\n        {\n\t  afi = ntohs (cap.mpc.afi);\n\t  safi = cap.mpc.safi;\n\n          /* Ignore capability when override-capability is set. */\n          if (CHECK_FLAG (peer->flags, PEER_FLAG_OVERRIDE_CAPABILITY))\n\t    continue;\n\n\t  /* Address family check.  */\n\t  if ((afi == AFI_IP \n\t       || afi == AFI_IP6)\n\t      && (safi == SAFI_UNICAST \n\t\t  || safi == SAFI_MULTICAST \n\t\t  || safi == BGP_SAFI_VPNV4))\n\t    {\n\t      if (BGP_DEBUG (normal, NORMAL))\n\t\tzlog_debug (\"%s CAPABILITY has %s MP_EXT CAP for afi/safi: %u/%u\",\n\t\t\t   peer->host,\n\t\t\t   action == CAPABILITY_ACTION_SET \n\t\t\t   ? \"Advertising\" : \"Removing\",\n\t\t\t   ntohs(cap.mpc.afi) , cap.mpc.safi);\n\t\t  \n\t      /* Adjust safi code. */\n\t      if (safi == BGP_SAFI_VPNV4)\n\t\tsafi = SAFI_MPLS_VPN;\n\t      \n\t      if (action == CAPABILITY_ACTION_SET)\n\t\t{\n\t\t  peer->afc_recv[afi][safi] = 1;\n\t\t  if (peer->afc[afi][safi])\n\t\t    {\n\t\t      peer->afc_nego[afi][safi] = 1;\n\t\t      bgp_announce_route (peer, afi, safi);\n\t\t    }\n\t\t}\n\t      else\n\t\t{\n\t\t  peer->afc_recv[afi][safi] = 0;\n\t\t  peer->afc_nego[afi][safi] = 0;\n\n\t\t  if (peer_active_nego (peer))\n\t\t    bgp_clear_route (peer, afi, safi);\n\t\t  else\n\t\t    BGP_EVENT_ADD (peer, BGP_Stop);\n\t\t} \n\t    }\n        }\n      else\n        {\n          zlog_warn (\"%s unrecognized capability code: %d - ignored\",\n                     peer->host, cap.code);\n        }\n      pnt += cap.length + 3;\n    }\n  return 0;\n}", "func_hash": 158680384884701932457641345037828096002, "file_name": "bgp_packet.c", "file_hash": 16679227999356180294013513559974077753, "cwe": ["CWE-125"], "cve": "CVE-2022-37032", "cve_desc": "An out-of-bounds read in the BGP daemon of FRRouting FRR before 8.4 may lead to a segmentation fault and denial of service. This occurs in bgp_capability_msg_parse in bgpd/bgp_packet.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-37032"}
{"idx": 359365, "project": "frr", "commit_id": "6d58272b4cf96f0daa846210dd2104877900f921", "project_url": "https://github.com/FRRouting/frr", "commit_url": "https://github.com/FRRouting/frr/commit/6d58272b4cf96f0daa846210dd2104877900f921", "commit_message": "[bgpd] cleanup, compact and consolidate capability parsing code\n\n2007-07-26 Paul Jakma \n\n\t* (general) Clean up and compact capability parsing slightly.\n\t  Consolidate validation of length and logging of generic TLV, and\n\t  memcpy of capability data, thus removing such from cap specifc\n\t  code (not always present or correct).\n\t* bgp_open.h: Add structures for the generic capability TLV header\n\t  and for the data formats of the various specific capabilities we\n\t  support.  Hence remove the badly named, or else misdefined, struct\n\t  capability.\n\t* bgp_open.c: (bgp_capability_vty_out) Use struct capability_mp_data.\n\t  Do the length checks *before* memcpy()'ing based on that length\n\t  (stored capability - should have been validated anyway on input,\n\t  but..).\n\t  (bgp_afi_safi_valid_indices) new function to validate (afi,safi)\n\t  which is about to be used as index into arrays, consolidates\n\t  several instances of same, at least one of which appeared to be\n\t  incomplete..\n\t  (bgp_capability_mp) Much condensed.\n\t  (bgp_capability_orf_entry) New, process one ORF entry\n\t  (bgp_capability_orf) Condensed. Fixed to process all ORF entries.\n\t  (bgp_capability_restart) Condensed, and fixed to use a\n\t  cap-specific type, rather than abusing capability_mp.\n\t  (struct message capcode_str) added to aid generic logging.\n\t  (size_t cap_minsizes[]) added to aid generic validation of\n\t  capability length field.\n\t  (bgp_capability_parse) Generic logging and validation of TLV\n\t  consolidated here. Code compacted as much as possible.\n\t* bgp_packet.c: (bgp_open_receive) Capability parsers now use\n\t  streams, so no more need here to manually fudge the input stream\n\t  getp.\n\t  (bgp_capability_msg_parse) use struct capability_mp_data. Validate\n\t  lengths /before/ memcpy. Use bgp_afi_safi_valid_indices.\n\t  (bgp_capability_receive) Exported for use by test harness.\n\t* bgp_vty.c: (bgp_show_summary) fix conversion warning\n\t  (bgp_show_peer) ditto\n\t* bgp_debug.h: Fix storage 'extern' after type 'const'.\n        * lib/log.c: (mes_lookup) warning about code not being in\n          same-number array slot should be debug, not warning. E.g. BGP\n          has several discontigious number spaces, allocating from\n          different parts of a space is not uncommon (e.g. IANA\n          assigned versus vendor-assigned code points in some number\n          space).", "target": 0, "func": "bgp_capability_msg_parse (struct peer *peer, u_char *pnt, bgp_size_t length)\n{\n  u_char *end;\n  struct capability_mp_data mpc;\n  struct capability_header *hdr;\n  u_char action;\n  struct bgp *bgp;\n  afi_t afi;\n  safi_t safi;\n\n  bgp = peer->bgp;\n  end = pnt + length;\n\n  while (pnt < end)\n    {      \n      /* We need at least action, capability code and capability length. */\n      if (pnt + 3 > end)\n        {\n          zlog_info (\"%s Capability length error\", peer->host);\n          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);\n          return -1;\n        }\n      action = *pnt;\n      hdr = (struct capability_header *)(pnt + 1);\n      \n      /* Action value check.  */\n      if (action != CAPABILITY_ACTION_SET\n\t  && action != CAPABILITY_ACTION_UNSET)\n        {\n          zlog_info (\"%s Capability Action Value error %d\",\n\t\t     peer->host, action);\n          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);\n          return -1;\n        }\n\n      if (BGP_DEBUG (normal, NORMAL))\n\tzlog_debug (\"%s CAPABILITY has action: %d, code: %u, length %u\",\n\t\t   peer->host, action, hdr->code, hdr->length);\n\n      /* Capability length check. */\n      if ((pnt + hdr->length + 3) > end)\n        {\n          zlog_info (\"%s Capability length error\", peer->host);\n          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);\n          return -1;\n        }\n\n      /* Fetch structure to the byte stream. */\n      memcpy (&mpc, pnt + 3, sizeof (struct capability_mp_data));\n\n      /* We know MP Capability Code. */\n      if (hdr->code == CAPABILITY_CODE_MP)\n        {\n\t  afi = ntohs (mpc.afi);\n\t  safi = mpc.safi;\n\n          /* Ignore capability when override-capability is set. */\n          if (CHECK_FLAG (peer->flags, PEER_FLAG_OVERRIDE_CAPABILITY))\n\t    continue;\n          \n          if (!bgp_afi_safi_valid_indices (afi, &safi))\n            {\n              if (BGP_DEBUG (normal, NORMAL))\n                zlog_debug (\"%s Dynamic Capability MP_EXT afi/safi invalid\",\n                            peer->host, afi, safi);\n              continue;\n            }\n          \n\t  /* Address family check.  */\n          if (BGP_DEBUG (normal, NORMAL))\n            zlog_debug (\"%s CAPABILITY has %s MP_EXT CAP for afi/safi: %u/%u\",\n                       peer->host,\n                       action == CAPABILITY_ACTION_SET \n                       ? \"Advertising\" : \"Removing\",\n                       ntohs(mpc.afi) , mpc.safi);\n              \n          if (action == CAPABILITY_ACTION_SET)\n            {\n              peer->afc_recv[afi][safi] = 1;\n              if (peer->afc[afi][safi])\n                {\n                  peer->afc_nego[afi][safi] = 1;\n                  bgp_announce_route (peer, afi, safi);\n                }\n            }\n          else\n            {\n              peer->afc_recv[afi][safi] = 0;\n              peer->afc_nego[afi][safi] = 0;\n\n              if (peer_active_nego (peer))\n                bgp_clear_route (peer, afi, safi);\n              else\n                BGP_EVENT_ADD (peer, BGP_Stop);\n            }\n        }\n      else\n        {\n          zlog_warn (\"%s unrecognized capability code: %d - ignored\",\n                     peer->host, hdr->code);\n        }\n      pnt += hdr->length + 3;\n    }\n  return 0;\n}", "func_hash": 222322579110596507029051344758915923400, "file_name": "bgp_packet.c", "file_hash": 203634856057323248974002745421549823051, "cwe": ["CWE-125"], "cve": "CVE-2022-37032", "cve_desc": "An out-of-bounds read in the BGP daemon of FRRouting FRR before 8.4 may lead to a segmentation fault and denial of service. This occurs in bgp_capability_msg_parse in bgpd/bgp_packet.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-37032"}
{"idx": 204438, "project": "ImageMagick", "commit_id": "716496e6df0add89e9679d6da9c0afca814cfe49", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/716496e6df0add89e9679d6da9c0afca814cfe49", "commit_message": "do not attempt to write a null image list (thanks to Vinay Rohila)", "target": 1, "func": "WandPrivate void CLINoImageOperator(MagickCLI *cli_wand,\n  const char *option,const char *arg1n,const char *arg2n)\n{\n  const char    /* percent escaped versions of the args */\n    *arg1,\n    *arg2;\n\n#define _image_info     (cli_wand->wand.image_info)\n#define _images         (cli_wand->wand.images)\n#define _exception      (cli_wand->wand.exception)\n#define _process_flags  (cli_wand->process_flags)\n#define _option_type    ((CommandOptionFlags) cli_wand->command->flags)\n#define IfNormalOp      (*option=='-')\n#define IfPlusOp        (*option!='-')\n\n  assert(cli_wand != (MagickCLI *) NULL);\n  assert(cli_wand->signature == MagickWandSignature);\n  assert(cli_wand->wand.signature == MagickWandSignature);\n\n  if (cli_wand->wand.debug != MagickFalse)\n    (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),\n      \"- NoImage Operator: %s \\\"%s\\\" \\\"%s\\\"\", option,\n      arg1n != (char *) NULL ? arg1n : \"\",\n      arg2n != (char *) NULL ? arg2n : \"\");\n\n  arg1 = arg1n;\n  arg2 = arg2n;\n\n  /* Interpret Percent Escapes in Arguments - using first image */\n  if ( (((_process_flags & ProcessInterpretProperities) != 0 )\n        || ((_option_type & AlwaysInterpretArgsFlag) != 0)\n       )  && ((_option_type & NeverInterpretArgsFlag) == 0) ) {\n    /* Interpret Percent escapes in argument 1 */\n    if (arg1n != (char *) NULL) {\n      arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception);\n      if (arg1 == (char *) NULL) {\n        CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option);\n        arg1=arg1n;  /* use the given argument as is */\n      }\n    }\n    if (arg2n != (char *) NULL) {\n      arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);\n      if (arg2 == (char *) NULL) {\n        CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option);\n        arg2=arg2n;  /* use the given argument as is */\n      }\n    }\n  }\n#undef _process_flags\n#undef _option_type\n\n  do {  /* break to exit code */\n    /*\n      No-op options  (ignore these)\n    */\n    if (LocaleCompare(\"noop\",option+1) == 0)   /* zero argument */\n      break;\n    if (LocaleCompare(\"sans\",option+1) == 0)   /* one argument */\n      break;\n    if (LocaleCompare(\"sans0\",option+1) == 0)  /* zero argument */\n      break;\n    if (LocaleCompare(\"sans1\",option+1) == 0)  /* one argument */\n      break;\n    if (LocaleCompare(\"sans2\",option+1) == 0)  /* two arguments */\n      break;\n    /*\n      Image Reading\n    */\n    if ( ( LocaleCompare(\"read\",option+1) == 0 ) ||\n      ( LocaleCompare(\"--\",option) == 0 ) ) {\n      /* Do Glob filename Expansion for 'arg1' then read all images.\n      *\n      * Expansion handles '@', '~', '*', and '?' meta-characters while ignoring\n      * (but attaching to the filenames in the generated argument list) any\n      * [...] read modifiers that may be present.\n      *\n      * For example: It will expand '*.gif[20x20]' into a list such as\n      * 'abc.gif[20x20]',  'foobar.gif[20x20]',  'xyzzy.gif[20x20]'\n      *\n      * NOTE: In IMv6 this was done globally across all images. This\n      * meant you could include IM options in '@filename' lists, but you\n      * could not include comments.   Doing it only for image read makes\n      * it far more secure.\n      *\n      * Note: arguments do not have percent escapes expanded for security\n      * reasons.\n      */\n      int      argc;\n      char     **argv;\n      ssize_t  i;\n\n      argc = 1;\n      argv = (char **) &arg1;\n\n      /* Expand 'glob' expressions in the given filename.\n        Expansion handles any 'coder:' prefix, or read modifiers attached\n        to the filename, including them in the resulting expanded list.\n      */\n      if (ExpandFilenames(&argc,&argv) == MagickFalse)\n        CLIWandExceptArgBreak(ResourceLimitError,\"MemoryAllocationFailed\",\n            option,GetExceptionMessage(errno));\n\n      /* loop over expanded filename list, and read then all in */\n      for (i=0; i < (ssize_t) argc; i++) {\n        Image *\n          new_images;\n        if (_image_info->ping != MagickFalse)\n          new_images=PingImages(_image_info,argv[i],_exception);\n        else\n          new_images=ReadImages(_image_info,argv[i],_exception);\n        AppendImageToList(&_images, new_images);\n        argv[i]=DestroyString(argv[i]);\n      }\n      argv=(char **) RelinquishMagickMemory(argv);\n      break;\n    }\n    /*\n      Image Writing\n      Note: Writing a empty image list is valid in specific cases\n    */\n    if (LocaleCompare(\"write\",option+1) == 0) {\n      /* Note: arguments do not have percent escapes expanded */\n      char\n        key[MagickPathExtent];\n\n      Image\n        *write_images;\n\n      ImageInfo\n        *write_info;\n\n      /* Need images, unless a \"null:\" output coder is used */\n      if ( _images == (Image *) NULL ) {\n        if ( LocaleCompare(arg1,\"null:\") == 0 )\n          break;\n        CLIWandExceptArgBreak(OptionError,\"NoImagesForWrite\",option,arg1);\n      }\n\n      (void) FormatLocaleString(key,MagickPathExtent,\"cache:%s\",arg1);\n      (void) DeleteImageRegistry(key);\n      write_images=CloneImageList(_images,_exception);\n      write_info=CloneImageInfo(_image_info);\n      (void) WriteImages(write_info,write_images,arg1,_exception);\n      write_info=DestroyImageInfo(write_info);\n      write_images=DestroyImageList(write_images);\n      break;\n    }\n    /*\n      Parenthesis and Brace operations\n    */\n    if (LocaleCompare(\"(\",option) == 0) {\n      /* stack 'push' images */\n      Stack\n        *node;\n\n      size_t\n        size;\n\n      size=0;\n      node=cli_wand->image_list_stack;\n      for ( ; node != (Stack *) NULL; node=node->next)\n        size++;\n      if ( size >= MAX_STACK_DEPTH )\n        CLIWandExceptionBreak(OptionError,\"ParenthesisNestedTooDeeply\",option);\n      node=(Stack *) AcquireMagickMemory(sizeof(*node));\n      if (node == (Stack *) NULL)\n        CLIWandExceptionBreak(ResourceLimitFatalError,\n            \"MemoryAllocationFailed\",option);\n      node->data = (void *)cli_wand->wand.images;\n      node->next = cli_wand->image_list_stack;\n      cli_wand->image_list_stack = node;\n      cli_wand->wand.images = NewImageList();\n\n      /* handle respect-parenthesis */\n      if (IsStringTrue(GetImageOption(cli_wand->wand.image_info,\n                    \"respect-parenthesis\")) != MagickFalse)\n        option=\"{\"; /* fall-thru so as to push image settings too */\n      else\n        break;\n      /* fall thru to operation */\n    }\n    if (LocaleCompare(\"{\",option) == 0) {\n      /* stack 'push' of image_info settings */\n      Stack\n        *node;\n\n      size_t\n        size;\n\n      size=0;\n      node=cli_wand->image_info_stack;\n      for ( ; node != (Stack *) NULL; node=node->next)\n        size++;\n      if ( size >= MAX_STACK_DEPTH )\n        CLIWandExceptionBreak(OptionError,\"CurlyBracesNestedTooDeeply\",option);\n      node=(Stack *) AcquireMagickMemory(sizeof(*node));\n      if (node == (Stack *) NULL)\n        CLIWandExceptionBreak(ResourceLimitFatalError,\n            \"MemoryAllocationFailed\",option);\n\n      node->data = (void *)cli_wand->wand.image_info;\n      node->next = cli_wand->image_info_stack;\n\n      cli_wand->image_info_stack = node;\n      cli_wand->wand.image_info = CloneImageInfo(cli_wand->wand.image_info);\n      if (cli_wand->wand.image_info == (ImageInfo *) NULL) {\n        CLIWandException(ResourceLimitFatalError,\"MemoryAllocationFailed\",\n            option);\n        cli_wand->wand.image_info = (ImageInfo *)node->data;\n        node = (Stack *)RelinquishMagickMemory(node);\n        break;\n      }\n\n      break;\n    }\n    if (LocaleCompare(\")\",option) == 0) {\n      /* pop images from stack */\n      Stack\n        *node;\n\n      node = (Stack *)cli_wand->image_list_stack;\n      if ( node == (Stack *) NULL)\n        CLIWandExceptionBreak(OptionError,\"UnbalancedParenthesis\",option);\n      cli_wand->image_list_stack = node->next;\n\n      AppendImageToList((Image **)&node->data,cli_wand->wand.images);\n      cli_wand->wand.images= (Image *)node->data;\n      node = (Stack *)RelinquishMagickMemory(node);\n\n      /* handle respect-parenthesis - of the previous 'pushed' settings */\n      node = cli_wand->image_info_stack;\n      if ( node != (Stack *) NULL)\n        {\n          if (IsStringTrue(GetImageOption(\n                cli_wand->wand.image_info,\"respect-parenthesis\")) != MagickFalse)\n            option=\"}\"; /* fall-thru so as to pop image settings too */\n          else\n            break;\n        }\n      else\n        break;\n      /* fall thru to next if */\n    }\n    if (LocaleCompare(\"}\",option) == 0) {\n      /* pop image_info settings from stack */\n      Stack\n        *node;\n\n      node = (Stack *)cli_wand->image_info_stack;\n      if ( node == (Stack *) NULL)\n        CLIWandExceptionBreak(OptionError,\"UnbalancedCurlyBraces\",option);\n      cli_wand->image_info_stack = node->next;\n\n      (void) DestroyImageInfo(cli_wand->wand.image_info);\n      cli_wand->wand.image_info = (ImageInfo *)node->data;\n      node = (Stack *)RelinquishMagickMemory(node);\n\n      GetDrawInfo(cli_wand->wand.image_info, cli_wand->draw_info);\n      cli_wand->quantize_info=DestroyQuantizeInfo(cli_wand->quantize_info);\n      cli_wand->quantize_info=AcquireQuantizeInfo(cli_wand->wand.image_info);\n\n      break;\n    }\n      if (LocaleCompare(\"print\",option+1) == 0)\n        {\n          (void) FormatLocaleFile(stdout,\"%s\",arg1);\n          break;\n        }\n    if (LocaleCompare(\"set\",option+1) == 0)\n      {\n        /* Settings are applied to each image in memory in turn (if any).\n           While a option: only need to be applied once globally.\n\n           NOTE: rguments have not been automatically percent expaneded\n        */\n\n        /* escape the 'key' once only, using first image. */\n        arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception);\n        if (arg1 == (char *) NULL)\n          CLIWandExceptionBreak(OptionWarning,\"InterpretPropertyFailure\",\n                option);\n\n        if (LocaleNCompare(arg1,\"registry:\",9) == 0)\n          {\n            if (IfPlusOp)\n              {\n                (void) DeleteImageRegistry(arg1+9);\n                arg1=DestroyString((char *)arg1);\n                break;\n              }\n            arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);\n            if (arg2 == (char *) NULL) {\n              arg1=DestroyString((char *)arg1);\n              CLIWandExceptionBreak(OptionWarning,\"InterpretPropertyFailure\",\n                    option);\n            }\n            (void) SetImageRegistry(StringRegistryType,arg1+9,arg2,_exception);\n            arg1=DestroyString((char *)arg1);\n            arg2=DestroyString((char *)arg2);\n            break;\n          }\n        if (LocaleNCompare(arg1,\"option:\",7) == 0)\n          {\n            /* delete equivelent artifact from all images (if any) */\n            if (_images != (Image *) NULL)\n              {\n                MagickResetIterator(&cli_wand->wand);\n                while (MagickNextImage(&cli_wand->wand) != MagickFalse)\n                  (void) DeleteImageArtifact(_images,arg1+7);\n                MagickResetIterator(&cli_wand->wand);\n              }\n            /* now set/delete the global option as needed */\n            /* FUTURE: make escapes in a global 'option:' delayed */\n            arg2=(char *) NULL;\n            if (IfNormalOp)\n              {\n                arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);\n                if (arg2 == (char *) NULL)\n                  CLIWandExceptionBreak(OptionWarning,\n                       \"InterpretPropertyFailure\",option);\n              }\n            (void) SetImageOption(_image_info,arg1+7,arg2);\n            arg1=DestroyString((char *)arg1);\n            arg2=DestroyString((char *)arg2);\n            break;\n          }\n        /* Set Artifacts/Properties/Attributes all images (required) */\n        if ( _images == (Image *) NULL )\n          CLIWandExceptArgBreak(OptionWarning,\"NoImageForProperty\",option,arg1);\n\n        MagickResetIterator(&cli_wand->wand);\n        while (MagickNextImage(&cli_wand->wand) != MagickFalse)\n          {\n            arg2=(char *) NULL;\n            if (IfNormalOp)\n              {\n                arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);\n                if (arg2 == (char *) NULL)\n                  CLIWandExceptionBreak(OptionWarning,\n                       \"InterpretPropertyFailure\",option);\n              }\n            if (LocaleNCompare(arg1,\"artifact:\",9) == 0)\n              (void) SetImageArtifact(_images,arg1+9,arg2);\n            else if (LocaleNCompare(arg1,\"property:\",9) == 0)\n              (void) SetImageProperty(_images,arg1+9,arg2,_exception);\n            else\n              (void) SetImageProperty(_images,arg1,arg2,_exception);\n            arg2=DestroyString((char *)arg2);\n          }\n        MagickResetIterator(&cli_wand->wand);\n        arg1=DestroyString((char *)arg1);\n        break;\n     }\n    if (LocaleCompare(\"clone\",option+1) == 0) {\n        Image\n          *new_images;\n\n        if (*option == '+')\n          arg1=AcquireString(\"-1\");\n        if (IsSceneGeometry(arg1,MagickFalse) == MagickFalse)\n          CLIWandExceptionBreak(OptionError,\"InvalidArgument\",option);\n        if ( cli_wand->image_list_stack == (Stack *) NULL)\n          CLIWandExceptionBreak(OptionError,\"UnableToCloneImage\",option);\n        new_images = (Image *)cli_wand->image_list_stack->data;\n        if (new_images == (Image *) NULL)\n          CLIWandExceptionBreak(OptionError,\"UnableToCloneImage\",option);\n        new_images=CloneImages(new_images,arg1,_exception);\n        if (new_images == (Image *) NULL)\n          CLIWandExceptionBreak(OptionError,\"NoSuchImage\",option);\n        AppendImageToList(&_images,new_images);\n        break;\n      }\n    /*\n       Informational Operations.\n\n       Note that these do not require either a cli-wand or images!\n       Though currently a cli-wand much be provided regardless.\n    */\n    if (LocaleCompare(\"version\",option+1) == 0)\n      {\n        ListMagickVersion(stdout);\n        break;\n      }\n    if (LocaleCompare(\"list\",option+1) == 0) {\n      /*\n         FUTURE: This 'switch' should really be part of MagickCore\n      */\n      ssize_t\n        list;\n\n      list=ParseCommandOption(MagickListOptions,MagickFalse,arg1);\n      if ( list < 0 ) {\n        CLIWandExceptionArg(OptionError,\"UnrecognizedListType\",option,arg1);\n        break;\n      }\n      switch (list)\n      {\n        case MagickCoderOptions:\n        {\n          (void) ListCoderInfo((FILE *) NULL,_exception);\n          break;\n        }\n        case MagickColorOptions:\n        {\n          (void) ListColorInfo((FILE *) NULL,_exception);\n          break;\n        }\n        case MagickConfigureOptions:\n        {\n          (void) ListConfigureInfo((FILE *) NULL,_exception);\n          break;\n        }\n        case MagickDelegateOptions:\n        {\n          (void) ListDelegateInfo((FILE *) NULL,_exception);\n          break;\n        }\n        case MagickFontOptions:\n        {\n          (void) ListTypeInfo((FILE *) NULL,_exception);\n          break;\n        }\n        case MagickFormatOptions:\n          (void) ListMagickInfo((FILE *) NULL,_exception);\n          break;\n        case MagickLocaleOptions:\n          (void) ListLocaleInfo((FILE *) NULL,_exception);\n          break;\n        case MagickLogOptions:\n          (void) ListLogInfo((FILE *) NULL,_exception);\n          break;\n        case MagickMagicOptions:\n          (void) ListMagicInfo((FILE *) NULL,_exception);\n          break;\n        case MagickMimeOptions:\n          (void) ListMimeInfo((FILE *) NULL,_exception);\n          break;\n        case MagickModuleOptions:\n          (void) ListModuleInfo((FILE *) NULL,_exception);\n          break;\n        case MagickPolicyOptions:\n          (void) ListPolicyInfo((FILE *) NULL,_exception);\n          break;\n        case MagickResourceOptions:\n          (void) ListMagickResourceInfo((FILE *) NULL,_exception);\n          break;\n        case MagickThresholdOptions:\n          (void) ListThresholdMaps((FILE *) NULL,_exception);\n          break;\n        default:\n          (void) ListCommandOptions((FILE *) NULL,(CommandOption) list,\n            _exception);\n          break;\n      }\n      break;\n    }\n\n    CLIWandException(OptionError,\"UnrecognizedOption\",option);\n\nDisableMSCWarning(4127)\n  } while (0);  /* break to exit code. */\nRestoreMSCWarning\n\n  /* clean up percent escape interpreted strings */\n  if (arg1 != arg1n )\n    arg1=DestroyString((char *)arg1);\n  if (arg2 != arg2n )\n    arg2=DestroyString((char *)arg2);\n\n#undef _image_info\n#undef _images\n#undef _exception\n#undef IfNormalOp\n#undef IfPlusOp\n}", "func_hash": 310441418553941793285963012286957612842, "file_name": "operation.c", "file_hash": 209735039697633444699043395330012675070, "cwe": ["CWE-617"], "cve": "CVE-2022-2719", "cve_desc": "In ImageMagick, a crafted file could trigger an assertion failure when a call to WriteImages was made in MagickWand/operation.c, due to a NULL image list. This could potentially cause a denial of service. This was fixed in upstream ImageMagick version 7.1.0-30.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2719"}
{"idx": 359843, "project": "ImageMagick", "commit_id": "716496e6df0add89e9679d6da9c0afca814cfe49", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/716496e6df0add89e9679d6da9c0afca814cfe49", "commit_message": "do not attempt to write a null image list (thanks to Vinay Rohila)", "target": 0, "func": "WandPrivate void CLINoImageOperator(MagickCLI *cli_wand,\n  const char *option,const char *arg1n,const char *arg2n)\n{\n  const char    /* percent escaped versions of the args */\n    *arg1,\n    *arg2;\n\n#define _image_info     (cli_wand->wand.image_info)\n#define _images         (cli_wand->wand.images)\n#define _exception      (cli_wand->wand.exception)\n#define _process_flags  (cli_wand->process_flags)\n#define _option_type    ((CommandOptionFlags) cli_wand->command->flags)\n#define IfNormalOp      (*option=='-')\n#define IfPlusOp        (*option!='-')\n\n  assert(cli_wand != (MagickCLI *) NULL);\n  assert(cli_wand->signature == MagickWandSignature);\n  assert(cli_wand->wand.signature == MagickWandSignature);\n\n  if (cli_wand->wand.debug != MagickFalse)\n    (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),\n      \"- NoImage Operator: %s \\\"%s\\\" \\\"%s\\\"\", option,\n      arg1n != (char *) NULL ? arg1n : \"\",\n      arg2n != (char *) NULL ? arg2n : \"\");\n\n  arg1 = arg1n;\n  arg2 = arg2n;\n\n  /* Interpret Percent Escapes in Arguments - using first image */\n  if ( (((_process_flags & ProcessInterpretProperities) != 0 )\n        || ((_option_type & AlwaysInterpretArgsFlag) != 0)\n       )  && ((_option_type & NeverInterpretArgsFlag) == 0) ) {\n    /* Interpret Percent escapes in argument 1 */\n    if (arg1n != (char *) NULL) {\n      arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception);\n      if (arg1 == (char *) NULL) {\n        CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option);\n        arg1=arg1n;  /* use the given argument as is */\n      }\n    }\n    if (arg2n != (char *) NULL) {\n      arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);\n      if (arg2 == (char *) NULL) {\n        CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option);\n        arg2=arg2n;  /* use the given argument as is */\n      }\n    }\n  }\n#undef _process_flags\n#undef _option_type\n\n  do {  /* break to exit code */\n    /*\n      No-op options  (ignore these)\n    */\n    if (LocaleCompare(\"noop\",option+1) == 0)   /* zero argument */\n      break;\n    if (LocaleCompare(\"sans\",option+1) == 0)   /* one argument */\n      break;\n    if (LocaleCompare(\"sans0\",option+1) == 0)  /* zero argument */\n      break;\n    if (LocaleCompare(\"sans1\",option+1) == 0)  /* one argument */\n      break;\n    if (LocaleCompare(\"sans2\",option+1) == 0)  /* two arguments */\n      break;\n    /*\n      Image Reading\n    */\n    if ( ( LocaleCompare(\"read\",option+1) == 0 ) ||\n      ( LocaleCompare(\"--\",option) == 0 ) ) {\n      /* Do Glob filename Expansion for 'arg1' then read all images.\n      *\n      * Expansion handles '@', '~', '*', and '?' meta-characters while ignoring\n      * (but attaching to the filenames in the generated argument list) any\n      * [...] read modifiers that may be present.\n      *\n      * For example: It will expand '*.gif[20x20]' into a list such as\n      * 'abc.gif[20x20]',  'foobar.gif[20x20]',  'xyzzy.gif[20x20]'\n      *\n      * NOTE: In IMv6 this was done globally across all images. This\n      * meant you could include IM options in '@filename' lists, but you\n      * could not include comments.   Doing it only for image read makes\n      * it far more secure.\n      *\n      * Note: arguments do not have percent escapes expanded for security\n      * reasons.\n      */\n      int      argc;\n      char     **argv;\n      ssize_t  i;\n\n      argc = 1;\n      argv = (char **) &arg1;\n\n      /* Expand 'glob' expressions in the given filename.\n        Expansion handles any 'coder:' prefix, or read modifiers attached\n        to the filename, including them in the resulting expanded list.\n      */\n      if (ExpandFilenames(&argc,&argv) == MagickFalse)\n        CLIWandExceptArgBreak(ResourceLimitError,\"MemoryAllocationFailed\",\n            option,GetExceptionMessage(errno));\n\n      /* loop over expanded filename list, and read then all in */\n      for (i=0; i < (ssize_t) argc; i++) {\n        Image *\n          new_images;\n        if (_image_info->ping != MagickFalse)\n          new_images=PingImages(_image_info,argv[i],_exception);\n        else\n          new_images=ReadImages(_image_info,argv[i],_exception);\n        AppendImageToList(&_images, new_images);\n        argv[i]=DestroyString(argv[i]);\n      }\n      argv=(char **) RelinquishMagickMemory(argv);\n      break;\n    }\n    /*\n      Image Writing\n      Note: Writing a empty image list is valid in specific cases\n    */\n    if (LocaleCompare(\"write\",option+1) == 0) {\n      /* Note: arguments do not have percent escapes expanded */\n      char\n        key[MagickPathExtent];\n\n      Image\n        *write_images;\n\n      ImageInfo\n        *write_info;\n\n      /* Need images, unless a \"null:\" output coder is used */\n      if ( _images == (Image *) NULL ) {\n        if ( LocaleCompare(arg1,\"null:\") == 0 )\n          break;\n        CLIWandExceptArgBreak(OptionError,\"NoImagesForWrite\",option,arg1);\n      }\n\n      (void) FormatLocaleString(key,MagickPathExtent,\"cache:%s\",arg1);\n      (void) DeleteImageRegistry(key);\n      write_images=CloneImageList(_images,_exception);\n      write_info=CloneImageInfo(_image_info);\n      if (write_images != (Image *) NULL)\n        (void) WriteImages(write_info,write_images,arg1,_exception);\n      write_info=DestroyImageInfo(write_info);\n      write_images=DestroyImageList(write_images);\n      break;\n    }\n    /*\n      Parenthesis and Brace operations\n    */\n    if (LocaleCompare(\"(\",option) == 0) {\n      /* stack 'push' images */\n      Stack\n        *node;\n\n      size_t\n        size;\n\n      size=0;\n      node=cli_wand->image_list_stack;\n      for ( ; node != (Stack *) NULL; node=node->next)\n        size++;\n      if ( size >= MAX_STACK_DEPTH )\n        CLIWandExceptionBreak(OptionError,\"ParenthesisNestedTooDeeply\",option);\n      node=(Stack *) AcquireMagickMemory(sizeof(*node));\n      if (node == (Stack *) NULL)\n        CLIWandExceptionBreak(ResourceLimitFatalError,\n            \"MemoryAllocationFailed\",option);\n      node->data = (void *)cli_wand->wand.images;\n      node->next = cli_wand->image_list_stack;\n      cli_wand->image_list_stack = node;\n      cli_wand->wand.images = NewImageList();\n\n      /* handle respect-parenthesis */\n      if (IsStringTrue(GetImageOption(cli_wand->wand.image_info,\n                    \"respect-parenthesis\")) != MagickFalse)\n        option=\"{\"; /* fall-thru so as to push image settings too */\n      else\n        break;\n      /* fall thru to operation */\n    }\n    if (LocaleCompare(\"{\",option) == 0) {\n      /* stack 'push' of image_info settings */\n      Stack\n        *node;\n\n      size_t\n        size;\n\n      size=0;\n      node=cli_wand->image_info_stack;\n      for ( ; node != (Stack *) NULL; node=node->next)\n        size++;\n      if ( size >= MAX_STACK_DEPTH )\n        CLIWandExceptionBreak(OptionError,\"CurlyBracesNestedTooDeeply\",option);\n      node=(Stack *) AcquireMagickMemory(sizeof(*node));\n      if (node == (Stack *) NULL)\n        CLIWandExceptionBreak(ResourceLimitFatalError,\n            \"MemoryAllocationFailed\",option);\n\n      node->data = (void *)cli_wand->wand.image_info;\n      node->next = cli_wand->image_info_stack;\n\n      cli_wand->image_info_stack = node;\n      cli_wand->wand.image_info = CloneImageInfo(cli_wand->wand.image_info);\n      if (cli_wand->wand.image_info == (ImageInfo *) NULL) {\n        CLIWandException(ResourceLimitFatalError,\"MemoryAllocationFailed\",\n            option);\n        cli_wand->wand.image_info = (ImageInfo *)node->data;\n        node = (Stack *)RelinquishMagickMemory(node);\n        break;\n      }\n\n      break;\n    }\n    if (LocaleCompare(\")\",option) == 0) {\n      /* pop images from stack */\n      Stack\n        *node;\n\n      node = (Stack *)cli_wand->image_list_stack;\n      if ( node == (Stack *) NULL)\n        CLIWandExceptionBreak(OptionError,\"UnbalancedParenthesis\",option);\n      cli_wand->image_list_stack = node->next;\n\n      AppendImageToList((Image **)&node->data,cli_wand->wand.images);\n      cli_wand->wand.images= (Image *)node->data;\n      node = (Stack *)RelinquishMagickMemory(node);\n\n      /* handle respect-parenthesis - of the previous 'pushed' settings */\n      node = cli_wand->image_info_stack;\n      if ( node != (Stack *) NULL)\n        {\n          if (IsStringTrue(GetImageOption(\n                cli_wand->wand.image_info,\"respect-parenthesis\")) != MagickFalse)\n            option=\"}\"; /* fall-thru so as to pop image settings too */\n          else\n            break;\n        }\n      else\n        break;\n      /* fall thru to next if */\n    }\n    if (LocaleCompare(\"}\",option) == 0) {\n      /* pop image_info settings from stack */\n      Stack\n        *node;\n\n      node = (Stack *)cli_wand->image_info_stack;\n      if ( node == (Stack *) NULL)\n        CLIWandExceptionBreak(OptionError,\"UnbalancedCurlyBraces\",option);\n      cli_wand->image_info_stack = node->next;\n\n      (void) DestroyImageInfo(cli_wand->wand.image_info);\n      cli_wand->wand.image_info = (ImageInfo *)node->data;\n      node = (Stack *)RelinquishMagickMemory(node);\n\n      GetDrawInfo(cli_wand->wand.image_info, cli_wand->draw_info);\n      cli_wand->quantize_info=DestroyQuantizeInfo(cli_wand->quantize_info);\n      cli_wand->quantize_info=AcquireQuantizeInfo(cli_wand->wand.image_info);\n\n      break;\n    }\n      if (LocaleCompare(\"print\",option+1) == 0)\n        {\n          (void) FormatLocaleFile(stdout,\"%s\",arg1);\n          break;\n        }\n    if (LocaleCompare(\"set\",option+1) == 0)\n      {\n        /* Settings are applied to each image in memory in turn (if any).\n           While a option: only need to be applied once globally.\n\n           NOTE: rguments have not been automatically percent expaneded\n        */\n\n        /* escape the 'key' once only, using first image. */\n        arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception);\n        if (arg1 == (char *) NULL)\n          CLIWandExceptionBreak(OptionWarning,\"InterpretPropertyFailure\",\n                option);\n\n        if (LocaleNCompare(arg1,\"registry:\",9) == 0)\n          {\n            if (IfPlusOp)\n              {\n                (void) DeleteImageRegistry(arg1+9);\n                arg1=DestroyString((char *)arg1);\n                break;\n              }\n            arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);\n            if (arg2 == (char *) NULL) {\n              arg1=DestroyString((char *)arg1);\n              CLIWandExceptionBreak(OptionWarning,\"InterpretPropertyFailure\",\n                    option);\n            }\n            (void) SetImageRegistry(StringRegistryType,arg1+9,arg2,_exception);\n            arg1=DestroyString((char *)arg1);\n            arg2=DestroyString((char *)arg2);\n            break;\n          }\n        if (LocaleNCompare(arg1,\"option:\",7) == 0)\n          {\n            /* delete equivelent artifact from all images (if any) */\n            if (_images != (Image *) NULL)\n              {\n                MagickResetIterator(&cli_wand->wand);\n                while (MagickNextImage(&cli_wand->wand) != MagickFalse)\n                  (void) DeleteImageArtifact(_images,arg1+7);\n                MagickResetIterator(&cli_wand->wand);\n              }\n            /* now set/delete the global option as needed */\n            /* FUTURE: make escapes in a global 'option:' delayed */\n            arg2=(char *) NULL;\n            if (IfNormalOp)\n              {\n                arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);\n                if (arg2 == (char *) NULL)\n                  CLIWandExceptionBreak(OptionWarning,\n                       \"InterpretPropertyFailure\",option);\n              }\n            (void) SetImageOption(_image_info,arg1+7,arg2);\n            arg1=DestroyString((char *)arg1);\n            arg2=DestroyString((char *)arg2);\n            break;\n          }\n        /* Set Artifacts/Properties/Attributes all images (required) */\n        if ( _images == (Image *) NULL )\n          CLIWandExceptArgBreak(OptionWarning,\"NoImageForProperty\",option,arg1);\n\n        MagickResetIterator(&cli_wand->wand);\n        while (MagickNextImage(&cli_wand->wand) != MagickFalse)\n          {\n            arg2=(char *) NULL;\n            if (IfNormalOp)\n              {\n                arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);\n                if (arg2 == (char *) NULL)\n                  CLIWandExceptionBreak(OptionWarning,\n                       \"InterpretPropertyFailure\",option);\n              }\n            if (LocaleNCompare(arg1,\"artifact:\",9) == 0)\n              (void) SetImageArtifact(_images,arg1+9,arg2);\n            else if (LocaleNCompare(arg1,\"property:\",9) == 0)\n              (void) SetImageProperty(_images,arg1+9,arg2,_exception);\n            else\n              (void) SetImageProperty(_images,arg1,arg2,_exception);\n            arg2=DestroyString((char *)arg2);\n          }\n        MagickResetIterator(&cli_wand->wand);\n        arg1=DestroyString((char *)arg1);\n        break;\n     }\n    if (LocaleCompare(\"clone\",option+1) == 0) {\n        Image\n          *new_images;\n\n        if (*option == '+')\n          arg1=AcquireString(\"-1\");\n        if (IsSceneGeometry(arg1,MagickFalse) == MagickFalse)\n          CLIWandExceptionBreak(OptionError,\"InvalidArgument\",option);\n        if ( cli_wand->image_list_stack == (Stack *) NULL)\n          CLIWandExceptionBreak(OptionError,\"UnableToCloneImage\",option);\n        new_images = (Image *)cli_wand->image_list_stack->data;\n        if (new_images == (Image *) NULL)\n          CLIWandExceptionBreak(OptionError,\"UnableToCloneImage\",option);\n        new_images=CloneImages(new_images,arg1,_exception);\n        if (new_images == (Image *) NULL)\n          CLIWandExceptionBreak(OptionError,\"NoSuchImage\",option);\n        AppendImageToList(&_images,new_images);\n        break;\n      }\n    /*\n       Informational Operations.\n\n       Note that these do not require either a cli-wand or images!\n       Though currently a cli-wand much be provided regardless.\n    */\n    if (LocaleCompare(\"version\",option+1) == 0)\n      {\n        ListMagickVersion(stdout);\n        break;\n      }\n    if (LocaleCompare(\"list\",option+1) == 0) {\n      /*\n         FUTURE: This 'switch' should really be part of MagickCore\n      */\n      ssize_t\n        list;\n\n      list=ParseCommandOption(MagickListOptions,MagickFalse,arg1);\n      if ( list < 0 ) {\n        CLIWandExceptionArg(OptionError,\"UnrecognizedListType\",option,arg1);\n        break;\n      }\n      switch (list)\n      {\n        case MagickCoderOptions:\n        {\n          (void) ListCoderInfo((FILE *) NULL,_exception);\n          break;\n        }\n        case MagickColorOptions:\n        {\n          (void) ListColorInfo((FILE *) NULL,_exception);\n          break;\n        }\n        case MagickConfigureOptions:\n        {\n          (void) ListConfigureInfo((FILE *) NULL,_exception);\n          break;\n        }\n        case MagickDelegateOptions:\n        {\n          (void) ListDelegateInfo((FILE *) NULL,_exception);\n          break;\n        }\n        case MagickFontOptions:\n        {\n          (void) ListTypeInfo((FILE *) NULL,_exception);\n          break;\n        }\n        case MagickFormatOptions:\n          (void) ListMagickInfo((FILE *) NULL,_exception);\n          break;\n        case MagickLocaleOptions:\n          (void) ListLocaleInfo((FILE *) NULL,_exception);\n          break;\n        case MagickLogOptions:\n          (void) ListLogInfo((FILE *) NULL,_exception);\n          break;\n        case MagickMagicOptions:\n          (void) ListMagicInfo((FILE *) NULL,_exception);\n          break;\n        case MagickMimeOptions:\n          (void) ListMimeInfo((FILE *) NULL,_exception);\n          break;\n        case MagickModuleOptions:\n          (void) ListModuleInfo((FILE *) NULL,_exception);\n          break;\n        case MagickPolicyOptions:\n          (void) ListPolicyInfo((FILE *) NULL,_exception);\n          break;\n        case MagickResourceOptions:\n          (void) ListMagickResourceInfo((FILE *) NULL,_exception);\n          break;\n        case MagickThresholdOptions:\n          (void) ListThresholdMaps((FILE *) NULL,_exception);\n          break;\n        default:\n          (void) ListCommandOptions((FILE *) NULL,(CommandOption) list,\n            _exception);\n          break;\n      }\n      break;\n    }\n\n    CLIWandException(OptionError,\"UnrecognizedOption\",option);\n\nDisableMSCWarning(4127)\n  } while (0);  /* break to exit code. */\nRestoreMSCWarning\n\n  /* clean up percent escape interpreted strings */\n  if (arg1 != arg1n )\n    arg1=DestroyString((char *)arg1);\n  if (arg2 != arg2n )\n    arg2=DestroyString((char *)arg2);\n\n#undef _image_info\n#undef _images\n#undef _exception\n#undef IfNormalOp\n#undef IfPlusOp\n}", "func_hash": 579576062025196307167021581529787649, "file_name": "operation.c", "file_hash": 114606754670284270817581814822080534295, "cwe": ["CWE-617"], "cve": "CVE-2022-2719", "cve_desc": "In ImageMagick, a crafted file could trigger an assertion failure when a call to WriteImages was made in MagickWand/operation.c, due to a NULL image list. This could potentially cause a denial of service. This was fixed in upstream ImageMagick version 7.1.0-30.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2719"}
{"idx": 204495, "project": "linux", "commit_id": "47abea041f897d64dbd5777f0cf7745148f85d75", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/47abea041f897d64dbd5777f0cf7745148f85d75", "commit_message": "io_uring: fix off-by-one in sync cancelation file check\n\nThe passed in index should be validated against the number of registered\nfiles we have, it needs to be smaller than the index value to avoid going\none beyond the end.\n\nFixes: 78a861b94959 (\"io_uring: add sync cancelation API through io_uring_register()\")\nReported-by: Luo Likang \nSigned-off-by: Jens Axboe ", "target": 1, "func": "static int __io_sync_cancel(struct io_uring_task *tctx,\n\t\t\t    struct io_cancel_data *cd, int fd)\n{\n\tstruct io_ring_ctx *ctx = cd->ctx;\n\n\t/* fixed must be grabbed every time since we drop the uring_lock */\n\tif ((cd->flags & IORING_ASYNC_CANCEL_FD) &&\n\t    (cd->flags & IORING_ASYNC_CANCEL_FD_FIXED)) {\n\t\tunsigned long file_ptr;\n\n\t\tif (unlikely(fd > ctx->nr_user_files))\n\t\t\treturn -EBADF;\n\t\tfd = array_index_nospec(fd, ctx->nr_user_files);\n\t\tfile_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;\n\t\tcd->file = (struct file *) (file_ptr & FFS_MASK);\n\t\tif (!cd->file)\n\t\t\treturn -EBADF;\n\t}\n\n\treturn __io_async_cancel(cd, tctx, 0);\n}", "func_hash": 178631003172617197260225259743936148137, "file_name": "cancel.c", "file_hash": 251597362135051290688561510710144448867, "cwe": ["CWE-193"], "cve": "CVE-2022-3103", "cve_desc": "off-by-one in io_uring module.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3103"}
{"idx": 360829, "project": "linux", "commit_id": "47abea041f897d64dbd5777f0cf7745148f85d75", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/47abea041f897d64dbd5777f0cf7745148f85d75", "commit_message": "io_uring: fix off-by-one in sync cancelation file check\n\nThe passed in index should be validated against the number of registered\nfiles we have, it needs to be smaller than the index value to avoid going\none beyond the end.\n\nFixes: 78a861b94959 (\"io_uring: add sync cancelation API through io_uring_register()\")\nReported-by: Luo Likang \nSigned-off-by: Jens Axboe ", "target": 0, "func": "static int __io_sync_cancel(struct io_uring_task *tctx,\n\t\t\t    struct io_cancel_data *cd, int fd)\n{\n\tstruct io_ring_ctx *ctx = cd->ctx;\n\n\t/* fixed must be grabbed every time since we drop the uring_lock */\n\tif ((cd->flags & IORING_ASYNC_CANCEL_FD) &&\n\t    (cd->flags & IORING_ASYNC_CANCEL_FD_FIXED)) {\n\t\tunsigned long file_ptr;\n\n\t\tif (unlikely(fd >= ctx->nr_user_files))\n\t\t\treturn -EBADF;\n\t\tfd = array_index_nospec(fd, ctx->nr_user_files);\n\t\tfile_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;\n\t\tcd->file = (struct file *) (file_ptr & FFS_MASK);\n\t\tif (!cd->file)\n\t\t\treturn -EBADF;\n\t}\n\n\treturn __io_async_cancel(cd, tctx, 0);\n}", "func_hash": 191453192245381781842321164119198990689, "file_name": "cancel.c", "file_hash": 191362883793091950391767824989989369401, "cwe": ["CWE-193"], "cve": "CVE-2022-3103", "cve_desc": "off-by-one in io_uring module.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3103"}
{"idx": 204534, "project": "admesh", "commit_id": "e84d8353f1347e1f26f0a95770d92ba14e6ede38", "project_url": "https://github.com/admesh/admesh", "commit_url": "https://github.com/admesh/admesh/commit/e84d8353f1347e1f26f0a95770d92ba14e6ede38", "commit_message": "Fix heap buffer overflow in stl_update_connects_remove_1\n\n\n- Add argument value check to the stl_update_connects_remove_1\n- Add neighbor value check in stl_remove_degenerate\n\nFixes https://github.com/admesh/admesh/issues/28\nMerges https://github.com/admesh/admesh/pull/55", "target": 1, "func": "stl_remove_degenerate(stl_file *stl, int facet) {\n  int edge1;\n  int edge2;\n  int edge3;\n  int neighbor1;\n  int neighbor2;\n  int neighbor3;\n  int vnot1;\n  int vnot2;\n  int vnot3;\n\n  if (stl->error) return;\n\n  if(   !memcmp(&stl->facet_start[facet].vertex[0],\n                &stl->facet_start[facet].vertex[1], sizeof(stl_vertex))\n        && !memcmp(&stl->facet_start[facet].vertex[1],\n                   &stl->facet_start[facet].vertex[2], sizeof(stl_vertex))) {\n    /* all 3 vertices are equal.  Just remove the facet.  I don't think*/\n    /* this is really possible, but just in case... */\n    printf(\"removing a facet in stl_remove_degenerate\\n\");\n\n    stl_remove_facet(stl, facet);\n    return;\n  }\n\n  if(!memcmp(&stl->facet_start[facet].vertex[0],\n             &stl->facet_start[facet].vertex[1], sizeof(stl_vertex))) {\n    edge1 = 1;\n    edge2 = 2;\n    edge3 = 0;\n  } else if(!memcmp(&stl->facet_start[facet].vertex[1],\n                    &stl->facet_start[facet].vertex[2], sizeof(stl_vertex))) {\n    edge1 = 0;\n    edge2 = 2;\n    edge3 = 1;\n  } else if(!memcmp(&stl->facet_start[facet].vertex[2],\n                    &stl->facet_start[facet].vertex[0], sizeof(stl_vertex))) {\n    edge1 = 0;\n    edge2 = 1;\n    edge3 = 2;\n  } else {\n    /* No degenerate. Function shouldn't have been called. */\n    return;\n  }\n  neighbor1 = stl->neighbors_start[facet].neighbor[edge1];\n  neighbor2 = stl->neighbors_start[facet].neighbor[edge2];\n\n  if(neighbor1 == -1) {\n    stl_update_connects_remove_1(stl, neighbor2);\n  }\n  if(neighbor2 == -1) {\n    stl_update_connects_remove_1(stl, neighbor1);\n  }\n\n\n  neighbor3 = stl->neighbors_start[facet].neighbor[edge3];\n  vnot1 = stl->neighbors_start[facet].which_vertex_not[edge1];\n  vnot2 = stl->neighbors_start[facet].which_vertex_not[edge2];\n  vnot3 = stl->neighbors_start[facet].which_vertex_not[edge3];\n\n  if(neighbor1 != -1){\n    stl->neighbors_start[neighbor1].neighbor[(vnot1 + 1) % 3] = neighbor2;\n    stl->neighbors_start[neighbor1].which_vertex_not[(vnot1 + 1) % 3] = vnot2;\n  }\n  if(neighbor2 != -1){\n    stl->neighbors_start[neighbor2].neighbor[(vnot2 + 1) % 3] = neighbor1;\n    stl->neighbors_start[neighbor2].which_vertex_not[(vnot2 + 1) % 3] = vnot1;\n  }\n\n  stl_remove_facet(stl, facet);\n\n  if(neighbor3 != -1) {\n    stl_update_connects_remove_1(stl, neighbor3);\n    stl->neighbors_start[neighbor3].neighbor[(vnot3 + 1) % 3] = -1;\n  }\n}", "func_hash": 62749783590026466291303120848549680020, "file_name": "connect.c", "file_hash": 88334157411234536587499947341326463538, "cwe": ["CWE-125"], "cve": "CVE-2018-25033", "cve_desc": "ADMesh through 0.98.4 has a heap-based buffer over-read in stl_update_connects_remove_1 (called from stl_remove_degenerate) in connect.c in libadmesh.a.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-25033"}
{"idx": 361303, "project": "admesh", "commit_id": "e84d8353f1347e1f26f0a95770d92ba14e6ede38", "project_url": "https://github.com/admesh/admesh", "commit_url": "https://github.com/admesh/admesh/commit/e84d8353f1347e1f26f0a95770d92ba14e6ede38", "commit_message": "Fix heap buffer overflow in stl_update_connects_remove_1\n\n\n- Add argument value check to the stl_update_connects_remove_1\n- Add neighbor value check in stl_remove_degenerate\n\nFixes https://github.com/admesh/admesh/issues/28\nMerges https://github.com/admesh/admesh/pull/55", "target": 0, "func": "stl_remove_degenerate(stl_file *stl, int facet) {\n  int edge1;\n  int edge2;\n  int edge3;\n  int neighbor1;\n  int neighbor2;\n  int neighbor3;\n  int vnot1;\n  int vnot2;\n  int vnot3;\n\n  if (stl->error) return;\n\n  if(   !memcmp(&stl->facet_start[facet].vertex[0],\n                &stl->facet_start[facet].vertex[1], sizeof(stl_vertex))\n        && !memcmp(&stl->facet_start[facet].vertex[1],\n                   &stl->facet_start[facet].vertex[2], sizeof(stl_vertex))) {\n    /* all 3 vertices are equal.  Just remove the facet.  I don't think*/\n    /* this is really possible, but just in case... */\n    printf(\"removing a facet in stl_remove_degenerate\\n\");\n\n    stl_remove_facet(stl, facet);\n    return;\n  }\n\n  if(!memcmp(&stl->facet_start[facet].vertex[0],\n             &stl->facet_start[facet].vertex[1], sizeof(stl_vertex))) {\n    edge1 = 1;\n    edge2 = 2;\n    edge3 = 0;\n  } else if(!memcmp(&stl->facet_start[facet].vertex[1],\n                    &stl->facet_start[facet].vertex[2], sizeof(stl_vertex))) {\n    edge1 = 0;\n    edge2 = 2;\n    edge3 = 1;\n  } else if(!memcmp(&stl->facet_start[facet].vertex[2],\n                    &stl->facet_start[facet].vertex[0], sizeof(stl_vertex))) {\n    edge1 = 0;\n    edge2 = 1;\n    edge3 = 2;\n  } else {\n    /* No degenerate. Function shouldn't have been called. */\n    return;\n  }\n  neighbor1 = stl->neighbors_start[facet].neighbor[edge1];\n  neighbor2 = stl->neighbors_start[facet].neighbor[edge2];\n\n  if(neighbor1 == -1 && neighbor2 != -1) {\n    stl_update_connects_remove_1(stl, neighbor2);\n  }\n  else if (neighbor2 == -1 && neighbor1 != -1) {\n    stl_update_connects_remove_1(stl, neighbor1);\n  }\n\n  neighbor3 = stl->neighbors_start[facet].neighbor[edge3];\n  vnot1 = stl->neighbors_start[facet].which_vertex_not[edge1];\n  vnot2 = stl->neighbors_start[facet].which_vertex_not[edge2];\n  vnot3 = stl->neighbors_start[facet].which_vertex_not[edge3];\n\n  if(neighbor1 != -1){\n    stl->neighbors_start[neighbor1].neighbor[(vnot1 + 1) % 3] = neighbor2;\n    stl->neighbors_start[neighbor1].which_vertex_not[(vnot1 + 1) % 3] = vnot2;\n  }\n  if(neighbor2 != -1){\n    stl->neighbors_start[neighbor2].neighbor[(vnot2 + 1) % 3] = neighbor1;\n    stl->neighbors_start[neighbor2].which_vertex_not[(vnot2 + 1) % 3] = vnot1;\n  }\n\n  stl_remove_facet(stl, facet);\n\n  if(neighbor3 != -1) {\n    stl_update_connects_remove_1(stl, neighbor3);\n    stl->neighbors_start[neighbor3].neighbor[(vnot3 + 1) % 3] = -1;\n  }\n}", "func_hash": 25155049141523797391201320731237896996, "file_name": "connect.c", "file_hash": 216745481854892780790975730037335372174, "cwe": ["CWE-125"], "cve": "CVE-2018-25033", "cve_desc": "ADMesh through 0.98.4 has a heap-based buffer over-read in stl_update_connects_remove_1 (called from stl_remove_degenerate) in connect.c in libadmesh.a.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-25033"}
{"idx": 204535, "project": "admesh", "commit_id": "e84d8353f1347e1f26f0a95770d92ba14e6ede38", "project_url": "https://github.com/admesh/admesh", "commit_url": "https://github.com/admesh/admesh/commit/e84d8353f1347e1f26f0a95770d92ba14e6ede38", "commit_message": "Fix heap buffer overflow in stl_update_connects_remove_1\n\n\n- Add argument value check to the stl_update_connects_remove_1\n- Add neighbor value check in stl_remove_degenerate\n\nFixes https://github.com/admesh/admesh/issues/28\nMerges https://github.com/admesh/admesh/pull/55", "target": 1, "func": "stl_update_connects_remove_1(stl_file *stl, int facet_num) {\n  int j;\n\n  if (stl->error) return;\n  /* Update list of connected edges */\n  j = ((stl->neighbors_start[facet_num].neighbor[0] == -1) +\n       (stl->neighbors_start[facet_num].neighbor[1] == -1) +\n       (stl->neighbors_start[facet_num].neighbor[2] == -1));\n  if(j == 0) {\t\t       /* Facet has 3 neighbors */\n    stl->stats.connected_facets_3_edge -= 1;\n  } else if(j == 1) {\t     /* Facet has 2 neighbors */\n    stl->stats.connected_facets_2_edge -= 1;\n  } else if(j == 2) {\t     /* Facet has 1 neighbor  */\n    stl->stats.connected_facets_1_edge -= 1;\n  }\n}", "func_hash": 254021536794522665519440114453059072369, "file_name": "connect.c", "file_hash": 88334157411234536587499947341326463538, "cwe": ["CWE-125"], "cve": "CVE-2018-25033", "cve_desc": "ADMesh through 0.98.4 has a heap-based buffer over-read in stl_update_connects_remove_1 (called from stl_remove_degenerate) in connect.c in libadmesh.a.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-25033"}
{"idx": 361298, "project": "admesh", "commit_id": "e84d8353f1347e1f26f0a95770d92ba14e6ede38", "project_url": "https://github.com/admesh/admesh", "commit_url": "https://github.com/admesh/admesh/commit/e84d8353f1347e1f26f0a95770d92ba14e6ede38", "commit_message": "Fix heap buffer overflow in stl_update_connects_remove_1\n\n\n- Add argument value check to the stl_update_connects_remove_1\n- Add neighbor value check in stl_remove_degenerate\n\nFixes https://github.com/admesh/admesh/issues/28\nMerges https://github.com/admesh/admesh/pull/55", "target": 0, "func": "stl_update_connects_remove_1(stl_file *stl, int facet_num) {\n  int j;\n\n  if (\n    stl->error ||\n    facet_num < 0\n  ) return;\n\n  /* Update list of connected edges */\n  j = ((stl->neighbors_start[facet_num].neighbor[0] == -1) +\n       (stl->neighbors_start[facet_num].neighbor[1] == -1) +\n       (stl->neighbors_start[facet_num].neighbor[2] == -1));\n  if(j == 0) {\t\t       /* Facet has 3 neighbors */\n    stl->stats.connected_facets_3_edge -= 1;\n  } else if(j == 1) {\t     /* Facet has 2 neighbors */\n    stl->stats.connected_facets_2_edge -= 1;\n  } else if(j == 2) {\t     /* Facet has 1 neighbor  */\n    stl->stats.connected_facets_1_edge -= 1;\n  }\n}", "func_hash": 169061681318997992993751796896877966474, "file_name": "connect.c", "file_hash": 216745481854892780790975730037335372174, "cwe": ["CWE-125"], "cve": "CVE-2018-25033", "cve_desc": "ADMesh through 0.98.4 has a heap-based buffer over-read in stl_update_connects_remove_1 (called from stl_remove_degenerate) in connect.c in libadmesh.a.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-25033"}
{"idx": 204544, "project": "linux", "commit_id": "c08eadca1bdfa099e20a32f8fa4b52b2f672236d", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=c08eadca1bdfa099e20a32f8fa4b52b2f672236d", "commit_message": "media: em28xx: initialize refcount before kref_get\n\nThe commit 47677e51e2a4(\"[media] em28xx: Only deallocate struct\nem28xx after finishing all extensions\") adds kref_get to many init\nfunctions (e.g., em28xx_audio_init). However, kref_init is called too\nlate in em28xx_usb_probe, since em28xx_init_dev before will invoke\nthose init functions and call kref_get function. Then refcount bug\noccurs in my local syzkaller instance.\n\nFix it by moving kref_init before em28xx_init_dev. This issue occurs\nnot only in dev but also dev->dev_next.\n\nFixes: 47677e51e2a4 (\"[media] em28xx: Only deallocate struct em28xx after finishing all extensions\")\nReported-by: syzkaller \nSigned-off-by: Dongliang Mu \nSigned-off-by: Hans Verkuil ", "target": 1, "func": "static int em28xx_usb_probe(struct usb_interface *intf,\n\t\t\t    const struct usb_device_id *id)\n{\n\tstruct usb_device *udev;\n\tstruct em28xx *dev = NULL;\n\tint retval;\n\tbool has_vendor_audio = false, has_video = false, has_dvb = false;\n\tint i, nr, try_bulk;\n\tconst int ifnum = intf->altsetting[0].desc.bInterfaceNumber;\n\tchar *speed;\n\n\tudev = usb_get_dev(interface_to_usbdev(intf));\n\n\t/* Check to see next free device and mark as used */\n\tdo {\n\t\tnr = find_first_zero_bit(em28xx_devused, EM28XX_MAXBOARDS);\n\t\tif (nr >= EM28XX_MAXBOARDS) {\n\t\t\t/* No free device slots */\n\t\t\tdev_err(&intf->dev,\n\t\t\t\t\"Driver supports up to %i em28xx boards.\\n\",\n\t\t\t       EM28XX_MAXBOARDS);\n\t\t\tretval = -ENOMEM;\n\t\t\tgoto err_no_slot;\n\t\t}\n\t} while (test_and_set_bit(nr, em28xx_devused));\n\n\t/* Don't register audio interfaces */\n\tif (intf->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {\n\t\tdev_info(&intf->dev,\n\t\t\t\"audio device (%04x:%04x): interface %i, class %i\\n\",\n\t\t\tle16_to_cpu(udev->descriptor.idVendor),\n\t\t\tle16_to_cpu(udev->descriptor.idProduct),\n\t\t\tifnum,\n\t\t\tintf->altsetting[0].desc.bInterfaceClass);\n\n\t\tretval = -ENODEV;\n\t\tgoto err;\n\t}\n\n\t/* allocate memory for our device state and initialize it */\n\tdev = kzalloc(sizeof(*dev), GFP_KERNEL);\n\tif (!dev) {\n\t\tretval = -ENOMEM;\n\t\tgoto err;\n\t}\n\n\t/* compute alternate max packet sizes */\n\tdev->alt_max_pkt_size_isoc = kcalloc(intf->num_altsetting,\n\t\t\t\t\t     sizeof(dev->alt_max_pkt_size_isoc[0]),\n\t\t\t\t\t     GFP_KERNEL);\n\tif (!dev->alt_max_pkt_size_isoc) {\n\t\tkfree(dev);\n\t\tretval = -ENOMEM;\n\t\tgoto err;\n\t}\n\n\t/* Get endpoints */\n\tfor (i = 0; i < intf->num_altsetting; i++) {\n\t\tint ep;\n\n\t\tfor (ep = 0;\n\t\t     ep < intf->altsetting[i].desc.bNumEndpoints;\n\t\t     ep++)\n\t\t\tem28xx_check_usb_descriptor(dev, udev, intf,\n\t\t\t\t\t\t    i, ep,\n\t\t\t\t\t\t    &has_vendor_audio,\n\t\t\t\t\t\t    &has_video,\n\t\t\t\t\t\t    &has_dvb);\n\t}\n\n\tif (!(has_vendor_audio || has_video || has_dvb)) {\n\t\tretval = -ENODEV;\n\t\tgoto err_free;\n\t}\n\n\tswitch (udev->speed) {\n\tcase USB_SPEED_LOW:\n\t\tspeed = \"1.5\";\n\t\tbreak;\n\tcase USB_SPEED_UNKNOWN:\n\tcase USB_SPEED_FULL:\n\t\tspeed = \"12\";\n\t\tbreak;\n\tcase USB_SPEED_HIGH:\n\t\tspeed = \"480\";\n\t\tbreak;\n\tdefault:\n\t\tspeed = \"unknown\";\n\t}\n\n\tdev_info(&intf->dev,\n\t\t\"New device %s %s @ %s Mbps (%04x:%04x, interface %d, class %d)\\n\",\n\t\tudev->manufacturer ? udev->manufacturer : \"\",\n\t\tudev->product ? udev->product : \"\",\n\t\tspeed,\n\t\tle16_to_cpu(udev->descriptor.idVendor),\n\t\tle16_to_cpu(udev->descriptor.idProduct),\n\t\tifnum,\n\t\tintf->altsetting->desc.bInterfaceNumber);\n\n\t/*\n\t * Make sure we have 480 Mbps of bandwidth, otherwise things like\n\t * video stream wouldn't likely work, since 12 Mbps is generally\n\t * not enough even for most Digital TV streams.\n\t */\n\tif (udev->speed != USB_SPEED_HIGH && disable_usb_speed_check == 0) {\n\t\tdev_err(&intf->dev, \"Device initialization failed.\\n\");\n\t\tdev_err(&intf->dev,\n\t\t\t\"Device must be connected to a high-speed USB 2.0 port.\\n\");\n\t\tretval = -ENODEV;\n\t\tgoto err_free;\n\t}\n\n\tdev->devno = nr;\n\tdev->model = id->driver_info;\n\tdev->alt   = -1;\n\tdev->is_audio_only = has_vendor_audio && !(has_video || has_dvb);\n\tdev->has_video = has_video;\n\tdev->ifnum = ifnum;\n\n\tdev->ts = PRIMARY_TS;\n\tsnprintf(dev->name, 28, \"em28xx\");\n\tdev->dev_next = NULL;\n\n\tif (has_vendor_audio) {\n\t\tdev_info(&intf->dev,\n\t\t\t\"Audio interface %i found (Vendor Class)\\n\", ifnum);\n\t\tdev->usb_audio_type = EM28XX_USB_AUDIO_VENDOR;\n\t}\n\t/* Checks if audio is provided by a USB Audio Class intf */\n\tfor (i = 0; i < udev->config->desc.bNumInterfaces; i++) {\n\t\tstruct usb_interface *uif = udev->config->interface[i];\n\n\t\tif (uif->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {\n\t\t\tif (has_vendor_audio)\n\t\t\t\tdev_err(&intf->dev,\n\t\t\t\t\t\"em28xx: device seems to have vendor AND usb audio class interfaces !\\n\"\n\t\t\t\t\t\"\\t\\tThe vendor interface will be ignored. Please contact the developers \\n\");\n\t\t\tdev->usb_audio_type = EM28XX_USB_AUDIO_CLASS;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (has_video)\n\t\tdev_info(&intf->dev, \"Video interface %i found:%s%s\\n\",\n\t\t\tifnum,\n\t\t\tdev->analog_ep_bulk ? \" bulk\" : \"\",\n\t\t\tdev->analog_ep_isoc ? \" isoc\" : \"\");\n\tif (has_dvb)\n\t\tdev_info(&intf->dev, \"DVB interface %i found:%s%s\\n\",\n\t\t\tifnum,\n\t\t\tdev->dvb_ep_bulk ? \" bulk\" : \"\",\n\t\t\tdev->dvb_ep_isoc ? \" isoc\" : \"\");\n\n\tdev->num_alt = intf->num_altsetting;\n\n\tif ((unsigned int)card[nr] < em28xx_bcount)\n\t\tdev->model = card[nr];\n\n\t/* save our data pointer in this intf device */\n\tusb_set_intfdata(intf, dev);\n\n\t/* allocate device struct and check if the device is a webcam */\n\tmutex_init(&dev->lock);\n\tretval = em28xx_init_dev(dev, udev, intf, nr);\n\tif (retval)\n\t\tgoto err_free;\n\n\tif (usb_xfer_mode < 0) {\n\t\tif (dev->is_webcam)\n\t\t\ttry_bulk = 1;\n\t\telse\n\t\t\ttry_bulk = 0;\n\t} else {\n\t\ttry_bulk = usb_xfer_mode > 0;\n\t}\n\n\t/* Disable V4L2 if the device doesn't have a decoder or image sensor */\n\tif (has_video &&\n\t    dev->board.decoder == EM28XX_NODECODER &&\n\t    dev->em28xx_sensor == EM28XX_NOSENSOR) {\n\t\tdev_err(&intf->dev,\n\t\t\t\"Currently, V4L2 is not supported on this model\\n\");\n\t\thas_video = false;\n\t\tdev->has_video = false;\n\t}\n\n\tif (dev->board.has_dual_ts &&\n\t    (dev->tuner_type != TUNER_ABSENT || INPUT(0)->type)) {\n\t\t/*\n\t\t * The logic with sets alternate is not ready for dual-tuners\n\t\t * which analog modes.\n\t\t */\n\t\tdev_err(&intf->dev,\n\t\t\t\"We currently don't support analog TV or stream capture on dual tuners.\\n\");\n\t\thas_video = false;\n\t}\n\n\t/* Select USB transfer types to use */\n\tif (has_video) {\n\t\tif (!dev->analog_ep_isoc || (try_bulk && dev->analog_ep_bulk))\n\t\t\tdev->analog_xfer_bulk = 1;\n\t\tdev_info(&intf->dev, \"analog set to %s mode.\\n\",\n\t\t\tdev->analog_xfer_bulk ? \"bulk\" : \"isoc\");\n\t}\n\tif (has_dvb) {\n\t\tif (!dev->dvb_ep_isoc || (try_bulk && dev->dvb_ep_bulk))\n\t\t\tdev->dvb_xfer_bulk = 1;\n\t\tdev_info(&intf->dev, \"dvb set to %s mode.\\n\",\n\t\t\tdev->dvb_xfer_bulk ? \"bulk\" : \"isoc\");\n\t}\n\n\tif (dev->board.has_dual_ts && em28xx_duplicate_dev(dev) == 0) {\n\t\tdev->dev_next->ts = SECONDARY_TS;\n\t\tdev->dev_next->alt   = -1;\n\t\tdev->dev_next->is_audio_only = has_vendor_audio &&\n\t\t\t\t\t\t!(has_video || has_dvb);\n\t\tdev->dev_next->has_video = false;\n\t\tdev->dev_next->ifnum = ifnum;\n\t\tdev->dev_next->model = id->driver_info;\n\n\t\tmutex_init(&dev->dev_next->lock);\n\t\tretval = em28xx_init_dev(dev->dev_next, udev, intf,\n\t\t\t\t\t dev->dev_next->devno);\n\t\tif (retval)\n\t\t\tgoto err_free;\n\n\t\tdev->dev_next->board.ir_codes = NULL; /* No IR for 2nd tuner */\n\t\tdev->dev_next->board.has_ir_i2c = 0; /* No IR for 2nd tuner */\n\n\t\tif (usb_xfer_mode < 0) {\n\t\t\tif (dev->dev_next->is_webcam)\n\t\t\t\ttry_bulk = 1;\n\t\t\telse\n\t\t\t\ttry_bulk = 0;\n\t\t} else {\n\t\t\ttry_bulk = usb_xfer_mode > 0;\n\t\t}\n\n\t\t/* Select USB transfer types to use */\n\t\tif (has_dvb) {\n\t\t\tif (!dev->dvb_ep_isoc_ts2 ||\n\t\t\t    (try_bulk && dev->dvb_ep_bulk_ts2))\n\t\t\t\tdev->dev_next->dvb_xfer_bulk = 1;\n\t\t\tdev_info(&dev->intf->dev, \"dvb ts2 set to %s mode.\\n\",\n\t\t\t\t dev->dev_next->dvb_xfer_bulk ? \"bulk\" : \"isoc\");\n\t\t}\n\n\t\tdev->dev_next->dvb_ep_isoc = dev->dvb_ep_isoc_ts2;\n\t\tdev->dev_next->dvb_ep_bulk = dev->dvb_ep_bulk_ts2;\n\t\tdev->dev_next->dvb_max_pkt_size_isoc = dev->dvb_max_pkt_size_isoc_ts2;\n\t\tdev->dev_next->dvb_alt_isoc = dev->dvb_alt_isoc;\n\n\t\t/* Configure hardware to support TS2*/\n\t\tif (dev->dvb_xfer_bulk) {\n\t\t\t/* The ep4 and ep5 are configured for BULK */\n\t\t\tem28xx_write_reg(dev, 0x0b, 0x96);\n\t\t\tmdelay(100);\n\t\t\tem28xx_write_reg(dev, 0x0b, 0x80);\n\t\t\tmdelay(100);\n\t\t} else {\n\t\t\t/* The ep4 and ep5 are configured for ISO */\n\t\t\tem28xx_write_reg(dev, 0x0b, 0x96);\n\t\t\tmdelay(100);\n\t\t\tem28xx_write_reg(dev, 0x0b, 0x82);\n\t\t\tmdelay(100);\n\t\t}\n\n\t\tkref_init(&dev->dev_next->ref);\n\t}\n\n\tkref_init(&dev->ref);\n\n\trequest_modules(dev);\n\n\t/*\n\t * Do it at the end, to reduce dynamic configuration changes during\n\t * the device init. Yet, as request_modules() can be async, the\n\t * topology will likely change after the load of the em28xx subdrivers.\n\t */\n#ifdef CONFIG_MEDIA_CONTROLLER\n\tretval = media_device_register(dev->media_dev);\n#endif\n\n\treturn 0;\n\nerr_free:\n\tkfree(dev->alt_max_pkt_size_isoc);\n\tkfree(dev);\n\nerr:\n\tclear_bit(nr, em28xx_devused);\n\nerr_no_slot:\n\tusb_put_dev(udev);\n\treturn retval;\n}", "func_hash": 76668846820258934149802408473302303407, "file_name": "em28xx-cards.c", "file_hash": 309061862626800090542744203029600987742, "cwe": ["CWE-416"], "cve": "CVE-2022-3239", "cve_desc": "A flaw use after free in the Linux kernel video4linux driver was found in the way user triggers em28xx_usb_probe() for the Empia 28xx based TV cards. A local user could use this flaw to crash the system or potentially escalate their privileges on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3239"}
{"idx": 361755, "project": "linux", "commit_id": "c08eadca1bdfa099e20a32f8fa4b52b2f672236d", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=c08eadca1bdfa099e20a32f8fa4b52b2f672236d", "commit_message": "media: em28xx: initialize refcount before kref_get\n\nThe commit 47677e51e2a4(\"[media] em28xx: Only deallocate struct\nem28xx after finishing all extensions\") adds kref_get to many init\nfunctions (e.g., em28xx_audio_init). However, kref_init is called too\nlate in em28xx_usb_probe, since em28xx_init_dev before will invoke\nthose init functions and call kref_get function. Then refcount bug\noccurs in my local syzkaller instance.\n\nFix it by moving kref_init before em28xx_init_dev. This issue occurs\nnot only in dev but also dev->dev_next.\n\nFixes: 47677e51e2a4 (\"[media] em28xx: Only deallocate struct em28xx after finishing all extensions\")\nReported-by: syzkaller \nSigned-off-by: Dongliang Mu \nSigned-off-by: Hans Verkuil ", "target": 0, "func": "static int em28xx_usb_probe(struct usb_interface *intf,\n\t\t\t    const struct usb_device_id *id)\n{\n\tstruct usb_device *udev;\n\tstruct em28xx *dev = NULL;\n\tint retval;\n\tbool has_vendor_audio = false, has_video = false, has_dvb = false;\n\tint i, nr, try_bulk;\n\tconst int ifnum = intf->altsetting[0].desc.bInterfaceNumber;\n\tchar *speed;\n\n\tudev = usb_get_dev(interface_to_usbdev(intf));\n\n\t/* Check to see next free device and mark as used */\n\tdo {\n\t\tnr = find_first_zero_bit(em28xx_devused, EM28XX_MAXBOARDS);\n\t\tif (nr >= EM28XX_MAXBOARDS) {\n\t\t\t/* No free device slots */\n\t\t\tdev_err(&intf->dev,\n\t\t\t\t\"Driver supports up to %i em28xx boards.\\n\",\n\t\t\t       EM28XX_MAXBOARDS);\n\t\t\tretval = -ENOMEM;\n\t\t\tgoto err_no_slot;\n\t\t}\n\t} while (test_and_set_bit(nr, em28xx_devused));\n\n\t/* Don't register audio interfaces */\n\tif (intf->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {\n\t\tdev_info(&intf->dev,\n\t\t\t\"audio device (%04x:%04x): interface %i, class %i\\n\",\n\t\t\tle16_to_cpu(udev->descriptor.idVendor),\n\t\t\tle16_to_cpu(udev->descriptor.idProduct),\n\t\t\tifnum,\n\t\t\tintf->altsetting[0].desc.bInterfaceClass);\n\n\t\tretval = -ENODEV;\n\t\tgoto err;\n\t}\n\n\t/* allocate memory for our device state and initialize it */\n\tdev = kzalloc(sizeof(*dev), GFP_KERNEL);\n\tif (!dev) {\n\t\tretval = -ENOMEM;\n\t\tgoto err;\n\t}\n\n\t/* compute alternate max packet sizes */\n\tdev->alt_max_pkt_size_isoc = kcalloc(intf->num_altsetting,\n\t\t\t\t\t     sizeof(dev->alt_max_pkt_size_isoc[0]),\n\t\t\t\t\t     GFP_KERNEL);\n\tif (!dev->alt_max_pkt_size_isoc) {\n\t\tkfree(dev);\n\t\tretval = -ENOMEM;\n\t\tgoto err;\n\t}\n\n\t/* Get endpoints */\n\tfor (i = 0; i < intf->num_altsetting; i++) {\n\t\tint ep;\n\n\t\tfor (ep = 0;\n\t\t     ep < intf->altsetting[i].desc.bNumEndpoints;\n\t\t     ep++)\n\t\t\tem28xx_check_usb_descriptor(dev, udev, intf,\n\t\t\t\t\t\t    i, ep,\n\t\t\t\t\t\t    &has_vendor_audio,\n\t\t\t\t\t\t    &has_video,\n\t\t\t\t\t\t    &has_dvb);\n\t}\n\n\tif (!(has_vendor_audio || has_video || has_dvb)) {\n\t\tretval = -ENODEV;\n\t\tgoto err_free;\n\t}\n\n\tswitch (udev->speed) {\n\tcase USB_SPEED_LOW:\n\t\tspeed = \"1.5\";\n\t\tbreak;\n\tcase USB_SPEED_UNKNOWN:\n\tcase USB_SPEED_FULL:\n\t\tspeed = \"12\";\n\t\tbreak;\n\tcase USB_SPEED_HIGH:\n\t\tspeed = \"480\";\n\t\tbreak;\n\tdefault:\n\t\tspeed = \"unknown\";\n\t}\n\n\tdev_info(&intf->dev,\n\t\t\"New device %s %s @ %s Mbps (%04x:%04x, interface %d, class %d)\\n\",\n\t\tudev->manufacturer ? udev->manufacturer : \"\",\n\t\tudev->product ? udev->product : \"\",\n\t\tspeed,\n\t\tle16_to_cpu(udev->descriptor.idVendor),\n\t\tle16_to_cpu(udev->descriptor.idProduct),\n\t\tifnum,\n\t\tintf->altsetting->desc.bInterfaceNumber);\n\n\t/*\n\t * Make sure we have 480 Mbps of bandwidth, otherwise things like\n\t * video stream wouldn't likely work, since 12 Mbps is generally\n\t * not enough even for most Digital TV streams.\n\t */\n\tif (udev->speed != USB_SPEED_HIGH && disable_usb_speed_check == 0) {\n\t\tdev_err(&intf->dev, \"Device initialization failed.\\n\");\n\t\tdev_err(&intf->dev,\n\t\t\t\"Device must be connected to a high-speed USB 2.0 port.\\n\");\n\t\tretval = -ENODEV;\n\t\tgoto err_free;\n\t}\n\n\tkref_init(&dev->ref);\n\n\tdev->devno = nr;\n\tdev->model = id->driver_info;\n\tdev->alt   = -1;\n\tdev->is_audio_only = has_vendor_audio && !(has_video || has_dvb);\n\tdev->has_video = has_video;\n\tdev->ifnum = ifnum;\n\n\tdev->ts = PRIMARY_TS;\n\tsnprintf(dev->name, 28, \"em28xx\");\n\tdev->dev_next = NULL;\n\n\tif (has_vendor_audio) {\n\t\tdev_info(&intf->dev,\n\t\t\t\"Audio interface %i found (Vendor Class)\\n\", ifnum);\n\t\tdev->usb_audio_type = EM28XX_USB_AUDIO_VENDOR;\n\t}\n\t/* Checks if audio is provided by a USB Audio Class intf */\n\tfor (i = 0; i < udev->config->desc.bNumInterfaces; i++) {\n\t\tstruct usb_interface *uif = udev->config->interface[i];\n\n\t\tif (uif->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {\n\t\t\tif (has_vendor_audio)\n\t\t\t\tdev_err(&intf->dev,\n\t\t\t\t\t\"em28xx: device seems to have vendor AND usb audio class interfaces !\\n\"\n\t\t\t\t\t\"\\t\\tThe vendor interface will be ignored. Please contact the developers \\n\");\n\t\t\tdev->usb_audio_type = EM28XX_USB_AUDIO_CLASS;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (has_video)\n\t\tdev_info(&intf->dev, \"Video interface %i found:%s%s\\n\",\n\t\t\tifnum,\n\t\t\tdev->analog_ep_bulk ? \" bulk\" : \"\",\n\t\t\tdev->analog_ep_isoc ? \" isoc\" : \"\");\n\tif (has_dvb)\n\t\tdev_info(&intf->dev, \"DVB interface %i found:%s%s\\n\",\n\t\t\tifnum,\n\t\t\tdev->dvb_ep_bulk ? \" bulk\" : \"\",\n\t\t\tdev->dvb_ep_isoc ? \" isoc\" : \"\");\n\n\tdev->num_alt = intf->num_altsetting;\n\n\tif ((unsigned int)card[nr] < em28xx_bcount)\n\t\tdev->model = card[nr];\n\n\t/* save our data pointer in this intf device */\n\tusb_set_intfdata(intf, dev);\n\n\t/* allocate device struct and check if the device is a webcam */\n\tmutex_init(&dev->lock);\n\tretval = em28xx_init_dev(dev, udev, intf, nr);\n\tif (retval)\n\t\tgoto err_free;\n\n\tif (usb_xfer_mode < 0) {\n\t\tif (dev->is_webcam)\n\t\t\ttry_bulk = 1;\n\t\telse\n\t\t\ttry_bulk = 0;\n\t} else {\n\t\ttry_bulk = usb_xfer_mode > 0;\n\t}\n\n\t/* Disable V4L2 if the device doesn't have a decoder or image sensor */\n\tif (has_video &&\n\t    dev->board.decoder == EM28XX_NODECODER &&\n\t    dev->em28xx_sensor == EM28XX_NOSENSOR) {\n\t\tdev_err(&intf->dev,\n\t\t\t\"Currently, V4L2 is not supported on this model\\n\");\n\t\thas_video = false;\n\t\tdev->has_video = false;\n\t}\n\n\tif (dev->board.has_dual_ts &&\n\t    (dev->tuner_type != TUNER_ABSENT || INPUT(0)->type)) {\n\t\t/*\n\t\t * The logic with sets alternate is not ready for dual-tuners\n\t\t * which analog modes.\n\t\t */\n\t\tdev_err(&intf->dev,\n\t\t\t\"We currently don't support analog TV or stream capture on dual tuners.\\n\");\n\t\thas_video = false;\n\t}\n\n\t/* Select USB transfer types to use */\n\tif (has_video) {\n\t\tif (!dev->analog_ep_isoc || (try_bulk && dev->analog_ep_bulk))\n\t\t\tdev->analog_xfer_bulk = 1;\n\t\tdev_info(&intf->dev, \"analog set to %s mode.\\n\",\n\t\t\tdev->analog_xfer_bulk ? \"bulk\" : \"isoc\");\n\t}\n\tif (has_dvb) {\n\t\tif (!dev->dvb_ep_isoc || (try_bulk && dev->dvb_ep_bulk))\n\t\t\tdev->dvb_xfer_bulk = 1;\n\t\tdev_info(&intf->dev, \"dvb set to %s mode.\\n\",\n\t\t\tdev->dvb_xfer_bulk ? \"bulk\" : \"isoc\");\n\t}\n\n\tif (dev->board.has_dual_ts && em28xx_duplicate_dev(dev) == 0) {\n\t\tkref_init(&dev->dev_next->ref);\n\n\t\tdev->dev_next->ts = SECONDARY_TS;\n\t\tdev->dev_next->alt   = -1;\n\t\tdev->dev_next->is_audio_only = has_vendor_audio &&\n\t\t\t\t\t\t!(has_video || has_dvb);\n\t\tdev->dev_next->has_video = false;\n\t\tdev->dev_next->ifnum = ifnum;\n\t\tdev->dev_next->model = id->driver_info;\n\n\t\tmutex_init(&dev->dev_next->lock);\n\t\tretval = em28xx_init_dev(dev->dev_next, udev, intf,\n\t\t\t\t\t dev->dev_next->devno);\n\t\tif (retval)\n\t\t\tgoto err_free;\n\n\t\tdev->dev_next->board.ir_codes = NULL; /* No IR for 2nd tuner */\n\t\tdev->dev_next->board.has_ir_i2c = 0; /* No IR for 2nd tuner */\n\n\t\tif (usb_xfer_mode < 0) {\n\t\t\tif (dev->dev_next->is_webcam)\n\t\t\t\ttry_bulk = 1;\n\t\t\telse\n\t\t\t\ttry_bulk = 0;\n\t\t} else {\n\t\t\ttry_bulk = usb_xfer_mode > 0;\n\t\t}\n\n\t\t/* Select USB transfer types to use */\n\t\tif (has_dvb) {\n\t\t\tif (!dev->dvb_ep_isoc_ts2 ||\n\t\t\t    (try_bulk && dev->dvb_ep_bulk_ts2))\n\t\t\t\tdev->dev_next->dvb_xfer_bulk = 1;\n\t\t\tdev_info(&dev->intf->dev, \"dvb ts2 set to %s mode.\\n\",\n\t\t\t\t dev->dev_next->dvb_xfer_bulk ? \"bulk\" : \"isoc\");\n\t\t}\n\n\t\tdev->dev_next->dvb_ep_isoc = dev->dvb_ep_isoc_ts2;\n\t\tdev->dev_next->dvb_ep_bulk = dev->dvb_ep_bulk_ts2;\n\t\tdev->dev_next->dvb_max_pkt_size_isoc = dev->dvb_max_pkt_size_isoc_ts2;\n\t\tdev->dev_next->dvb_alt_isoc = dev->dvb_alt_isoc;\n\n\t\t/* Configure hardware to support TS2*/\n\t\tif (dev->dvb_xfer_bulk) {\n\t\t\t/* The ep4 and ep5 are configured for BULK */\n\t\t\tem28xx_write_reg(dev, 0x0b, 0x96);\n\t\t\tmdelay(100);\n\t\t\tem28xx_write_reg(dev, 0x0b, 0x80);\n\t\t\tmdelay(100);\n\t\t} else {\n\t\t\t/* The ep4 and ep5 are configured for ISO */\n\t\t\tem28xx_write_reg(dev, 0x0b, 0x96);\n\t\t\tmdelay(100);\n\t\t\tem28xx_write_reg(dev, 0x0b, 0x82);\n\t\t\tmdelay(100);\n\t\t}\n\t}\n\n\trequest_modules(dev);\n\n\t/*\n\t * Do it at the end, to reduce dynamic configuration changes during\n\t * the device init. Yet, as request_modules() can be async, the\n\t * topology will likely change after the load of the em28xx subdrivers.\n\t */\n#ifdef CONFIG_MEDIA_CONTROLLER\n\tretval = media_device_register(dev->media_dev);\n#endif\n\n\treturn 0;\n\nerr_free:\n\tkfree(dev->alt_max_pkt_size_isoc);\n\tkfree(dev);\n\nerr:\n\tclear_bit(nr, em28xx_devused);\n\nerr_no_slot:\n\tusb_put_dev(udev);\n\treturn retval;\n}", "func_hash": 34268190257933110062727844673317729884, "file_name": "em28xx-cards.c", "file_hash": 107764567079866010944769027860344599929, "cwe": ["CWE-416"], "cve": "CVE-2022-3239", "cve_desc": "A flaw use after free in the Linux kernel video4linux driver was found in the way user triggers em28xx_usb_probe() for the Empia 28xx based TV cards. A local user could use this flaw to crash the system or potentially escalate their privileges on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3239"}
{"idx": 204814, "project": "linux", "commit_id": "efe4186e6a1b54bf38b9e05450d43b0da1fd7739", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/efe4186e6a1b54bf38b9e05450d43b0da1fd7739", "commit_message": "drivers: hamradio: 6pack: fix UAF bug caused by mod_timer()\n\nWhen a 6pack device is detaching, the sixpack_close() will act to cleanup\nnecessary resources. Although del_timer_sync() in sixpack_close()\nwon't return if there is an active timer, one could use mod_timer() in\nsp_xmit_on_air() to wake up timer again by calling userspace syscall such\nas ax25_sendmsg(), ax25_connect() and ax25_ioctl().\n\nThis unexpected waked handler, sp_xmit_on_air(), realizes nothing about\nthe undergoing cleanup and may still call pty_write() to use driver layer\nresources that have already been released.\n\nOne of the possible race conditions is shown below:\n\n      (USE)                      |      (FREE)\nax25_sendmsg()                   |\n ax25_queue_xmit()               |\n  ...                            |\n  sp_xmit()                      |\n   sp_encaps()                   | sixpack_close()\n    sp_xmit_on_air()             |  del_timer_sync(&sp->tx_t)\n     mod_timer(&sp->tx_t,...)    |  ...\n                                 |  unregister_netdev()\n                                 |  ...\n     (wait a while)              | tty_release()\n                                 |  tty_release_struct()\n                                 |   release_tty()\n    sp_xmit_on_air()             |    tty_kref_put(tty_struct) //FREE\n     pty_write(tty_struct) //USE |    ...\n\nThe corresponding fail log is shown below:\n===============================================================\nBUG: KASAN: use-after-free in __run_timers.part.0+0x170/0x470\nWrite of size 8 at addr ffff88800a652ab8 by task swapper/2/0\n...\nCall Trace:\n  ...\n  queue_work_on+0x3f/0x50\n  pty_write+0xcd/0xe0pty_write+0xcd/0xe0\n  sp_xmit_on_air+0xb2/0x1f0\n  call_timer_fn+0x28/0x150\n  __run_timers.part.0+0x3c2/0x470\n  run_timer_softirq+0x3b/0x80\n  __do_softirq+0xf1/0x380\n  ...\n\nThis patch reorders the del_timer_sync() after the unregister_netdev()\nto avoid UAF bugs. Because the unregister_netdev() is well synchronized,\nit flushs out any pending queues, waits the refcount of net_device\ndecreases to zero and removes net_device from kernel. There is not any\nrunning routines after executing unregister_netdev(). Therefore, we could\nnot arouse timer from userspace again.\n\nSigned-off-by: Duoming Zhou \nReviewed-by: Lin Ma \nSigned-off-by: David S. Miller ", "target": 1, "func": "static void sixpack_close(struct tty_struct *tty)\n{\n\tstruct sixpack *sp;\n\n\twrite_lock_irq(&disc_data_lock);\n\tsp = tty->disc_data;\n\ttty->disc_data = NULL;\n\twrite_unlock_irq(&disc_data_lock);\n\tif (!sp)\n\t\treturn;\n\n\t/*\n\t * We have now ensured that nobody can start using ap from now on, but\n\t * we have to wait for all existing users to finish.\n\t */\n\tif (!refcount_dec_and_test(&sp->refcnt))\n\t\twait_for_completion(&sp->dead);\n\n\t/* We must stop the queue to avoid potentially scribbling\n\t * on the free buffers. The sp->dead completion is not sufficient\n\t * to protect us from sp->xbuff access.\n\t */\n\tnetif_stop_queue(sp->dev);\n\n\tdel_timer_sync(&sp->tx_t);\n\tdel_timer_sync(&sp->resync_t);\n\n\tunregister_netdev(sp->dev);\n\n\t/* Free all 6pack frame buffers after unreg. */\n\tkfree(sp->rbuff);\n\tkfree(sp->xbuff);\n\n\tfree_netdev(sp->dev);\n}", "func_hash": 162259032331314568256565537664821735227, "file_name": "None", "file_hash": null, "cwe": ["CWE-703"], "cve": "CVE-2022-1198", "cve_desc": "A use-after-free vulnerabilitity was discovered in drivers/net/hamradio/6pack.c of linux that allows an attacker to crash linux kernel by simulating ax25 device using 6pack driver from user space.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1198"}
{"idx": 365760, "project": "linux", "commit_id": "efe4186e6a1b54bf38b9e05450d43b0da1fd7739", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/efe4186e6a1b54bf38b9e05450d43b0da1fd7739", "commit_message": "drivers: hamradio: 6pack: fix UAF bug caused by mod_timer()\n\nWhen a 6pack device is detaching, the sixpack_close() will act to cleanup\nnecessary resources. Although del_timer_sync() in sixpack_close()\nwon't return if there is an active timer, one could use mod_timer() in\nsp_xmit_on_air() to wake up timer again by calling userspace syscall such\nas ax25_sendmsg(), ax25_connect() and ax25_ioctl().\n\nThis unexpected waked handler, sp_xmit_on_air(), realizes nothing about\nthe undergoing cleanup and may still call pty_write() to use driver layer\nresources that have already been released.\n\nOne of the possible race conditions is shown below:\n\n      (USE)                      |      (FREE)\nax25_sendmsg()                   |\n ax25_queue_xmit()               |\n  ...                            |\n  sp_xmit()                      |\n   sp_encaps()                   | sixpack_close()\n    sp_xmit_on_air()             |  del_timer_sync(&sp->tx_t)\n     mod_timer(&sp->tx_t,...)    |  ...\n                                 |  unregister_netdev()\n                                 |  ...\n     (wait a while)              | tty_release()\n                                 |  tty_release_struct()\n                                 |   release_tty()\n    sp_xmit_on_air()             |    tty_kref_put(tty_struct) //FREE\n     pty_write(tty_struct) //USE |    ...\n\nThe corresponding fail log is shown below:\n===============================================================\nBUG: KASAN: use-after-free in __run_timers.part.0+0x170/0x470\nWrite of size 8 at addr ffff88800a652ab8 by task swapper/2/0\n...\nCall Trace:\n  ...\n  queue_work_on+0x3f/0x50\n  pty_write+0xcd/0xe0pty_write+0xcd/0xe0\n  sp_xmit_on_air+0xb2/0x1f0\n  call_timer_fn+0x28/0x150\n  __run_timers.part.0+0x3c2/0x470\n  run_timer_softirq+0x3b/0x80\n  __do_softirq+0xf1/0x380\n  ...\n\nThis patch reorders the del_timer_sync() after the unregister_netdev()\nto avoid UAF bugs. Because the unregister_netdev() is well synchronized,\nit flushs out any pending queues, waits the refcount of net_device\ndecreases to zero and removes net_device from kernel. There is not any\nrunning routines after executing unregister_netdev(). Therefore, we could\nnot arouse timer from userspace again.\n\nSigned-off-by: Duoming Zhou \nReviewed-by: Lin Ma \nSigned-off-by: David S. Miller ", "target": 0, "func": "static void sixpack_close(struct tty_struct *tty)\n{\n\tstruct sixpack *sp;\n\n\twrite_lock_irq(&disc_data_lock);\n\tsp = tty->disc_data;\n\ttty->disc_data = NULL;\n\twrite_unlock_irq(&disc_data_lock);\n\tif (!sp)\n\t\treturn;\n\n\t/*\n\t * We have now ensured that nobody can start using ap from now on, but\n\t * we have to wait for all existing users to finish.\n\t */\n\tif (!refcount_dec_and_test(&sp->refcnt))\n\t\twait_for_completion(&sp->dead);\n\n\t/* We must stop the queue to avoid potentially scribbling\n\t * on the free buffers. The sp->dead completion is not sufficient\n\t * to protect us from sp->xbuff access.\n\t */\n\tnetif_stop_queue(sp->dev);\n\n\tunregister_netdev(sp->dev);\n\n\tdel_timer_sync(&sp->tx_t);\n\tdel_timer_sync(&sp->resync_t);\n\n\t/* Free all 6pack frame buffers after unreg. */\n\tkfree(sp->rbuff);\n\tkfree(sp->xbuff);\n\n\tfree_netdev(sp->dev);\n}", "func_hash": 179190846282520948095757872677047237728, "file_name": "None", "file_hash": null, "cwe": ["CWE-703"], "cve": "CVE-2022-1198", "cve_desc": "A use-after-free vulnerabilitity was discovered in drivers/net/hamradio/6pack.c of linux that allows an attacker to crash linux kernel by simulating ax25 device using 6pack driver from user space.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1198"}
{"idx": 204830, "project": "linux", "commit_id": "427215d85e8d1476da1a86b8d67aceb485eb3631", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/427215d85e8d1476da1a86b8d67aceb485eb3631", "commit_message": "ovl: prevent private clone if bind mount is not allowed\n\nAdd the following checks from __do_loopback() to clone_private_mount() as\nwell:\n\n - verify that the mount is in the current namespace\n\n - verify that there are no locked children\n\nReported-by: Alois Wohlschlager \nFixes: c771d683a62e (\"vfs: introduce clone_private_mount()\")\nCc:  # v3.18\nSigned-off-by: Miklos Szeredi ", "target": 1, "func": "struct vfsmount *clone_private_mount(const struct path *path)\n{\n\tstruct mount *old_mnt = real_mount(path->mnt);\n\tstruct mount *new_mnt;\n\n\tif (IS_MNT_UNBINDABLE(old_mnt))\n\t\treturn ERR_PTR(-EINVAL);\n\n\tnew_mnt = clone_mnt(old_mnt, path->dentry, CL_PRIVATE);\n\tif (IS_ERR(new_mnt))\n\t\treturn ERR_CAST(new_mnt);\n\n\t/* Longterm mount to be removed by kern_unmount*() */\n\tnew_mnt->mnt_ns = MNT_NS_INTERNAL;\n\n\treturn &new_mnt->mnt;\n}", "func_hash": 260474936923487005378622883442342647421, "file_name": "namespace.c", "file_hash": 336414911625449496230254298040232985694, "cwe": ["CWE-200"], "cve": "CVE-2021-3732", "cve_desc": "A flaw was found in the Linux kernel's OverlayFS subsystem in the way the user mounts the TmpFS filesystem with OverlayFS. This flaw allows a local user to gain access to hidden files that should not be accessible.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3732"}
{"idx": 366223, "project": "linux", "commit_id": "427215d85e8d1476da1a86b8d67aceb485eb3631", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/427215d85e8d1476da1a86b8d67aceb485eb3631", "commit_message": "ovl: prevent private clone if bind mount is not allowed\n\nAdd the following checks from __do_loopback() to clone_private_mount() as\nwell:\n\n - verify that the mount is in the current namespace\n\n - verify that there are no locked children\n\nReported-by: Alois Wohlschlager \nFixes: c771d683a62e (\"vfs: introduce clone_private_mount()\")\nCc:  # v3.18\nSigned-off-by: Miklos Szeredi ", "target": 0, "func": "struct vfsmount *clone_private_mount(const struct path *path)\n{\n\tstruct mount *old_mnt = real_mount(path->mnt);\n\tstruct mount *new_mnt;\n\n\tdown_read(&namespace_sem);\n\tif (IS_MNT_UNBINDABLE(old_mnt))\n\t\tgoto invalid;\n\n\tif (!check_mnt(old_mnt))\n\t\tgoto invalid;\n\n\tif (has_locked_children(old_mnt, path->dentry))\n\t\tgoto invalid;\n\n\tnew_mnt = clone_mnt(old_mnt, path->dentry, CL_PRIVATE);\n\tup_read(&namespace_sem);\n\n\tif (IS_ERR(new_mnt))\n\t\treturn ERR_CAST(new_mnt);\n\n\t/* Longterm mount to be removed by kern_unmount*() */\n\tnew_mnt->mnt_ns = MNT_NS_INTERNAL;\n\n\treturn &new_mnt->mnt;\n\ninvalid:\n\tup_read(&namespace_sem);\n\treturn ERR_PTR(-EINVAL);\n}", "func_hash": 181653158150363696384647639482948263222, "file_name": "namespace.c", "file_hash": 152664695598789977004881235289769073267, "cwe": ["CWE-200"], "cve": "CVE-2021-3732", "cve_desc": "A flaw was found in the Linux kernel's OverlayFS subsystem in the way the user mounts the TmpFS filesystem with OverlayFS. This flaw allows a local user to gain access to hidden files that should not be accessible.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3732"}
{"idx": 205630, "project": "linux", "commit_id": "32452a3eb8b64e01e2be717f518c0be046975b9d", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/32452a3eb8b64e01e2be717f518c0be046975b9d", "commit_message": "io_uring: fix uninitialized field in rw io_kiocb\n\nio_rw_init_file does not initialize kiocb->private, so when iocb_bio_iopoll\nreads kiocb->private it can contain uninitialized data.\n\nFixes: 3e08773c3841 (\"block: switch polling to be bio based\")\nSigned-off-by: Joseph Ravichandran \nSigned-off-by: Jens Axboe ", "target": 1, "func": "static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)\n{\n\tstruct kiocb *kiocb = &req->rw.kiocb;\n\tstruct io_ring_ctx *ctx = req->ctx;\n\tstruct file *file = req->file;\n\tint ret;\n\n\tif (unlikely(!file || !(file->f_mode & mode)))\n\t\treturn -EBADF;\n\n\tif (!io_req_ffs_set(req))\n\t\treq->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;\n\n\tkiocb->ki_flags = iocb_flags(file);\n\tret = kiocb_set_rw_flags(kiocb, req->rw.flags);\n\tif (unlikely(ret))\n\t\treturn ret;\n\n\t/*\n\t * If the file is marked O_NONBLOCK, still allow retry for it if it\n\t * supports async. Otherwise it's impossible to use O_NONBLOCK files\n\t * reliably. If not, or it IOCB_NOWAIT is set, don't retry.\n\t */\n\tif ((kiocb->ki_flags & IOCB_NOWAIT) ||\n\t    ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))\n\t\treq->flags |= REQ_F_NOWAIT;\n\n\tif (ctx->flags & IORING_SETUP_IOPOLL) {\n\t\tif (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)\n\t\t\treturn -EOPNOTSUPP;\n\n\t\tkiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;\n\t\tkiocb->ki_complete = io_complete_rw_iopoll;\n\t\treq->iopoll_completed = 0;\n\t} else {\n\t\tif (kiocb->ki_flags & IOCB_HIPRI)\n\t\t\treturn -EINVAL;\n\t\tkiocb->ki_complete = io_complete_rw;\n\t}\n\n\treturn 0;\n}", "func_hash": 85149610434779656690730201934331639704, "file_name": "io_uring.c", "file_hash": 148301731450961138992553369142373286456, "cwe": ["CWE-94"], "cve": "CVE-2022-29968", "cve_desc": "An issue was discovered in the Linux kernel through 5.17.5. io_rw_init_file in fs/io_uring.c lacks initialization of kiocb->private.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29968"}
{"idx": 369215, "project": "linux", "commit_id": "32452a3eb8b64e01e2be717f518c0be046975b9d", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/32452a3eb8b64e01e2be717f518c0be046975b9d", "commit_message": "io_uring: fix uninitialized field in rw io_kiocb\n\nio_rw_init_file does not initialize kiocb->private, so when iocb_bio_iopoll\nreads kiocb->private it can contain uninitialized data.\n\nFixes: 3e08773c3841 (\"block: switch polling to be bio based\")\nSigned-off-by: Joseph Ravichandran \nSigned-off-by: Jens Axboe ", "target": 0, "func": "static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)\n{\n\tstruct kiocb *kiocb = &req->rw.kiocb;\n\tstruct io_ring_ctx *ctx = req->ctx;\n\tstruct file *file = req->file;\n\tint ret;\n\n\tif (unlikely(!file || !(file->f_mode & mode)))\n\t\treturn -EBADF;\n\n\tif (!io_req_ffs_set(req))\n\t\treq->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;\n\n\tkiocb->ki_flags = iocb_flags(file);\n\tret = kiocb_set_rw_flags(kiocb, req->rw.flags);\n\tif (unlikely(ret))\n\t\treturn ret;\n\n\t/*\n\t * If the file is marked O_NONBLOCK, still allow retry for it if it\n\t * supports async. Otherwise it's impossible to use O_NONBLOCK files\n\t * reliably. If not, or it IOCB_NOWAIT is set, don't retry.\n\t */\n\tif ((kiocb->ki_flags & IOCB_NOWAIT) ||\n\t    ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))\n\t\treq->flags |= REQ_F_NOWAIT;\n\n\tif (ctx->flags & IORING_SETUP_IOPOLL) {\n\t\tif (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)\n\t\t\treturn -EOPNOTSUPP;\n\n\t\tkiocb->private = NULL;\n\t\tkiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;\n\t\tkiocb->ki_complete = io_complete_rw_iopoll;\n\t\treq->iopoll_completed = 0;\n\t} else {\n\t\tif (kiocb->ki_flags & IOCB_HIPRI)\n\t\t\treturn -EINVAL;\n\t\tkiocb->ki_complete = io_complete_rw;\n\t}\n\n\treturn 0;\n}", "func_hash": 263180021211529326245362863666357731272, "file_name": "io_uring.c", "file_hash": 302939069770693315001046423619225683925, "cwe": ["CWE-94"], "cve": "CVE-2022-29968", "cve_desc": "An issue was discovered in the Linux kernel through 5.17.5. io_rw_init_file in fs/io_uring.c lacks initialization of kiocb->private.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29968"}
{"idx": 205734, "project": "rizin", "commit_id": "38d8006cd609ac75de82b705891d3508d2c218d5", "project_url": "https://github.com/rizinorg/rizin", "commit_url": "https://github.com/rizinorg/rizin/commit/38d8006cd609ac75de82b705891d3508d2c218d5", "commit_message": "fix #2963 - oob write (1 byte) in pyc/marshal.c", "target": 1, "func": "static pyc_object *get_complex_object(RzBinPycObj *pyc, RzBuffer *buffer) {\n\tpyc_object *ret = NULL;\n\tbool error = false;\n\tut32 size = 0;\n\tut32 n1 = 0;\n\tut32 n2 = 0;\n\n\tret = RZ_NEW0(pyc_object);\n\tif (!ret) {\n\t\treturn NULL;\n\t}\n\n\tif ((pyc->magic_int & 0xffff) <= 62061) {\n\t\tn1 = get_ut8(buffer, &error);\n\t} else {\n\t\tn1 = get_st32(buffer, &error);\n\t}\n\tif (error) {\n\t\tfree(ret);\n\t\treturn NULL;\n\t}\n\tut8 *s1 = malloc(n1 + 1);\n\tif (!s1) {\n\t\treturn NULL;\n\t}\n\t/* object contain string representation of the number */\n\tsize = rz_buf_read(buffer, s1, n1);\n\tif (size != n1) {\n\t\tRZ_FREE(s1);\n\t\tRZ_FREE(ret);\n\t\treturn NULL;\n\t}\n\ts1[n1] = '\\0';\n\n\tif ((pyc->magic_int & 0xffff) <= 62061) {\n\t\tn2 = get_ut8(buffer, &error);\n\t} else\n\t\tn2 = get_st32(buffer, &error);\n\tif (error) {\n\t\treturn NULL;\n\t}\n\tut8 *s2 = malloc(n2 + 1);\n\tif (!s2) {\n\t\treturn NULL;\n\t}\n\t/* object contain string representation of the number */\n\tsize = rz_buf_read(buffer, s2, n2);\n\tif (size != n2) {\n\t\tRZ_FREE(s1);\n\t\tRZ_FREE(s2);\n\t\tRZ_FREE(ret);\n\t\treturn NULL;\n\t}\n\ts2[n2] = '\\0';\n\n\tret->type = TYPE_COMPLEX;\n\tret->data = rz_str_newf(\"%s+%sj\", s1, s2);\n\tRZ_FREE(s1);\n\tRZ_FREE(s2);\n\tif (!ret->data) {\n\t\tRZ_FREE(ret);\n\t\treturn NULL;\n\t}\n\treturn ret;\n}", "func_hash": 339221193473342829219562491579233996408, "file_name": "marshal.c", "file_hash": 62206307764182880841643297994357401149, "cwe": ["CWE-787"], "cve": "CVE-2022-36040", "cve_desc": "Rizin is a UNIX-like reverse engineering framework and command-line toolset. Versions 0.4.0 and prior are vulnerable to an out-of-bounds write when getting data from PYC(python) files. A user opening a malicious PYC file could be affected by this vulnerability, allowing an attacker to execute code on the user's machine. Commit number 68948017423a12786704e54227b8b2f918c2fd27 contains a patch.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-36040"}
{"idx": 371185, "project": "rizin", "commit_id": "38d8006cd609ac75de82b705891d3508d2c218d5", "project_url": "https://github.com/rizinorg/rizin", "commit_url": "https://github.com/rizinorg/rizin/commit/38d8006cd609ac75de82b705891d3508d2c218d5", "commit_message": "fix #2963 - oob write (1 byte) in pyc/marshal.c", "target": 0, "func": "static pyc_object *get_complex_object(RzBinPycObj *pyc, RzBuffer *buffer) {\n\tpyc_object *ret = NULL;\n\tbool error = false;\n\tut32 n1 = 0;\n\tut32 n2 = 0;\n\n\tret = RZ_NEW0(pyc_object);\n\tif (!ret) {\n\t\treturn NULL;\n\t}\n\n\tif ((pyc->magic_int & 0xffff) <= 62061) {\n\t\tn1 = get_ut8(buffer, &error);\n\t} else {\n\t\tn1 = get_st32(buffer, &error);\n\t}\n\tif (error || UT32_ADD_OVFCHK(n1, 1)) {\n\t\tfree(ret);\n\t\treturn NULL;\n\t}\n\tut8 *s1 = malloc(n1 + 1);\n\tif (!s1) {\n\t\treturn NULL;\n\t}\n\t/* object contain string representation of the number */\n\tif (rz_buf_read(buffer, s1, n1) != n1) {\n\t\tRZ_FREE(s1);\n\t\tRZ_FREE(ret);\n\t\treturn NULL;\n\t}\n\ts1[n1] = '\\0';\n\n\tif ((pyc->magic_int & 0xffff) <= 62061) {\n\t\tn2 = get_ut8(buffer, &error);\n\t} else {\n\t\tn2 = get_st32(buffer, &error);\n\t}\n\tif (error || UT32_ADD_OVFCHK(n2, 1)) {\n\t\treturn NULL;\n\t}\n\tut8 *s2 = malloc(n2 + 1);\n\tif (!s2) {\n\t\treturn NULL;\n\t}\n\t/* object contain string representation of the number */\n\tif (rz_buf_read(buffer, s2, n2) != n2) {\n\t\tRZ_FREE(s1);\n\t\tRZ_FREE(s2);\n\t\tRZ_FREE(ret);\n\t\treturn NULL;\n\t}\n\ts2[n2] = '\\0';\n\n\tret->type = TYPE_COMPLEX;\n\tret->data = rz_str_newf(\"%s+%sj\", s1, s2);\n\tRZ_FREE(s1);\n\tRZ_FREE(s2);\n\tif (!ret->data) {\n\t\tRZ_FREE(ret);\n\t\treturn NULL;\n\t}\n\treturn ret;\n}", "func_hash": 99548148027118090642314481180057035575, "file_name": "marshal.c", "file_hash": 23141269581653768082758645127626248017, "cwe": ["CWE-787"], "cve": "CVE-2022-36040", "cve_desc": "Rizin is a UNIX-like reverse engineering framework and command-line toolset. Versions 0.4.0 and prior are vulnerable to an out-of-bounds write when getting data from PYC(python) files. A user opening a malicious PYC file could be affected by this vulnerability, allowing an attacker to execute code on the user's machine. Commit number 68948017423a12786704e54227b8b2f918c2fd27 contains a patch.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-36040"}
{"idx": 205736, "project": "linux", "commit_id": "775c5033a0d164622d9d10dd0f0a5531639ed3ed", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=775c5033a0d164622d9d10dd0f0a5531639ed3ed", "commit_message": "fuse: fix live lock in fuse_iget()\n\nCommit 5d069dbe8aaf (\"fuse: fix bad inode\") replaced make_bad_inode()\nin fuse_iget() with a private implementation fuse_make_bad().\n\nThe private implementation fails to remove the bad inode from inode\ncache, so the retry loop with iget5_locked() finds the same bad inode\nand marks it bad forever.\n\nkmsg snip:\n\n[ ] rcu: INFO: rcu_sched self-detected stall on CPU\n...\n[ ]  ? bit_wait_io+0x50/0x50\n[ ]  ? fuse_init_file_inode+0x70/0x70\n[ ]  ? find_inode.isra.32+0x60/0xb0\n[ ]  ? fuse_init_file_inode+0x70/0x70\n[ ]  ilookup5_nowait+0x65/0x90\n[ ]  ? fuse_init_file_inode+0x70/0x70\n[ ]  ilookup5.part.36+0x2e/0x80\n[ ]  ? fuse_init_file_inode+0x70/0x70\n[ ]  ? fuse_inode_eq+0x20/0x20\n[ ]  iget5_locked+0x21/0x80\n[ ]  ? fuse_inode_eq+0x20/0x20\n[ ]  fuse_iget+0x96/0x1b0\n\nFixes: 5d069dbe8aaf (\"fuse: fix bad inode\")\nCc: stable@vger.kernel.org # 5.10+\nSigned-off-by: Amir Goldstein \nSigned-off-by: Miklos Szeredi ", "target": 1, "func": "static inline void fuse_make_bad(struct inode *inode)\n{\n\tset_bit(FUSE_I_BAD, &get_fuse_inode(inode)->state);\n}", "func_hash": 47372311033330775185323042617136550109, "file_name": "fuse_i.h", "file_hash": 275513758194031113369959181365685841551, "cwe": ["CWE-834"], "cve": "CVE-2021-28950", "cve_desc": "An issue was discovered in fs/fuse/fuse_i.h in the Linux kernel before 5.11.8. A \"stall on CPU\" can occur because a retry loop continually finds the same bad inode, aka CID-775c5033a0d1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28950"}
{"idx": 371226, "project": "linux", "commit_id": "775c5033a0d164622d9d10dd0f0a5531639ed3ed", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=775c5033a0d164622d9d10dd0f0a5531639ed3ed", "commit_message": "fuse: fix live lock in fuse_iget()\n\nCommit 5d069dbe8aaf (\"fuse: fix bad inode\") replaced make_bad_inode()\nin fuse_iget() with a private implementation fuse_make_bad().\n\nThe private implementation fails to remove the bad inode from inode\ncache, so the retry loop with iget5_locked() finds the same bad inode\nand marks it bad forever.\n\nkmsg snip:\n\n[ ] rcu: INFO: rcu_sched self-detected stall on CPU\n...\n[ ]  ? bit_wait_io+0x50/0x50\n[ ]  ? fuse_init_file_inode+0x70/0x70\n[ ]  ? find_inode.isra.32+0x60/0xb0\n[ ]  ? fuse_init_file_inode+0x70/0x70\n[ ]  ilookup5_nowait+0x65/0x90\n[ ]  ? fuse_init_file_inode+0x70/0x70\n[ ]  ilookup5.part.36+0x2e/0x80\n[ ]  ? fuse_init_file_inode+0x70/0x70\n[ ]  ? fuse_inode_eq+0x20/0x20\n[ ]  iget5_locked+0x21/0x80\n[ ]  ? fuse_inode_eq+0x20/0x20\n[ ]  fuse_iget+0x96/0x1b0\n\nFixes: 5d069dbe8aaf (\"fuse: fix bad inode\")\nCc: stable@vger.kernel.org # 5.10+\nSigned-off-by: Amir Goldstein \nSigned-off-by: Miklos Szeredi ", "target": 0, "func": "static inline void fuse_make_bad(struct inode *inode)\n{\n\tremove_inode_hash(inode);\n\tset_bit(FUSE_I_BAD, &get_fuse_inode(inode)->state);\n}", "func_hash": 322879755488186541223674702992331788623, "file_name": "fuse_i.h", "file_hash": 37876063683408329716495167282300176867, "cwe": ["CWE-834"], "cve": "CVE-2021-28950", "cve_desc": "An issue was discovered in fs/fuse/fuse_i.h in the Linux kernel before 5.11.8. A \"stall on CPU\" can occur because a retry loop continually finds the same bad inode, aka CID-775c5033a0d1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28950"}
{"idx": 205806, "project": "Singular", "commit_id": "5f28fbf066626fa9c4a8f0e6408c0bb362fb386c", "project_url": "https://github.com/Singular/Singular", "commit_url": "https://github.com/Singular/Singular/commit/5f28fbf066626fa9c4a8f0e6408c0bb362fb386c", "commit_message": "use mkstemp for sdb", "target": 1, "func": "void sdb_edit(procinfo *pi)\n{\n  char * filename = omStrDup(\"/tmp/sd000000\");\n  sprintf(filename+7,\"%d\",getpid());\n  FILE *fp=fopen(filename,\"w\");\n  if (fp==NULL)\n  {\n    Print(\"cannot open %s\\n\",filename);\n    omFree(filename);\n    return;\n  }\n  if (pi->language!= LANG_SINGULAR)\n  {\n    Print(\"cannot edit type %d\\n\",pi->language);\n    fclose(fp);\n    fp=NULL;\n  }\n  else\n  {\n    const char *editor=getenv(\"EDITOR\");\n    if (editor==NULL)\n      editor=getenv(\"VISUAL\");\n    if (editor==NULL)\n      editor=\"vi\";\n    editor=omStrDup(editor);\n\n    if (pi->data.s.body==NULL)\n    {\n      iiGetLibProcBuffer(pi);\n      if (pi->data.s.body==NULL)\n      {\n        PrintS(\"cannot get the procedure body\\n\");\n        fclose(fp);\n        si_unlink(filename);\n        omFree(filename);\n        return;\n      }\n    }\n\n    fwrite(pi->data.s.body,1,strlen(pi->data.s.body),fp);\n    fclose(fp);\n\n    int pid=fork();\n    if (pid!=0)\n    {\n      si_wait(&pid);\n    }\n    else if(pid==0)\n    {\n      if (strchr(editor,' ')==NULL)\n      {\n        execlp(editor,editor,filename,NULL);\n        Print(\"cannot exec %s\\n\",editor);\n      }\n      else\n      {\n        char *p=(char *)omAlloc(strlen(editor)+strlen(filename)+2);\n        sprintf(p,\"%s %s\",editor,filename);\n        system(p);\n      }\n      exit(0);\n    }\n    else\n    {\n      PrintS(\"cannot fork\\n\");\n    }\n\n    fp=fopen(filename,\"r\");\n    if (fp==NULL)\n    {\n      Print(\"cannot read from %s\\n\",filename);\n    }\n    else\n    {\n      fseek(fp,0L,SEEK_END);\n      long len=ftell(fp);\n      fseek(fp,0L,SEEK_SET);\n\n      omFree((ADDRESS)pi->data.s.body);\n      pi->data.s.body=(char *)omAlloc((int)len+1);\n      myfread( pi->data.s.body, len, 1, fp);\n      pi->data.s.body[len]='\\0';\n      fclose(fp);\n    }\n  }\n  si_unlink(filename);\n  omFree(filename);\n}", "func_hash": 10048081884359234906707051996001966428, "file_name": "None", "file_hash": null, "cwe": ["CWE-269"], "cve": "CVE-2022-40299", "cve_desc": "In Singular before 4.3.1, a predictable /tmp pathname is used (e.g., by sdb.cc), which allows local users to gain the privileges of other users via a procedure in a file under /tmp. NOTE: this CVE Record is about sdb.cc and similar files in the Singular interface that have predictable /tmp pathnames; this CVE Record is not about the lack of a safe temporary-file creation capability in the Singular language.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-40299"}
{"idx": 372352, "project": "Singular", "commit_id": "5f28fbf066626fa9c4a8f0e6408c0bb362fb386c", "project_url": "https://github.com/Singular/Singular", "commit_url": "https://github.com/Singular/Singular/commit/5f28fbf066626fa9c4a8f0e6408c0bb362fb386c", "commit_message": "use mkstemp for sdb", "target": 0, "func": "void sdb_edit(procinfo *pi)\n{\n  char * filename = omStrDup(\"/tmp/sdXXXXXX\");\n  int f=mkstemp(filename);\n  if (f==-1)\n  {\n    Print(\"cannot open %s\\n\",filename);\n    omFree(filename);\n    return;\n  }\n  if (pi->language!= LANG_SINGULAR)\n  {\n    Print(\"cannot edit type %d\\n\",pi->language);\n    close(f);\n    f=NULL;\n  }\n  else\n  {\n    const char *editor=getenv(\"EDITOR\");\n    if (editor==NULL)\n      editor=getenv(\"VISUAL\");\n    if (editor==NULL)\n      editor=\"vi\";\n    editor=omStrDup(editor);\n\n    if (pi->data.s.body==NULL)\n    {\n      iiGetLibProcBuffer(pi);\n      if (pi->data.s.body==NULL)\n      {\n        PrintS(\"cannot get the procedure body\\n\");\n        close(f);\n        si_unlink(filename);\n        omFree(filename);\n        return;\n      }\n    }\n\n    write(f,pi->data.s.body,strlen(pi->data.s.body));\n    close(f);\n\n    int pid=fork();\n    if (pid!=0)\n    {\n      si_wait(&pid);\n    }\n    else if(pid==0)\n    {\n      if (strchr(editor,' ')==NULL)\n      {\n        execlp(editor,editor,filename,NULL);\n        Print(\"cannot exec %s\\n\",editor);\n      }\n      else\n      {\n        char *p=(char *)omAlloc(strlen(editor)+strlen(filename)+2);\n        sprintf(p,\"%s %s\",editor,filename);\n        system(p);\n      }\n      exit(0);\n    }\n    else\n    {\n      PrintS(\"cannot fork\\n\");\n    }\n\n    FILE* fp=fopen(filename,\"r\");\n    if (fp==NULL)\n    {\n      Print(\"cannot read from %s\\n\",filename);\n    }\n    else\n    {\n      fseek(fp,0L,SEEK_END);\n      long len=ftell(fp);\n      fseek(fp,0L,SEEK_SET);\n\n      omFree((ADDRESS)pi->data.s.body);\n      pi->data.s.body=(char *)omAlloc((int)len+1);\n      myfread( pi->data.s.body, len, 1, fp);\n      pi->data.s.body[len]='\\0';\n      fclose(fp);\n    }\n  }\n  si_unlink(filename);\n  omFree(filename);\n}", "func_hash": 297505880534279409095461525065078196664, "file_name": "None", "file_hash": null, "cwe": ["CWE-269"], "cve": "CVE-2022-40299", "cve_desc": "In Singular before 4.3.1, a predictable /tmp pathname is used (e.g., by sdb.cc), which allows local users to gain the privileges of other users via a procedure in a file under /tmp. NOTE: this CVE Record is about sdb.cc and similar files in the Singular interface that have predictable /tmp pathnames; this CVE Record is not about the lack of a safe temporary-file creation capability in the Singular language.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-40299"}
{"idx": 205823, "project": "ovs", "commit_id": "803ed12e31b0377c37d7aa8c94b3b92f2081e349", "project_url": "https://github.com/openvswitch/ovs", "commit_url": "https://github.com/openvswitch/ovs/commit/803ed12e31b0377c37d7aa8c94b3b92f2081e349", "commit_message": "ipf: release unhandled packets from the batch\n\nSince 640d4db788ed (\"ipf: Fix a use-after-free error, ...\") the ipf\nframework unconditionally allocates a new dp_packet to track\nindividual fragments.  This prevents a use-after-free.  However, an\nadditional issue was present - even when the packet buffer is cloned,\nif the ip fragment handling code keeps it, the original buffer is\nleaked during the refill loop.  Even in the original processing code,\nthe hardcoded dnsteal branches would always leak a packet buffer from\nthe refill loop.\n\nThis can be confirmed with valgrind:\n\n==717566== 16,672 (4,480 direct, 12,192 indirect) bytes in 8 blocks are definitely lost in loss record 390 of 390\n==717566==    at 0x484086F: malloc (vg_replace_malloc.c:380)\n==717566==    by 0x537BFD: xmalloc__ (util.c:137)\n==717566==    by 0x537BFD: xmalloc (util.c:172)\n==717566==    by 0x46DDD4: dp_packet_new (dp-packet.c:153)\n==717566==    by 0x46DDD4: dp_packet_new_with_headroom (dp-packet.c:163)\n==717566==    by 0x550AA6: netdev_linux_batch_rxq_recv_sock.constprop.0 (netdev-linux.c:1262)\n==717566==    by 0x5512AF: netdev_linux_rxq_recv (netdev-linux.c:1511)\n==717566==    by 0x4AB7E0: netdev_rxq_recv (netdev.c:727)\n==717566==    by 0x47F00D: dp_netdev_process_rxq_port (dpif-netdev.c:4699)\n==717566==    by 0x47FD13: dpif_netdev_run (dpif-netdev.c:5957)\n==717566==    by 0x4331D2: type_run (ofproto-dpif.c:370)\n==717566==    by 0x41DFD8: ofproto_type_run (ofproto.c:1768)\n==717566==    by 0x40A7FB: bridge_run__ (bridge.c:3245)\n==717566==    by 0x411269: bridge_run (bridge.c:3310)\n==717566==    by 0x406E6C: main (ovs-vswitchd.c:127)\n\nThe fix is to delete the original packet when it isn't able to be\nreinserted into the packet batch.  Subsequent valgrind runs show that\nthe packets are not leaked from the batch any longer.\n\nFixes: 640d4db788ed (\"ipf: Fix a use-after-free error, and remove the 'do_not_steal' flag.\")\nFixes: 4ea96698f667 (\"Userspace datapath: Add fragmentation handling.\")\nReported-by: Wan Junjie \nReported-at: https://github.com/openvswitch/ovs-issues/issues/226\nSigned-off-by: Aaron Conole \nReviewed-by: David Marchand \nTested-by: Wan Junjie \nSigned-off-by: Alin-Gabriel Serdean ", "target": 1, "func": "ipf_extract_frags_from_batch(struct ipf *ipf, struct dp_packet_batch *pb,\n                             ovs_be16 dl_type, uint16_t zone, long long now,\n                             uint32_t hash_basis)\n{\n    const size_t pb_cnt = dp_packet_batch_size(pb);\n    int pb_idx; /* Index in a packet batch. */\n    struct dp_packet *pkt;\n\n    DP_PACKET_BATCH_REFILL_FOR_EACH (pb_idx, pb_cnt, pkt, pb) {\n        if (OVS_UNLIKELY((dl_type == htons(ETH_TYPE_IP) &&\n                          ipf_is_valid_v4_frag(ipf, pkt))\n                          ||\n                          (dl_type == htons(ETH_TYPE_IPV6) &&\n                          ipf_is_valid_v6_frag(ipf, pkt)))) {\n\n            ovs_mutex_lock(&ipf->ipf_lock);\n            if (!ipf_handle_frag(ipf, pkt, dl_type, zone, now, hash_basis)) {\n                dp_packet_batch_refill(pb, pkt, pb_idx);\n            }\n            ovs_mutex_unlock(&ipf->ipf_lock);\n        } else {\n            dp_packet_batch_refill(pb, pkt, pb_idx);\n        }\n    }\n}", "func_hash": 268719993787134993398351954055334505161, "file_name": "ipf.c", "file_hash": 8691777507480014794600271586586377411, "cwe": ["CWE-401"], "cve": "CVE-2021-3905", "cve_desc": "A memory leak was found in Open vSwitch (OVS) during userspace IP fragmentation processing. An attacker could use this flaw to potentially exhaust available memory by keeping sending packet fragments.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3905"}
{"idx": 373535, "project": "ovs", "commit_id": "803ed12e31b0377c37d7aa8c94b3b92f2081e349", "project_url": "https://github.com/openvswitch/ovs", "commit_url": "https://github.com/openvswitch/ovs/commit/803ed12e31b0377c37d7aa8c94b3b92f2081e349", "commit_message": "ipf: release unhandled packets from the batch\n\nSince 640d4db788ed (\"ipf: Fix a use-after-free error, ...\") the ipf\nframework unconditionally allocates a new dp_packet to track\nindividual fragments.  This prevents a use-after-free.  However, an\nadditional issue was present - even when the packet buffer is cloned,\nif the ip fragment handling code keeps it, the original buffer is\nleaked during the refill loop.  Even in the original processing code,\nthe hardcoded dnsteal branches would always leak a packet buffer from\nthe refill loop.\n\nThis can be confirmed with valgrind:\n\n==717566== 16,672 (4,480 direct, 12,192 indirect) bytes in 8 blocks are definitely lost in loss record 390 of 390\n==717566==    at 0x484086F: malloc (vg_replace_malloc.c:380)\n==717566==    by 0x537BFD: xmalloc__ (util.c:137)\n==717566==    by 0x537BFD: xmalloc (util.c:172)\n==717566==    by 0x46DDD4: dp_packet_new (dp-packet.c:153)\n==717566==    by 0x46DDD4: dp_packet_new_with_headroom (dp-packet.c:163)\n==717566==    by 0x550AA6: netdev_linux_batch_rxq_recv_sock.constprop.0 (netdev-linux.c:1262)\n==717566==    by 0x5512AF: netdev_linux_rxq_recv (netdev-linux.c:1511)\n==717566==    by 0x4AB7E0: netdev_rxq_recv (netdev.c:727)\n==717566==    by 0x47F00D: dp_netdev_process_rxq_port (dpif-netdev.c:4699)\n==717566==    by 0x47FD13: dpif_netdev_run (dpif-netdev.c:5957)\n==717566==    by 0x4331D2: type_run (ofproto-dpif.c:370)\n==717566==    by 0x41DFD8: ofproto_type_run (ofproto.c:1768)\n==717566==    by 0x40A7FB: bridge_run__ (bridge.c:3245)\n==717566==    by 0x411269: bridge_run (bridge.c:3310)\n==717566==    by 0x406E6C: main (ovs-vswitchd.c:127)\n\nThe fix is to delete the original packet when it isn't able to be\nreinserted into the packet batch.  Subsequent valgrind runs show that\nthe packets are not leaked from the batch any longer.\n\nFixes: 640d4db788ed (\"ipf: Fix a use-after-free error, and remove the 'do_not_steal' flag.\")\nFixes: 4ea96698f667 (\"Userspace datapath: Add fragmentation handling.\")\nReported-by: Wan Junjie \nReported-at: https://github.com/openvswitch/ovs-issues/issues/226\nSigned-off-by: Aaron Conole \nReviewed-by: David Marchand \nTested-by: Wan Junjie \nSigned-off-by: Alin-Gabriel Serdean ", "target": 0, "func": "ipf_extract_frags_from_batch(struct ipf *ipf, struct dp_packet_batch *pb,\n                             ovs_be16 dl_type, uint16_t zone, long long now,\n                             uint32_t hash_basis)\n{\n    const size_t pb_cnt = dp_packet_batch_size(pb);\n    int pb_idx; /* Index in a packet batch. */\n    struct dp_packet *pkt;\n\n    DP_PACKET_BATCH_REFILL_FOR_EACH (pb_idx, pb_cnt, pkt, pb) {\n        if (OVS_UNLIKELY((dl_type == htons(ETH_TYPE_IP) &&\n                          ipf_is_valid_v4_frag(ipf, pkt))\n                          ||\n                          (dl_type == htons(ETH_TYPE_IPV6) &&\n                          ipf_is_valid_v6_frag(ipf, pkt)))) {\n\n            ovs_mutex_lock(&ipf->ipf_lock);\n            if (!ipf_handle_frag(ipf, pkt, dl_type, zone, now, hash_basis)) {\n                dp_packet_batch_refill(pb, pkt, pb_idx);\n            } else {\n                dp_packet_delete(pkt);\n            }\n            ovs_mutex_unlock(&ipf->ipf_lock);\n        } else {\n            dp_packet_batch_refill(pb, pkt, pb_idx);\n        }\n    }\n}", "func_hash": 120994420466199339145680136614353279460, "file_name": "ipf.c", "file_hash": 251424754321869382912198899459965953031, "cwe": ["CWE-401"], "cve": "CVE-2021-3905", "cve_desc": "A memory leak was found in Open vSwitch (OVS) during userspace IP fragmentation processing. An attacker could use this flaw to potentially exhaust available memory by keeping sending packet fragments.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3905"}
{"idx": 206025, "project": "evolution-data-server", "commit_id": "5d8b92c622f6927b253762ff9310479dd3ac627d", "project_url": "https://git.gnome.org/browse/evolution-data-server", "commit_url": "https://git.gnome.org/browse/evolution-data-server/commit/?id=5d8b92c622f6927b253762ff9310479dd3ac627d", "commit_message": "CamelGpgContext: Enclose email addresses in brackets.\n\nThe recipient list for encrypting can be specified by either key ID or\nemail address.  Enclose email addresses in brackets to ensure an exact\nmatch, as per the gpg man page:\n\nHOW TO SPECIFY A USER ID\n\n       ...\n\n       By exact match on an email address.\n              This is indicated by enclosing the email address in the\n              usual way with left and right angles.\n\n         \n\nWithout the brackets gpg uses a substring match, which risks selecting\nthe wrong recipient.", "target": 1, "func": "gpg_ctx_add_recipient (struct _GpgCtx *gpg,\n                       const gchar *keyid)\n{\n\tif (gpg->mode != GPG_CTX_MODE_ENCRYPT && gpg->mode != GPG_CTX_MODE_EXPORT)\n\t\treturn;\n\n\tif (!gpg->recipients)\n\t\tgpg->recipients = g_ptr_array_new ();\n\n\tg_ptr_array_add (gpg->recipients, g_strdup (keyid));\n}", "func_hash": 52853002144529989504123015024381136054, "file_name": "None", "file_hash": null, "cwe": ["CWE-200"], "cve": "CVE-2013-4166", "cve_desc": "The gpg_ctx_add_recipient function in camel/camel-gpg-context.c in GNOME Evolution 3.8.4 and earlier and Evolution Data Server 3.9.5 and earlier does not properly select the GPG key to use for email encryption, which might cause the email to be encrypted with the wrong key and allow remote attackers to obtain sensitive information.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-4166"}
{"idx": 376350, "project": "evolution-data-server", "commit_id": "5d8b92c622f6927b253762ff9310479dd3ac627d", "project_url": "https://git.gnome.org/browse/evolution-data-server", "commit_url": "https://git.gnome.org/browse/evolution-data-server/commit/?id=5d8b92c622f6927b253762ff9310479dd3ac627d", "commit_message": "CamelGpgContext: Enclose email addresses in brackets.\n\nThe recipient list for encrypting can be specified by either key ID or\nemail address.  Enclose email addresses in brackets to ensure an exact\nmatch, as per the gpg man page:\n\nHOW TO SPECIFY A USER ID\n\n       ...\n\n       By exact match on an email address.\n              This is indicated by enclosing the email address in the\n              usual way with left and right angles.\n\n         \n\nWithout the brackets gpg uses a substring match, which risks selecting\nthe wrong recipient.", "target": 0, "func": "gpg_ctx_add_recipient (struct _GpgCtx *gpg,\n                       const gchar *keyid)\n{\n\tgchar *safe_keyid;\n\n\tif (gpg->mode != GPG_CTX_MODE_ENCRYPT && gpg->mode != GPG_CTX_MODE_EXPORT)\n\t\treturn;\n\n\tif (!gpg->recipients)\n\t\tgpg->recipients = g_ptr_array_new ();\n\n\tg_return_if_fail (keyid != NULL);\n\n\t/* If the recipient looks like an email address,\n\t * enclose it in brackets to ensure an exact match. */\n\tif (strchr (keyid, '@') != NULL) {\n\t\tsafe_keyid = g_strdup_printf (\"<%s>\", keyid);\n\t} else {\n\t\tsafe_keyid = g_strdup (keyid);\n\t}\n\n\tg_ptr_array_add (gpg->recipients, safe_keyid);\n}", "func_hash": 104115978280820788064995186839232167760, "file_name": "None", "file_hash": null, "cwe": ["CWE-200"], "cve": "CVE-2013-4166", "cve_desc": "The gpg_ctx_add_recipient function in camel/camel-gpg-context.c in GNOME Evolution 3.8.4 and earlier and Evolution Data Server 3.9.5 and earlier does not properly select the GPG key to use for email encryption, which might cause the email to be encrypted with the wrong key and allow remote attackers to obtain sensitive information.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-4166"}
{"idx": 206043, "project": "gimp", "commit_id": "c57f9dcf1934a9ab0cd67650f2dea18cb0902270", "project_url": "https://github.com/GNOME/gimp", "commit_url": "https://git.gnome.org/browse/gimp/commit/?id=c57f9dcf1934a9ab0cd67650f2dea18cb0902270", "commit_message": "Bug 790784 - (CVE-2017-17784) heap overread in gbr parser / load_image.\n\nWe were assuming the input name was well formed, hence was\nnul-terminated. As any data coming from external input, this has to be\nthorougly checked.\nSimilar to commit 06d24a79af94837d615d0024916bb95a01bf3c59 but adapted\nto older gimp-2-8 code.", "target": 1, "func": "load_image (const gchar  *filename,\n            GError      **error)\n{\n  gchar             *name;\n  gint               fd;\n  BrushHeader        bh;\n  guchar            *brush_buf = NULL;\n  gint32             image_ID;\n  gint32             layer_ID;\n  GimpParasite      *parasite;\n  GimpDrawable      *drawable;\n  GimpPixelRgn       pixel_rgn;\n  gint               bn_size;\n  GimpImageBaseType  base_type;\n  GimpImageType      image_type;\n  gsize              size;\n\n  fd = g_open (filename, O_RDONLY | _O_BINARY, 0);\n\n  if (fd == -1)\n    {\n      g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno),\n                   _(\"Could not open '%s' for reading: %s\"),\n                   gimp_filename_to_utf8 (filename), g_strerror (errno));\n      return -1;\n    }\n\n  gimp_progress_init_printf (_(\"Opening '%s'\"),\n                             gimp_filename_to_utf8 (filename));\n\n  if (read (fd, &bh, sizeof (BrushHeader)) != sizeof (BrushHeader))\n    {\n      close (fd);\n      return -1;\n    }\n\n  /*  rearrange the bytes in each unsigned int  */\n  bh.header_size  = g_ntohl (bh.header_size);\n  bh.version      = g_ntohl (bh.version);\n  bh.width        = g_ntohl (bh.width);\n  bh.height       = g_ntohl (bh.height);\n  bh.bytes        = g_ntohl (bh.bytes);\n  bh.magic_number = g_ntohl (bh.magic_number);\n  bh.spacing      = g_ntohl (bh.spacing);\n\n  /* Sanitize values */\n  if ((bh.width == 0) || (bh.width > GIMP_MAX_IMAGE_SIZE) ||\n      (bh.height == 0) || (bh.height > GIMP_MAX_IMAGE_SIZE) ||\n      ((bh.bytes != 1) && (bh.bytes != 2) && (bh.bytes != 4) &&\n       (bh.bytes != 18)) ||\n      (G_MAXSIZE / bh.width / bh.height / bh.bytes < 1))\n    {\n      g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,\n                   _(\"Invalid header data in '%s': width=%lu, height=%lu, \"\n                     \"bytes=%lu\"), gimp_filename_to_utf8 (filename),\n                   (unsigned long int)bh.width, (unsigned long int)bh.height,\n                   (unsigned long int)bh.bytes);\n      return -1;\n    }\n\n  switch (bh.version)\n    {\n    case 1:\n      /* Version 1 didn't have a magic number and had no spacing  */\n      bh.spacing = 25;\n      /* And we need to rewind the handle, 4 due spacing and 4 due magic */\n      lseek (fd, -8, SEEK_CUR);\n      bh.header_size += 8;\n      break;\n\n    case 3: /*  cinepaint brush  */\n      if (bh.bytes == 18 /* FLOAT16_GRAY_GIMAGE */)\n        {\n          bh.bytes = 2;\n        }\n      else\n        {\n          g_message (_(\"Unsupported brush format\"));\n          close (fd);\n          return -1;\n        }\n      /*  fallthrough  */\n\n    case 2:\n      if (bh.magic_number == GBRUSH_MAGIC &&\n          bh.header_size  >  sizeof (BrushHeader))\n        break;\n\n    default:\n      g_message (_(\"Unsupported brush format\"));\n      close (fd);\n      return -1;\n    }\n\n  if ((bn_size = (bh.header_size - sizeof (BrushHeader))) > 0)\n    {\n      gchar *temp = g_new (gchar, bn_size);\n\n      if ((read (fd, temp, bn_size)) < bn_size)\n        {\n          g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,\n                       _(\"Error in GIMP brush file '%s'\"),\n                       gimp_filename_to_utf8 (filename));\n          close (fd);\n          g_free (temp);\n          return -1;\n        }\n\n      name = gimp_any_to_utf8 (temp, -1,\n                               _(\"Invalid UTF-8 string in brush file '%s'.\"),\n                               gimp_filename_to_utf8 (filename));\n      g_free (temp);\n    }\n  else\n    {\n      name = g_strdup (_(\"Unnamed\"));\n    }\n\n  /* Now there's just raw data left. */\n\n  size = bh.width * bh.height * bh.bytes;\n  brush_buf = g_malloc (size);\n\n  if (read (fd, brush_buf, size) != size)\n    {\n      close (fd);\n      g_free (brush_buf);\n      g_free (name);\n      return -1;\n    }\n\n  switch (bh.bytes)\n    {\n    case 1:\n      {\n        PatternHeader ph;\n\n        /*  For backwards-compatibility, check if a pattern follows.\n            The obsolete .gpb format did it this way.  */\n\n        if (read (fd, &ph, sizeof (PatternHeader)) == sizeof(PatternHeader))\n          {\n            /*  rearrange the bytes in each unsigned int  */\n            ph.header_size  = g_ntohl (ph.header_size);\n            ph.version      = g_ntohl (ph.version);\n            ph.width        = g_ntohl (ph.width);\n            ph.height       = g_ntohl (ph.height);\n            ph.bytes        = g_ntohl (ph.bytes);\n            ph.magic_number = g_ntohl (ph.magic_number);\n\n            if (ph.magic_number == GPATTERN_MAGIC        &&\n                ph.version      == 1                     &&\n                ph.header_size  > sizeof (PatternHeader) &&\n                ph.bytes        == 3                     &&\n                ph.width        == bh.width              &&\n                ph.height       == bh.height             &&\n                lseek (fd, ph.header_size - sizeof (PatternHeader),\n                       SEEK_CUR) > 0)\n              {\n                guchar *plain_brush = brush_buf;\n                gint    i;\n\n                bh.bytes = 4;\n                brush_buf = g_malloc (4 * bh.width * bh.height);\n\n                for (i = 0; i < ph.width * ph.height; i++)\n                  {\n                    if (read (fd, brush_buf + i * 4, 3) != 3)\n                      {\n                        close (fd);\n                        g_free (name);\n                        g_free (plain_brush);\n                        g_free (brush_buf);\n                        return -1;\n                      }\n                    brush_buf[i * 4 + 3] = plain_brush[i];\n                  }\n                g_free (plain_brush);\n              }\n          }\n      }\n      break;\n\n    case 2:\n      {\n        guint16 *buf = (guint16 *) brush_buf;\n        gint     i;\n\n        for (i = 0; i < bh.width * bh.height; i++, buf++)\n          {\n            union\n            {\n              guint16 u[2];\n              gfloat  f;\n            } short_float;\n\n#if G_BYTE_ORDER == G_LITTLE_ENDIAN\n            short_float.u[0] = 0;\n            short_float.u[1] = GUINT16_FROM_BE (*buf);\n#else\n            short_float.u[0] = GUINT16_FROM_BE (*buf);\n            short_float.u[1] = 0;\n#endif\n\n            brush_buf[i] = (guchar) (short_float.f * 255.0 + 0.5);\n          }\n\n        bh.bytes = 1;\n      }\n      break;\n\n    default:\n      break;\n    }\n\n  /*\n   * Create a new image of the proper size and\n   * associate the filename with it.\n   */\n\n  switch (bh.bytes)\n    {\n    case 1:\n      base_type = GIMP_GRAY;\n      image_type = GIMP_GRAY_IMAGE;\n      break;\n\n    case 4:\n      base_type = GIMP_RGB;\n      image_type = GIMP_RGBA_IMAGE;\n      break;\n\n    default:\n      g_message (\"Unsupported brush depth: %d\\n\"\n                 \"GIMP Brushes must be GRAY or RGBA\\n\",\n                 bh.bytes);\n      g_free (name);\n      return -1;\n    }\n\n  image_ID = gimp_image_new (bh.width, bh.height, base_type);\n  gimp_image_set_filename (image_ID, filename);\n\n  parasite = gimp_parasite_new (\"gimp-brush-name\",\n                                GIMP_PARASITE_PERSISTENT,\n                                strlen (name) + 1, name);\n  gimp_image_attach_parasite (image_ID, parasite);\n  gimp_parasite_free (parasite);\n\n  layer_ID = gimp_layer_new (image_ID, name, bh.width, bh.height,\n                             image_type, 100, GIMP_NORMAL_MODE);\n  gimp_image_insert_layer (image_ID, layer_ID, -1, 0);\n\n  g_free (name);\n\n  drawable = gimp_drawable_get (layer_ID);\n  gimp_pixel_rgn_init (&pixel_rgn, drawable,\n                       0, 0, drawable->width, drawable->height,\n                       TRUE, FALSE);\n\n  gimp_pixel_rgn_set_rect (&pixel_rgn, brush_buf,\n                           0, 0, bh.width, bh.height);\n  g_free (brush_buf);\n\n  if (image_type == GIMP_GRAY_IMAGE)\n    gimp_invert (layer_ID);\n\n  close (fd);\n\n  gimp_drawable_flush (drawable);\n  gimp_progress_update (1.0);\n\n  return image_ID;\n}", "func_hash": 219487381392289910094593757172224969152, "file_name": "file-gbr.c", "file_hash": 210537502330856952427982223109888523462, "cwe": ["CWE-125"], "cve": "CVE-2017-17784", "cve_desc": "In GIMP 2.8.22, there is a heap-based buffer over-read in load_image in plug-ins/common/file-gbr.c in the gbr import parser, related to mishandling of UTF-8 data.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-17784"}
{"idx": 376678, "project": "gimp", "commit_id": "c57f9dcf1934a9ab0cd67650f2dea18cb0902270", "project_url": "https://github.com/GNOME/gimp", "commit_url": "https://git.gnome.org/browse/gimp/commit/?id=c57f9dcf1934a9ab0cd67650f2dea18cb0902270", "commit_message": "Bug 790784 - (CVE-2017-17784) heap overread in gbr parser / load_image.\n\nWe were assuming the input name was well formed, hence was\nnul-terminated. As any data coming from external input, this has to be\nthorougly checked.\nSimilar to commit 06d24a79af94837d615d0024916bb95a01bf3c59 but adapted\nto older gimp-2-8 code.", "target": 0, "func": "load_image (const gchar  *filename,\n            GError      **error)\n{\n  gchar             *name;\n  gint               fd;\n  BrushHeader        bh;\n  guchar            *brush_buf = NULL;\n  gint32             image_ID;\n  gint32             layer_ID;\n  GimpParasite      *parasite;\n  GimpDrawable      *drawable;\n  GimpPixelRgn       pixel_rgn;\n  gint               bn_size;\n  GimpImageBaseType  base_type;\n  GimpImageType      image_type;\n  gsize              size;\n\n  fd = g_open (filename, O_RDONLY | _O_BINARY, 0);\n\n  if (fd == -1)\n    {\n      g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno),\n                   _(\"Could not open '%s' for reading: %s\"),\n                   gimp_filename_to_utf8 (filename), g_strerror (errno));\n      return -1;\n    }\n\n  gimp_progress_init_printf (_(\"Opening '%s'\"),\n                             gimp_filename_to_utf8 (filename));\n\n  if (read (fd, &bh, sizeof (BrushHeader)) != sizeof (BrushHeader))\n    {\n      close (fd);\n      return -1;\n    }\n\n  /*  rearrange the bytes in each unsigned int  */\n  bh.header_size  = g_ntohl (bh.header_size);\n  bh.version      = g_ntohl (bh.version);\n  bh.width        = g_ntohl (bh.width);\n  bh.height       = g_ntohl (bh.height);\n  bh.bytes        = g_ntohl (bh.bytes);\n  bh.magic_number = g_ntohl (bh.magic_number);\n  bh.spacing      = g_ntohl (bh.spacing);\n\n  /* Sanitize values */\n  if ((bh.width == 0) || (bh.width > GIMP_MAX_IMAGE_SIZE) ||\n      (bh.height == 0) || (bh.height > GIMP_MAX_IMAGE_SIZE) ||\n      ((bh.bytes != 1) && (bh.bytes != 2) && (bh.bytes != 4) &&\n       (bh.bytes != 18)) ||\n      (G_MAXSIZE / bh.width / bh.height / bh.bytes < 1))\n    {\n      g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,\n                   _(\"Invalid header data in '%s': width=%lu, height=%lu, \"\n                     \"bytes=%lu\"), gimp_filename_to_utf8 (filename),\n                   (unsigned long int)bh.width, (unsigned long int)bh.height,\n                   (unsigned long int)bh.bytes);\n      return -1;\n    }\n\n  switch (bh.version)\n    {\n    case 1:\n      /* Version 1 didn't have a magic number and had no spacing  */\n      bh.spacing = 25;\n      /* And we need to rewind the handle, 4 due spacing and 4 due magic */\n      lseek (fd, -8, SEEK_CUR);\n      bh.header_size += 8;\n      break;\n\n    case 3: /*  cinepaint brush  */\n      if (bh.bytes == 18 /* FLOAT16_GRAY_GIMAGE */)\n        {\n          bh.bytes = 2;\n        }\n      else\n        {\n          g_message (_(\"Unsupported brush format\"));\n          close (fd);\n          return -1;\n        }\n      /*  fallthrough  */\n\n    case 2:\n      if (bh.magic_number == GBRUSH_MAGIC &&\n          bh.header_size  >  sizeof (BrushHeader))\n        break;\n\n    default:\n      g_message (_(\"Unsupported brush format\"));\n      close (fd);\n      return -1;\n    }\n\n  if ((bn_size = (bh.header_size - sizeof (BrushHeader))) > 0)\n    {\n      gchar *temp = g_new (gchar, bn_size);\n\n      if ((read (fd, temp, bn_size)) < bn_size ||\n          temp[bn_size - 1] != '\\0')\n        {\n          g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,\n                       _(\"Error in GIMP brush file '%s'\"),\n                       gimp_filename_to_utf8 (filename));\n          close (fd);\n          g_free (temp);\n          return -1;\n        }\n\n      name = gimp_any_to_utf8 (temp, -1,\n                               _(\"Invalid UTF-8 string in brush file '%s'.\"),\n                               gimp_filename_to_utf8 (filename));\n      g_free (temp);\n    }\n  else\n    {\n      name = g_strdup (_(\"Unnamed\"));\n    }\n\n  /* Now there's just raw data left. */\n\n  size = bh.width * bh.height * bh.bytes;\n  brush_buf = g_malloc (size);\n\n  if (read (fd, brush_buf, size) != size)\n    {\n      close (fd);\n      g_free (brush_buf);\n      g_free (name);\n      return -1;\n    }\n\n  switch (bh.bytes)\n    {\n    case 1:\n      {\n        PatternHeader ph;\n\n        /*  For backwards-compatibility, check if a pattern follows.\n            The obsolete .gpb format did it this way.  */\n\n        if (read (fd, &ph, sizeof (PatternHeader)) == sizeof(PatternHeader))\n          {\n            /*  rearrange the bytes in each unsigned int  */\n            ph.header_size  = g_ntohl (ph.header_size);\n            ph.version      = g_ntohl (ph.version);\n            ph.width        = g_ntohl (ph.width);\n            ph.height       = g_ntohl (ph.height);\n            ph.bytes        = g_ntohl (ph.bytes);\n            ph.magic_number = g_ntohl (ph.magic_number);\n\n            if (ph.magic_number == GPATTERN_MAGIC        &&\n                ph.version      == 1                     &&\n                ph.header_size  > sizeof (PatternHeader) &&\n                ph.bytes        == 3                     &&\n                ph.width        == bh.width              &&\n                ph.height       == bh.height             &&\n                lseek (fd, ph.header_size - sizeof (PatternHeader),\n                       SEEK_CUR) > 0)\n              {\n                guchar *plain_brush = brush_buf;\n                gint    i;\n\n                bh.bytes = 4;\n                brush_buf = g_malloc (4 * bh.width * bh.height);\n\n                for (i = 0; i < ph.width * ph.height; i++)\n                  {\n                    if (read (fd, brush_buf + i * 4, 3) != 3)\n                      {\n                        close (fd);\n                        g_free (name);\n                        g_free (plain_brush);\n                        g_free (brush_buf);\n                        return -1;\n                      }\n                    brush_buf[i * 4 + 3] = plain_brush[i];\n                  }\n                g_free (plain_brush);\n              }\n          }\n      }\n      break;\n\n    case 2:\n      {\n        guint16 *buf = (guint16 *) brush_buf;\n        gint     i;\n\n        for (i = 0; i < bh.width * bh.height; i++, buf++)\n          {\n            union\n            {\n              guint16 u[2];\n              gfloat  f;\n            } short_float;\n\n#if G_BYTE_ORDER == G_LITTLE_ENDIAN\n            short_float.u[0] = 0;\n            short_float.u[1] = GUINT16_FROM_BE (*buf);\n#else\n            short_float.u[0] = GUINT16_FROM_BE (*buf);\n            short_float.u[1] = 0;\n#endif\n\n            brush_buf[i] = (guchar) (short_float.f * 255.0 + 0.5);\n          }\n\n        bh.bytes = 1;\n      }\n      break;\n\n    default:\n      break;\n    }\n\n  /*\n   * Create a new image of the proper size and\n   * associate the filename with it.\n   */\n\n  switch (bh.bytes)\n    {\n    case 1:\n      base_type = GIMP_GRAY;\n      image_type = GIMP_GRAY_IMAGE;\n      break;\n\n    case 4:\n      base_type = GIMP_RGB;\n      image_type = GIMP_RGBA_IMAGE;\n      break;\n\n    default:\n      g_message (\"Unsupported brush depth: %d\\n\"\n                 \"GIMP Brushes must be GRAY or RGBA\\n\",\n                 bh.bytes);\n      g_free (name);\n      return -1;\n    }\n\n  image_ID = gimp_image_new (bh.width, bh.height, base_type);\n  gimp_image_set_filename (image_ID, filename);\n\n  parasite = gimp_parasite_new (\"gimp-brush-name\",\n                                GIMP_PARASITE_PERSISTENT,\n                                strlen (name) + 1, name);\n  gimp_image_attach_parasite (image_ID, parasite);\n  gimp_parasite_free (parasite);\n\n  layer_ID = gimp_layer_new (image_ID, name, bh.width, bh.height,\n                             image_type, 100, GIMP_NORMAL_MODE);\n  gimp_image_insert_layer (image_ID, layer_ID, -1, 0);\n\n  g_free (name);\n\n  drawable = gimp_drawable_get (layer_ID);\n  gimp_pixel_rgn_init (&pixel_rgn, drawable,\n                       0, 0, drawable->width, drawable->height,\n                       TRUE, FALSE);\n\n  gimp_pixel_rgn_set_rect (&pixel_rgn, brush_buf,\n                           0, 0, bh.width, bh.height);\n  g_free (brush_buf);\n\n  if (image_type == GIMP_GRAY_IMAGE)\n    gimp_invert (layer_ID);\n\n  close (fd);\n\n  gimp_drawable_flush (drawable);\n  gimp_progress_update (1.0);\n\n  return image_ID;\n}", "func_hash": 269327823766609487068724383051357537961, "file_name": "file-gbr.c", "file_hash": 146644042188037261041231342134151379601, "cwe": ["CWE-125"], "cve": "CVE-2017-17784", "cve_desc": "In GIMP 2.8.22, there is a heap-based buffer over-read in load_image in plug-ins/common/file-gbr.c in the gbr import parser, related to mishandling of UTF-8 data.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-17784"}
{"idx": 206044, "project": "tigervnc", "commit_id": "d61a767d6842b530ffb532ddd5a3d233119aad40", "project_url": "https://github.com/CendioOssman/tigervnc", "commit_url": "https://github.com/CendioOssman/tigervnc/commit/d61a767d6842b530ffb532ddd5a3d233119aad40", "commit_message": "Make ZlibInStream more robust against failures\n\nMove the checks around to avoid missing cases where we might access\nmemory that is no longer valid. Also avoid touching the underlying\nstream implicitly (e.g. via the destructor) as it might also no\nlonger be valid.\n\nA malicious server could theoretically use this for remote code\nexecution in the client.\n\nIssue found by Pavel Cheremushkin from Kaspersky Lab", "target": 1, "func": "void ZRLE_DECODE (const Rect& r, rdr::InStream* is,\n                  rdr::ZlibInStream* zis,\n                  const PixelFormat& pf, ModifiablePixelBuffer* pb)\n{\n  int length = is->readU32();\n  zis->setUnderlying(is, length);\n  Rect t;\n  PIXEL_T buf[64 * 64];\n\n  for (t.tl.y = r.tl.y; t.tl.y < r.br.y; t.tl.y += 64) {\n\n    t.br.y = __rfbmin(r.br.y, t.tl.y + 64);\n\n    for (t.tl.x = r.tl.x; t.tl.x < r.br.x; t.tl.x += 64) {\n\n      t.br.x = __rfbmin(r.br.x, t.tl.x + 64);\n\n      int mode = zis->readU8();\n      bool rle = mode & 128;\n      int palSize = mode & 127;\n      PIXEL_T palette[128];\n\n      for (int i = 0; i < palSize; i++) {\n        palette[i] = READ_PIXEL(zis);\n      }\n\n      if (palSize == 1) {\n        PIXEL_T pix = palette[0];\n        pb->fillRect(pf, t, &pix);\n        continue;\n      }\n\n      if (!rle) {\n        if (palSize == 0) {\n\n          // raw\n\n#ifdef CPIXEL\n          for (PIXEL_T* ptr = buf; ptr < buf+t.area(); ptr++) {\n            *ptr = READ_PIXEL(zis);\n          }\n#else\n          zis->readBytes(buf, t.area() * (BPP / 8));\n#endif\n\n        } else {\n\n          // packed pixels\n          int bppp = ((palSize > 16) ? 8 :\n                      ((palSize > 4) ? 4 : ((palSize > 2) ? 2 : 1)));\n\n          PIXEL_T* ptr = buf;\n\n          for (int i = 0; i < t.height(); i++) {\n            PIXEL_T* eol = ptr + t.width();\n            rdr::U8 byte = 0;\n            rdr::U8 nbits = 0;\n\n            while (ptr < eol) {\n              if (nbits == 0) {\n                byte = zis->readU8();\n                nbits = 8;\n              }\n              nbits -= bppp;\n              rdr::U8 index = (byte >> nbits) & ((1 << bppp) - 1) & 127;\n              *ptr++ = palette[index];\n            }\n          }\n        }\n\n      } else {\n\n        if (palSize == 0) {\n\n          // plain RLE\n\n          PIXEL_T* ptr = buf;\n          PIXEL_T* end = ptr + t.area();\n          while (ptr < end) {\n            PIXEL_T pix = READ_PIXEL(zis);\n            int len = 1;\n            int b;\n            do {\n              b = zis->readU8();\n              len += b;\n            } while (b == 255);\n\n            if (end - ptr < len) {\n              throw Exception (\"ZRLE decode error\");\n            }\n\n            while (len-- > 0) *ptr++ = pix;\n\n          }\n        } else {\n\n          // palette RLE\n\n          PIXEL_T* ptr = buf;\n          PIXEL_T* end = ptr + t.area();\n          while (ptr < end) {\n            int index = zis->readU8();\n            int len = 1;\n            if (index & 128) {\n              int b;\n              do {\n                b = zis->readU8();\n                len += b;\n              } while (b == 255);\n\n              if (end - ptr < len) {\n                throw Exception (\"ZRLE decode error\");\n              }\n            }\n\n            index &= 127;\n\n            PIXEL_T pix = palette[index];\n\n            while (len-- > 0) *ptr++ = pix;\n          }\n        }\n      }\n\n      pb->imageRect(pf, t, buf);\n    }\n  }\n\n  zis->removeUnderlying();\n}", "func_hash": 266797184622822909427515310440359797331, "file_name": "None", "file_hash": null, "cwe": ["CWE-672"], "cve": "CVE-2019-15691", "cve_desc": "TigerVNC version prior to 1.10.1 is vulnerable to stack use-after-return, which occurs due to incorrect usage of stack memory in ZRLEDecoder. If decoding routine would throw an exception, ZRLEDecoder may try to access stack variable, which has been already freed during the process of stack unwinding. Exploitation of this vulnerability could potentially result into remote code execution. This attack appear to be exploitable via network connectivity.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-15691"}
{"idx": 376682, "project": "tigervnc", "commit_id": "d61a767d6842b530ffb532ddd5a3d233119aad40", "project_url": "https://github.com/CendioOssman/tigervnc", "commit_url": "https://github.com/CendioOssman/tigervnc/commit/d61a767d6842b530ffb532ddd5a3d233119aad40", "commit_message": "Make ZlibInStream more robust against failures\n\nMove the checks around to avoid missing cases where we might access\nmemory that is no longer valid. Also avoid touching the underlying\nstream implicitly (e.g. via the destructor) as it might also no\nlonger be valid.\n\nA malicious server could theoretically use this for remote code\nexecution in the client.\n\nIssue found by Pavel Cheremushkin from Kaspersky Lab", "target": 0, "func": "void ZRLE_DECODE (const Rect& r, rdr::InStream* is,\n                  rdr::ZlibInStream* zis,\n                  const PixelFormat& pf, ModifiablePixelBuffer* pb)\n{\n  int length = is->readU32();\n  zis->setUnderlying(is, length);\n  Rect t;\n  PIXEL_T buf[64 * 64];\n\n  for (t.tl.y = r.tl.y; t.tl.y < r.br.y; t.tl.y += 64) {\n\n    t.br.y = __rfbmin(r.br.y, t.tl.y + 64);\n\n    for (t.tl.x = r.tl.x; t.tl.x < r.br.x; t.tl.x += 64) {\n\n      t.br.x = __rfbmin(r.br.x, t.tl.x + 64);\n\n      int mode = zis->readU8();\n      bool rle = mode & 128;\n      int palSize = mode & 127;\n      PIXEL_T palette[128];\n\n      for (int i = 0; i < palSize; i++) {\n        palette[i] = READ_PIXEL(zis);\n      }\n\n      if (palSize == 1) {\n        PIXEL_T pix = palette[0];\n        pb->fillRect(pf, t, &pix);\n        continue;\n      }\n\n      if (!rle) {\n        if (palSize == 0) {\n\n          // raw\n\n#ifdef CPIXEL\n          for (PIXEL_T* ptr = buf; ptr < buf+t.area(); ptr++) {\n            *ptr = READ_PIXEL(zis);\n          }\n#else\n          zis->readBytes(buf, t.area() * (BPP / 8));\n#endif\n\n        } else {\n\n          // packed pixels\n          int bppp = ((palSize > 16) ? 8 :\n                      ((palSize > 4) ? 4 : ((palSize > 2) ? 2 : 1)));\n\n          PIXEL_T* ptr = buf;\n\n          for (int i = 0; i < t.height(); i++) {\n            PIXEL_T* eol = ptr + t.width();\n            rdr::U8 byte = 0;\n            rdr::U8 nbits = 0;\n\n            while (ptr < eol) {\n              if (nbits == 0) {\n                byte = zis->readU8();\n                nbits = 8;\n              }\n              nbits -= bppp;\n              rdr::U8 index = (byte >> nbits) & ((1 << bppp) - 1) & 127;\n              *ptr++ = palette[index];\n            }\n          }\n        }\n\n      } else {\n\n        if (palSize == 0) {\n\n          // plain RLE\n\n          PIXEL_T* ptr = buf;\n          PIXEL_T* end = ptr + t.area();\n          while (ptr < end) {\n            PIXEL_T pix = READ_PIXEL(zis);\n            int len = 1;\n            int b;\n            do {\n              b = zis->readU8();\n              len += b;\n            } while (b == 255);\n\n            if (end - ptr < len) {\n              throw Exception (\"ZRLE decode error\");\n            }\n\n            while (len-- > 0) *ptr++ = pix;\n\n          }\n        } else {\n\n          // palette RLE\n\n          PIXEL_T* ptr = buf;\n          PIXEL_T* end = ptr + t.area();\n          while (ptr < end) {\n            int index = zis->readU8();\n            int len = 1;\n            if (index & 128) {\n              int b;\n              do {\n                b = zis->readU8();\n                len += b;\n              } while (b == 255);\n\n              if (end - ptr < len) {\n                throw Exception (\"ZRLE decode error\");\n              }\n            }\n\n            index &= 127;\n\n            PIXEL_T pix = palette[index];\n\n            while (len-- > 0) *ptr++ = pix;\n          }\n        }\n      }\n\n      pb->imageRect(pf, t, buf);\n    }\n  }\n\n  zis->flushUnderlying();\n  zis->setUnderlying(NULL, 0);\n}", "func_hash": 147406355021092564490243997240144808169, "file_name": "None", "file_hash": null, "cwe": ["CWE-672"], "cve": "CVE-2019-15691", "cve_desc": "TigerVNC version prior to 1.10.1 is vulnerable to stack use-after-return, which occurs due to incorrect usage of stack memory in ZRLEDecoder. If decoding routine would throw an exception, ZRLEDecoder may try to access stack variable, which has been already freed during the process of stack unwinding. Exploitation of this vulnerability could potentially result into remote code execution. This attack appear to be exploitable via network connectivity.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-15691"}
{"idx": 206262, "project": "vim", "commit_id": "c6fdb15d423df22e1776844811d082322475e48a", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/c6fdb15d423df22e1776844811d082322475e48a", "commit_message": "patch 9.0.0025: accessing beyond allocated memory with the cmdline window\n\nProblem:    Accessing beyond allocated memory when using the cmdline window in\n            Ex mode.\nSolution:   Use \"*\" instead of \"'<,'>\" for Visual mode.", "target": 1, "func": "parse_command_modifiers(\n\texarg_T\t    *eap,\n\tchar\t    **errormsg,\n\tcmdmod_T    *cmod,\n\tint\t    skip_only)\n{\n    char_u  *orig_cmd = eap->cmd;\n    char_u  *cmd_start = NULL;\n    int\t    use_plus_cmd = FALSE;\n    int\t    starts_with_colon = FALSE;\n    int\t    vim9script = in_vim9script();\n    int\t    has_visual_range = FALSE;\n\n    CLEAR_POINTER(cmod);\n    cmod->cmod_flags = sticky_cmdmod_flags;\n\n    if (STRNCMP(eap->cmd, \"'<,'>\", 5) == 0)\n    {\n\t// The automatically inserted Visual area range is skipped, so that\n\t// typing \":cmdmod cmd\" in Visual mode works without having to move the\n\t// range to after the modififiers. The command will be\n\t// \"'<,'>cmdmod cmd\", parse \"cmdmod cmd\" and then put back \"'<,'>\"\n\t// before \"cmd\" below.\n\teap->cmd += 5;\n\tcmd_start = eap->cmd;\n\thas_visual_range = TRUE;\n    }\n\n    // Repeat until no more command modifiers are found.\n    for (;;)\n    {\n\tchar_u  *p;\n\n\twhile (*eap->cmd == ' ' || *eap->cmd == '\\t' || *eap->cmd == ':')\n\t{\n\t    if (*eap->cmd == ':')\n\t\tstarts_with_colon = TRUE;\n\t    ++eap->cmd;\n\t}\n\n\t// in ex mode, an empty command (after modifiers) works like :+\n\tif (*eap->cmd == NUL && exmode_active\n\t\t   && (getline_equal(eap->getline, eap->cookie, getexmodeline)\n\t\t       || getline_equal(eap->getline, eap->cookie, getexline))\n\t\t\t&& curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)\n\t{\n\t    use_plus_cmd = TRUE;\n\t    if (!skip_only)\n\t\tex_pressedreturn = TRUE;\n\t    break;  // no modifiers following\n\t}\n\n\t// ignore comment and empty lines\n\tif (comment_start(eap->cmd, starts_with_colon))\n\t{\n\t    // a comment ends at a NL\n\t    if (eap->nextcmd == NULL)\n\t    {\n\t\teap->nextcmd = vim_strchr(eap->cmd, '\\n');\n\t\tif (eap->nextcmd != NULL)\n\t\t    ++eap->nextcmd;\n\t    }\n\t    if (vim9script && has_cmdmod(cmod, FALSE))\n\t\t*errormsg = _(e_command_modifier_without_command);\n\t    return FAIL;\n\t}\n\tif (*eap->cmd == NUL)\n\t{\n\t    if (!skip_only)\n\t    {\n\t\tex_pressedreturn = TRUE;\n\t\tif (vim9script && has_cmdmod(cmod, FALSE))\n\t\t    *errormsg = _(e_command_modifier_without_command);\n\t    }\n\t    return FAIL;\n\t}\n\n\tp = skip_range(eap->cmd, TRUE, NULL);\n\n\t// In Vim9 script a variable can shadow a command modifier:\n\t//   verbose = 123\n\t//   verbose += 123\n\t//   silent! verbose = func()\n\t//   verbose.member = 2\n\t//   verbose[expr] = 2\n\t// But not:\n\t//   verbose [a, b] = list\n\tif (vim9script)\n\t{\n\t    char_u *s, *n;\n\n\t    for (s = eap->cmd; ASCII_ISALPHA(*s); ++s)\n\t\t;\n\t    n = skipwhite(s);\n\t    if (*n == '.' || *n == '=' || (*n != NUL && n[1] == '=')\n\t\t    || *s == '[')\n\t\tbreak;\n\t}\n\n\tswitch (*p)\n\t{\n\t    // When adding an entry, also modify cmd_exists().\n\t    case 'a':\tif (!checkforcmd_noparen(&eap->cmd, \"aboveleft\", 3))\n\t\t\t    break;\n\t\t\tcmod->cmod_split |= WSP_ABOVE;\n\t\t\tcontinue;\n\n\t    case 'b':\tif (checkforcmd_noparen(&eap->cmd, \"belowright\", 3))\n\t\t\t{\n\t\t\t    cmod->cmod_split |= WSP_BELOW;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (checkforcmd_opt(&eap->cmd, \"browse\", 3, TRUE))\n\t\t\t{\n#ifdef FEAT_BROWSE_CMD\n\t\t\t    cmod->cmod_flags |= CMOD_BROWSE;\n#endif\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (!checkforcmd_noparen(&eap->cmd, \"botright\", 2))\n\t\t\t    break;\n\t\t\tcmod->cmod_split |= WSP_BOT;\n\t\t\tcontinue;\n\n\t    case 'c':\tif (!checkforcmd_opt(&eap->cmd, \"confirm\", 4, TRUE))\n\t\t\t    break;\n#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)\n\t\t\tcmod->cmod_flags |= CMOD_CONFIRM;\n#endif\n\t\t\tcontinue;\n\n\t    case 'k':\tif (checkforcmd_noparen(&eap->cmd, \"keepmarks\", 3))\n\t\t\t{\n\t\t\t    cmod->cmod_flags |= CMOD_KEEPMARKS;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (checkforcmd_noparen(&eap->cmd, \"keepalt\", 5))\n\t\t\t{\n\t\t\t    cmod->cmod_flags |= CMOD_KEEPALT;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (checkforcmd_noparen(&eap->cmd, \"keeppatterns\", 5))\n\t\t\t{\n\t\t\t    cmod->cmod_flags |= CMOD_KEEPPATTERNS;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (!checkforcmd_noparen(&eap->cmd, \"keepjumps\", 5))\n\t\t\t    break;\n\t\t\tcmod->cmod_flags |= CMOD_KEEPJUMPS;\n\t\t\tcontinue;\n\n\t    case 'f':\t// only accept \":filter {pat} cmd\"\n\t\t\t{\n\t\t\t    char_u  *reg_pat;\n\t\t\t    char_u  *nulp = NULL;\n\t\t\t    int\t    c = 0;\n\n\t\t\t    if (!checkforcmd_noparen(&p, \"filter\", 4)\n\t\t\t\t    || *p == NUL\n\t\t\t\t    || (ends_excmd(*p)\n#ifdef FEAT_EVAL\n\t\t\t\t\t// in \":filter #pat# cmd\" # does not\n\t\t\t\t\t// start a comment\n\t\t\t\t     && (!vim9script || VIM_ISWHITE(p[1]))\n#endif\n\t\t\t\t     ))\n\t\t\t\tbreak;\n\t\t\t    if (*p == '!')\n\t\t\t    {\n\t\t\t\tcmod->cmod_filter_force = TRUE;\n\t\t\t\tp = skipwhite(p + 1);\n\t\t\t\tif (*p == NUL || ends_excmd(*p))\n\t\t\t\t    break;\n\t\t\t    }\n#ifdef FEAT_EVAL\n\t\t\t    // Avoid that \"filter(arg)\" is recognized.\n\t\t\t    if (vim9script && !VIM_ISWHITE(p[-1]))\n\t\t\t\tbreak;\n#endif\n\t\t\t    if (skip_only)\n\t\t\t\tp = skip_vimgrep_pat(p, NULL, NULL);\n\t\t\t    else\n\t\t\t\t// NOTE: This puts a NUL after the pattern.\n\t\t\t\tp = skip_vimgrep_pat_ext(p, ®_pat, NULL,\n\t\t\t\t\t\t\t\t    &nulp, &c);\n\t\t\t    if (p == NULL || *p == NUL)\n\t\t\t\tbreak;\n\t\t\t    if (!skip_only)\n\t\t\t    {\n\t\t\t\tcmod->cmod_filter_regmatch.regprog =\n\t\t\t\t\t\tvim_regcomp(reg_pat, RE_MAGIC);\n\t\t\t\tif (cmod->cmod_filter_regmatch.regprog == NULL)\n\t\t\t\t    break;\n\t\t\t\t// restore the character overwritten by NUL\n\t\t\t\tif (nulp != NULL)\n\t\t\t\t    *nulp = c;\n\t\t\t    }\n\t\t\t    eap->cmd = p;\n\t\t\t    continue;\n\t\t\t}\n\n\t\t\t// \":hide\" and \":hide | cmd\" are not modifiers\n\t    case 'h':\tif (p != eap->cmd || !checkforcmd_noparen(&p, \"hide\", 3)\n\t\t\t\t\t       || *p == NUL || ends_excmd(*p))\n\t\t\t    break;\n\t\t\teap->cmd = p;\n\t\t\tcmod->cmod_flags |= CMOD_HIDE;\n\t\t\tcontinue;\n\n\t    case 'l':\tif (checkforcmd_noparen(&eap->cmd, \"lockmarks\", 3))\n\t\t\t{\n\t\t\t    cmod->cmod_flags |= CMOD_LOCKMARKS;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (checkforcmd_noparen(&eap->cmd, \"legacy\", 3))\n\t\t\t{\n\t\t\t    if (ends_excmd2(p, eap->cmd))\n\t\t\t    {\n\t\t\t\t*errormsg =\n\t\t\t\t      _(e_legacy_must_be_followed_by_command);\n\t\t\t\treturn FAIL;\n\t\t\t    }\n\t\t\t    cmod->cmod_flags |= CMOD_LEGACY;\n\t\t\t    continue;\n\t\t\t}\n\n\t\t\tif (!checkforcmd_noparen(&eap->cmd, \"leftabove\", 5))\n\t\t\t    break;\n\t\t\tcmod->cmod_split |= WSP_ABOVE;\n\t\t\tcontinue;\n\n\t    case 'n':\tif (checkforcmd_noparen(&eap->cmd, \"noautocmd\", 3))\n\t\t\t{\n\t\t\t    cmod->cmod_flags |= CMOD_NOAUTOCMD;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (!checkforcmd_noparen(&eap->cmd, \"noswapfile\", 3))\n\t\t\t    break;\n\t\t\tcmod->cmod_flags |= CMOD_NOSWAPFILE;\n\t\t\tcontinue;\n\n\t    case 'r':\tif (!checkforcmd_noparen(&eap->cmd, \"rightbelow\", 6))\n\t\t\t    break;\n\t\t\tcmod->cmod_split |= WSP_BELOW;\n\t\t\tcontinue;\n\n\t    case 's':\tif (checkforcmd_noparen(&eap->cmd, \"sandbox\", 3))\n\t\t\t{\n\t\t\t    cmod->cmod_flags |= CMOD_SANDBOX;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (!checkforcmd_noparen(&eap->cmd, \"silent\", 3))\n\t\t\t    break;\n\t\t\tcmod->cmod_flags |= CMOD_SILENT;\n\t\t\tif (*eap->cmd == '!' && !VIM_ISWHITE(eap->cmd[-1]))\n\t\t\t{\n\t\t\t    // \":silent!\", but not \"silent !cmd\"\n\t\t\t    eap->cmd = skipwhite(eap->cmd + 1);\n\t\t\t    cmod->cmod_flags |= CMOD_ERRSILENT;\n\t\t\t}\n\t\t\tcontinue;\n\n\t    case 't':\tif (checkforcmd_noparen(&p, \"tab\", 3))\n\t\t\t{\n\t\t\t    if (!skip_only)\n\t\t\t    {\n\t\t\t\tlong tabnr = get_address(eap, &eap->cmd,\n\t\t\t\t\t\t    ADDR_TABS, eap->skip,\n\t\t\t\t\t\t    skip_only, FALSE, 1);\n\t\t\t\tif (tabnr == MAXLNUM)\n\t\t\t\t    cmod->cmod_tab = tabpage_index(curtab) + 1;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t    if (tabnr < 0 || tabnr > LAST_TAB_NR)\n\t\t\t\t    {\n\t\t\t\t\t*errormsg = _(e_invalid_range);\n\t\t\t\t\treturn FAIL;\n\t\t\t\t    }\n\t\t\t\t    cmod->cmod_tab = tabnr + 1;\n\t\t\t\t}\n\t\t\t    }\n\t\t\t    eap->cmd = p;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (!checkforcmd_noparen(&eap->cmd, \"topleft\", 2))\n\t\t\t    break;\n\t\t\tcmod->cmod_split |= WSP_TOP;\n\t\t\tcontinue;\n\n\t    case 'u':\tif (!checkforcmd_noparen(&eap->cmd, \"unsilent\", 3))\n\t\t\t    break;\n\t\t\tcmod->cmod_flags |= CMOD_UNSILENT;\n\t\t\tcontinue;\n\n\t    case 'v':\tif (checkforcmd_noparen(&eap->cmd, \"vertical\", 4))\n\t\t\t{\n\t\t\t    cmod->cmod_split |= WSP_VERT;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (checkforcmd_noparen(&eap->cmd, \"vim9cmd\", 4))\n\t\t\t{\n\t\t\t    if (ends_excmd2(p, eap->cmd))\n\t\t\t    {\n\t\t\t\t*errormsg =\n\t\t\t\t      _(e_vim9cmd_must_be_followed_by_command);\n\t\t\t\treturn FAIL;\n\t\t\t    }\n\t\t\t    cmod->cmod_flags |= CMOD_VIM9CMD;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (!checkforcmd_noparen(&p, \"verbose\", 4))\n\t\t\t    break;\n\t\t\tif (vim_isdigit(*eap->cmd))\n\t\t\t{\n\t\t\t    // zero means not set, one is verbose == 0, etc.\n\t\t\t    cmod->cmod_verbose = atoi((char *)eap->cmd) + 1;\n\t\t\t}\n\t\t\telse\n\t\t\t    cmod->cmod_verbose = 2;  // default: verbose == 1\n\t\t\teap->cmd = p;\n\t\t\tcontinue;\n\t}\n\tbreak;\n    }\n\n    if (has_visual_range)\n    {\n\tif (eap->cmd > cmd_start)\n\t{\n\t    // Move the '<,'> range to after the modifiers and insert a colon.\n\t    // Since the modifiers have been parsed put the colon on top of the\n\t    // space: \"'<,'>mod cmd\" -> \"mod:'<,'>cmd\n\t    // Put eap->cmd after the colon.\n\t    if (use_plus_cmd)\n\t    {\n\t\tsize_t len = STRLEN(cmd_start);\n\n\t\t// Special case: empty command uses \"+\":\n\t\t//  \"'<,'>mods\" -> \"mods'<,'>+\n\t\tmch_memmove(orig_cmd, cmd_start, len);\n\t\tSTRCPY(orig_cmd + len, \"'<,'>+\");\n\t    }\n\t    else\n\t    {\n\t\tmch_memmove(cmd_start - 5, cmd_start, eap->cmd - cmd_start);\n\t\teap->cmd -= 5;\n\t\tmch_memmove(eap->cmd - 1, \":'<,'>\", 6);\n\t    }\n\t}\n\telse\n\t    // No modifiers, move the pointer back.\n\t    // Special case: change empty command to \"+\".\n\t    if (use_plus_cmd)\n\t\teap->cmd = (char_u *)\"'<,'>+\";\n\t    else\n\t\teap->cmd = orig_cmd;\n    }\n    else if (use_plus_cmd)\n\teap->cmd = (char_u *)\"+\";\n\n    return OK;\n}", "func_hash": 61928994098668347793112269457604758897, "file_name": "ex_docmd.c", "file_hash": 287878878694425028301990758845576774946, "cwe": ["CWE-787"], "cve": "CVE-2022-2288", "cve_desc": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2288"}
{"idx": 379334, "project": "vim", "commit_id": "c6fdb15d423df22e1776844811d082322475e48a", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/c6fdb15d423df22e1776844811d082322475e48a", "commit_message": "patch 9.0.0025: accessing beyond allocated memory with the cmdline window\n\nProblem:    Accessing beyond allocated memory when using the cmdline window in\n            Ex mode.\nSolution:   Use \"*\" instead of \"'<,'>\" for Visual mode.", "target": 0, "func": "parse_command_modifiers(\n\texarg_T\t    *eap,\n\tchar\t    **errormsg,\n\tcmdmod_T    *cmod,\n\tint\t    skip_only)\n{\n    char_u  *orig_cmd = eap->cmd;\n    char_u  *cmd_start = NULL;\n    int\t    use_plus_cmd = FALSE;\n    int\t    starts_with_colon = FALSE;\n    int\t    vim9script = in_vim9script();\n    int\t    has_visual_range = FALSE;\n\n    CLEAR_POINTER(cmod);\n    cmod->cmod_flags = sticky_cmdmod_flags;\n\n    if (STRNCMP(eap->cmd, \"'<,'>\", 5) == 0)\n    {\n\t// The automatically inserted Visual area range is skipped, so that\n\t// typing \":cmdmod cmd\" in Visual mode works without having to move the\n\t// range to after the modififiers. The command will be\n\t// \"'<,'>cmdmod cmd\", parse \"cmdmod cmd\" and then put back \"'<,'>\"\n\t// before \"cmd\" below.\n\teap->cmd += 5;\n\tcmd_start = eap->cmd;\n\thas_visual_range = TRUE;\n    }\n\n    // Repeat until no more command modifiers are found.\n    for (;;)\n    {\n\tchar_u  *p;\n\n\twhile (*eap->cmd == ' ' || *eap->cmd == '\\t' || *eap->cmd == ':')\n\t{\n\t    if (*eap->cmd == ':')\n\t\tstarts_with_colon = TRUE;\n\t    ++eap->cmd;\n\t}\n\n\t// in ex mode, an empty command (after modifiers) works like :+\n\tif (*eap->cmd == NUL && exmode_active\n\t\t   && (getline_equal(eap->getline, eap->cookie, getexmodeline)\n\t\t       || getline_equal(eap->getline, eap->cookie, getexline))\n\t\t\t&& curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)\n\t{\n\t    use_plus_cmd = TRUE;\n\t    if (!skip_only)\n\t\tex_pressedreturn = TRUE;\n\t    break;  // no modifiers following\n\t}\n\n\t// ignore comment and empty lines\n\tif (comment_start(eap->cmd, starts_with_colon))\n\t{\n\t    // a comment ends at a NL\n\t    if (eap->nextcmd == NULL)\n\t    {\n\t\teap->nextcmd = vim_strchr(eap->cmd, '\\n');\n\t\tif (eap->nextcmd != NULL)\n\t\t    ++eap->nextcmd;\n\t    }\n\t    if (vim9script && has_cmdmod(cmod, FALSE))\n\t\t*errormsg = _(e_command_modifier_without_command);\n\t    return FAIL;\n\t}\n\tif (*eap->cmd == NUL)\n\t{\n\t    if (!skip_only)\n\t    {\n\t\tex_pressedreturn = TRUE;\n\t\tif (vim9script && has_cmdmod(cmod, FALSE))\n\t\t    *errormsg = _(e_command_modifier_without_command);\n\t    }\n\t    return FAIL;\n\t}\n\n\tp = skip_range(eap->cmd, TRUE, NULL);\n\n\t// In Vim9 script a variable can shadow a command modifier:\n\t//   verbose = 123\n\t//   verbose += 123\n\t//   silent! verbose = func()\n\t//   verbose.member = 2\n\t//   verbose[expr] = 2\n\t// But not:\n\t//   verbose [a, b] = list\n\tif (vim9script)\n\t{\n\t    char_u *s, *n;\n\n\t    for (s = eap->cmd; ASCII_ISALPHA(*s); ++s)\n\t\t;\n\t    n = skipwhite(s);\n\t    if (*n == '.' || *n == '=' || (*n != NUL && n[1] == '=')\n\t\t    || *s == '[')\n\t\tbreak;\n\t}\n\n\tswitch (*p)\n\t{\n\t    // When adding an entry, also modify cmd_exists().\n\t    case 'a':\tif (!checkforcmd_noparen(&eap->cmd, \"aboveleft\", 3))\n\t\t\t    break;\n\t\t\tcmod->cmod_split |= WSP_ABOVE;\n\t\t\tcontinue;\n\n\t    case 'b':\tif (checkforcmd_noparen(&eap->cmd, \"belowright\", 3))\n\t\t\t{\n\t\t\t    cmod->cmod_split |= WSP_BELOW;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (checkforcmd_opt(&eap->cmd, \"browse\", 3, TRUE))\n\t\t\t{\n#ifdef FEAT_BROWSE_CMD\n\t\t\t    cmod->cmod_flags |= CMOD_BROWSE;\n#endif\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (!checkforcmd_noparen(&eap->cmd, \"botright\", 2))\n\t\t\t    break;\n\t\t\tcmod->cmod_split |= WSP_BOT;\n\t\t\tcontinue;\n\n\t    case 'c':\tif (!checkforcmd_opt(&eap->cmd, \"confirm\", 4, TRUE))\n\t\t\t    break;\n#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)\n\t\t\tcmod->cmod_flags |= CMOD_CONFIRM;\n#endif\n\t\t\tcontinue;\n\n\t    case 'k':\tif (checkforcmd_noparen(&eap->cmd, \"keepmarks\", 3))\n\t\t\t{\n\t\t\t    cmod->cmod_flags |= CMOD_KEEPMARKS;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (checkforcmd_noparen(&eap->cmd, \"keepalt\", 5))\n\t\t\t{\n\t\t\t    cmod->cmod_flags |= CMOD_KEEPALT;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (checkforcmd_noparen(&eap->cmd, \"keeppatterns\", 5))\n\t\t\t{\n\t\t\t    cmod->cmod_flags |= CMOD_KEEPPATTERNS;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (!checkforcmd_noparen(&eap->cmd, \"keepjumps\", 5))\n\t\t\t    break;\n\t\t\tcmod->cmod_flags |= CMOD_KEEPJUMPS;\n\t\t\tcontinue;\n\n\t    case 'f':\t// only accept \":filter {pat} cmd\"\n\t\t\t{\n\t\t\t    char_u  *reg_pat;\n\t\t\t    char_u  *nulp = NULL;\n\t\t\t    int\t    c = 0;\n\n\t\t\t    if (!checkforcmd_noparen(&p, \"filter\", 4)\n\t\t\t\t    || *p == NUL\n\t\t\t\t    || (ends_excmd(*p)\n#ifdef FEAT_EVAL\n\t\t\t\t\t// in \":filter #pat# cmd\" # does not\n\t\t\t\t\t// start a comment\n\t\t\t\t     && (!vim9script || VIM_ISWHITE(p[1]))\n#endif\n\t\t\t\t     ))\n\t\t\t\tbreak;\n\t\t\t    if (*p == '!')\n\t\t\t    {\n\t\t\t\tcmod->cmod_filter_force = TRUE;\n\t\t\t\tp = skipwhite(p + 1);\n\t\t\t\tif (*p == NUL || ends_excmd(*p))\n\t\t\t\t    break;\n\t\t\t    }\n#ifdef FEAT_EVAL\n\t\t\t    // Avoid that \"filter(arg)\" is recognized.\n\t\t\t    if (vim9script && !VIM_ISWHITE(p[-1]))\n\t\t\t\tbreak;\n#endif\n\t\t\t    if (skip_only)\n\t\t\t\tp = skip_vimgrep_pat(p, NULL, NULL);\n\t\t\t    else\n\t\t\t\t// NOTE: This puts a NUL after the pattern.\n\t\t\t\tp = skip_vimgrep_pat_ext(p, ®_pat, NULL,\n\t\t\t\t\t\t\t\t    &nulp, &c);\n\t\t\t    if (p == NULL || *p == NUL)\n\t\t\t\tbreak;\n\t\t\t    if (!skip_only)\n\t\t\t    {\n\t\t\t\tcmod->cmod_filter_regmatch.regprog =\n\t\t\t\t\t\tvim_regcomp(reg_pat, RE_MAGIC);\n\t\t\t\tif (cmod->cmod_filter_regmatch.regprog == NULL)\n\t\t\t\t    break;\n\t\t\t\t// restore the character overwritten by NUL\n\t\t\t\tif (nulp != NULL)\n\t\t\t\t    *nulp = c;\n\t\t\t    }\n\t\t\t    eap->cmd = p;\n\t\t\t    continue;\n\t\t\t}\n\n\t\t\t// \":hide\" and \":hide | cmd\" are not modifiers\n\t    case 'h':\tif (p != eap->cmd || !checkforcmd_noparen(&p, \"hide\", 3)\n\t\t\t\t\t       || *p == NUL || ends_excmd(*p))\n\t\t\t    break;\n\t\t\teap->cmd = p;\n\t\t\tcmod->cmod_flags |= CMOD_HIDE;\n\t\t\tcontinue;\n\n\t    case 'l':\tif (checkforcmd_noparen(&eap->cmd, \"lockmarks\", 3))\n\t\t\t{\n\t\t\t    cmod->cmod_flags |= CMOD_LOCKMARKS;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (checkforcmd_noparen(&eap->cmd, \"legacy\", 3))\n\t\t\t{\n\t\t\t    if (ends_excmd2(p, eap->cmd))\n\t\t\t    {\n\t\t\t\t*errormsg =\n\t\t\t\t      _(e_legacy_must_be_followed_by_command);\n\t\t\t\treturn FAIL;\n\t\t\t    }\n\t\t\t    cmod->cmod_flags |= CMOD_LEGACY;\n\t\t\t    continue;\n\t\t\t}\n\n\t\t\tif (!checkforcmd_noparen(&eap->cmd, \"leftabove\", 5))\n\t\t\t    break;\n\t\t\tcmod->cmod_split |= WSP_ABOVE;\n\t\t\tcontinue;\n\n\t    case 'n':\tif (checkforcmd_noparen(&eap->cmd, \"noautocmd\", 3))\n\t\t\t{\n\t\t\t    cmod->cmod_flags |= CMOD_NOAUTOCMD;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (!checkforcmd_noparen(&eap->cmd, \"noswapfile\", 3))\n\t\t\t    break;\n\t\t\tcmod->cmod_flags |= CMOD_NOSWAPFILE;\n\t\t\tcontinue;\n\n\t    case 'r':\tif (!checkforcmd_noparen(&eap->cmd, \"rightbelow\", 6))\n\t\t\t    break;\n\t\t\tcmod->cmod_split |= WSP_BELOW;\n\t\t\tcontinue;\n\n\t    case 's':\tif (checkforcmd_noparen(&eap->cmd, \"sandbox\", 3))\n\t\t\t{\n\t\t\t    cmod->cmod_flags |= CMOD_SANDBOX;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (!checkforcmd_noparen(&eap->cmd, \"silent\", 3))\n\t\t\t    break;\n\t\t\tcmod->cmod_flags |= CMOD_SILENT;\n\t\t\tif (*eap->cmd == '!' && !VIM_ISWHITE(eap->cmd[-1]))\n\t\t\t{\n\t\t\t    // \":silent!\", but not \"silent !cmd\"\n\t\t\t    eap->cmd = skipwhite(eap->cmd + 1);\n\t\t\t    cmod->cmod_flags |= CMOD_ERRSILENT;\n\t\t\t}\n\t\t\tcontinue;\n\n\t    case 't':\tif (checkforcmd_noparen(&p, \"tab\", 3))\n\t\t\t{\n\t\t\t    if (!skip_only)\n\t\t\t    {\n\t\t\t\tlong tabnr = get_address(eap, &eap->cmd,\n\t\t\t\t\t\t    ADDR_TABS, eap->skip,\n\t\t\t\t\t\t    skip_only, FALSE, 1);\n\t\t\t\tif (tabnr == MAXLNUM)\n\t\t\t\t    cmod->cmod_tab = tabpage_index(curtab) + 1;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t    if (tabnr < 0 || tabnr > LAST_TAB_NR)\n\t\t\t\t    {\n\t\t\t\t\t*errormsg = _(e_invalid_range);\n\t\t\t\t\treturn FAIL;\n\t\t\t\t    }\n\t\t\t\t    cmod->cmod_tab = tabnr + 1;\n\t\t\t\t}\n\t\t\t    }\n\t\t\t    eap->cmd = p;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (!checkforcmd_noparen(&eap->cmd, \"topleft\", 2))\n\t\t\t    break;\n\t\t\tcmod->cmod_split |= WSP_TOP;\n\t\t\tcontinue;\n\n\t    case 'u':\tif (!checkforcmd_noparen(&eap->cmd, \"unsilent\", 3))\n\t\t\t    break;\n\t\t\tcmod->cmod_flags |= CMOD_UNSILENT;\n\t\t\tcontinue;\n\n\t    case 'v':\tif (checkforcmd_noparen(&eap->cmd, \"vertical\", 4))\n\t\t\t{\n\t\t\t    cmod->cmod_split |= WSP_VERT;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (checkforcmd_noparen(&eap->cmd, \"vim9cmd\", 4))\n\t\t\t{\n\t\t\t    if (ends_excmd2(p, eap->cmd))\n\t\t\t    {\n\t\t\t\t*errormsg =\n\t\t\t\t      _(e_vim9cmd_must_be_followed_by_command);\n\t\t\t\treturn FAIL;\n\t\t\t    }\n\t\t\t    cmod->cmod_flags |= CMOD_VIM9CMD;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif (!checkforcmd_noparen(&p, \"verbose\", 4))\n\t\t\t    break;\n\t\t\tif (vim_isdigit(*eap->cmd))\n\t\t\t{\n\t\t\t    // zero means not set, one is verbose == 0, etc.\n\t\t\t    cmod->cmod_verbose = atoi((char *)eap->cmd) + 1;\n\t\t\t}\n\t\t\telse\n\t\t\t    cmod->cmod_verbose = 2;  // default: verbose == 1\n\t\t\teap->cmd = p;\n\t\t\tcontinue;\n\t}\n\tbreak;\n    }\n\n    if (has_visual_range)\n    {\n\tif (eap->cmd > cmd_start)\n\t{\n\t    // Move the '<,'> range to after the modifiers and insert a colon.\n\t    // Since the modifiers have been parsed put the colon on top of the\n\t    // space: \"'<,'>mod cmd\" -> \"mod:'<,'>cmd\n\t    // Put eap->cmd after the colon.\n\t    if (use_plus_cmd)\n\t    {\n\t\tsize_t len = STRLEN(cmd_start);\n\n\t\t// Special case: empty command uses \"+\":\n\t\t//  \"'<,'>mods\" -> \"mods *+\n\t\t//  Use \"*\" instead of \"'<,'>\" to avoid the command getting\n\t\t//  longer, in case is was allocated.\n\t\tmch_memmove(orig_cmd, cmd_start, len);\n\t\tSTRCPY(orig_cmd + len, \" *+\");\n\t    }\n\t    else\n\t    {\n\t\tmch_memmove(cmd_start - 5, cmd_start, eap->cmd - cmd_start);\n\t\teap->cmd -= 5;\n\t\tmch_memmove(eap->cmd - 1, \":'<,'>\", 6);\n\t    }\n\t}\n\telse\n\t    // No modifiers, move the pointer back.\n\t    // Special case: change empty command to \"+\".\n\t    if (use_plus_cmd)\n\t\teap->cmd = (char_u *)\"'<,'>+\";\n\t    else\n\t\teap->cmd = orig_cmd;\n    }\n    else if (use_plus_cmd)\n\teap->cmd = (char_u *)\"+\";\n\n    return OK;\n}", "func_hash": 128847198820720658441664267481456465295, "file_name": "ex_docmd.c", "file_hash": 80050062526332961104670632599823980115, "cwe": ["CWE-787"], "cve": "CVE-2022-2288", "cve_desc": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2288"}
{"idx": 206273, "project": "radare2", "commit_id": "a7ce29647fcb38386d7439696375e16e093d6acb", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/a7ce29647fcb38386d7439696375e16e093d6acb", "commit_message": "Fix UAF in aaaa on arm/thumb switching ##crash\n\n* Reported by @peacock-doris via huntr.dev\n* Reproducer tests_65185\n* This is a logic fix, but not the fully safe as changes in the code\n  can result on UAF again, to properly protect r2 from crashing we\n  need to break the ABI and add refcounting to RRegItem, which can't\n  happen in 5.6.x because of abi-compat rules", "target": 1, "func": "static void extract_arg(RAnal *anal, RAnalFunction *fcn, RAnalOp *op, const char *reg, const char *sign, char type) {\n\tst64 ptr = 0;\n\tchar *addr, *esil_buf = NULL;\n\tconst st64 maxstackframe = 1024 * 8; \n\n\tr_return_if_fail (anal && fcn && op && reg);\n\n\tsize_t i;\n\tfor (i = 0; i < R_ARRAY_SIZE (op->src); i++) {\n\t\tif (op->src[i] && op->src[i]->reg && op->src[i]->reg->name) {\n\t\t\tif (!strcmp (reg, op->src[i]->reg->name)) {\n\t\t\t\tst64 delta = op->src[i]->delta;\n\t\t\t\tif ((delta > 0 && *sign == '+') || (delta < 0 && *sign == '-')) {\n\t\t\t\t\tptr = R_ABS (op->src[i]->delta);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!ptr) {\n\t\tconst char *op_esil = r_strbuf_get (&op->esil);\n\t\tif (!op_esil) {\n\t\t\treturn;\n\t\t}\n\t\tesil_buf = strdup (op_esil);\n\t\tif (!esil_buf) {\n\t\t\treturn;\n\t\t}\n\t\tr_strf_var (esilexpr, 64, \",%s,%s,\", reg, sign);\n\t\tchar *ptr_end = strstr (esil_buf, esilexpr);\n\t\tif (!ptr_end) {\n\t\t\tfree (esil_buf);\n\t\t\treturn;\n\t\t}\n\t\t*ptr_end = 0;\n\t\taddr = ptr_end;\n\t\twhile ((addr[0] != '0' || addr[1] != 'x') && addr >= esil_buf + 1 && *addr != ',') {\n\t\t\taddr--;\n\t\t}\n\t\tif (strncmp (addr, \"0x\", 2)) {\n\t\t\t//XXX: This is a workaround for inconsistent esil\n\t\t\tif (!op->stackop && op->dst) {\n\t\t\t\tconst char *sp = r_reg_get_name (anal->reg, R_REG_NAME_SP);\n\t\t\t\tconst char *bp = r_reg_get_name (anal->reg, R_REG_NAME_BP);\n\t\t\t\tconst char *rn = op->dst->reg ? op->dst->reg->name : NULL;\n\t\t\t\tif (rn && ((bp && !strcmp (bp, rn)) || (sp && !strcmp (sp, rn)))) {\n\t\t\t\t\tif (anal->verbose) {\n\t\t\t\t\t\teprintf (\"Warning: Analysis didn't fill op->stackop for instruction that alters stack at 0x%\" PFMT64x \".\\n\", op->addr);\n\t\t\t\t\t}\n\t\t\t\t\tgoto beach;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (*addr == ',') {\n\t\t\t\taddr++;\n\t\t\t}\n\t\t\tif (!op->stackop && op->type != R_ANAL_OP_TYPE_PUSH && op->type != R_ANAL_OP_TYPE_POP\n\t\t\t\t&& op->type != R_ANAL_OP_TYPE_RET && r_str_isnumber (addr)) {\n\t\t\t\tptr = (st64)r_num_get (NULL, addr);\n\t\t\t\tif (ptr && op->src[0] && ptr == op->src[0]->imm) {\n\t\t\t\t\tgoto beach;\n\t\t\t\t}\n\t\t\t} else if ((op->stackop == R_ANAL_STACK_SET) || (op->stackop == R_ANAL_STACK_GET)) {\n\t\t\t\tif (op->ptr % 4) {\n\t\t\t\t\tgoto beach;\n\t\t\t\t}\n\t\t\t\tptr = R_ABS (op->ptr);\n\t\t\t} else {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t} else {\n\t\t\tptr = (st64)r_num_get (NULL, addr);\n\t\t}\n\t}\n\n\tif (anal->verbose && (!op->src[0] || !op->dst)) {\n\t\teprintf (\"Warning: Analysis didn't fill op->src/dst at 0x%\" PFMT64x \".\\n\", op->addr);\n\t}\n\n\tint rw = (op->direction == R_ANAL_OP_DIR_WRITE) ? R_ANAL_VAR_ACCESS_TYPE_WRITE : R_ANAL_VAR_ACCESS_TYPE_READ;\n\tif (*sign == '+') {\n\t\tconst bool isarg = type == R_ANAL_VAR_KIND_SPV ? ptr >= fcn->stack : ptr >= fcn->bp_off;\n\t\tconst char *pfx = isarg ? ARGPREFIX : VARPREFIX;\n\t\tst64 frame_off;\n\t\tif (type == R_ANAL_VAR_KIND_SPV) {\n\t\t\tframe_off = ptr - fcn->stack;\n\t\t} else {\n\t\t\tframe_off = ptr - fcn->bp_off;\n\t\t}\n\t\tif (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {\n\t\t\tgoto beach;\n\t\t}\n\t\tRAnalVar *var = get_stack_var (fcn, frame_off);\n\t\tif (var) {\n\t\t\tr_anal_var_set_access (var, reg, op->addr, rw, ptr);\n\t\t\tgoto beach;\n\t\t}\n\t\tchar *varname = NULL, *vartype = NULL;\n\t\tif (isarg) {\n\t\t\tconst char *place = fcn->cc ? r_anal_cc_arg (anal, fcn->cc, ST32_MAX) : NULL;\n\t\t\tbool stack_rev = place ? !strcmp (place, \"stack_rev\") : false;\n\t\t\tchar *fname = r_type_func_guess (anal->sdb_types, fcn->name);\n\t\t\tif (fname) {\n\t\t\t\tut64 sum_sz = 0;\n\t\t\t\tsize_t from, to, i;\n\t\t\t\tif (stack_rev) {\n\t\t\t\t\tconst size_t cnt = r_type_func_args_count (anal->sdb_types, fname);\n\t\t\t\t\tfrom = cnt ? cnt - 1 : cnt;\n\t\t\t\t\tto = fcn->cc ? r_anal_cc_max_arg (anal, fcn->cc) : 0;\n\t\t\t\t} else {\n\t\t\t\t\tfrom = fcn->cc ? r_anal_cc_max_arg (anal, fcn->cc) : 0;\n\t\t\t\t\tto = r_type_func_args_count (anal->sdb_types, fname);\n\t\t\t\t}\n\t\t\t\tconst int bytes = (fcn->bits ? fcn->bits : anal->bits) / 8;\n\t\t\t\tfor (i = from; stack_rev ? i >= to : i < to; stack_rev ? i-- : i++) {\n\t\t\t\t\tchar *tp = r_type_func_args_type (anal->sdb_types, fname, i);\n\t\t\t\t\tif (!tp) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (sum_sz == frame_off) {\n\t\t\t\t\t\tvartype = tp;\n\t\t\t\t\t\tvarname = strdup (r_type_func_args_name (anal->sdb_types, fname, i));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tut64 bit_sz = r_type_get_bitsize (anal->sdb_types, tp);\n\t\t\t\t\tsum_sz += bit_sz ? bit_sz / 8 : bytes;\n\t\t\t\t\tsum_sz = R_ROUND (sum_sz, bytes);\n\t\t\t\t\tfree (tp);\n\t\t\t\t}\n\t\t\t\tfree (fname);\n\t\t\t}\n\t\t}\n\t\tif (!varname) {\n\t\t\tif (anal->opt.varname_stack) {\n\t\t\t\tvarname = r_str_newf (\"%s_%\" PFMT64x \"h\", pfx, R_ABS (frame_off));\n\t\t\t} else {\n\t\t\t\tvarname = r_anal_function_autoname_var (fcn, type, pfx, ptr);\n\t\t\t}\n\t\t}\n\t\tif (varname) {\n#if 0\n\t\t\tif (isarg && frame_off > 48) {\n\t\t\t\tfree (varname);\n\t\t\t\tgoto beach;\n\t\t\t}\n#endif\n\t\t\tRAnalVar *var = r_anal_function_set_var (fcn, frame_off, type, vartype, anal->bits / 8, isarg, varname);\n\t\t\tif (var) {\n\t\t\t\tr_anal_var_set_access (var, reg, op->addr, rw, ptr);\n\t\t\t}\n\t\t\tfree (varname);\n\t\t}\n\t\tfree (vartype);\n\t} else {\n\t\tst64 frame_off = -(ptr + fcn->bp_off);\n\t\tif (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {\n\t\t\tgoto beach;\n\t\t}\n\t\tRAnalVar *var = get_stack_var (fcn, frame_off);\n\t\tif (var) {\n\t\t\tr_anal_var_set_access (var, reg, op->addr, rw, -ptr);\n\t\t\tgoto beach;\n\t\t}\n\t\tchar *varname = anal->opt.varname_stack\n\t\t\t? r_str_newf (\"%s_%\" PFMT64x \"h\", VARPREFIX, R_ABS (frame_off))\n\t\t\t: r_anal_function_autoname_var (fcn, type, VARPREFIX, -ptr);\n\t\tif (varname) {\n\t\t\tRAnalVar *var = r_anal_function_set_var (fcn, frame_off, type, NULL, anal->bits / 8, false, varname);\n\t\t\tif (var) {\n\t\t\t\tr_anal_var_set_access (var, reg, op->addr, rw, -ptr);\n\t\t\t}\n\t\t\tfree (varname);\n\t\t}\n\t}\nbeach:\n\tfree (esil_buf);\n}", "func_hash": 336184840247355587470651192558617642560, "file_name": "None", "file_hash": null, "cwe": ["CWE-416"], "cve": "CVE-2022-1031", "cve_desc": "Use After Free in op_is_set_bp in GitHub repository radareorg/radare2 prior to 5.6.6.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1031"}
{"idx": 379671, "project": "radare2", "commit_id": "a7ce29647fcb38386d7439696375e16e093d6acb", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/a7ce29647fcb38386d7439696375e16e093d6acb", "commit_message": "Fix UAF in aaaa on arm/thumb switching ##crash\n\n* Reported by @peacock-doris via huntr.dev\n* Reproducer tests_65185\n* This is a logic fix, but not the fully safe as changes in the code\n  can result on UAF again, to properly protect r2 from crashing we\n  need to break the ABI and add refcounting to RRegItem, which can't\n  happen in 5.6.x because of abi-compat rules", "target": 0, "func": "static void extract_arg(RAnal *anal, RAnalFunction *fcn, RAnalOp *op, const char *reg, const char *sign, char type) {\n\tst64 ptr = 0;\n\tchar *addr, *esil_buf = NULL;\n\tconst st64 maxstackframe = 1024 * 8; \n\n\tr_return_if_fail (anal && fcn && op && reg);\n\n\tsize_t i;\n\tfor (i = 0; i < R_ARRAY_SIZE (op->src); i++) {\n\t\tif (op->src[i] && op->src[i]->reg && op->src[i]->reg->name) {\n\t\t\tif (!strcmp (reg, op->src[i]->reg->name)) {\n\t\t\t\tst64 delta = op->src[i]->delta;\n\t\t\t\tif ((delta > 0 && *sign == '+') || (delta < 0 && *sign == '-')) {\n\t\t\t\t\tptr = R_ABS (op->src[i]->delta);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!ptr) {\n\t\tconst char *op_esil = r_strbuf_get (&op->esil);\n\t\tif (!op_esil) {\n\t\t\treturn;\n\t\t}\n\t\tesil_buf = strdup (op_esil);\n\t\tif (!esil_buf) {\n\t\t\treturn;\n\t\t}\n\t\tr_strf_var (esilexpr, 64, \",%s,%s,\", reg, sign);\n\t\tchar *ptr_end = strstr (esil_buf, esilexpr);\n\t\tif (!ptr_end) {\n\t\t\tfree (esil_buf);\n\t\t\treturn;\n\t\t}\n\t\t*ptr_end = 0;\n\t\taddr = ptr_end;\n\t\twhile ((addr[0] != '0' || addr[1] != 'x') && addr >= esil_buf + 1 && *addr != ',') {\n\t\t\taddr--;\n\t\t}\n\t\tif (strncmp (addr, \"0x\", 2)) {\n\t\t\t//XXX: This is a workaround for inconsistent esil\n\t\t\tif (!op->stackop && op->dst) {\n\t\t\t\tconst char *sp = r_reg_get_name (anal->reg, R_REG_NAME_SP);\n\t\t\t\tconst char *bp = r_reg_get_name (anal->reg, R_REG_NAME_BP);\n\t\t\t\tconst char *rn = op->dst->reg ? op->dst->reg->name : NULL;\n\t\t\t\tif (rn && ((bp && !strcmp (bp, rn)) || (sp && !strcmp (sp, rn)))) {\n\t\t\t\t\tif (anal->verbose) {\n\t\t\t\t\t\teprintf (\"Warning: Analysis didn't fill op->stackop for instruction that alters stack at 0x%\" PFMT64x \".\\n\", op->addr);\n\t\t\t\t\t}\n\t\t\t\t\tgoto beach;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (*addr == ',') {\n\t\t\t\taddr++;\n\t\t\t}\n\t\t\tif (!op->stackop && op->type != R_ANAL_OP_TYPE_PUSH && op->type != R_ANAL_OP_TYPE_POP\n\t\t\t\t&& op->type != R_ANAL_OP_TYPE_RET && r_str_isnumber (addr)) {\n\t\t\t\tptr = (st64)r_num_get (NULL, addr);\n\t\t\t\tif (ptr && op->src[0] && ptr == op->src[0]->imm) {\n\t\t\t\t\tgoto beach;\n\t\t\t\t}\n\t\t\t} else if ((op->stackop == R_ANAL_STACK_SET) || (op->stackop == R_ANAL_STACK_GET)) {\n\t\t\t\tif (op->ptr % 4) {\n\t\t\t\t\tgoto beach;\n\t\t\t\t}\n\t\t\t\tptr = R_ABS (op->ptr);\n\t\t\t} else {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t} else {\n\t\t\tptr = (st64)r_num_get (NULL, addr);\n\t\t}\n\t}\n\n\tif (anal->verbose && (!op->src[0] || !op->dst)) {\n\t\teprintf (\"Warning: Analysis didn't fill op->src/dst at 0x%\" PFMT64x \".\\n\", op->addr);\n\t}\n\n\tint rw = (op->direction == R_ANAL_OP_DIR_WRITE) ? R_ANAL_VAR_ACCESS_TYPE_WRITE : R_ANAL_VAR_ACCESS_TYPE_READ;\n\tif (*sign == '+') {\n\t\tconst bool isarg = type == R_ANAL_VAR_KIND_SPV ? ptr >= fcn->stack : ptr >= fcn->bp_off;\n\t\tconst char *pfx = isarg ? ARGPREFIX : VARPREFIX;\n\t\tst64 frame_off;\n\t\tif (type == R_ANAL_VAR_KIND_SPV) {\n\t\t\tframe_off = ptr - fcn->stack;\n\t\t} else {\n\t\t\tframe_off = ptr - fcn->bp_off;\n\t\t}\n\t\tif (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {\n\t\t\tgoto beach;\n\t\t}\n\t\tRAnalVar *var = get_stack_var (fcn, frame_off);\n\t\tif (var) {\n\t\t\tr_anal_var_set_access (var, reg, op->addr, rw, ptr);\n\t\t\tgoto beach;\n\t\t}\n\t\tchar *varname = NULL, *vartype = NULL;\n\t\tif (isarg) {\n\t\t\tconst char *place = fcn->cc ? r_anal_cc_arg (anal, fcn->cc, ST32_MAX) : NULL;\n\t\t\tbool stack_rev = place ? !strcmp (place, \"stack_rev\") : false;\n\t\t\tchar *fname = r_type_func_guess (anal->sdb_types, fcn->name);\n\t\t\tif (fname) {\n\t\t\t\tut64 sum_sz = 0;\n\t\t\t\tsize_t from, to, i;\n\t\t\t\tif (stack_rev) {\n\t\t\t\t\tconst size_t cnt = r_type_func_args_count (anal->sdb_types, fname);\n\t\t\t\t\tfrom = cnt ? cnt - 1 : cnt;\n\t\t\t\t\tto = fcn->cc ? r_anal_cc_max_arg (anal, fcn->cc) : 0;\n\t\t\t\t} else {\n\t\t\t\t\tfrom = fcn->cc ? r_anal_cc_max_arg (anal, fcn->cc) : 0;\n\t\t\t\t\tto = r_type_func_args_count (anal->sdb_types, fname);\n\t\t\t\t}\n\t\t\t\tconst int bytes = (fcn->bits ? fcn->bits : anal->bits) / 8;\n\t\t\t\tfor (i = from; stack_rev ? i >= to : i < to; stack_rev ? i-- : i++) {\n\t\t\t\t\tchar *tp = r_type_func_args_type (anal->sdb_types, fname, i);\n\t\t\t\t\tif (!tp) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (sum_sz == frame_off) {\n\t\t\t\t\t\tvartype = tp;\n\t\t\t\t\t\tvarname = strdup (r_type_func_args_name (anal->sdb_types, fname, i));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tut64 bit_sz = r_type_get_bitsize (anal->sdb_types, tp);\n\t\t\t\t\tsum_sz += bit_sz ? bit_sz / 8 : bytes;\n\t\t\t\t\tsum_sz = R_ROUND (sum_sz, bytes);\n\t\t\t\t\tfree (tp);\n\t\t\t\t}\n\t\t\t\tfree (fname);\n\t\t\t}\n\t\t}\n\t\tif (!varname) {\n\t\t\tif (anal->opt.varname_stack) {\n\t\t\t\tvarname = r_str_newf (\"%s_%\" PFMT64x \"h\", pfx, R_ABS (frame_off));\n\t\t\t} else {\n\t\t\t\tvarname = r_anal_function_autoname_var (fcn, type, pfx, ptr);\n\t\t\t}\n\t\t}\n\t\tif (varname) {\n#if 0\n\t\t\tif (isarg && frame_off > 48) {\n\t\t\t\tfree (varname);\n\t\t\t\tgoto beach;\n\t\t\t}\n#endif\n\t\t\tRAnalVar *var = r_anal_function_set_var (fcn, frame_off, type, vartype, anal->bits / 8, isarg, varname);\n\t\t\tif (var) {\n\t\t\t\tr_anal_var_set_access (var, reg, op->addr, rw, ptr);\n\t\t\t}\n\t\t\tfree (varname);\n\t\t}\n\t\tfree (vartype);\n\t} else {\n\t\tst64 frame_off = -(ptr + fcn->bp_off);\n\t\tif (maxstackframe > 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {\n\t\t\tgoto beach;\n\t\t}\n\t\tRAnalVar *var = get_stack_var (fcn, frame_off);\n\t\tif (var) {\n\t\t\tr_anal_var_set_access (var, reg, op->addr, rw, -ptr);\n\t\t\tgoto beach;\n\t\t}\n\t\tchar *varname = anal->opt.varname_stack\n\t\t\t? r_str_newf (\"%s_%\" PFMT64x \"h\", VARPREFIX, R_ABS (frame_off))\n\t\t\t: r_anal_function_autoname_var (fcn, type, VARPREFIX, -ptr);\n\t\tif (varname) {\n\t\t\tRAnalVar *var = r_anal_function_set_var (fcn, frame_off, type, NULL, anal->bits / 8, false, varname);\n\t\t\tif (var) {\n\t\t\t\tr_anal_var_set_access (var, reg, op->addr, rw, -ptr);\n\t\t\t}\n\t\t\tfree (varname);\n\t\t}\n\t}\nbeach:\n\tfree (esil_buf);\n}", "func_hash": 117008167646492270733743639992860727677, "file_name": "None", "file_hash": null, "cwe": ["CWE-416"], "cve": "CVE-2022-1031", "cve_desc": "Use After Free in op_is_set_bp in GitHub repository radareorg/radare2 prior to 5.6.6.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1031"}
{"idx": 206417, "project": "vim", "commit_id": "0971c7a4e537ea120a6bb2195960be8d0815e97b", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/0971c7a4e537ea120a6bb2195960be8d0815e97b", "commit_message": "patch 8.2.5162: reading before the start of the line with BS in Replace mode\n\nProblem:    Reading before the start of the line with BS in Replace mode.\nSolution:   Check the cursor column is more than zero.", "target": 1, "func": "ins_bs(\n    int\t\tc,\n    int\t\tmode,\n    int\t\t*inserted_space_p)\n{\n    linenr_T\tlnum;\n    int\t\tcc;\n    int\t\ttemp = 0;\t    // init for GCC\n    colnr_T\tsave_col;\n    colnr_T\tmincol;\n    int\t\tdid_backspace = FALSE;\n    int\t\tin_indent;\n    int\t\toldState;\n    int\t\tcpc[MAX_MCO];\t    // composing characters\n    int\t\tcall_fix_indent = FALSE;\n\n    /*\n     * can't delete anything in an empty file\n     * can't backup past first character in buffer\n     * can't backup past starting point unless 'backspace' > 1\n     * can backup to a previous line if 'backspace' == 0\n     */\n    if (       BUFEMPTY()\n\t    || (\n#ifdef FEAT_RIGHTLEFT\n\t\t!revins_on &&\n#endif\n\t\t((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)\n\t\t    || (!can_bs(BS_START)\n\t\t\t&& ((arrow_used\n#ifdef FEAT_JOB_CHANNEL\n\t\t\t\t&& !bt_prompt(curbuf)\n#endif\n\t\t\t) || (curwin->w_cursor.lnum == Insstart_orig.lnum\n\t\t\t\t&& curwin->w_cursor.col <= Insstart_orig.col)))\n\t\t    || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0\n\t\t\t\t\t && curwin->w_cursor.col <= ai_col)\n\t\t    || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))\n    {\n\tvim_beep(BO_BS);\n\treturn FALSE;\n    }\n\n    if (stop_arrow() == FAIL)\n\treturn FALSE;\n    in_indent = inindent(0);\n    if (in_indent)\n\tcan_cindent = FALSE;\n    end_comment_pending = NUL;\t// After BS, don't auto-end comment\n#ifdef FEAT_RIGHTLEFT\n    if (revins_on)\t    // put cursor after last inserted char\n\tinc_cursor();\n#endif\n\n    // Virtualedit:\n    //\tBACKSPACE_CHAR eats a virtual space\n    //\tBACKSPACE_WORD eats all coladd\n    //\tBACKSPACE_LINE eats all coladd and keeps going\n    if (curwin->w_cursor.coladd > 0)\n    {\n\tif (mode == BACKSPACE_CHAR)\n\t{\n\t    --curwin->w_cursor.coladd;\n\t    return TRUE;\n\t}\n\tif (mode == BACKSPACE_WORD)\n\t{\n\t    curwin->w_cursor.coladd = 0;\n\t    return TRUE;\n\t}\n\tcurwin->w_cursor.coladd = 0;\n    }\n\n    /*\n     * Delete newline!\n     */\n    if (curwin->w_cursor.col == 0)\n    {\n\tlnum = Insstart.lnum;\n\tif (curwin->w_cursor.lnum == lnum\n#ifdef FEAT_RIGHTLEFT\n\t\t\t|| revins_on\n#endif\n\t\t\t\t    )\n\t{\n\t    if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),\n\t\t\t       (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)\n\t\treturn FALSE;\n\t    --Insstart.lnum;\n\t    Insstart.col = (colnr_T)STRLEN(ml_get(Insstart.lnum));\n\t}\n\t/*\n\t * In replace mode:\n\t * cc < 0: NL was inserted, delete it\n\t * cc >= 0: NL was replaced, put original characters back\n\t */\n\tcc = -1;\n\tif (State & REPLACE_FLAG)\n\t    cc = replace_pop();\t    // returns -1 if NL was inserted\n\t/*\n\t * In replace mode, in the line we started replacing, we only move the\n\t * cursor.\n\t */\n\tif ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)\n\t{\n\t    dec_cursor();\n\t}\n\telse\n\t{\n\t    if (!(State & VREPLACE_FLAG)\n\t\t\t\t   || curwin->w_cursor.lnum > orig_line_count)\n\t    {\n\t\ttemp = gchar_cursor();\t// remember current char\n\t\t--curwin->w_cursor.lnum;\n\n\t\t// When \"aw\" is in 'formatoptions' we must delete the space at\n\t\t// the end of the line, otherwise the line will be broken\n\t\t// again when auto-formatting.\n\t\tif (has_format_option(FO_AUTO)\n\t\t\t\t\t   && has_format_option(FO_WHITE_PAR))\n\t\t{\n\t\t    char_u  *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,\n\t\t\t\t\t\t\t\t\tTRUE);\n\t\t    int\t    len;\n\n\t\t    len = (int)STRLEN(ptr);\n\t\t    if (len > 0 && ptr[len - 1] == ' ')\n\t\t\tptr[len - 1] = NUL;\n\t\t}\n\n\t\t(void)do_join(2, FALSE, FALSE, FALSE, FALSE);\n\t\tif (temp == NUL && gchar_cursor() != NUL)\n\t\t    inc_cursor();\n\t    }\n\t    else\n\t\tdec_cursor();\n\n\t    /*\n\t     * In MODE_REPLACE mode we have to put back the text that was\n\t     * replaced by the NL. On the replace stack is first a\n\t     * NUL-terminated sequence of characters that were deleted and then\n\t     * the characters that NL replaced.\n\t     */\n\t    if (State & REPLACE_FLAG)\n\t    {\n\t\t/*\n\t\t * Do the next ins_char() in MODE_NORMAL state, to\n\t\t * prevent ins_char() from replacing characters and\n\t\t * avoiding showmatch().\n\t\t */\n\t\toldState = State;\n\t\tState = MODE_NORMAL;\n\t\t/*\n\t\t * restore characters (blanks) deleted after cursor\n\t\t */\n\t\twhile (cc > 0)\n\t\t{\n\t\t    save_col = curwin->w_cursor.col;\n\t\t    mb_replace_pop_ins(cc);\n\t\t    curwin->w_cursor.col = save_col;\n\t\t    cc = replace_pop();\n\t\t}\n\t\t// restore the characters that NL replaced\n\t\treplace_pop_ins();\n\t\tState = oldState;\n\t    }\n\t}\n\tdid_ai = FALSE;\n    }\n    else\n    {\n\t/*\n\t * Delete character(s) before the cursor.\n\t */\n#ifdef FEAT_RIGHTLEFT\n\tif (revins_on)\t\t// put cursor on last inserted char\n\t    dec_cursor();\n#endif\n\tmincol = 0;\n\t\t\t\t\t\t// keep indent\n\tif (mode == BACKSPACE_LINE\n\t\t&& (curbuf->b_p_ai || cindent_on())\n#ifdef FEAT_RIGHTLEFT\n\t\t&& !revins_on\n#endif\n\t\t\t    )\n\t{\n\t    save_col = curwin->w_cursor.col;\n\t    beginline(BL_WHITE);\n\t    if (curwin->w_cursor.col < save_col)\n\t    {\n\t\tmincol = curwin->w_cursor.col;\n\t\t// should now fix the indent to match with the previous line\n\t\tcall_fix_indent = TRUE;\n\t    }\n\t    curwin->w_cursor.col = save_col;\n\t}\n\n\t/*\n\t * Handle deleting one 'shiftwidth' or 'softtabstop'.\n\t */\n\tif (\t   mode == BACKSPACE_CHAR\n\t\t&& ((p_sta && in_indent)\n\t\t    || ((get_sts_value() != 0\n#ifdef FEAT_VARTABS\n\t\t\t|| tabstop_count(curbuf->b_p_vsts_array)\n#endif\n\t\t\t)\n\t\t\t&& curwin->w_cursor.col > 0\n\t\t\t&& (*(ml_get_cursor() - 1) == TAB\n\t\t\t    || (*(ml_get_cursor() - 1) == ' '\n\t\t\t\t&& (!*inserted_space_p\n\t\t\t\t    || arrow_used))))))\n\t{\n\t    int\t\tts;\n\t    colnr_T\tvcol;\n\t    colnr_T\twant_vcol;\n\t    colnr_T\tstart_vcol;\n\n\t    *inserted_space_p = FALSE;\n\t    // Compute the virtual column where we want to be.  Since\n\t    // 'showbreak' may get in the way, need to get the last column of\n\t    // the previous character.\n\t    getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);\n\t    start_vcol = vcol;\n\t    dec_cursor();\n\t    getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);\n\t    inc_cursor();\n#ifdef FEAT_VARTABS\n\t    if (p_sta && in_indent)\n\t    {\n\t\tts = (int)get_sw_value(curbuf);\n\t\twant_vcol = (want_vcol / ts) * ts;\n\t    }\n\t    else\n\t\twant_vcol = tabstop_start(want_vcol, get_sts_value(),\n\t\t\t\t\t\t       curbuf->b_p_vsts_array);\n#else\n\t    if (p_sta && in_indent)\n\t\tts = (int)get_sw_value(curbuf);\n\t    else\n\t\tts = (int)get_sts_value();\n\t    want_vcol = (want_vcol / ts) * ts;\n#endif\n\n\t    // delete characters until we are at or before want_vcol\n\t    while (vcol > want_vcol\n\t\t    && (cc = *(ml_get_cursor() - 1), VIM_ISWHITE(cc)))\n\t\tins_bs_one(&vcol);\n\n\t    // insert extra spaces until we are at want_vcol\n\t    while (vcol < want_vcol)\n\t    {\n\t\t// Remember the first char we inserted\n\t\tif (curwin->w_cursor.lnum == Insstart_orig.lnum\n\t\t\t\t   && curwin->w_cursor.col < Insstart_orig.col)\n\t\t    Insstart_orig.col = curwin->w_cursor.col;\n\n\t\tif (State & VREPLACE_FLAG)\n\t\t    ins_char(' ');\n\t\telse\n\t\t{\n\t\t    ins_str((char_u *)\" \");\n\t\t    if ((State & REPLACE_FLAG))\n\t\t\treplace_push(NUL);\n\t\t}\n\t\tgetvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);\n\t    }\n\n\t    // If we are now back where we started delete one character.  Can\n\t    // happen when using 'sts' and 'linebreak'.\n\t    if (vcol >= start_vcol)\n\t\tins_bs_one(&vcol);\n\t}\n\n\t/*\n\t * Delete up to starting point, start of line or previous word.\n\t */\n\telse\n\t{\n\t    int cclass = 0, prev_cclass = 0;\n\n\t    if (has_mbyte)\n\t\tcclass = mb_get_class(ml_get_cursor());\n\t    do\n\t    {\n#ifdef FEAT_RIGHTLEFT\n\t\tif (!revins_on) // put cursor on char to be deleted\n#endif\n\t\t    dec_cursor();\n\n\t\tcc = gchar_cursor();\n\t\t// look multi-byte character class\n\t\tif (has_mbyte)\n\t\t{\n\t\t    prev_cclass = cclass;\n\t\t    cclass = mb_get_class(ml_get_cursor());\n\t\t}\n\n\t\t// start of word?\n\t\tif (mode == BACKSPACE_WORD && !vim_isspace(cc))\n\t\t{\n\t\t    mode = BACKSPACE_WORD_NOT_SPACE;\n\t\t    temp = vim_iswordc(cc);\n\t\t}\n\t\t// end of word?\n\t\telse if (mode == BACKSPACE_WORD_NOT_SPACE\n\t\t\t&& ((vim_isspace(cc) || vim_iswordc(cc) != temp)\n\t\t\t|| prev_cclass != cclass))\n\t\t{\n#ifdef FEAT_RIGHTLEFT\n\t\t    if (!revins_on)\n#endif\n\t\t\tinc_cursor();\n#ifdef FEAT_RIGHTLEFT\n\t\t    else if (State & REPLACE_FLAG)\n\t\t\tdec_cursor();\n#endif\n\t\t    break;\n\t\t}\n\t\tif (State & REPLACE_FLAG)\n\t\t    replace_do_bs(-1);\n\t\telse\n\t\t{\n\t\t    if (enc_utf8 && p_deco)\n\t\t\t(void)utfc_ptr2char(ml_get_cursor(), cpc);\n\t\t    (void)del_char(FALSE);\n\t\t    /*\n\t\t     * If there are combining characters and 'delcombine' is set\n\t\t     * move the cursor back.  Don't back up before the base\n\t\t     * character.\n\t\t     */\n\t\t    if (enc_utf8 && p_deco && cpc[0] != NUL)\n\t\t\tinc_cursor();\n#ifdef FEAT_RIGHTLEFT\n\t\t    if (revins_chars)\n\t\t    {\n\t\t\trevins_chars--;\n\t\t\trevins_legal++;\n\t\t    }\n\t\t    if (revins_on && gchar_cursor() == NUL)\n\t\t\tbreak;\n#endif\n\t\t}\n\t\t// Just a single backspace?:\n\t\tif (mode == BACKSPACE_CHAR)\n\t\t    break;\n\t    } while (\n#ifdef FEAT_RIGHTLEFT\n\t\t    revins_on ||\n#endif\n\t\t    (curwin->w_cursor.col > mincol\n\t\t    &&  (can_bs(BS_NOSTOP)\n\t\t\t|| (curwin->w_cursor.lnum != Insstart_orig.lnum\n\t\t\t|| curwin->w_cursor.col != Insstart_orig.col)\n\t\t    )));\n\t}\n\tdid_backspace = TRUE;\n    }\n    did_si = FALSE;\n    can_si = FALSE;\n    can_si_back = FALSE;\n    if (curwin->w_cursor.col <= 1)\n\tdid_ai = FALSE;\n\n    if (call_fix_indent)\n\tfix_indent();\n\n    /*\n     * It's a little strange to put backspaces into the redo\n     * buffer, but it makes auto-indent a lot easier to deal\n     * with.\n     */\n    AppendCharToRedobuff(c);\n\n    // If deleted before the insertion point, adjust it\n    if (curwin->w_cursor.lnum == Insstart_orig.lnum\n\t\t\t\t  && curwin->w_cursor.col < Insstart_orig.col)\n\tInsstart_orig.col = curwin->w_cursor.col;\n\n    // vi behaviour: the cursor moves backward but the character that\n    //\t\t     was there remains visible\n    // Vim behaviour: the cursor moves backward and the character that\n    //\t\t      was there is erased from the screen.\n    // We can emulate the vi behaviour by pretending there is a dollar\n    // displayed even when there isn't.\n    //  --pkv Sun Jan 19 01:56:40 EST 2003\n    if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == -1)\n\tdollar_vcol = curwin->w_virtcol;\n\n#ifdef FEAT_FOLDING\n    // When deleting a char the cursor line must never be in a closed fold.\n    // E.g., when 'foldmethod' is indent and deleting the first non-white\n    // char before a Tab.\n    if (did_backspace)\n\tfoldOpenCursor();\n#endif\n\n    return did_backspace;\n}", "func_hash": 172194519756788339453675041357999010208, "file_name": "edit.c", "file_hash": 334216402611901751671385717284214475763, "cwe": ["CWE-787"], "cve": "CVE-2022-2207", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2207"}
{"idx": 380955, "project": "vim", "commit_id": "0971c7a4e537ea120a6bb2195960be8d0815e97b", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/0971c7a4e537ea120a6bb2195960be8d0815e97b", "commit_message": "patch 8.2.5162: reading before the start of the line with BS in Replace mode\n\nProblem:    Reading before the start of the line with BS in Replace mode.\nSolution:   Check the cursor column is more than zero.", "target": 0, "func": "ins_bs(\n    int\t\tc,\n    int\t\tmode,\n    int\t\t*inserted_space_p)\n{\n    linenr_T\tlnum;\n    int\t\tcc;\n    int\t\ttemp = 0;\t    // init for GCC\n    colnr_T\tsave_col;\n    colnr_T\tmincol;\n    int\t\tdid_backspace = FALSE;\n    int\t\tin_indent;\n    int\t\toldState;\n    int\t\tcpc[MAX_MCO];\t    // composing characters\n    int\t\tcall_fix_indent = FALSE;\n\n    /*\n     * can't delete anything in an empty file\n     * can't backup past first character in buffer\n     * can't backup past starting point unless 'backspace' > 1\n     * can backup to a previous line if 'backspace' == 0\n     */\n    if (       BUFEMPTY()\n\t    || (\n#ifdef FEAT_RIGHTLEFT\n\t\t!revins_on &&\n#endif\n\t\t((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)\n\t\t    || (!can_bs(BS_START)\n\t\t\t&& ((arrow_used\n#ifdef FEAT_JOB_CHANNEL\n\t\t\t\t&& !bt_prompt(curbuf)\n#endif\n\t\t\t) || (curwin->w_cursor.lnum == Insstart_orig.lnum\n\t\t\t\t&& curwin->w_cursor.col <= Insstart_orig.col)))\n\t\t    || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0\n\t\t\t\t\t && curwin->w_cursor.col <= ai_col)\n\t\t    || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))\n    {\n\tvim_beep(BO_BS);\n\treturn FALSE;\n    }\n\n    if (stop_arrow() == FAIL)\n\treturn FALSE;\n    in_indent = inindent(0);\n    if (in_indent)\n\tcan_cindent = FALSE;\n    end_comment_pending = NUL;\t// After BS, don't auto-end comment\n#ifdef FEAT_RIGHTLEFT\n    if (revins_on)\t    // put cursor after last inserted char\n\tinc_cursor();\n#endif\n\n    // Virtualedit:\n    //\tBACKSPACE_CHAR eats a virtual space\n    //\tBACKSPACE_WORD eats all coladd\n    //\tBACKSPACE_LINE eats all coladd and keeps going\n    if (curwin->w_cursor.coladd > 0)\n    {\n\tif (mode == BACKSPACE_CHAR)\n\t{\n\t    --curwin->w_cursor.coladd;\n\t    return TRUE;\n\t}\n\tif (mode == BACKSPACE_WORD)\n\t{\n\t    curwin->w_cursor.coladd = 0;\n\t    return TRUE;\n\t}\n\tcurwin->w_cursor.coladd = 0;\n    }\n\n    /*\n     * Delete newline!\n     */\n    if (curwin->w_cursor.col == 0)\n    {\n\tlnum = Insstart.lnum;\n\tif (curwin->w_cursor.lnum == lnum\n#ifdef FEAT_RIGHTLEFT\n\t\t\t|| revins_on\n#endif\n\t\t\t\t    )\n\t{\n\t    if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),\n\t\t\t       (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)\n\t\treturn FALSE;\n\t    --Insstart.lnum;\n\t    Insstart.col = (colnr_T)STRLEN(ml_get(Insstart.lnum));\n\t}\n\t/*\n\t * In replace mode:\n\t * cc < 0: NL was inserted, delete it\n\t * cc >= 0: NL was replaced, put original characters back\n\t */\n\tcc = -1;\n\tif (State & REPLACE_FLAG)\n\t    cc = replace_pop();\t    // returns -1 if NL was inserted\n\t/*\n\t * In replace mode, in the line we started replacing, we only move the\n\t * cursor.\n\t */\n\tif ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)\n\t{\n\t    dec_cursor();\n\t}\n\telse\n\t{\n\t    if (!(State & VREPLACE_FLAG)\n\t\t\t\t   || curwin->w_cursor.lnum > orig_line_count)\n\t    {\n\t\ttemp = gchar_cursor();\t// remember current char\n\t\t--curwin->w_cursor.lnum;\n\n\t\t// When \"aw\" is in 'formatoptions' we must delete the space at\n\t\t// the end of the line, otherwise the line will be broken\n\t\t// again when auto-formatting.\n\t\tif (has_format_option(FO_AUTO)\n\t\t\t\t\t   && has_format_option(FO_WHITE_PAR))\n\t\t{\n\t\t    char_u  *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,\n\t\t\t\t\t\t\t\t\tTRUE);\n\t\t    int\t    len;\n\n\t\t    len = (int)STRLEN(ptr);\n\t\t    if (len > 0 && ptr[len - 1] == ' ')\n\t\t\tptr[len - 1] = NUL;\n\t\t}\n\n\t\t(void)do_join(2, FALSE, FALSE, FALSE, FALSE);\n\t\tif (temp == NUL && gchar_cursor() != NUL)\n\t\t    inc_cursor();\n\t    }\n\t    else\n\t\tdec_cursor();\n\n\t    /*\n\t     * In MODE_REPLACE mode we have to put back the text that was\n\t     * replaced by the NL. On the replace stack is first a\n\t     * NUL-terminated sequence of characters that were deleted and then\n\t     * the characters that NL replaced.\n\t     */\n\t    if (State & REPLACE_FLAG)\n\t    {\n\t\t/*\n\t\t * Do the next ins_char() in MODE_NORMAL state, to\n\t\t * prevent ins_char() from replacing characters and\n\t\t * avoiding showmatch().\n\t\t */\n\t\toldState = State;\n\t\tState = MODE_NORMAL;\n\t\t/*\n\t\t * restore characters (blanks) deleted after cursor\n\t\t */\n\t\twhile (cc > 0)\n\t\t{\n\t\t    save_col = curwin->w_cursor.col;\n\t\t    mb_replace_pop_ins(cc);\n\t\t    curwin->w_cursor.col = save_col;\n\t\t    cc = replace_pop();\n\t\t}\n\t\t// restore the characters that NL replaced\n\t\treplace_pop_ins();\n\t\tState = oldState;\n\t    }\n\t}\n\tdid_ai = FALSE;\n    }\n    else\n    {\n\t/*\n\t * Delete character(s) before the cursor.\n\t */\n#ifdef FEAT_RIGHTLEFT\n\tif (revins_on)\t\t// put cursor on last inserted char\n\t    dec_cursor();\n#endif\n\tmincol = 0;\n\t\t\t\t\t\t// keep indent\n\tif (mode == BACKSPACE_LINE\n\t\t&& (curbuf->b_p_ai || cindent_on())\n#ifdef FEAT_RIGHTLEFT\n\t\t&& !revins_on\n#endif\n\t\t\t    )\n\t{\n\t    save_col = curwin->w_cursor.col;\n\t    beginline(BL_WHITE);\n\t    if (curwin->w_cursor.col < save_col)\n\t    {\n\t\tmincol = curwin->w_cursor.col;\n\t\t// should now fix the indent to match with the previous line\n\t\tcall_fix_indent = TRUE;\n\t    }\n\t    curwin->w_cursor.col = save_col;\n\t}\n\n\t/*\n\t * Handle deleting one 'shiftwidth' or 'softtabstop'.\n\t */\n\tif (\t   mode == BACKSPACE_CHAR\n\t\t&& ((p_sta && in_indent)\n\t\t    || ((get_sts_value() != 0\n#ifdef FEAT_VARTABS\n\t\t\t|| tabstop_count(curbuf->b_p_vsts_array)\n#endif\n\t\t\t)\n\t\t\t&& curwin->w_cursor.col > 0\n\t\t\t&& (*(ml_get_cursor() - 1) == TAB\n\t\t\t    || (*(ml_get_cursor() - 1) == ' '\n\t\t\t\t&& (!*inserted_space_p\n\t\t\t\t    || arrow_used))))))\n\t{\n\t    int\t\tts;\n\t    colnr_T\tvcol;\n\t    colnr_T\twant_vcol;\n\t    colnr_T\tstart_vcol;\n\n\t    *inserted_space_p = FALSE;\n\t    // Compute the virtual column where we want to be.  Since\n\t    // 'showbreak' may get in the way, need to get the last column of\n\t    // the previous character.\n\t    getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);\n\t    start_vcol = vcol;\n\t    dec_cursor();\n\t    getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);\n\t    inc_cursor();\n#ifdef FEAT_VARTABS\n\t    if (p_sta && in_indent)\n\t    {\n\t\tts = (int)get_sw_value(curbuf);\n\t\twant_vcol = (want_vcol / ts) * ts;\n\t    }\n\t    else\n\t\twant_vcol = tabstop_start(want_vcol, get_sts_value(),\n\t\t\t\t\t\t       curbuf->b_p_vsts_array);\n#else\n\t    if (p_sta && in_indent)\n\t\tts = (int)get_sw_value(curbuf);\n\t    else\n\t\tts = (int)get_sts_value();\n\t    want_vcol = (want_vcol / ts) * ts;\n#endif\n\n\t    // delete characters until we are at or before want_vcol\n\t    while (vcol > want_vcol && curwin->w_cursor.col > 0\n\t\t    && (cc = *(ml_get_cursor() - 1), VIM_ISWHITE(cc)))\n\t\tins_bs_one(&vcol);\n\n\t    // insert extra spaces until we are at want_vcol\n\t    while (vcol < want_vcol)\n\t    {\n\t\t// Remember the first char we inserted\n\t\tif (curwin->w_cursor.lnum == Insstart_orig.lnum\n\t\t\t\t   && curwin->w_cursor.col < Insstart_orig.col)\n\t\t    Insstart_orig.col = curwin->w_cursor.col;\n\n\t\tif (State & VREPLACE_FLAG)\n\t\t    ins_char(' ');\n\t\telse\n\t\t{\n\t\t    ins_str((char_u *)\" \");\n\t\t    if ((State & REPLACE_FLAG))\n\t\t\treplace_push(NUL);\n\t\t}\n\t\tgetvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);\n\t    }\n\n\t    // If we are now back where we started delete one character.  Can\n\t    // happen when using 'sts' and 'linebreak'.\n\t    if (vcol >= start_vcol)\n\t\tins_bs_one(&vcol);\n\t}\n\n\t/*\n\t * Delete up to starting point, start of line or previous word.\n\t */\n\telse\n\t{\n\t    int cclass = 0, prev_cclass = 0;\n\n\t    if (has_mbyte)\n\t\tcclass = mb_get_class(ml_get_cursor());\n\t    do\n\t    {\n#ifdef FEAT_RIGHTLEFT\n\t\tif (!revins_on) // put cursor on char to be deleted\n#endif\n\t\t    dec_cursor();\n\n\t\tcc = gchar_cursor();\n\t\t// look multi-byte character class\n\t\tif (has_mbyte)\n\t\t{\n\t\t    prev_cclass = cclass;\n\t\t    cclass = mb_get_class(ml_get_cursor());\n\t\t}\n\n\t\t// start of word?\n\t\tif (mode == BACKSPACE_WORD && !vim_isspace(cc))\n\t\t{\n\t\t    mode = BACKSPACE_WORD_NOT_SPACE;\n\t\t    temp = vim_iswordc(cc);\n\t\t}\n\t\t// end of word?\n\t\telse if (mode == BACKSPACE_WORD_NOT_SPACE\n\t\t\t&& ((vim_isspace(cc) || vim_iswordc(cc) != temp)\n\t\t\t|| prev_cclass != cclass))\n\t\t{\n#ifdef FEAT_RIGHTLEFT\n\t\t    if (!revins_on)\n#endif\n\t\t\tinc_cursor();\n#ifdef FEAT_RIGHTLEFT\n\t\t    else if (State & REPLACE_FLAG)\n\t\t\tdec_cursor();\n#endif\n\t\t    break;\n\t\t}\n\t\tif (State & REPLACE_FLAG)\n\t\t    replace_do_bs(-1);\n\t\telse\n\t\t{\n\t\t    if (enc_utf8 && p_deco)\n\t\t\t(void)utfc_ptr2char(ml_get_cursor(), cpc);\n\t\t    (void)del_char(FALSE);\n\t\t    /*\n\t\t     * If there are combining characters and 'delcombine' is set\n\t\t     * move the cursor back.  Don't back up before the base\n\t\t     * character.\n\t\t     */\n\t\t    if (enc_utf8 && p_deco && cpc[0] != NUL)\n\t\t\tinc_cursor();\n#ifdef FEAT_RIGHTLEFT\n\t\t    if (revins_chars)\n\t\t    {\n\t\t\trevins_chars--;\n\t\t\trevins_legal++;\n\t\t    }\n\t\t    if (revins_on && gchar_cursor() == NUL)\n\t\t\tbreak;\n#endif\n\t\t}\n\t\t// Just a single backspace?:\n\t\tif (mode == BACKSPACE_CHAR)\n\t\t    break;\n\t    } while (\n#ifdef FEAT_RIGHTLEFT\n\t\t    revins_on ||\n#endif\n\t\t    (curwin->w_cursor.col > mincol\n\t\t    &&  (can_bs(BS_NOSTOP)\n\t\t\t|| (curwin->w_cursor.lnum != Insstart_orig.lnum\n\t\t\t|| curwin->w_cursor.col != Insstart_orig.col)\n\t\t    )));\n\t}\n\tdid_backspace = TRUE;\n    }\n    did_si = FALSE;\n    can_si = FALSE;\n    can_si_back = FALSE;\n    if (curwin->w_cursor.col <= 1)\n\tdid_ai = FALSE;\n\n    if (call_fix_indent)\n\tfix_indent();\n\n    /*\n     * It's a little strange to put backspaces into the redo\n     * buffer, but it makes auto-indent a lot easier to deal\n     * with.\n     */\n    AppendCharToRedobuff(c);\n\n    // If deleted before the insertion point, adjust it\n    if (curwin->w_cursor.lnum == Insstart_orig.lnum\n\t\t\t\t  && curwin->w_cursor.col < Insstart_orig.col)\n\tInsstart_orig.col = curwin->w_cursor.col;\n\n    // vi behaviour: the cursor moves backward but the character that\n    //\t\t     was there remains visible\n    // Vim behaviour: the cursor moves backward and the character that\n    //\t\t      was there is erased from the screen.\n    // We can emulate the vi behaviour by pretending there is a dollar\n    // displayed even when there isn't.\n    //  --pkv Sun Jan 19 01:56:40 EST 2003\n    if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == -1)\n\tdollar_vcol = curwin->w_virtcol;\n\n#ifdef FEAT_FOLDING\n    // When deleting a char the cursor line must never be in a closed fold.\n    // E.g., when 'foldmethod' is indent and deleting the first non-white\n    // char before a Tab.\n    if (did_backspace)\n\tfoldOpenCursor();\n#endif\n\n    return did_backspace;\n}", "func_hash": 64259932111379563055532506605085485351, "file_name": "edit.c", "file_hash": 91657375912486719968624749742093008286, "cwe": ["CWE-787"], "cve": "CVE-2022-2207", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2207"}
{"idx": 206555, "project": "php-src", "commit_id": "cc08cbc84d46933c1e9e0149633f1ed5d19e45e9", "project_url": "https://github.com/php/php-src", "commit_url": "https://git.php.net/?p=php-src.git;a=commit;h=cc08cbc84d46933c1e9e0149633f1ed5d19e45e9", "commit_message": "Fix #73280: Stack Buffer Overflow in GD dynamicGetbuf\n\nWe make sure to never pass a negative `rlen` as size to memcpy().\n\nCf. .", "target": 1, "func": "static int dynamicGetbuf (gdIOCtxPtr ctx, void *buf, int len)\n{\n\tint rlen, remain;\n\tdpIOCtxPtr dctx;\n\tdynamicPtr *dp;\n\n\tdctx = (dpIOCtxPtr) ctx;\n\tdp = dctx->dp;\n\n\tremain = dp->logicalSize - dp->pos;\n\tif (remain >= len) {\n\t\trlen = len;\n\t} else {\n\t\tif (remain == 0) {\n\t\t\treturn EOF;\n\t\t}\n\t\trlen = remain;\n\t}\n\n\tmemcpy(buf, (void *) ((char *) dp->data + dp->pos), rlen);\n\tdp->pos += rlen;\n\n\treturn rlen;\n}", "func_hash": 44554623121680820346289655905713695377, "file_name": "gd_io_dp.c", "file_hash": 66950500877592745162628589676156559345, "cwe": ["CWE-119"], "cve": "CVE-2016-8670", "cve_desc": "Integer signedness error in the dynamicGetbuf function in gd_io_dp.c in the GD Graphics Library (aka libgd) through 2.2.3, as used in PHP before 5.6.28 and 7.x before 7.0.13, allows remote attackers to cause a denial of service (stack-based buffer overflow) or possibly have unspecified other impact via a crafted imagecreatefromstring call.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-8670"}
{"idx": 382797, "project": "php-src", "commit_id": "cc08cbc84d46933c1e9e0149633f1ed5d19e45e9", "project_url": "https://github.com/php/php-src", "commit_url": "https://git.php.net/?p=php-src.git;a=commit;h=cc08cbc84d46933c1e9e0149633f1ed5d19e45e9", "commit_message": "Fix #73280: Stack Buffer Overflow in GD dynamicGetbuf\n\nWe make sure to never pass a negative `rlen` as size to memcpy().\n\nCf. .", "target": 0, "func": "static int dynamicGetbuf (gdIOCtxPtr ctx, void *buf, int len)\n{\n\tint rlen, remain;\n\tdpIOCtxPtr dctx;\n\tdynamicPtr *dp;\n\n\tdctx = (dpIOCtxPtr) ctx;\n\tdp = dctx->dp;\n\n\tremain = dp->logicalSize - dp->pos;\n\tif (remain >= len) {\n\t\trlen = len;\n\t} else {\n\t\tif (remain <= 0) {\n\t\t\treturn EOF;\n\t\t}\n\t\trlen = remain;\n\t}\n\n\tmemcpy(buf, (void *) ((char *) dp->data + dp->pos), rlen);\n\tdp->pos += rlen;\n\n\treturn rlen;\n}", "func_hash": 227798178939410399739015256330671261805, "file_name": "gd_io_dp.c", "file_hash": 171487762597506665250744911889099357441, "cwe": ["CWE-119"], "cve": "CVE-2016-8670", "cve_desc": "Integer signedness error in the dynamicGetbuf function in gd_io_dp.c in the GD Graphics Library (aka libgd) through 2.2.3, as used in PHP before 5.6.28 and 7.x before 7.0.13, allows remote attackers to cause a denial of service (stack-based buffer overflow) or possibly have unspecified other impact via a crafted imagecreatefromstring call.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-8670"}
{"idx": 206588, "project": "php-src", "commit_id": "feba44546c27b0158f9ac20e72040a224b918c75", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commitdiff;h=feba44546c27b0158f9ac20e72040a224b918c75", "commit_message": "Fixed bug #22965 (Crash in gd lib's ImageFillToBorder()).", "target": 1, "func": "gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)\n{\n  int lastBorder;\n  /* Seek left */\n  int leftLimit, rightLimit;\n  int i;\n  leftLimit = (-1);\n  if (border < 0)\n    {\n      /* Refuse to fill to a non-solid border */\n      return;\n    }\n  for (i = x; (i >= 0); i--)\n    {\n      if (gdImageGetPixel (im, i, y) == border)\n\t{\n\t  break;\n\t}\n      gdImageSetPixel (im, i, y, color);\n      leftLimit = i;\n    }\n  if (leftLimit == (-1))\n    {\n      return;\n    }\n  /* Seek right */\n  rightLimit = x;\n  for (i = (x + 1); (i < im->sx); i++)\n    {\n      if (gdImageGetPixel (im, i, y) == border)\n\t{\n\t  break;\n\t}\n      gdImageSetPixel (im, i, y, color);\n      rightLimit = i;\n    }\n  /* Look at lines above and below and start paints */\n  /* Above */\n  if (y > 0)\n    {\n      lastBorder = 1;\n      for (i = leftLimit; (i <= rightLimit); i++)\n\t{\n\t  int c;\n\t  c = gdImageGetPixel (im, i, y - 1);\n\t  if (lastBorder)\n\t    {\n\t      if ((c != border) && (c != color))\n\t\t{\n\t\t  gdImageFillToBorder (im, i, y - 1,\n\t\t\t\t       border, color);\n\t\t  lastBorder = 0;\n\t\t}\n\t    }\n\t  else if ((c == border) || (c == color))\n\t    {\n\t      lastBorder = 1;\n\t    }\n\t}\n    }\n  /* Below */\n  if (y < ((im->sy) - 1))\n    {\n      lastBorder = 1;\n      for (i = leftLimit; (i <= rightLimit); i++)\n\t{\n\t  int c;\n\t  c = gdImageGetPixel (im, i, y + 1);\n\t  if (lastBorder)\n\t    {\n\t      if ((c != border) && (c != color))\n\t\t{\n\t\t  gdImageFillToBorder (im, i, y + 1,\n\t\t\t\t       border, color);\n\t\t  lastBorder = 0;\n\t\t}\n\t    }\n\t  else if ((c == border) || (c == color))\n\t    {\n\t      lastBorder = 1;\n\t    }\n\t}\n    }\n}", "func_hash": 198226344899217828573742271884272950799, "file_name": "None", "file_hash": null, "cwe": ["CWE-119"], "cve": "CVE-2015-8874", "cve_desc": "Stack consumption vulnerability in GD in PHP before 5.6.12 allows remote attackers to cause a denial of service via a crafted imagefilltoborder call.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-8874"}
{"idx": 383316, "project": "php-src", "commit_id": "feba44546c27b0158f9ac20e72040a224b918c75", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commitdiff;h=feba44546c27b0158f9ac20e72040a224b918c75", "commit_message": "Fixed bug #22965 (Crash in gd lib's ImageFillToBorder()).", "target": 0, "func": "void gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)\n{\n\tint lastBorder;\n\t/* Seek left */\n\tint leftLimit = -1, rightLimit;\n\tint i;\n\n\tif (border < 0) {\n\t\t/* Refuse to fill to a non-solid border */\n\t\treturn;\n\t}\n\n\tif (x >= im->sx) {\n\t\tx = im->sx - 1;\n\t}\n\tif (y >= im->sy) {\n\t\ty = im->sy - 1;\n\t}\n\n\tfor (i = x; i >= 0; i--) {\n\t\tif (gdImageGetPixel(im, i, y) == border) {\n\t\t\tbreak;\n\t\t}\n\t\tgdImageSetPixel(im, i, y, color);\n\t\tleftLimit = i;\n\t}\n\tif (leftLimit == -1) {\n\t\treturn;\n\t}\n\t/* Seek right */\n\trightLimit = x;\n\tfor (i = (x + 1); i < im->sx; i++) {\n\t\tif (gdImageGetPixel(im, i, y) == border) {\n\t\t\tbreak;\n\t\t}\n\t\tgdImageSetPixel(im, i, y, color);\n\t\trightLimit = i;\n\t}\n\t/* Look at lines above and below and start paints */\n\t/* Above */\n\tif (y > 0) {\n\t\tlastBorder = 1;\n\t\tfor (i = leftLimit; i <= rightLimit; i++) {\n\t\t\tint c = gdImageGetPixel(im, i, y - 1);\n\t\t\tif (lastBorder) {\n\t\t\t\tif ((c != border) && (c != color)) {\n\t\t\t\t\tgdImageFillToBorder(im, i, y - 1, border, color);\n\t\t\t\t\tlastBorder = 0;\n\t\t\t\t}\n\t\t\t} else if ((c == border) || (c == color)) {\n\t\t\t\tlastBorder = 1;\n\t\t\t}\n\t\t}\n\t}\n\t/* Below */\n\tif (y < ((im->sy) - 1)) {\n\t\tlastBorder = 1;\n\t\tfor (i = leftLimit; i <= rightLimit; i++) {\n\t\t\tint c = gdImageGetPixel(im, i, y + 1);\n\n\t\t\tif (lastBorder) {\n\t\t\t\tif ((c != border) && (c != color)) {\n\t\t\t\t\tgdImageFillToBorder(im, i, y + 1, border, color);\n\t\t\t\t\tlastBorder = 0;\n\t\t\t\t}\n\t\t\t} else if ((c == border) || (c == color)) {\n\t\t\t\tlastBorder = 1;\n\t\t\t}\n\t\t}\n\t}\n}", "func_hash": 4519916874419069747672345142292777613, "file_name": "None", "file_hash": null, "cwe": ["CWE-119"], "cve": "CVE-2015-8874", "cve_desc": "Stack consumption vulnerability in GD in PHP before 5.6.12 allows remote attackers to cause a denial of service via a crafted imagefilltoborder call.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-8874"}
{"idx": 206625, "project": "raptor", "commit_id": "590681e546cd9aa18d57dc2ea1858cb734a3863f", "project_url": "https://github.com/dajobe/raptor", "commit_url": "https://github.com/dajobe/raptor/commit/590681e546cd9aa18d57dc2ea1858cb734a3863f", "commit_message": "Calcualte max nspace declarations correctly for XML writer\n\n(raptor_xml_writer_start_element_common): Calculate max including for\neach attribute a potential name and value.\n\nFixes Issues #0000617 http://bugs.librdf.org/mantis/view.php?id=617\nand #0000618 http://bugs.librdf.org/mantis/view.php?id=618", "target": 1, "func": "raptor_xml_writer_start_element_common(raptor_xml_writer* xml_writer,\n                                       raptor_xml_element* element,\n                                       int auto_empty)\n{\n  raptor_iostream* iostr = xml_writer->iostr;\n  raptor_namespace_stack *nstack = xml_writer->nstack;\n  int depth = xml_writer->depth;\n  int auto_indent = XML_WRITER_AUTO_INDENT(xml_writer);\n  struct nsd *nspace_declarations = NULL;\n  size_t nspace_declarations_count = 0;  \n  unsigned int i;\n\n  /* max is 1 per element and 1 for each attribute + size of declared */\n  if(nstack) {\n    int nspace_max_count = element->attribute_count+1;\n    if(element->declared_nspaces)\n      nspace_max_count += raptor_sequence_size(element->declared_nspaces);\n    if(element->xml_language)\n      nspace_max_count++;\n\n    nspace_declarations = RAPTOR_CALLOC(struct nsd*, nspace_max_count,\n                                        sizeof(struct nsd));\n    if(!nspace_declarations)\n      return 1;\n  }\n\n  if(element->name->nspace) {\n    if(nstack && !raptor_namespaces_namespace_in_scope(nstack, element->name->nspace)) {\n      nspace_declarations[0].declaration=\n        raptor_namespace_format_as_xml(element->name->nspace,\n                                       &nspace_declarations[0].length);\n      if(!nspace_declarations[0].declaration)\n        goto error;\n      nspace_declarations[0].nspace = element->name->nspace;\n      nspace_declarations_count++;\n    }\n  }\n\n  if(nstack && element->attributes) {\n    for(i = 0; i < element->attribute_count; i++) {\n      /* qname */\n      if(element->attributes[i]->nspace) {\n        /* Check if we need a namespace declaration attribute */\n        if(nstack && \n           !raptor_namespaces_namespace_in_scope(nstack, element->attributes[i]->nspace) && element->attributes[i]->nspace != element->name->nspace) {\n          /* not in scope and not same as element (so already going to be declared)*/\n          unsigned int j;\n          int declare_me = 1;\n          \n          /* check it wasn't an earlier declaration too */\n          for(j = 0; j < nspace_declarations_count; j++)\n            if(nspace_declarations[j].nspace == element->attributes[j]->nspace) {\n              declare_me = 0;\n              break;\n            }\n            \n          if(declare_me) {\n            nspace_declarations[nspace_declarations_count].declaration=\n              raptor_namespace_format_as_xml(element->attributes[i]->nspace,\n                                             &nspace_declarations[nspace_declarations_count].length);\n            if(!nspace_declarations[nspace_declarations_count].declaration)\n              goto error;\n            nspace_declarations[nspace_declarations_count].nspace = element->attributes[i]->nspace;\n            nspace_declarations_count++;\n          }\n        }\n      }\n\n      /* Add the attribute + value */\n      nspace_declarations[nspace_declarations_count].declaration=\n        raptor_qname_format_as_xml(element->attributes[i],\n                                   &nspace_declarations[nspace_declarations_count].length);\n      if(!nspace_declarations[nspace_declarations_count].declaration)\n        goto error;\n      nspace_declarations[nspace_declarations_count].nspace = NULL;\n      nspace_declarations_count++;\n\n    }\n  }\n\n  if(nstack && element->declared_nspaces &&\n     raptor_sequence_size(element->declared_nspaces) > 0) {\n    for(i = 0; i< (unsigned int)raptor_sequence_size(element->declared_nspaces); i++) {\n      raptor_namespace* nspace = (raptor_namespace*)raptor_sequence_get_at(element->declared_nspaces, i);\n      unsigned int j;\n      int declare_me = 1;\n      \n      /* check it wasn't an earlier declaration too */\n      for(j = 0; j < nspace_declarations_count; j++)\n        if(nspace_declarations[j].nspace == nspace) {\n          declare_me = 0;\n          break;\n        }\n      \n      if(declare_me) {\n        nspace_declarations[nspace_declarations_count].declaration=\n          raptor_namespace_format_as_xml(nspace,\n                                         &nspace_declarations[nspace_declarations_count].length);\n        if(!nspace_declarations[nspace_declarations_count].declaration)\n          goto error;\n        nspace_declarations[nspace_declarations_count].nspace = nspace;\n        nspace_declarations_count++;\n      }\n\n    }\n  }\n\n  if(nstack && element->xml_language) {\n    size_t lang_len = strlen(RAPTOR_GOOD_CAST(char*, element->xml_language));\n#define XML_LANG_PREFIX_LEN 10\n    size_t buf_length = XML_LANG_PREFIX_LEN + lang_len + 1;\n    unsigned char* buffer = RAPTOR_MALLOC(unsigned char*, buf_length + 1);\n    const char quote = '\\\"';\n    unsigned char* p;\n\n    memcpy(buffer, \"xml:lang=\\\"\", XML_LANG_PREFIX_LEN);\n    p = buffer + XML_LANG_PREFIX_LEN;\n    p += raptor_xml_escape_string(xml_writer->world,\n                                  element->xml_language, lang_len,\n                                  p, buf_length, quote);\n    *p++ = quote;\n    *p = '\\0';\n\n    nspace_declarations[nspace_declarations_count].declaration = buffer;\n    nspace_declarations[nspace_declarations_count].length = buf_length;\n    nspace_declarations[nspace_declarations_count].nspace = NULL;\n    nspace_declarations_count++;\n  }\n  \n\n  raptor_iostream_write_byte('<', iostr);\n\n  if(element->name->nspace && element->name->nspace->prefix_length > 0) {\n    raptor_iostream_counted_string_write((const char*)element->name->nspace->prefix, \n                                         element->name->nspace->prefix_length,\n                                         iostr);\n    raptor_iostream_write_byte(':', iostr);\n  }\n  raptor_iostream_counted_string_write((const char*)element->name->local_name,\n                                       element->name->local_name_length,\n                                       iostr);\n\n  /* declare namespaces and attributes */\n  if(nspace_declarations_count) {\n    int need_indent = 0;\n    \n    /* sort them into the canonical order */\n    qsort((void*)nspace_declarations, \n          nspace_declarations_count, sizeof(struct nsd),\n          raptor_xml_writer_nsd_compare);\n\n    /* declare namespaces first */\n    for(i = 0; i < nspace_declarations_count; i++) {\n      if(!nspace_declarations[i].nspace)\n        continue;\n\n      if(auto_indent && need_indent) {\n        /* indent attributes */\n        raptor_xml_writer_newline(xml_writer);\n        xml_writer->depth++;\n        raptor_xml_writer_indent(xml_writer);\n        xml_writer->depth--;\n      }\n      raptor_iostream_write_byte(' ', iostr);\n      raptor_iostream_counted_string_write((const char*)nspace_declarations[i].declaration,\n                                           nspace_declarations[i].length,\n                                           iostr);\n      RAPTOR_FREE(char*, nspace_declarations[i].declaration);\n      nspace_declarations[i].declaration = NULL;\n      need_indent = 1;\n      \n      if(raptor_namespace_stack_start_namespace(nstack,\n                                                (raptor_namespace*)nspace_declarations[i].nspace,\n                                                depth))\n        goto error;\n    }\n\n    /* declare attributes */\n    for(i = 0; i < nspace_declarations_count; i++) {\n      if(nspace_declarations[i].nspace)\n        continue;\n\n      if(auto_indent && need_indent) {\n        /* indent attributes */\n        raptor_xml_writer_newline(xml_writer);\n        xml_writer->depth++;\n        raptor_xml_writer_indent(xml_writer);\n        xml_writer->depth--;\n      }\n      raptor_iostream_write_byte(' ', iostr);\n      raptor_iostream_counted_string_write((const char*)nspace_declarations[i].declaration,\n                                           nspace_declarations[i].length,\n                                           iostr);\n      need_indent = 1;\n\n      RAPTOR_FREE(char*, nspace_declarations[i].declaration);\n      nspace_declarations[i].declaration = NULL;\n    }\n  }\n\n  if(!auto_empty)\n    raptor_iostream_write_byte('>', iostr);\n\n  if(nstack)\n    RAPTOR_FREE(stringarray, nspace_declarations);\n\n  return 0;\n\n  /* Clean up nspace_declarations on error */\n  error:\n\n  for(i = 0; i < nspace_declarations_count; i++) {\n    if(nspace_declarations[i].declaration)\n      RAPTOR_FREE(char*, nspace_declarations[i].declaration);\n  }\n\n  RAPTOR_FREE(stringarray, nspace_declarations);\n\n  return 1;\n}", "func_hash": 183974089624650942434351568312452779610, "file_name": "raptor_xml_writer.c", "file_hash": 303005196227120175198140448209688194758, "cwe": ["CWE-787"], "cve": "CVE-2017-18926", "cve_desc": "raptor_xml_writer_start_element_common in raptor_xml_writer.c in Raptor RDF Syntax Library 2.0.15 miscalculates the maximum nspace declarations for the XML writer, leading to heap-based buffer overflows (sometimes seen in raptor_qname_format_as_xml).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-18926"}
{"idx": 384124, "project": "raptor", "commit_id": "590681e546cd9aa18d57dc2ea1858cb734a3863f", "project_url": "https://github.com/dajobe/raptor", "commit_url": "https://github.com/dajobe/raptor/commit/590681e546cd9aa18d57dc2ea1858cb734a3863f", "commit_message": "Calcualte max nspace declarations correctly for XML writer\n\n(raptor_xml_writer_start_element_common): Calculate max including for\neach attribute a potential name and value.\n\nFixes Issues #0000617 http://bugs.librdf.org/mantis/view.php?id=617\nand #0000618 http://bugs.librdf.org/mantis/view.php?id=618", "target": 0, "func": "raptor_xml_writer_start_element_common(raptor_xml_writer* xml_writer,\n                                       raptor_xml_element* element,\n                                       int auto_empty)\n{\n  raptor_iostream* iostr = xml_writer->iostr;\n  raptor_namespace_stack *nstack = xml_writer->nstack;\n  int depth = xml_writer->depth;\n  int auto_indent = XML_WRITER_AUTO_INDENT(xml_writer);\n  struct nsd *nspace_declarations = NULL;\n  size_t nspace_declarations_count = 0;  \n  unsigned int i;\n\n  if(nstack) {\n    int nspace_max_count = element->attribute_count * 2; /* attr and value */\n    if(element->name->nspace)\n      nspace_max_count++;\n    if(element->declared_nspaces)\n      nspace_max_count += raptor_sequence_size(element->declared_nspaces);\n    if(element->xml_language)\n      nspace_max_count++;\n\n    nspace_declarations = RAPTOR_CALLOC(struct nsd*, nspace_max_count,\n                                        sizeof(struct nsd));\n    if(!nspace_declarations)\n      return 1;\n  }\n\n  if(element->name->nspace) {\n    if(nstack && !raptor_namespaces_namespace_in_scope(nstack, element->name->nspace)) {\n      nspace_declarations[0].declaration=\n        raptor_namespace_format_as_xml(element->name->nspace,\n                                       &nspace_declarations[0].length);\n      if(!nspace_declarations[0].declaration)\n        goto error;\n      nspace_declarations[0].nspace = element->name->nspace;\n      nspace_declarations_count++;\n    }\n  }\n\n  if(nstack && element->attributes) {\n    for(i = 0; i < element->attribute_count; i++) {\n      /* qname */\n      if(element->attributes[i]->nspace) {\n        /* Check if we need a namespace declaration attribute */\n        if(nstack && \n           !raptor_namespaces_namespace_in_scope(nstack, element->attributes[i]->nspace) && element->attributes[i]->nspace != element->name->nspace) {\n          /* not in scope and not same as element (so already going to be declared)*/\n          unsigned int j;\n          int declare_me = 1;\n          \n          /* check it wasn't an earlier declaration too */\n          for(j = 0; j < nspace_declarations_count; j++)\n            if(nspace_declarations[j].nspace == element->attributes[j]->nspace) {\n              declare_me = 0;\n              break;\n            }\n            \n          if(declare_me) {\n            nspace_declarations[nspace_declarations_count].declaration=\n              raptor_namespace_format_as_xml(element->attributes[i]->nspace,\n                                             &nspace_declarations[nspace_declarations_count].length);\n            if(!nspace_declarations[nspace_declarations_count].declaration)\n              goto error;\n            nspace_declarations[nspace_declarations_count].nspace = element->attributes[i]->nspace;\n            nspace_declarations_count++;\n          }\n        }\n      }\n\n      /* Add the attribute's value */\n      nspace_declarations[nspace_declarations_count].declaration=\n        raptor_qname_format_as_xml(element->attributes[i],\n                                   &nspace_declarations[nspace_declarations_count].length);\n      if(!nspace_declarations[nspace_declarations_count].declaration)\n        goto error;\n      nspace_declarations[nspace_declarations_count].nspace = NULL;\n      nspace_declarations_count++;\n\n    }\n  }\n\n  if(nstack && element->declared_nspaces &&\n     raptor_sequence_size(element->declared_nspaces) > 0) {\n    for(i = 0; i< (unsigned int)raptor_sequence_size(element->declared_nspaces); i++) {\n      raptor_namespace* nspace = (raptor_namespace*)raptor_sequence_get_at(element->declared_nspaces, i);\n      unsigned int j;\n      int declare_me = 1;\n      \n      /* check it wasn't an earlier declaration too */\n      for(j = 0; j < nspace_declarations_count; j++)\n        if(nspace_declarations[j].nspace == nspace) {\n          declare_me = 0;\n          break;\n        }\n      \n      if(declare_me) {\n        nspace_declarations[nspace_declarations_count].declaration=\n          raptor_namespace_format_as_xml(nspace,\n                                         &nspace_declarations[nspace_declarations_count].length);\n        if(!nspace_declarations[nspace_declarations_count].declaration)\n          goto error;\n        nspace_declarations[nspace_declarations_count].nspace = nspace;\n        nspace_declarations_count++;\n      }\n\n    }\n  }\n\n  if(nstack && element->xml_language) {\n    size_t lang_len = strlen(RAPTOR_GOOD_CAST(char*, element->xml_language));\n#define XML_LANG_PREFIX_LEN 10\n    size_t buf_length = XML_LANG_PREFIX_LEN + lang_len + 1;\n    unsigned char* buffer = RAPTOR_MALLOC(unsigned char*, buf_length + 1);\n    const char quote = '\\\"';\n    unsigned char* p;\n\n    memcpy(buffer, \"xml:lang=\\\"\", XML_LANG_PREFIX_LEN);\n    p = buffer + XML_LANG_PREFIX_LEN;\n    p += raptor_xml_escape_string(xml_writer->world,\n                                  element->xml_language, lang_len,\n                                  p, buf_length, quote);\n    *p++ = quote;\n    *p = '\\0';\n\n    nspace_declarations[nspace_declarations_count].declaration = buffer;\n    nspace_declarations[nspace_declarations_count].length = buf_length;\n    nspace_declarations[nspace_declarations_count].nspace = NULL;\n    nspace_declarations_count++;\n  }\n  \n\n  raptor_iostream_write_byte('<', iostr);\n\n  if(element->name->nspace && element->name->nspace->prefix_length > 0) {\n    raptor_iostream_counted_string_write((const char*)element->name->nspace->prefix, \n                                         element->name->nspace->prefix_length,\n                                         iostr);\n    raptor_iostream_write_byte(':', iostr);\n  }\n  raptor_iostream_counted_string_write((const char*)element->name->local_name,\n                                       element->name->local_name_length,\n                                       iostr);\n\n  /* declare namespaces and attributes */\n  if(nspace_declarations_count) {\n    int need_indent = 0;\n    \n    /* sort them into the canonical order */\n    qsort((void*)nspace_declarations, \n          nspace_declarations_count, sizeof(struct nsd),\n          raptor_xml_writer_nsd_compare);\n\n    /* declare namespaces first */\n    for(i = 0; i < nspace_declarations_count; i++) {\n      if(!nspace_declarations[i].nspace)\n        continue;\n\n      if(auto_indent && need_indent) {\n        /* indent attributes */\n        raptor_xml_writer_newline(xml_writer);\n        xml_writer->depth++;\n        raptor_xml_writer_indent(xml_writer);\n        xml_writer->depth--;\n      }\n      raptor_iostream_write_byte(' ', iostr);\n      raptor_iostream_counted_string_write((const char*)nspace_declarations[i].declaration,\n                                           nspace_declarations[i].length,\n                                           iostr);\n      RAPTOR_FREE(char*, nspace_declarations[i].declaration);\n      nspace_declarations[i].declaration = NULL;\n      need_indent = 1;\n      \n      if(raptor_namespace_stack_start_namespace(nstack,\n                                                (raptor_namespace*)nspace_declarations[i].nspace,\n                                                depth))\n        goto error;\n    }\n\n    /* declare attributes */\n    for(i = 0; i < nspace_declarations_count; i++) {\n      if(nspace_declarations[i].nspace)\n        continue;\n\n      if(auto_indent && need_indent) {\n        /* indent attributes */\n        raptor_xml_writer_newline(xml_writer);\n        xml_writer->depth++;\n        raptor_xml_writer_indent(xml_writer);\n        xml_writer->depth--;\n      }\n      raptor_iostream_write_byte(' ', iostr);\n      raptor_iostream_counted_string_write((const char*)nspace_declarations[i].declaration,\n                                           nspace_declarations[i].length,\n                                           iostr);\n      need_indent = 1;\n\n      RAPTOR_FREE(char*, nspace_declarations[i].declaration);\n      nspace_declarations[i].declaration = NULL;\n    }\n  }\n\n  if(!auto_empty)\n    raptor_iostream_write_byte('>', iostr);\n\n  if(nstack)\n    RAPTOR_FREE(stringarray, nspace_declarations);\n\n  return 0;\n\n  /* Clean up nspace_declarations on error */\n  error:\n\n  for(i = 0; i < nspace_declarations_count; i++) {\n    if(nspace_declarations[i].declaration)\n      RAPTOR_FREE(char*, nspace_declarations[i].declaration);\n  }\n\n  RAPTOR_FREE(stringarray, nspace_declarations);\n\n  return 1;\n}", "func_hash": 82963305933956175677502497774267767451, "file_name": "raptor_xml_writer.c", "file_hash": 139112831165877018854969912519011883099, "cwe": ["CWE-787"], "cve": "CVE-2017-18926", "cve_desc": "raptor_xml_writer_start_element_common in raptor_xml_writer.c in Raptor RDF Syntax Library 2.0.15 miscalculates the maximum nspace declarations for the XML writer, leading to heap-based buffer overflows (sometimes seen in raptor_qname_format_as_xml).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-18926"}
{"idx": 206639, "project": "linux", "commit_id": "e02f0d3970404bfea385b6edb86f2d936db0ea2b", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/e02f0d3970404bfea385b6edb86f2d936db0ea2b", "commit_message": "netfilter: nf_tables: disallow binding to already bound chain\n\nUpdate nft_data_init() to report EINVAL if chain is already bound.\n\nFixes: d0e2c7de92c7 (\"netfilter: nf_tables: add NFT_CHAIN_BINDING\")\nReported-by: Gwangun Jung \nSigned-off-by: Pablo Neira Ayuso ", "target": 1, "func": "static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,\n\t\t\t    struct nft_data_desc *desc, const struct nlattr *nla)\n{\n\tu8 genmask = nft_genmask_next(ctx->net);\n\tstruct nlattr *tb[NFTA_VERDICT_MAX + 1];\n\tstruct nft_chain *chain;\n\tint err;\n\n\terr = nla_parse_nested_deprecated(tb, NFTA_VERDICT_MAX, nla,\n\t\t\t\t\t  nft_verdict_policy, NULL);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (!tb[NFTA_VERDICT_CODE])\n\t\treturn -EINVAL;\n\tdata->verdict.code = ntohl(nla_get_be32(tb[NFTA_VERDICT_CODE]));\n\n\tswitch (data->verdict.code) {\n\tdefault:\n\t\tswitch (data->verdict.code & NF_VERDICT_MASK) {\n\t\tcase NF_ACCEPT:\n\t\tcase NF_DROP:\n\t\tcase NF_QUEUE:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tfallthrough;\n\tcase NFT_CONTINUE:\n\tcase NFT_BREAK:\n\tcase NFT_RETURN:\n\t\tbreak;\n\tcase NFT_JUMP:\n\tcase NFT_GOTO:\n\t\tif (tb[NFTA_VERDICT_CHAIN]) {\n\t\t\tchain = nft_chain_lookup(ctx->net, ctx->table,\n\t\t\t\t\t\t tb[NFTA_VERDICT_CHAIN],\n\t\t\t\t\t\t genmask);\n\t\t} else if (tb[NFTA_VERDICT_CHAIN_ID]) {\n\t\t\tchain = nft_chain_lookup_byid(ctx->net, ctx->table,\n\t\t\t\t\t\t      tb[NFTA_VERDICT_CHAIN_ID]);\n\t\t\tif (IS_ERR(chain))\n\t\t\t\treturn PTR_ERR(chain);\n\t\t} else {\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tif (IS_ERR(chain))\n\t\t\treturn PTR_ERR(chain);\n\t\tif (nft_is_base_chain(chain))\n\t\t\treturn -EOPNOTSUPP;\n\t\tif (desc->flags & NFT_DATA_DESC_SETELEM &&\n\t\t    chain->flags & NFT_CHAIN_BINDING)\n\t\t\treturn -EINVAL;\n\n\t\tchain->use++;\n\t\tdata->verdict.chain = chain;\n\t\tbreak;\n\t}\n\n\tdesc->len = sizeof(data->verdict);\n\n\treturn 0;\n}", "func_hash": 76294390154807140346030498178733770308, "file_name": "nf_tables_api.c", "file_hash": 280373467088228575441623327249382307245, "cwe": ["CWE-703"], "cve": "CVE-2022-39190", "cve_desc": "An issue was discovered in net/netfilter/nf_tables_api.c in the Linux kernel before 5.19.6. A denial of service can occur upon binding to an already bound chain.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-39190"}
{"idx": 384201, "project": "linux", "commit_id": "e02f0d3970404bfea385b6edb86f2d936db0ea2b", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/e02f0d3970404bfea385b6edb86f2d936db0ea2b", "commit_message": "netfilter: nf_tables: disallow binding to already bound chain\n\nUpdate nft_data_init() to report EINVAL if chain is already bound.\n\nFixes: d0e2c7de92c7 (\"netfilter: nf_tables: add NFT_CHAIN_BINDING\")\nReported-by: Gwangun Jung \nSigned-off-by: Pablo Neira Ayuso ", "target": 0, "func": "static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,\n\t\t\t    struct nft_data_desc *desc, const struct nlattr *nla)\n{\n\tu8 genmask = nft_genmask_next(ctx->net);\n\tstruct nlattr *tb[NFTA_VERDICT_MAX + 1];\n\tstruct nft_chain *chain;\n\tint err;\n\n\terr = nla_parse_nested_deprecated(tb, NFTA_VERDICT_MAX, nla,\n\t\t\t\t\t  nft_verdict_policy, NULL);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (!tb[NFTA_VERDICT_CODE])\n\t\treturn -EINVAL;\n\tdata->verdict.code = ntohl(nla_get_be32(tb[NFTA_VERDICT_CODE]));\n\n\tswitch (data->verdict.code) {\n\tdefault:\n\t\tswitch (data->verdict.code & NF_VERDICT_MASK) {\n\t\tcase NF_ACCEPT:\n\t\tcase NF_DROP:\n\t\tcase NF_QUEUE:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tfallthrough;\n\tcase NFT_CONTINUE:\n\tcase NFT_BREAK:\n\tcase NFT_RETURN:\n\t\tbreak;\n\tcase NFT_JUMP:\n\tcase NFT_GOTO:\n\t\tif (tb[NFTA_VERDICT_CHAIN]) {\n\t\t\tchain = nft_chain_lookup(ctx->net, ctx->table,\n\t\t\t\t\t\t tb[NFTA_VERDICT_CHAIN],\n\t\t\t\t\t\t genmask);\n\t\t} else if (tb[NFTA_VERDICT_CHAIN_ID]) {\n\t\t\tchain = nft_chain_lookup_byid(ctx->net, ctx->table,\n\t\t\t\t\t\t      tb[NFTA_VERDICT_CHAIN_ID]);\n\t\t\tif (IS_ERR(chain))\n\t\t\t\treturn PTR_ERR(chain);\n\t\t} else {\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tif (IS_ERR(chain))\n\t\t\treturn PTR_ERR(chain);\n\t\tif (nft_is_base_chain(chain))\n\t\t\treturn -EOPNOTSUPP;\n\t\tif (nft_chain_is_bound(chain))\n\t\t\treturn -EINVAL;\n\t\tif (desc->flags & NFT_DATA_DESC_SETELEM &&\n\t\t    chain->flags & NFT_CHAIN_BINDING)\n\t\t\treturn -EINVAL;\n\n\t\tchain->use++;\n\t\tdata->verdict.chain = chain;\n\t\tbreak;\n\t}\n\n\tdesc->len = sizeof(data->verdict);\n\n\treturn 0;\n}", "func_hash": 189225679685979204194302814541477257663, "file_name": "nf_tables_api.c", "file_hash": 161585463478410786724773068235961577198, "cwe": ["CWE-703"], "cve": "CVE-2022-39190", "cve_desc": "An issue was discovered in net/netfilter/nf_tables_api.c in the Linux kernel before 5.19.6. A denial of service can occur upon binding to an already bound chain.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-39190"}
{"idx": 206670, "project": "nbdkit", "commit_id": "6c5faac6a37077cf2366388a80862bb00616d0d8", "project_url": "https://github.com/libguestfs/nbdkit", "commit_url": "https://gitlab.com/nbdkit/nbdkit/-/commit/6c5faac6a37077cf2366388a80862bb00616d0d8", "commit_message": "server: reset meta context replies on starttls\n\nRelated to CVE-2021-3716, but not as severe.  No compliant client will\nsend NBD_CMD_BLOCK_STATUS unless it first negotiates\nNBD_OPT_SET_META_CONTEXT.  If an attacker injects a premature\nSET_META_CONTEXT, either the client will never notice (because it\nnever uses BLOCK_STATUS), or the client will overwrite the attacker's\nattempt with the client's own SET_META_CONTEXT request after\nencryption is enabled.  So I don't class this as having the potential\nto trigger denial-of-service due to any protocol mismatch between\ncompliant client and server (I don't care what happens with\nnon-compliant clients).\n\nFixes: 26455d45 (server: protocol: Implement Block Status \"base:allocation\".)", "target": 1, "func": "negotiate_handshake_newstyle_options (void)\n{\n  GET_CONN;\n  struct nbd_new_option new_option;\n  size_t nr_options;\n  bool list_seen = false;\n  uint64_t version;\n  uint32_t option;\n  uint32_t optlen;\n  struct nbd_export_name_option_reply handshake_finish;\n  const char *optname;\n  uint64_t exportsize;\n  struct backend *b;\n\n  for (nr_options = MAX_NR_OPTIONS; nr_options > 0; --nr_options) {\n    CLEANUP_FREE char *data = NULL;\n\n    if (conn_recv_full (&new_option, sizeof new_option,\n                        \"reading option: conn->recv: %m\") == -1)\n      return -1;\n\n    version = be64toh (new_option.version);\n    if (version != NBD_NEW_VERSION) {\n      nbdkit_error (\"unknown option version %\" PRIx64\n                    \", expecting %\" PRIx64,\n                    version, NBD_NEW_VERSION);\n      return -1;\n    }\n\n    /* There is a maximum option length we will accept, regardless\n     * of the option type.\n     */\n    optlen = be32toh (new_option.optlen);\n    if (optlen > MAX_REQUEST_SIZE) {\n      nbdkit_error (\"client option data too long (%\" PRIu32 \")\", optlen);\n      return -1;\n    }\n    data = malloc (optlen + 1); /* Allowing a trailing NUL helps some uses */\n    if (data == NULL) {\n      nbdkit_error (\"malloc: %m\");\n      return -1;\n    }\n\n    option = be32toh (new_option.option);\n    optname = name_of_nbd_opt (option);\n\n    /* If the client lacks fixed newstyle support, it should only send\n     * NBD_OPT_EXPORT_NAME.\n     */\n    if (!(conn->cflags & NBD_FLAG_FIXED_NEWSTYLE) &&\n        option != NBD_OPT_EXPORT_NAME) {\n      if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID))\n        return -1;\n      continue;\n    }\n\n    /* In --tls=require / FORCEDTLS mode the only options allowed\n     * before TLS negotiation are NBD_OPT_ABORT and NBD_OPT_STARTTLS.\n     */\n    if (tls == 2 && !conn->using_tls &&\n        !(option == NBD_OPT_ABORT || option == NBD_OPT_STARTTLS)) {\n      if (send_newstyle_option_reply (option, NBD_REP_ERR_TLS_REQD))\n        return -1;\n      continue;\n    }\n\n    switch (option) {\n    case NBD_OPT_EXPORT_NAME:\n      if (conn_recv_full (data, optlen,\n                          \"read: %s: %m\", name_of_nbd_opt (option)) == -1)\n        return -1;\n      if (check_export_name (option, data, optlen, optlen) == -1)\n        return -1;\n\n      /* We have to finish the handshake by sending handshake_finish.\n       * On failure, we have to disconnect.\n       */\n      if (finish_newstyle_options (&exportsize, data, optlen) == -1)\n        return -1;\n\n      memset (&handshake_finish, 0, sizeof handshake_finish);\n      handshake_finish.exportsize = htobe64 (exportsize);\n      handshake_finish.eflags = htobe16 (conn->eflags);\n\n      if (conn->send (&handshake_finish,\n                      (conn->cflags & NBD_FLAG_NO_ZEROES)\n                      ? offsetof (struct nbd_export_name_option_reply, zeroes)\n                      : sizeof handshake_finish, 0) == -1) {\n        nbdkit_error (\"write: %s: %m\", optname);\n        return -1;\n      }\n      break;\n\n    case NBD_OPT_ABORT:\n      if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)\n        return -1;\n      debug (\"client sent %s to abort the connection\",\n             name_of_nbd_opt (option));\n      return -1;\n\n    case NBD_OPT_LIST:\n      if (optlen != 0) {\n        if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n            == -1)\n          return -1;\n        if (conn_recv_full (data, optlen,\n                            \"read: %s: %m\", name_of_nbd_opt (option)) == -1)\n          return -1;\n        continue;\n      }\n\n      if (list_seen) {\n        debug (\"newstyle negotiation: %s: export list already advertised\",\n               name_of_nbd_opt (option));\n        if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID) == -1)\n          return -1;\n        continue;\n      }\n      else {\n        /* Send back the exportname list. */\n        debug (\"newstyle negotiation: %s: advertising exports\",\n               name_of_nbd_opt (option));\n        if (send_newstyle_option_reply_exportnames (option, &nr_options) == -1)\n          return -1;\n        list_seen = true;\n      }\n      break;\n\n    case NBD_OPT_STARTTLS:\n      if (optlen != 0) {\n        if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n            == -1)\n          return -1;\n        if (conn_recv_full (data, optlen,\n                            \"read: %s: %m\", name_of_nbd_opt (option)) == -1)\n          return -1;\n        continue;\n      }\n\n      if (tls == 0) {           /* --tls=off (NOTLS mode). */\n#ifdef HAVE_GNUTLS\n#define NO_TLS_REPLY NBD_REP_ERR_POLICY\n#else\n#define NO_TLS_REPLY NBD_REP_ERR_UNSUP\n#endif\n        if (send_newstyle_option_reply (option, NO_TLS_REPLY) == -1)\n          return -1;\n      }\n      else /* --tls=on or --tls=require */ {\n        /* We can't upgrade to TLS twice on the same connection. */\n        if (conn->using_tls) {\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID) == -1)\n            return -1;\n          continue;\n        }\n\n        /* We have to send the (unencrypted) reply before starting\n         * the handshake.\n         */\n        if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)\n          return -1;\n\n        /* Upgrade the connection to TLS.  Also performs access control. */\n        if (crypto_negotiate_tls (conn->sockin, conn->sockout) == -1)\n          return -1;\n        conn->using_tls = true;\n        debug (\"using TLS on this connection\");\n        /* Wipe out any cached state. */\n        conn->structured_replies = false;\n        for_each_backend (b) {\n          free (conn->default_exportname[b->i]);\n          conn->default_exportname[b->i] = NULL;\n        }\n      }\n      break;\n\n    case NBD_OPT_INFO:\n    case NBD_OPT_GO:\n      if (conn_recv_full (data, optlen, \"read: %s: %m\", optname) == -1)\n        return -1;\n\n      if (optlen < 6) { /* 32 bit export length + 16 bit nr info */\n        debug (\"newstyle negotiation: %s option length < 6\", optname);\n\n        if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n            == -1)\n          return -1;\n        continue;\n      }\n\n      {\n        uint32_t exportnamelen;\n        uint16_t nrinfos;\n        uint16_t info;\n        size_t i;\n\n        /* Validate the name length and number of INFO requests. */\n        memcpy (&exportnamelen, &data[0], 4);\n        exportnamelen = be32toh (exportnamelen);\n        if (exportnamelen > optlen-6 /* NB optlen >= 6, see above */) {\n          debug (\"newstyle negotiation: %s: export name too long\", optname);\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n              == -1)\n            return -1;\n          continue;\n        }\n        memcpy (&nrinfos, &data[exportnamelen+4], 2);\n        nrinfos = be16toh (nrinfos);\n        if (optlen != 4 + exportnamelen + 2 + 2*nrinfos) {\n          debug (\"newstyle negotiation: %s: \"\n                 \"number of information requests incorrect\", optname);\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n              == -1)\n            return -1;\n          continue;\n        }\n\n        /* As with NBD_OPT_EXPORT_NAME we print the export name and\n         * save it in the connection.  If an earlier\n         * NBD_OPT_SET_META_CONTEXT used an export name, it must match\n         * or else we drop the support for that context.\n         */\n        if (check_export_name (option, &data[4], exportnamelen,\n                               optlen - 6) == -1) {\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n              == -1)\n            return -1;\n          continue;\n        }\n\n        /* The spec is confusing, but it is required that we send back\n         * NBD_INFO_EXPORT, even if the client did not request it!\n         * qemu client in particular does not request this, but will\n         * fail if we don't send it.  Note that if .open fails, but we\n         * succeed at .close, then we merely return an error to the\n         * client and let them try another NBD_OPT, rather than\n         * disconnecting.\n         */\n        if (finish_newstyle_options (&exportsize,\n                                     &data[4], exportnamelen) == -1) {\n          if (conn->top_context) {\n            if (backend_finalize (conn->top_context) == -1)\n              return -1;\n            backend_close (conn->top_context);\n            conn->top_context = NULL;\n          }\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_UNKNOWN) == -1)\n            return -1;\n          continue;\n        }\n\n        if (send_newstyle_option_reply_info_export (option,\n                                                    NBD_REP_INFO,\n                                                    NBD_INFO_EXPORT,\n                                                    exportsize) == -1)\n          return -1;\n\n        /* For now we send NBD_INFO_NAME and NBD_INFO_DESCRIPTION if\n         * requested, and ignore all other info requests (including\n         * NBD_INFO_EXPORT if it was requested, because we replied\n         * already above).\n         */\n        for (i = 0; i < nrinfos; ++i) {\n          memcpy (&info, &data[4 + exportnamelen + 2 + i*2], 2);\n          info = be16toh (info);\n          switch (info) {\n          case NBD_INFO_EXPORT: /* ignore - reply sent above */ break;\n          case NBD_INFO_NAME:\n            {\n              const char *name = &data[4];\n              size_t namelen = exportnamelen;\n\n              if (exportnamelen == 0) {\n                name = backend_default_export (top, read_only);\n                if (!name) {\n                  debug (\"newstyle negotiation: %s: \"\n                         \"NBD_INFO_NAME: no name to send\", optname);\n                  break;\n                }\n                namelen = -1;\n              }\n              if (send_newstyle_option_reply_info_str (option,\n                                                       NBD_REP_INFO,\n                                                       NBD_INFO_NAME,\n                                                       name, namelen) == -1)\n                return -1;\n            }\n            break;\n          case NBD_INFO_DESCRIPTION:\n            {\n              const char *desc = backend_export_description (conn->top_context);\n\n              if (!desc) {\n                debug (\"newstyle negotiation: %s: \"\n                       \"NBD_INFO_DESCRIPTION: no description to send\",\n                       optname);\n                break;\n              }\n              if (send_newstyle_option_reply_info_str (option,\n                                                       NBD_REP_INFO,\n                                                       NBD_INFO_DESCRIPTION,\n                                                       desc, -1) == -1)\n                return -1;\n            }\n            break;\n          default:\n            debug (\"newstyle negotiation: %s: \"\n                   \"ignoring NBD_INFO_* request %u (%s)\",\n                   optname, (unsigned) info, name_of_nbd_info (info));\n            break;\n          }\n        }\n      }\n\n      /* Unlike NBD_OPT_EXPORT_NAME, NBD_OPT_GO sends back an ACK\n       * or ERROR packet.  If this was NBD_OPT_LIST, call .close.\n       */\n      if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)\n        return -1;\n\n      if (option == NBD_OPT_INFO) {\n        if (backend_finalize (conn->top_context) == -1)\n          return -1;\n        backend_close (conn->top_context);\n        conn->top_context = NULL;\n      }\n\n      break;\n\n    case NBD_OPT_STRUCTURED_REPLY:\n      if (optlen != 0) {\n        if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n            == -1)\n          return -1;\n        if (conn_recv_full (data, optlen,\n                            \"read: %s: %m\", name_of_nbd_opt (option)) == -1)\n          return -1;\n        continue;\n      }\n\n      debug (\"newstyle negotiation: %s: client requested structured replies\",\n             name_of_nbd_opt (option));\n\n      if (no_sr) {\n        /* Must fail with ERR_UNSUP for qemu 4.2 to remain happy;\n         * but failing with ERR_POLICY would have been nicer.\n         */\n        if (send_newstyle_option_reply (option, NBD_REP_ERR_UNSUP) == -1)\n          return -1;\n        debug (\"newstyle negotiation: %s: structured replies are disabled\",\n               name_of_nbd_opt (option));\n        break;\n      }\n\n      if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)\n        return -1;\n\n      conn->structured_replies = true;\n      break;\n\n    case NBD_OPT_LIST_META_CONTEXT:\n    case NBD_OPT_SET_META_CONTEXT:\n      {\n        uint32_t opt_index;\n        uint32_t exportnamelen;\n        uint32_t nr_queries;\n        uint32_t querylen;\n        const char *what;\n\n        if (conn_recv_full (data, optlen, \"read: %s: %m\", optname) == -1)\n          return -1;\n\n        /* Note that we support base:allocation whether or not the plugin\n         * supports can_extents.\n         */\n        if (!conn->structured_replies) {\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n              == -1)\n            return -1;\n          continue;\n        }\n\n        /* Minimum length of the option payload is:\n         *   32 bit export name length followed by empty export name\n         * + 32 bit number of queries followed by no queries\n         * = 8 bytes.\n         */\n        what = \"optlen < 8\";\n        if (optlen < 8) {\n        opt_meta_invalid_option_len:\n          debug (\"newstyle negotiation: %s: invalid option length: %s\",\n                 optname, what);\n\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n              == -1)\n            return -1;\n          continue;\n        }\n\n        memcpy (&exportnamelen, &data[0], 4);\n        exportnamelen = be32toh (exportnamelen);\n        what = \"validating export name\";\n        if (check_export_name (option, &data[4], exportnamelen,\n                               optlen - 8) == -1)\n          goto opt_meta_invalid_option_len;\n\n        /* Remember the export name: the NBD spec says that if the client\n         * later uses NBD_OPT_GO on a different export, then the context\n         * returned here is not usable.\n         */\n        if (option == NBD_OPT_SET_META_CONTEXT) {\n          conn->exportname_from_set_meta_context =\n            strndup (&data[4], exportnamelen);\n          if (conn->exportname_from_set_meta_context == NULL) {\n            nbdkit_error (\"malloc: %m\");\n            return -1;\n          }\n        }\n\n        opt_index = 4 + exportnamelen;\n\n        /* Read the number of queries. */\n        what = \"reading number of queries\";\n        if (opt_index+4 > optlen)\n          goto opt_meta_invalid_option_len;\n        memcpy (&nr_queries, &data[opt_index], 4);\n        nr_queries = be32toh (nr_queries);\n        opt_index += 4;\n\n        /* for LIST: nr_queries == 0 means return all meta contexts\n         * for SET: nr_queries == 0 means reset all contexts\n         */\n        debug (\"newstyle negotiation: %s: %s count: %d\", optname,\n               option == NBD_OPT_LIST_META_CONTEXT ? \"query\" : \"set\",\n               nr_queries);\n        if (option == NBD_OPT_SET_META_CONTEXT)\n          conn->meta_context_base_allocation = false;\n        if (nr_queries == 0) {\n          if (option == NBD_OPT_LIST_META_CONTEXT) {\n            if (send_newstyle_option_reply_meta_context (option,\n                                                         NBD_REP_META_CONTEXT,\n                                                         0, \"base:allocation\")\n                == -1)\n              return -1;\n          }\n\n          if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)\n            return -1;\n        }\n        else {\n          /* Read and answer each query. */\n          while (nr_queries > 0) {\n            what = \"reading query string length\";\n            if (opt_index+4 > optlen)\n              goto opt_meta_invalid_option_len;\n            memcpy (&querylen, &data[opt_index], 4);\n            querylen = be32toh (querylen);\n            opt_index += 4;\n            what = \"reading query string\";\n            if (check_string (option, &data[opt_index], querylen,\n                              optlen - opt_index, \"meta context query\") == -1)\n              goto opt_meta_invalid_option_len;\n\n            debug (\"newstyle negotiation: %s: %s %.*s\",\n                   optname,\n                   option == NBD_OPT_LIST_META_CONTEXT ? \"query\" : \"set\",\n                   (int) querylen, &data[opt_index]);\n\n            /* For LIST, \"base:\" returns all supported contexts in the\n             * base namespace.  We only support \"base:allocation\".\n             */\n            if (option == NBD_OPT_LIST_META_CONTEXT &&\n                querylen == 5 &&\n                strncmp (&data[opt_index], \"base:\", 5) == 0) {\n              if (send_newstyle_option_reply_meta_context\n                  (option, NBD_REP_META_CONTEXT,\n                   0, \"base:allocation\") == -1)\n                return -1;\n            }\n            /* \"base:allocation\" requested by name. */\n            else if (querylen == 15 &&\n                     strncmp (&data[opt_index], \"base:allocation\", 15) == 0) {\n              if (send_newstyle_option_reply_meta_context\n                  (option, NBD_REP_META_CONTEXT,\n                   option == NBD_OPT_SET_META_CONTEXT\n                   ? base_allocation_id : 0,\n                   \"base:allocation\") == -1)\n                return -1;\n              if (option == NBD_OPT_SET_META_CONTEXT)\n                conn->meta_context_base_allocation = true;\n            }\n            /* Every other query must be ignored. */\n\n            opt_index += querylen;\n            nr_queries--;\n          }\n          if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)\n            return -1;\n        }\n        debug (\"newstyle negotiation: %s: reply complete\", optname);\n      }\n      break;\n\n    default:\n      /* Unknown option. */\n      if (send_newstyle_option_reply (option, NBD_REP_ERR_UNSUP) == -1)\n        return -1;\n      if (conn_recv_full (data, optlen,\n                          \"reading unknown option data: conn->recv: %m\") == -1)\n        return -1;\n    }\n\n    /* Note, since it's not very clear from the protocol doc, that the\n     * client must send NBD_OPT_EXPORT_NAME or NBD_OPT_GO last, and\n     * that ends option negotiation.\n     */\n    if (option == NBD_OPT_EXPORT_NAME || option == NBD_OPT_GO)\n      break;\n  }\n\n  if (nr_options == 0) {\n    nbdkit_error (\"client spent too much time negotiating without selecting \"\n                  \"an export\");\n    return -1;\n  }\n\n  /* In --tls=require / FORCEDTLS mode, we must have upgraded to TLS\n   * by the time we finish option negotiation.  If not, give up.\n   */\n  if (tls == 2 && !conn->using_tls) {\n    nbdkit_error (\"non-TLS client tried to connect in --tls=require mode\");\n    return -1;\n  }\n\n  return 0;\n}", "func_hash": 230092713719482299459555478858076762309, "file_name": "protocol-handshake-newstyle.c", "file_hash": 263209595426945567952192628081217546469, "cwe": ["CWE-924"], "cve": "CVE-2021-3716", "cve_desc": "A flaw was found in nbdkit due to to improperly caching plaintext state across the STARTTLS encryption boundary. A MitM attacker could use this flaw to inject a plaintext NBD_OPT_STRUCTURED_REPLY before proxying everything else a client sends to the server, potentially leading the client to terminate the NBD session. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3716"}
{"idx": 384677, "project": "nbdkit", "commit_id": "6c5faac6a37077cf2366388a80862bb00616d0d8", "project_url": "https://github.com/libguestfs/nbdkit", "commit_url": "https://gitlab.com/nbdkit/nbdkit/-/commit/6c5faac6a37077cf2366388a80862bb00616d0d8", "commit_message": "server: reset meta context replies on starttls\n\nRelated to CVE-2021-3716, but not as severe.  No compliant client will\nsend NBD_CMD_BLOCK_STATUS unless it first negotiates\nNBD_OPT_SET_META_CONTEXT.  If an attacker injects a premature\nSET_META_CONTEXT, either the client will never notice (because it\nnever uses BLOCK_STATUS), or the client will overwrite the attacker's\nattempt with the client's own SET_META_CONTEXT request after\nencryption is enabled.  So I don't class this as having the potential\nto trigger denial-of-service due to any protocol mismatch between\ncompliant client and server (I don't care what happens with\nnon-compliant clients).\n\nFixes: 26455d45 (server: protocol: Implement Block Status \"base:allocation\".)", "target": 0, "func": "negotiate_handshake_newstyle_options (void)\n{\n  GET_CONN;\n  struct nbd_new_option new_option;\n  size_t nr_options;\n  bool list_seen = false;\n  uint64_t version;\n  uint32_t option;\n  uint32_t optlen;\n  struct nbd_export_name_option_reply handshake_finish;\n  const char *optname;\n  uint64_t exportsize;\n  struct backend *b;\n\n  for (nr_options = MAX_NR_OPTIONS; nr_options > 0; --nr_options) {\n    CLEANUP_FREE char *data = NULL;\n\n    if (conn_recv_full (&new_option, sizeof new_option,\n                        \"reading option: conn->recv: %m\") == -1)\n      return -1;\n\n    version = be64toh (new_option.version);\n    if (version != NBD_NEW_VERSION) {\n      nbdkit_error (\"unknown option version %\" PRIx64\n                    \", expecting %\" PRIx64,\n                    version, NBD_NEW_VERSION);\n      return -1;\n    }\n\n    /* There is a maximum option length we will accept, regardless\n     * of the option type.\n     */\n    optlen = be32toh (new_option.optlen);\n    if (optlen > MAX_REQUEST_SIZE) {\n      nbdkit_error (\"client option data too long (%\" PRIu32 \")\", optlen);\n      return -1;\n    }\n    data = malloc (optlen + 1); /* Allowing a trailing NUL helps some uses */\n    if (data == NULL) {\n      nbdkit_error (\"malloc: %m\");\n      return -1;\n    }\n\n    option = be32toh (new_option.option);\n    optname = name_of_nbd_opt (option);\n\n    /* If the client lacks fixed newstyle support, it should only send\n     * NBD_OPT_EXPORT_NAME.\n     */\n    if (!(conn->cflags & NBD_FLAG_FIXED_NEWSTYLE) &&\n        option != NBD_OPT_EXPORT_NAME) {\n      if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID))\n        return -1;\n      continue;\n    }\n\n    /* In --tls=require / FORCEDTLS mode the only options allowed\n     * before TLS negotiation are NBD_OPT_ABORT and NBD_OPT_STARTTLS.\n     */\n    if (tls == 2 && !conn->using_tls &&\n        !(option == NBD_OPT_ABORT || option == NBD_OPT_STARTTLS)) {\n      if (send_newstyle_option_reply (option, NBD_REP_ERR_TLS_REQD))\n        return -1;\n      continue;\n    }\n\n    switch (option) {\n    case NBD_OPT_EXPORT_NAME:\n      if (conn_recv_full (data, optlen,\n                          \"read: %s: %m\", name_of_nbd_opt (option)) == -1)\n        return -1;\n      if (check_export_name (option, data, optlen, optlen) == -1)\n        return -1;\n\n      /* We have to finish the handshake by sending handshake_finish.\n       * On failure, we have to disconnect.\n       */\n      if (finish_newstyle_options (&exportsize, data, optlen) == -1)\n        return -1;\n\n      memset (&handshake_finish, 0, sizeof handshake_finish);\n      handshake_finish.exportsize = htobe64 (exportsize);\n      handshake_finish.eflags = htobe16 (conn->eflags);\n\n      if (conn->send (&handshake_finish,\n                      (conn->cflags & NBD_FLAG_NO_ZEROES)\n                      ? offsetof (struct nbd_export_name_option_reply, zeroes)\n                      : sizeof handshake_finish, 0) == -1) {\n        nbdkit_error (\"write: %s: %m\", optname);\n        return -1;\n      }\n      break;\n\n    case NBD_OPT_ABORT:\n      if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)\n        return -1;\n      debug (\"client sent %s to abort the connection\",\n             name_of_nbd_opt (option));\n      return -1;\n\n    case NBD_OPT_LIST:\n      if (optlen != 0) {\n        if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n            == -1)\n          return -1;\n        if (conn_recv_full (data, optlen,\n                            \"read: %s: %m\", name_of_nbd_opt (option)) == -1)\n          return -1;\n        continue;\n      }\n\n      if (list_seen) {\n        debug (\"newstyle negotiation: %s: export list already advertised\",\n               name_of_nbd_opt (option));\n        if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID) == -1)\n          return -1;\n        continue;\n      }\n      else {\n        /* Send back the exportname list. */\n        debug (\"newstyle negotiation: %s: advertising exports\",\n               name_of_nbd_opt (option));\n        if (send_newstyle_option_reply_exportnames (option, &nr_options) == -1)\n          return -1;\n        list_seen = true;\n      }\n      break;\n\n    case NBD_OPT_STARTTLS:\n      if (optlen != 0) {\n        if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n            == -1)\n          return -1;\n        if (conn_recv_full (data, optlen,\n                            \"read: %s: %m\", name_of_nbd_opt (option)) == -1)\n          return -1;\n        continue;\n      }\n\n      if (tls == 0) {           /* --tls=off (NOTLS mode). */\n#ifdef HAVE_GNUTLS\n#define NO_TLS_REPLY NBD_REP_ERR_POLICY\n#else\n#define NO_TLS_REPLY NBD_REP_ERR_UNSUP\n#endif\n        if (send_newstyle_option_reply (option, NO_TLS_REPLY) == -1)\n          return -1;\n      }\n      else /* --tls=on or --tls=require */ {\n        /* We can't upgrade to TLS twice on the same connection. */\n        if (conn->using_tls) {\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID) == -1)\n            return -1;\n          continue;\n        }\n\n        /* We have to send the (unencrypted) reply before starting\n         * the handshake.\n         */\n        if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)\n          return -1;\n\n        /* Upgrade the connection to TLS.  Also performs access control. */\n        if (crypto_negotiate_tls (conn->sockin, conn->sockout) == -1)\n          return -1;\n        conn->using_tls = true;\n        debug (\"using TLS on this connection\");\n        /* Wipe out any cached state. */\n        conn->structured_replies = false;\n        free (conn->exportname_from_set_meta_context);\n        conn->exportname_from_set_meta_context = NULL;\n        conn->meta_context_base_allocation = false;\n        for_each_backend (b) {\n          free (conn->default_exportname[b->i]);\n          conn->default_exportname[b->i] = NULL;\n        }\n      }\n      break;\n\n    case NBD_OPT_INFO:\n    case NBD_OPT_GO:\n      if (conn_recv_full (data, optlen, \"read: %s: %m\", optname) == -1)\n        return -1;\n\n      if (optlen < 6) { /* 32 bit export length + 16 bit nr info */\n        debug (\"newstyle negotiation: %s option length < 6\", optname);\n\n        if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n            == -1)\n          return -1;\n        continue;\n      }\n\n      {\n        uint32_t exportnamelen;\n        uint16_t nrinfos;\n        uint16_t info;\n        size_t i;\n\n        /* Validate the name length and number of INFO requests. */\n        memcpy (&exportnamelen, &data[0], 4);\n        exportnamelen = be32toh (exportnamelen);\n        if (exportnamelen > optlen-6 /* NB optlen >= 6, see above */) {\n          debug (\"newstyle negotiation: %s: export name too long\", optname);\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n              == -1)\n            return -1;\n          continue;\n        }\n        memcpy (&nrinfos, &data[exportnamelen+4], 2);\n        nrinfos = be16toh (nrinfos);\n        if (optlen != 4 + exportnamelen + 2 + 2*nrinfos) {\n          debug (\"newstyle negotiation: %s: \"\n                 \"number of information requests incorrect\", optname);\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n              == -1)\n            return -1;\n          continue;\n        }\n\n        /* As with NBD_OPT_EXPORT_NAME we print the export name and\n         * save it in the connection.  If an earlier\n         * NBD_OPT_SET_META_CONTEXT used an export name, it must match\n         * or else we drop the support for that context.\n         */\n        if (check_export_name (option, &data[4], exportnamelen,\n                               optlen - 6) == -1) {\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n              == -1)\n            return -1;\n          continue;\n        }\n\n        /* The spec is confusing, but it is required that we send back\n         * NBD_INFO_EXPORT, even if the client did not request it!\n         * qemu client in particular does not request this, but will\n         * fail if we don't send it.  Note that if .open fails, but we\n         * succeed at .close, then we merely return an error to the\n         * client and let them try another NBD_OPT, rather than\n         * disconnecting.\n         */\n        if (finish_newstyle_options (&exportsize,\n                                     &data[4], exportnamelen) == -1) {\n          if (conn->top_context) {\n            if (backend_finalize (conn->top_context) == -1)\n              return -1;\n            backend_close (conn->top_context);\n            conn->top_context = NULL;\n          }\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_UNKNOWN) == -1)\n            return -1;\n          continue;\n        }\n\n        if (send_newstyle_option_reply_info_export (option,\n                                                    NBD_REP_INFO,\n                                                    NBD_INFO_EXPORT,\n                                                    exportsize) == -1)\n          return -1;\n\n        /* For now we send NBD_INFO_NAME and NBD_INFO_DESCRIPTION if\n         * requested, and ignore all other info requests (including\n         * NBD_INFO_EXPORT if it was requested, because we replied\n         * already above).\n         */\n        for (i = 0; i < nrinfos; ++i) {\n          memcpy (&info, &data[4 + exportnamelen + 2 + i*2], 2);\n          info = be16toh (info);\n          switch (info) {\n          case NBD_INFO_EXPORT: /* ignore - reply sent above */ break;\n          case NBD_INFO_NAME:\n            {\n              const char *name = &data[4];\n              size_t namelen = exportnamelen;\n\n              if (exportnamelen == 0) {\n                name = backend_default_export (top, read_only);\n                if (!name) {\n                  debug (\"newstyle negotiation: %s: \"\n                         \"NBD_INFO_NAME: no name to send\", optname);\n                  break;\n                }\n                namelen = -1;\n              }\n              if (send_newstyle_option_reply_info_str (option,\n                                                       NBD_REP_INFO,\n                                                       NBD_INFO_NAME,\n                                                       name, namelen) == -1)\n                return -1;\n            }\n            break;\n          case NBD_INFO_DESCRIPTION:\n            {\n              const char *desc = backend_export_description (conn->top_context);\n\n              if (!desc) {\n                debug (\"newstyle negotiation: %s: \"\n                       \"NBD_INFO_DESCRIPTION: no description to send\",\n                       optname);\n                break;\n              }\n              if (send_newstyle_option_reply_info_str (option,\n                                                       NBD_REP_INFO,\n                                                       NBD_INFO_DESCRIPTION,\n                                                       desc, -1) == -1)\n                return -1;\n            }\n            break;\n          default:\n            debug (\"newstyle negotiation: %s: \"\n                   \"ignoring NBD_INFO_* request %u (%s)\",\n                   optname, (unsigned) info, name_of_nbd_info (info));\n            break;\n          }\n        }\n      }\n\n      /* Unlike NBD_OPT_EXPORT_NAME, NBD_OPT_GO sends back an ACK\n       * or ERROR packet.  If this was NBD_OPT_LIST, call .close.\n       */\n      if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)\n        return -1;\n\n      if (option == NBD_OPT_INFO) {\n        if (backend_finalize (conn->top_context) == -1)\n          return -1;\n        backend_close (conn->top_context);\n        conn->top_context = NULL;\n      }\n\n      break;\n\n    case NBD_OPT_STRUCTURED_REPLY:\n      if (optlen != 0) {\n        if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n            == -1)\n          return -1;\n        if (conn_recv_full (data, optlen,\n                            \"read: %s: %m\", name_of_nbd_opt (option)) == -1)\n          return -1;\n        continue;\n      }\n\n      debug (\"newstyle negotiation: %s: client requested structured replies\",\n             name_of_nbd_opt (option));\n\n      if (no_sr) {\n        /* Must fail with ERR_UNSUP for qemu 4.2 to remain happy;\n         * but failing with ERR_POLICY would have been nicer.\n         */\n        if (send_newstyle_option_reply (option, NBD_REP_ERR_UNSUP) == -1)\n          return -1;\n        debug (\"newstyle negotiation: %s: structured replies are disabled\",\n               name_of_nbd_opt (option));\n        break;\n      }\n\n      if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)\n        return -1;\n\n      conn->structured_replies = true;\n      break;\n\n    case NBD_OPT_LIST_META_CONTEXT:\n    case NBD_OPT_SET_META_CONTEXT:\n      {\n        uint32_t opt_index;\n        uint32_t exportnamelen;\n        uint32_t nr_queries;\n        uint32_t querylen;\n        const char *what;\n\n        if (conn_recv_full (data, optlen, \"read: %s: %m\", optname) == -1)\n          return -1;\n\n        /* Note that we support base:allocation whether or not the plugin\n         * supports can_extents.\n         */\n        if (!conn->structured_replies) {\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n              == -1)\n            return -1;\n          continue;\n        }\n\n        /* Minimum length of the option payload is:\n         *   32 bit export name length followed by empty export name\n         * + 32 bit number of queries followed by no queries\n         * = 8 bytes.\n         */\n        what = \"optlen < 8\";\n        if (optlen < 8) {\n        opt_meta_invalid_option_len:\n          debug (\"newstyle negotiation: %s: invalid option length: %s\",\n                 optname, what);\n\n          if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)\n              == -1)\n            return -1;\n          continue;\n        }\n\n        memcpy (&exportnamelen, &data[0], 4);\n        exportnamelen = be32toh (exportnamelen);\n        what = \"validating export name\";\n        if (check_export_name (option, &data[4], exportnamelen,\n                               optlen - 8) == -1)\n          goto opt_meta_invalid_option_len;\n\n        /* Remember the export name: the NBD spec says that if the client\n         * later uses NBD_OPT_GO on a different export, then the context\n         * returned here is not usable.\n         */\n        if (option == NBD_OPT_SET_META_CONTEXT) {\n          conn->exportname_from_set_meta_context =\n            strndup (&data[4], exportnamelen);\n          if (conn->exportname_from_set_meta_context == NULL) {\n            nbdkit_error (\"malloc: %m\");\n            return -1;\n          }\n        }\n\n        opt_index = 4 + exportnamelen;\n\n        /* Read the number of queries. */\n        what = \"reading number of queries\";\n        if (opt_index+4 > optlen)\n          goto opt_meta_invalid_option_len;\n        memcpy (&nr_queries, &data[opt_index], 4);\n        nr_queries = be32toh (nr_queries);\n        opt_index += 4;\n\n        /* for LIST: nr_queries == 0 means return all meta contexts\n         * for SET: nr_queries == 0 means reset all contexts\n         */\n        debug (\"newstyle negotiation: %s: %s count: %d\", optname,\n               option == NBD_OPT_LIST_META_CONTEXT ? \"query\" : \"set\",\n               nr_queries);\n        if (option == NBD_OPT_SET_META_CONTEXT)\n          conn->meta_context_base_allocation = false;\n        if (nr_queries == 0) {\n          if (option == NBD_OPT_LIST_META_CONTEXT) {\n            if (send_newstyle_option_reply_meta_context (option,\n                                                         NBD_REP_META_CONTEXT,\n                                                         0, \"base:allocation\")\n                == -1)\n              return -1;\n          }\n\n          if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)\n            return -1;\n        }\n        else {\n          /* Read and answer each query. */\n          while (nr_queries > 0) {\n            what = \"reading query string length\";\n            if (opt_index+4 > optlen)\n              goto opt_meta_invalid_option_len;\n            memcpy (&querylen, &data[opt_index], 4);\n            querylen = be32toh (querylen);\n            opt_index += 4;\n            what = \"reading query string\";\n            if (check_string (option, &data[opt_index], querylen,\n                              optlen - opt_index, \"meta context query\") == -1)\n              goto opt_meta_invalid_option_len;\n\n            debug (\"newstyle negotiation: %s: %s %.*s\",\n                   optname,\n                   option == NBD_OPT_LIST_META_CONTEXT ? \"query\" : \"set\",\n                   (int) querylen, &data[opt_index]);\n\n            /* For LIST, \"base:\" returns all supported contexts in the\n             * base namespace.  We only support \"base:allocation\".\n             */\n            if (option == NBD_OPT_LIST_META_CONTEXT &&\n                querylen == 5 &&\n                strncmp (&data[opt_index], \"base:\", 5) == 0) {\n              if (send_newstyle_option_reply_meta_context\n                  (option, NBD_REP_META_CONTEXT,\n                   0, \"base:allocation\") == -1)\n                return -1;\n            }\n            /* \"base:allocation\" requested by name. */\n            else if (querylen == 15 &&\n                     strncmp (&data[opt_index], \"base:allocation\", 15) == 0) {\n              if (send_newstyle_option_reply_meta_context\n                  (option, NBD_REP_META_CONTEXT,\n                   option == NBD_OPT_SET_META_CONTEXT\n                   ? base_allocation_id : 0,\n                   \"base:allocation\") == -1)\n                return -1;\n              if (option == NBD_OPT_SET_META_CONTEXT)\n                conn->meta_context_base_allocation = true;\n            }\n            /* Every other query must be ignored. */\n\n            opt_index += querylen;\n            nr_queries--;\n          }\n          if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)\n            return -1;\n        }\n        debug (\"newstyle negotiation: %s: reply complete\", optname);\n      }\n      break;\n\n    default:\n      /* Unknown option. */\n      if (send_newstyle_option_reply (option, NBD_REP_ERR_UNSUP) == -1)\n        return -1;\n      if (conn_recv_full (data, optlen,\n                          \"reading unknown option data: conn->recv: %m\") == -1)\n        return -1;\n    }\n\n    /* Note, since it's not very clear from the protocol doc, that the\n     * client must send NBD_OPT_EXPORT_NAME or NBD_OPT_GO last, and\n     * that ends option negotiation.\n     */\n    if (option == NBD_OPT_EXPORT_NAME || option == NBD_OPT_GO)\n      break;\n  }\n\n  if (nr_options == 0) {\n    nbdkit_error (\"client spent too much time negotiating without selecting \"\n                  \"an export\");\n    return -1;\n  }\n\n  /* In --tls=require / FORCEDTLS mode, we must have upgraded to TLS\n   * by the time we finish option negotiation.  If not, give up.\n   */\n  if (tls == 2 && !conn->using_tls) {\n    nbdkit_error (\"non-TLS client tried to connect in --tls=require mode\");\n    return -1;\n  }\n\n  return 0;\n}", "func_hash": 13793654971535202622888110493636437287, "file_name": "protocol-handshake-newstyle.c", "file_hash": 210643238405506282504328455056206224474, "cwe": ["CWE-924"], "cve": "CVE-2021-3716", "cve_desc": "A flaw was found in nbdkit due to to improperly caching plaintext state across the STARTTLS encryption boundary. A MitM attacker could use this flaw to inject a plaintext NBD_OPT_STRUCTURED_REPLY before proxying everything else a client sends to the server, potentially leading the client to terminate the NBD session. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3716"}
{"idx": 206676, "project": "vim", "commit_id": "777e7c21b7627be80961848ac560cb0a9978ff43", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/777e7c21b7627be80961848ac560cb0a9978ff43", "commit_message": "patch 8.2.3564: invalid memory access when scrolling without valid screen\n\nProblem:    Invalid memory access when scrolling without a valid screen.\nSolution:   Do not set VALID_BOTLINE in w_valid.", "target": 1, "func": "update_topline(void)\n{\n    long\tline_count;\n    int\t\thalfheight;\n    int\t\tn;\n    linenr_T\told_topline;\n#ifdef FEAT_DIFF\n    int\t\told_topfill;\n#endif\n#ifdef FEAT_FOLDING\n    linenr_T\tlnum;\n#endif\n    int\t\tcheck_topline = FALSE;\n    int\t\tcheck_botline = FALSE;\n    long        *so_ptr = curwin->w_p_so >= 0 ? &curwin->w_p_so : &p_so;\n    int\t\tsave_so = *so_ptr;\n\n    // If there is no valid screen and when the window height is zero just use\n    // the cursor line.\n    if (!screen_valid(TRUE) || curwin->w_height == 0)\n    {\n\tcheck_cursor_lnum();\n\tcurwin->w_topline = curwin->w_cursor.lnum;\n\tcurwin->w_botline = curwin->w_topline;\n\tcurwin->w_valid |= VALID_BOTLINE|VALID_BOTLINE_AP;\n\tcurwin->w_scbind_pos = 1;\n\treturn;\n    }\n\n    check_cursor_moved(curwin);\n    if (curwin->w_valid & VALID_TOPLINE)\n\treturn;\n\n    // When dragging with the mouse, don't scroll that quickly\n    if (mouse_dragging > 0)\n\t*so_ptr = mouse_dragging - 1;\n\n    old_topline = curwin->w_topline;\n#ifdef FEAT_DIFF\n    old_topfill = curwin->w_topfill;\n#endif\n\n    /*\n     * If the buffer is empty, always set topline to 1.\n     */\n    if (BUFEMPTY())\t\t// special case - file is empty\n    {\n\tif (curwin->w_topline != 1)\n\t    redraw_later(NOT_VALID);\n\tcurwin->w_topline = 1;\n\tcurwin->w_botline = 2;\n\tcurwin->w_valid |= VALID_BOTLINE|VALID_BOTLINE_AP;\n\tcurwin->w_scbind_pos = 1;\n    }\n\n    /*\n     * If the cursor is above or near the top of the window, scroll the window\n     * to show the line the cursor is in, with 'scrolloff' context.\n     */\n    else\n    {\n\tif (curwin->w_topline > 1)\n\t{\n\t    // If the cursor is above topline, scrolling is always needed.\n\t    // If the cursor is far below topline and there is no folding,\n\t    // scrolling down is never needed.\n\t    if (curwin->w_cursor.lnum < curwin->w_topline)\n\t\tcheck_topline = TRUE;\n\t    else if (check_top_offset())\n\t\tcheck_topline = TRUE;\n\t}\n#ifdef FEAT_DIFF\n\t    // Check if there are more filler lines than allowed.\n\tif (!check_topline && curwin->w_topfill > diff_check_fill(curwin,\n\t\t\t\t\t\t\t   curwin->w_topline))\n\t    check_topline = TRUE;\n#endif\n\n\tif (check_topline)\n\t{\n\t    halfheight = curwin->w_height / 2 - 1;\n\t    if (halfheight < 2)\n\t\thalfheight = 2;\n\n#ifdef FEAT_FOLDING\n\t    if (hasAnyFolding(curwin))\n\t    {\n\t\t// Count the number of logical lines between the cursor and\n\t\t// topline + scrolloff (approximation of how much will be\n\t\t// scrolled).\n\t\tn = 0;\n\t\tfor (lnum = curwin->w_cursor.lnum;\n\t\t\t\t    lnum < curwin->w_topline + *so_ptr; ++lnum)\n\t\t{\n\t\t    ++n;\n\t\t    // stop at end of file or when we know we are far off\n\t\t    if (lnum >= curbuf->b_ml.ml_line_count || n >= halfheight)\n\t\t\tbreak;\n\t\t    (void)hasFolding(lnum, NULL, &lnum);\n\t\t}\n\t    }\n\t    else\n#endif\n\t\tn = curwin->w_topline + *so_ptr - curwin->w_cursor.lnum;\n\n\t    // If we weren't very close to begin with, we scroll to put the\n\t    // cursor in the middle of the window.  Otherwise put the cursor\n\t    // near the top of the window.\n\t    if (n >= halfheight)\n\t\tscroll_cursor_halfway(FALSE);\n\t    else\n\t    {\n\t\tscroll_cursor_top(scrolljump_value(), FALSE);\n\t\tcheck_botline = TRUE;\n\t    }\n\t}\n\n\telse\n\t{\n#ifdef FEAT_FOLDING\n\t    // Make sure topline is the first line of a fold.\n\t    (void)hasFolding(curwin->w_topline, &curwin->w_topline, NULL);\n#endif\n\t    check_botline = TRUE;\n\t}\n    }\n\n    /*\n     * If the cursor is below the bottom of the window, scroll the window\n     * to put the cursor on the window.\n     * When w_botline is invalid, recompute it first, to avoid a redraw later.\n     * If w_botline was approximated, we might need a redraw later in a few\n     * cases, but we don't want to spend (a lot of) time recomputing w_botline\n     * for every small change.\n     */\n    if (check_botline)\n    {\n\tif (!(curwin->w_valid & VALID_BOTLINE_AP))\n\t    validate_botline();\n\n\tif (curwin->w_botline <= curbuf->b_ml.ml_line_count)\n\t{\n\t    if (curwin->w_cursor.lnum < curwin->w_botline)\n\t    {\n\t      if (((long)curwin->w_cursor.lnum\n\t\t\t\t\t     >= (long)curwin->w_botline - *so_ptr\n#ifdef FEAT_FOLDING\n\t\t\t|| hasAnyFolding(curwin)\n#endif\n\t\t\t))\n\t      {\n\t\tlineoff_T\tloff;\n\n\t\t// Cursor is (a few lines) above botline, check if there are\n\t\t// 'scrolloff' window lines below the cursor.  If not, need to\n\t\t// scroll.\n\t\tn = curwin->w_empty_rows;\n\t\tloff.lnum = curwin->w_cursor.lnum;\n#ifdef FEAT_FOLDING\n\t\t// In a fold go to its last line.\n\t\t(void)hasFolding(loff.lnum, NULL, &loff.lnum);\n#endif\n#ifdef FEAT_DIFF\n\t\tloff.fill = 0;\n\t\tn += curwin->w_filler_rows;\n#endif\n\t\tloff.height = 0;\n\t\twhile (loff.lnum < curwin->w_botline\n#ifdef FEAT_DIFF\n\t\t\t&& (loff.lnum + 1 < curwin->w_botline || loff.fill == 0)\n#endif\n\t\t\t)\n\t\t{\n\t\t    n += loff.height;\n\t\t    if (n >= *so_ptr)\n\t\t\tbreak;\n\t\t    botline_forw(&loff);\n\t\t}\n\t\tif (n >= *so_ptr)\n\t\t    // sufficient context, no need to scroll\n\t\t    check_botline = FALSE;\n\t      }\n\t      else\n\t\t  // sufficient context, no need to scroll\n\t\t  check_botline = FALSE;\n\t    }\n\t    if (check_botline)\n\t    {\n#ifdef FEAT_FOLDING\n\t\tif (hasAnyFolding(curwin))\n\t\t{\n\t\t    // Count the number of logical lines between the cursor and\n\t\t    // botline - scrolloff (approximation of how much will be\n\t\t    // scrolled).\n\t\t    line_count = 0;\n\t\t    for (lnum = curwin->w_cursor.lnum;\n\t\t\t\t   lnum >= curwin->w_botline - *so_ptr; --lnum)\n\t\t    {\n\t\t\t++line_count;\n\t\t\t// stop at end of file or when we know we are far off\n\t\t\tif (lnum <= 0 || line_count > curwin->w_height + 1)\n\t\t\t    break;\n\t\t\t(void)hasFolding(lnum, &lnum, NULL);\n\t\t    }\n\t\t}\n\t\telse\n#endif\n\t\t    line_count = curwin->w_cursor.lnum - curwin->w_botline\n\t\t\t\t\t\t\t\t   + 1 + *so_ptr;\n\t\tif (line_count <= curwin->w_height + 1)\n\t\t    scroll_cursor_bot(scrolljump_value(), FALSE);\n\t\telse\n\t\t    scroll_cursor_halfway(FALSE);\n\t    }\n\t}\n    }\n    curwin->w_valid |= VALID_TOPLINE;\n\n    /*\n     * Need to redraw when topline changed.\n     */\n    if (curwin->w_topline != old_topline\n#ifdef FEAT_DIFF\n\t    || curwin->w_topfill != old_topfill\n#endif\n\t    )\n    {\n\tdollar_vcol = -1;\n\tif (curwin->w_skipcol != 0)\n\t{\n\t    curwin->w_skipcol = 0;\n\t    redraw_later(NOT_VALID);\n\t}\n\telse\n\t    redraw_later(VALID);\n\t// May need to set w_skipcol when cursor in w_topline.\n\tif (curwin->w_cursor.lnum == curwin->w_topline)\n\t    validate_cursor();\n    }\n\n    *so_ptr = save_so;\n}", "func_hash": 228543629723963000813717359055705778977, "file_name": "move.c", "file_hash": 235877722919937919149866597040080656666, "cwe": ["CWE-122"], "cve": "CVE-2021-3903", "cve_desc": "vim is vulnerable to Heap-based Buffer Overflow", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3903"}
{"idx": 384767, "project": "vim", "commit_id": "777e7c21b7627be80961848ac560cb0a9978ff43", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/777e7c21b7627be80961848ac560cb0a9978ff43", "commit_message": "patch 8.2.3564: invalid memory access when scrolling without valid screen\n\nProblem:    Invalid memory access when scrolling without a valid screen.\nSolution:   Do not set VALID_BOTLINE in w_valid.", "target": 0, "func": "update_topline(void)\n{\n    long\tline_count;\n    int\t\thalfheight;\n    int\t\tn;\n    linenr_T\told_topline;\n#ifdef FEAT_DIFF\n    int\t\told_topfill;\n#endif\n#ifdef FEAT_FOLDING\n    linenr_T\tlnum;\n#endif\n    int\t\tcheck_topline = FALSE;\n    int\t\tcheck_botline = FALSE;\n    long        *so_ptr = curwin->w_p_so >= 0 ? &curwin->w_p_so : &p_so;\n    int\t\tsave_so = *so_ptr;\n\n    // If there is no valid screen and when the window height is zero just use\n    // the cursor line.\n    if (!screen_valid(TRUE) || curwin->w_height == 0)\n    {\n\tcheck_cursor_lnum();\n\tcurwin->w_topline = curwin->w_cursor.lnum;\n\tcurwin->w_botline = curwin->w_topline;\n\tcurwin->w_scbind_pos = 1;\n\treturn;\n    }\n\n    check_cursor_moved(curwin);\n    if (curwin->w_valid & VALID_TOPLINE)\n\treturn;\n\n    // When dragging with the mouse, don't scroll that quickly\n    if (mouse_dragging > 0)\n\t*so_ptr = mouse_dragging - 1;\n\n    old_topline = curwin->w_topline;\n#ifdef FEAT_DIFF\n    old_topfill = curwin->w_topfill;\n#endif\n\n    /*\n     * If the buffer is empty, always set topline to 1.\n     */\n    if (BUFEMPTY())\t\t// special case - file is empty\n    {\n\tif (curwin->w_topline != 1)\n\t    redraw_later(NOT_VALID);\n\tcurwin->w_topline = 1;\n\tcurwin->w_botline = 2;\n\tcurwin->w_valid |= VALID_BOTLINE|VALID_BOTLINE_AP;\n\tcurwin->w_scbind_pos = 1;\n    }\n\n    /*\n     * If the cursor is above or near the top of the window, scroll the window\n     * to show the line the cursor is in, with 'scrolloff' context.\n     */\n    else\n    {\n\tif (curwin->w_topline > 1)\n\t{\n\t    // If the cursor is above topline, scrolling is always needed.\n\t    // If the cursor is far below topline and there is no folding,\n\t    // scrolling down is never needed.\n\t    if (curwin->w_cursor.lnum < curwin->w_topline)\n\t\tcheck_topline = TRUE;\n\t    else if (check_top_offset())\n\t\tcheck_topline = TRUE;\n\t}\n#ifdef FEAT_DIFF\n\t    // Check if there are more filler lines than allowed.\n\tif (!check_topline && curwin->w_topfill > diff_check_fill(curwin,\n\t\t\t\t\t\t\t   curwin->w_topline))\n\t    check_topline = TRUE;\n#endif\n\n\tif (check_topline)\n\t{\n\t    halfheight = curwin->w_height / 2 - 1;\n\t    if (halfheight < 2)\n\t\thalfheight = 2;\n\n#ifdef FEAT_FOLDING\n\t    if (hasAnyFolding(curwin))\n\t    {\n\t\t// Count the number of logical lines between the cursor and\n\t\t// topline + scrolloff (approximation of how much will be\n\t\t// scrolled).\n\t\tn = 0;\n\t\tfor (lnum = curwin->w_cursor.lnum;\n\t\t\t\t    lnum < curwin->w_topline + *so_ptr; ++lnum)\n\t\t{\n\t\t    ++n;\n\t\t    // stop at end of file or when we know we are far off\n\t\t    if (lnum >= curbuf->b_ml.ml_line_count || n >= halfheight)\n\t\t\tbreak;\n\t\t    (void)hasFolding(lnum, NULL, &lnum);\n\t\t}\n\t    }\n\t    else\n#endif\n\t\tn = curwin->w_topline + *so_ptr - curwin->w_cursor.lnum;\n\n\t    // If we weren't very close to begin with, we scroll to put the\n\t    // cursor in the middle of the window.  Otherwise put the cursor\n\t    // near the top of the window.\n\t    if (n >= halfheight)\n\t\tscroll_cursor_halfway(FALSE);\n\t    else\n\t    {\n\t\tscroll_cursor_top(scrolljump_value(), FALSE);\n\t\tcheck_botline = TRUE;\n\t    }\n\t}\n\n\telse\n\t{\n#ifdef FEAT_FOLDING\n\t    // Make sure topline is the first line of a fold.\n\t    (void)hasFolding(curwin->w_topline, &curwin->w_topline, NULL);\n#endif\n\t    check_botline = TRUE;\n\t}\n    }\n\n    /*\n     * If the cursor is below the bottom of the window, scroll the window\n     * to put the cursor on the window.\n     * When w_botline is invalid, recompute it first, to avoid a redraw later.\n     * If w_botline was approximated, we might need a redraw later in a few\n     * cases, but we don't want to spend (a lot of) time recomputing w_botline\n     * for every small change.\n     */\n    if (check_botline)\n    {\n\tif (!(curwin->w_valid & VALID_BOTLINE_AP))\n\t    validate_botline();\n\n\tif (curwin->w_botline <= curbuf->b_ml.ml_line_count)\n\t{\n\t    if (curwin->w_cursor.lnum < curwin->w_botline)\n\t    {\n\t      if (((long)curwin->w_cursor.lnum\n\t\t\t\t\t     >= (long)curwin->w_botline - *so_ptr\n#ifdef FEAT_FOLDING\n\t\t\t|| hasAnyFolding(curwin)\n#endif\n\t\t\t))\n\t      {\n\t\tlineoff_T\tloff;\n\n\t\t// Cursor is (a few lines) above botline, check if there are\n\t\t// 'scrolloff' window lines below the cursor.  If not, need to\n\t\t// scroll.\n\t\tn = curwin->w_empty_rows;\n\t\tloff.lnum = curwin->w_cursor.lnum;\n#ifdef FEAT_FOLDING\n\t\t// In a fold go to its last line.\n\t\t(void)hasFolding(loff.lnum, NULL, &loff.lnum);\n#endif\n#ifdef FEAT_DIFF\n\t\tloff.fill = 0;\n\t\tn += curwin->w_filler_rows;\n#endif\n\t\tloff.height = 0;\n\t\twhile (loff.lnum < curwin->w_botline\n#ifdef FEAT_DIFF\n\t\t\t&& (loff.lnum + 1 < curwin->w_botline || loff.fill == 0)\n#endif\n\t\t\t)\n\t\t{\n\t\t    n += loff.height;\n\t\t    if (n >= *so_ptr)\n\t\t\tbreak;\n\t\t    botline_forw(&loff);\n\t\t}\n\t\tif (n >= *so_ptr)\n\t\t    // sufficient context, no need to scroll\n\t\t    check_botline = FALSE;\n\t      }\n\t      else\n\t\t  // sufficient context, no need to scroll\n\t\t  check_botline = FALSE;\n\t    }\n\t    if (check_botline)\n\t    {\n#ifdef FEAT_FOLDING\n\t\tif (hasAnyFolding(curwin))\n\t\t{\n\t\t    // Count the number of logical lines between the cursor and\n\t\t    // botline - scrolloff (approximation of how much will be\n\t\t    // scrolled).\n\t\t    line_count = 0;\n\t\t    for (lnum = curwin->w_cursor.lnum;\n\t\t\t\t   lnum >= curwin->w_botline - *so_ptr; --lnum)\n\t\t    {\n\t\t\t++line_count;\n\t\t\t// stop at end of file or when we know we are far off\n\t\t\tif (lnum <= 0 || line_count > curwin->w_height + 1)\n\t\t\t    break;\n\t\t\t(void)hasFolding(lnum, &lnum, NULL);\n\t\t    }\n\t\t}\n\t\telse\n#endif\n\t\t    line_count = curwin->w_cursor.lnum - curwin->w_botline\n\t\t\t\t\t\t\t\t   + 1 + *so_ptr;\n\t\tif (line_count <= curwin->w_height + 1)\n\t\t    scroll_cursor_bot(scrolljump_value(), FALSE);\n\t\telse\n\t\t    scroll_cursor_halfway(FALSE);\n\t    }\n\t}\n    }\n    curwin->w_valid |= VALID_TOPLINE;\n\n    /*\n     * Need to redraw when topline changed.\n     */\n    if (curwin->w_topline != old_topline\n#ifdef FEAT_DIFF\n\t    || curwin->w_topfill != old_topfill\n#endif\n\t    )\n    {\n\tdollar_vcol = -1;\n\tif (curwin->w_skipcol != 0)\n\t{\n\t    curwin->w_skipcol = 0;\n\t    redraw_later(NOT_VALID);\n\t}\n\telse\n\t    redraw_later(VALID);\n\t// May need to set w_skipcol when cursor in w_topline.\n\tif (curwin->w_cursor.lnum == curwin->w_topline)\n\t    validate_cursor();\n    }\n\n    *so_ptr = save_so;\n}", "func_hash": 318695242827135485367008238388311307871, "file_name": "move.c", "file_hash": 216110417083492209479100354226379064539, "cwe": ["CWE-122"], "cve": "CVE-2021-3903", "cve_desc": "vim is vulnerable to Heap-based Buffer Overflow", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3903"}
{"idx": 206677, "project": "vim", "commit_id": "5921aeb5741fc6e84c870d68c7c35b93ad0c9f87", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/5921aeb5741fc6e84c870d68c7c35b93ad0c9f87", "commit_message": "patch 8.2.4418: crash when using special multi-byte character\n\nProblem:    Crash when using special multi-byte character.\nSolution:   Don't use isalpha() for an arbitrary character.", "target": 1, "func": "unix_expandpath(\n    garray_T\t*gap,\n    char_u\t*path,\n    int\t\twildoff,\n    int\t\tflags,\t\t// EW_* flags\n    int\t\tdidstar)\t// expanded \"**\" once already\n{\n    char_u\t*buf;\n    char_u\t*path_end;\n    char_u\t*p, *s, *e;\n    int\t\tstart_len = gap->ga_len;\n    char_u\t*pat;\n    regmatch_T\tregmatch;\n    int\t\tstarts_with_dot;\n    int\t\tmatches;\n    int\t\tlen;\n    int\t\tstarstar = FALSE;\n    static int\tstardepth = 0;\t    // depth for \"**\" expansion\n\n    DIR\t\t*dirp;\n    struct dirent *dp;\n\n    // Expanding \"**\" may take a long time, check for CTRL-C.\n    if (stardepth > 0)\n    {\n\tui_breakcheck();\n\tif (got_int)\n\t    return 0;\n    }\n\n    // make room for file name\n    buf = alloc(STRLEN(path) + BASENAMELEN + 5);\n    if (buf == NULL)\n\treturn 0;\n\n    /*\n     * Find the first part in the path name that contains a wildcard.\n     * When EW_ICASE is set every letter is considered to be a wildcard.\n     * Copy it into \"buf\", including the preceding characters.\n     */\n    p = buf;\n    s = buf;\n    e = NULL;\n    path_end = path;\n    while (*path_end != NUL)\n    {\n\t// May ignore a wildcard that has a backslash before it; it will\n\t// be removed by rem_backslash() or file_pat_to_reg_pat() below.\n\tif (path_end >= path + wildoff && rem_backslash(path_end))\n\t    *p++ = *path_end++;\n\telse if (*path_end == '/')\n\t{\n\t    if (e != NULL)\n\t\tbreak;\n\t    s = p + 1;\n\t}\n\telse if (path_end >= path + wildoff\n\t\t\t && (vim_strchr((char_u *)\"*?[{~$\", *path_end) != NULL\n\t\t\t     || (!p_fic && (flags & EW_ICASE)\n\t\t\t\t\t     && isalpha(PTR2CHAR(path_end)))))\n\t    e = p;\n\tif (has_mbyte)\n\t{\n\t    len = (*mb_ptr2len)(path_end);\n\t    STRNCPY(p, path_end, len);\n\t    p += len;\n\t    path_end += len;\n\t}\n\telse\n\t    *p++ = *path_end++;\n    }\n    e = p;\n    *e = NUL;\n\n    // Now we have one wildcard component between \"s\" and \"e\".\n    // Remove backslashes between \"wildoff\" and the start of the wildcard\n    // component.\n    for (p = buf + wildoff; p < s; ++p)\n\tif (rem_backslash(p))\n\t{\n\t    STRMOVE(p, p + 1);\n\t    --e;\n\t    --s;\n\t}\n\n    // Check for \"**\" between \"s\" and \"e\".\n    for (p = s; p < e; ++p)\n\tif (p[0] == '*' && p[1] == '*')\n\t    starstar = TRUE;\n\n    // convert the file pattern to a regexp pattern\n    starts_with_dot = *s == '.';\n    pat = file_pat_to_reg_pat(s, e, NULL, FALSE);\n    if (pat == NULL)\n    {\n\tvim_free(buf);\n\treturn 0;\n    }\n\n    // compile the regexp into a program\n    if (flags & EW_ICASE)\n\tregmatch.rm_ic = TRUE;\t\t// 'wildignorecase' set\n    else\n\tregmatch.rm_ic = p_fic;\t// ignore case when 'fileignorecase' is set\n    if (flags & (EW_NOERROR | EW_NOTWILD))\n\t++emsg_silent;\n    regmatch.regprog = vim_regcomp(pat, RE_MAGIC);\n    if (flags & (EW_NOERROR | EW_NOTWILD))\n\t--emsg_silent;\n    vim_free(pat);\n\n    if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)\n    {\n\tvim_free(buf);\n\treturn 0;\n    }\n\n    // If \"**\" is by itself, this is the first time we encounter it and more\n    // is following then find matches without any directory.\n    if (!didstar && stardepth < 100 && starstar && e - s == 2\n\t\t\t\t\t\t\t  && *path_end == '/')\n    {\n\tSTRCPY(s, path_end + 1);\n\t++stardepth;\n\t(void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);\n\t--stardepth;\n    }\n\n    // open the directory for scanning\n    *s = NUL;\n    dirp = opendir(*buf == NUL ? \".\" : (char *)buf);\n\n    // Find all matching entries\n    if (dirp != NULL)\n    {\n\tfor (;;)\n\t{\n\t    dp = readdir(dirp);\n\t    if (dp == NULL)\n\t\tbreak;\n\t    if ((dp->d_name[0] != '.' || starts_with_dot\n\t\t\t|| ((flags & EW_DODOT)\n\t\t\t    && dp->d_name[1] != NUL\n\t\t\t    && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))\n\t\t && ((regmatch.regprog != NULL && vim_regexec(®match,\n\t\t\t\t\t     (char_u *)dp->d_name, (colnr_T)0))\n\t\t   || ((flags & EW_NOTWILD)\n\t\t     && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))\n\t    {\n\t\tSTRCPY(s, dp->d_name);\n\t\tlen = STRLEN(buf);\n\n\t\tif (starstar && stardepth < 100)\n\t\t{\n\t\t    // For \"**\" in the pattern first go deeper in the tree to\n\t\t    // find matches.\n\t\t    STRCPY(buf + len, \"/**\");\n\t\t    STRCPY(buf + len + 3, path_end);\n\t\t    ++stardepth;\n\t\t    (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);\n\t\t    --stardepth;\n\t\t}\n\n\t\tSTRCPY(buf + len, path_end);\n\t\tif (mch_has_exp_wildcard(path_end)) // handle more wildcards\n\t\t{\n\t\t    // need to expand another component of the path\n\t\t    // remove backslashes for the remaining components only\n\t\t    (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);\n\t\t}\n\t\telse\n\t\t{\n\t\t    stat_T  sb;\n\n\t\t    // no more wildcards, check if there is a match\n\t\t    // remove backslashes for the remaining components only\n\t\t    if (*path_end != NUL)\n\t\t\tbackslash_halve(buf + len + 1);\n\t\t    // add existing file or symbolic link\n\t\t    if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0\n\t\t\t\t\t\t      : mch_getperm(buf) >= 0)\n\t\t    {\n#ifdef MACOS_CONVERT\n\t\t\tsize_t precomp_len = STRLEN(buf)+1;\n\t\t\tchar_u *precomp_buf =\n\t\t\t    mac_precompose_path(buf, precomp_len, &precomp_len);\n\n\t\t\tif (precomp_buf)\n\t\t\t{\n\t\t\t    mch_memmove(buf, precomp_buf, precomp_len);\n\t\t\t    vim_free(precomp_buf);\n\t\t\t}\n#endif\n\t\t\taddfile(gap, buf, flags);\n\t\t    }\n\t\t}\n\t    }\n\t}\n\n\tclosedir(dirp);\n    }\n\n    vim_free(buf);\n    vim_regfree(regmatch.regprog);\n\n    matches = gap->ga_len - start_len;\n    if (matches > 0)\n\tqsort(((char_u **)gap->ga_data) + start_len, matches,\n\t\t\t\t\t\t   sizeof(char_u *), pstrcmp);\n    return matches;\n}", "func_hash": 312674114892145176500352390912517515307, "file_name": "filepath.c", "file_hash": 229066241137802797352238773426978474827, "cwe": ["CWE-703"], "cve": "CVE-2022-0685", "cve_desc": "Use of Out-of-range Pointer Offset in GitHub repository vim/vim prior to 8.2.4418.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0685"}
{"idx": 384803, "project": "vim", "commit_id": "5921aeb5741fc6e84c870d68c7c35b93ad0c9f87", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/5921aeb5741fc6e84c870d68c7c35b93ad0c9f87", "commit_message": "patch 8.2.4418: crash when using special multi-byte character\n\nProblem:    Crash when using special multi-byte character.\nSolution:   Don't use isalpha() for an arbitrary character.", "target": 0, "func": "unix_expandpath(\n    garray_T\t*gap,\n    char_u\t*path,\n    int\t\twildoff,\n    int\t\tflags,\t\t// EW_* flags\n    int\t\tdidstar)\t// expanded \"**\" once already\n{\n    char_u\t*buf;\n    char_u\t*path_end;\n    char_u\t*p, *s, *e;\n    int\t\tstart_len = gap->ga_len;\n    char_u\t*pat;\n    regmatch_T\tregmatch;\n    int\t\tstarts_with_dot;\n    int\t\tmatches;\n    int\t\tlen;\n    int\t\tstarstar = FALSE;\n    static int\tstardepth = 0;\t    // depth for \"**\" expansion\n\n    DIR\t\t*dirp;\n    struct dirent *dp;\n\n    // Expanding \"**\" may take a long time, check for CTRL-C.\n    if (stardepth > 0)\n    {\n\tui_breakcheck();\n\tif (got_int)\n\t    return 0;\n    }\n\n    // make room for file name\n    buf = alloc(STRLEN(path) + BASENAMELEN + 5);\n    if (buf == NULL)\n\treturn 0;\n\n    /*\n     * Find the first part in the path name that contains a wildcard.\n     * When EW_ICASE is set every letter is considered to be a wildcard.\n     * Copy it into \"buf\", including the preceding characters.\n     */\n    p = buf;\n    s = buf;\n    e = NULL;\n    path_end = path;\n    while (*path_end != NUL)\n    {\n\t// May ignore a wildcard that has a backslash before it; it will\n\t// be removed by rem_backslash() or file_pat_to_reg_pat() below.\n\tif (path_end >= path + wildoff && rem_backslash(path_end))\n\t    *p++ = *path_end++;\n\telse if (*path_end == '/')\n\t{\n\t    if (e != NULL)\n\t\tbreak;\n\t    s = p + 1;\n\t}\n\telse if (path_end >= path + wildoff\n\t\t\t && (vim_strchr((char_u *)\"*?[{~$\", *path_end) != NULL\n\t\t\t     || (!p_fic && (flags & EW_ICASE)\n\t\t\t\t\t  && vim_isalpha(PTR2CHAR(path_end)))))\n\t    e = p;\n\tif (has_mbyte)\n\t{\n\t    len = (*mb_ptr2len)(path_end);\n\t    STRNCPY(p, path_end, len);\n\t    p += len;\n\t    path_end += len;\n\t}\n\telse\n\t    *p++ = *path_end++;\n    }\n    e = p;\n    *e = NUL;\n\n    // Now we have one wildcard component between \"s\" and \"e\".\n    // Remove backslashes between \"wildoff\" and the start of the wildcard\n    // component.\n    for (p = buf + wildoff; p < s; ++p)\n\tif (rem_backslash(p))\n\t{\n\t    STRMOVE(p, p + 1);\n\t    --e;\n\t    --s;\n\t}\n\n    // Check for \"**\" between \"s\" and \"e\".\n    for (p = s; p < e; ++p)\n\tif (p[0] == '*' && p[1] == '*')\n\t    starstar = TRUE;\n\n    // convert the file pattern to a regexp pattern\n    starts_with_dot = *s == '.';\n    pat = file_pat_to_reg_pat(s, e, NULL, FALSE);\n    if (pat == NULL)\n    {\n\tvim_free(buf);\n\treturn 0;\n    }\n\n    // compile the regexp into a program\n    if (flags & EW_ICASE)\n\tregmatch.rm_ic = TRUE;\t\t// 'wildignorecase' set\n    else\n\tregmatch.rm_ic = p_fic;\t// ignore case when 'fileignorecase' is set\n    if (flags & (EW_NOERROR | EW_NOTWILD))\n\t++emsg_silent;\n    regmatch.regprog = vim_regcomp(pat, RE_MAGIC);\n    if (flags & (EW_NOERROR | EW_NOTWILD))\n\t--emsg_silent;\n    vim_free(pat);\n\n    if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)\n    {\n\tvim_free(buf);\n\treturn 0;\n    }\n\n    // If \"**\" is by itself, this is the first time we encounter it and more\n    // is following then find matches without any directory.\n    if (!didstar && stardepth < 100 && starstar && e - s == 2\n\t\t\t\t\t\t\t  && *path_end == '/')\n    {\n\tSTRCPY(s, path_end + 1);\n\t++stardepth;\n\t(void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);\n\t--stardepth;\n    }\n\n    // open the directory for scanning\n    *s = NUL;\n    dirp = opendir(*buf == NUL ? \".\" : (char *)buf);\n\n    // Find all matching entries\n    if (dirp != NULL)\n    {\n\tfor (;;)\n\t{\n\t    dp = readdir(dirp);\n\t    if (dp == NULL)\n\t\tbreak;\n\t    if ((dp->d_name[0] != '.' || starts_with_dot\n\t\t\t|| ((flags & EW_DODOT)\n\t\t\t    && dp->d_name[1] != NUL\n\t\t\t    && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))\n\t\t && ((regmatch.regprog != NULL && vim_regexec(®match,\n\t\t\t\t\t     (char_u *)dp->d_name, (colnr_T)0))\n\t\t   || ((flags & EW_NOTWILD)\n\t\t     && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))\n\t    {\n\t\tSTRCPY(s, dp->d_name);\n\t\tlen = STRLEN(buf);\n\n\t\tif (starstar && stardepth < 100)\n\t\t{\n\t\t    // For \"**\" in the pattern first go deeper in the tree to\n\t\t    // find matches.\n\t\t    STRCPY(buf + len, \"/**\");\n\t\t    STRCPY(buf + len + 3, path_end);\n\t\t    ++stardepth;\n\t\t    (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);\n\t\t    --stardepth;\n\t\t}\n\n\t\tSTRCPY(buf + len, path_end);\n\t\tif (mch_has_exp_wildcard(path_end)) // handle more wildcards\n\t\t{\n\t\t    // need to expand another component of the path\n\t\t    // remove backslashes for the remaining components only\n\t\t    (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);\n\t\t}\n\t\telse\n\t\t{\n\t\t    stat_T  sb;\n\n\t\t    // no more wildcards, check if there is a match\n\t\t    // remove backslashes for the remaining components only\n\t\t    if (*path_end != NUL)\n\t\t\tbackslash_halve(buf + len + 1);\n\t\t    // add existing file or symbolic link\n\t\t    if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0\n\t\t\t\t\t\t      : mch_getperm(buf) >= 0)\n\t\t    {\n#ifdef MACOS_CONVERT\n\t\t\tsize_t precomp_len = STRLEN(buf)+1;\n\t\t\tchar_u *precomp_buf =\n\t\t\t    mac_precompose_path(buf, precomp_len, &precomp_len);\n\n\t\t\tif (precomp_buf)\n\t\t\t{\n\t\t\t    mch_memmove(buf, precomp_buf, precomp_len);\n\t\t\t    vim_free(precomp_buf);\n\t\t\t}\n#endif\n\t\t\taddfile(gap, buf, flags);\n\t\t    }\n\t\t}\n\t    }\n\t}\n\n\tclosedir(dirp);\n    }\n\n    vim_free(buf);\n    vim_regfree(regmatch.regprog);\n\n    matches = gap->ga_len - start_len;\n    if (matches > 0)\n\tqsort(((char_u **)gap->ga_data) + start_len, matches,\n\t\t\t\t\t\t   sizeof(char_u *), pstrcmp);\n    return matches;\n}", "func_hash": 314207374277767272342244288300260252688, "file_name": "filepath.c", "file_hash": 268435853121240029622170757643385181583, "cwe": ["CWE-703"], "cve": "CVE-2022-0685", "cve_desc": "Use of Out-of-range Pointer Offset in GitHub repository vim/vim prior to 8.2.4418.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0685"}
{"idx": 206771, "project": "qcad", "commit_id": "1eeffc5daf5a06cf6213ffc19e95923cdebb2eb8", "project_url": "https://github.com/qcad/qcad", "commit_url": "https://github.com/qcad/qcad/commit/1eeffc5daf5a06cf6213ffc19e95923cdebb2eb8", "commit_message": "check vertexIndex which might be -1 for broken DXF", "target": 1, "func": "bool DL_Dxf::handleLWPolylineData(DL_CreationInterface* /*creationInterface*/) {\n    // Allocate LWPolyline vertices (group code 90):\n    if (groupCode==90) {\n        maxVertices = toInt(groupValue);\n        if (maxVertices>0) {\n            if (vertices!=NULL) {\n                delete[] vertices;\n            }\n            vertices = new double[4*maxVertices];\n            for (int i=0; i=0 && vertexIndex0) {\n            if (vertices!=NULL) {\n                delete[] vertices;\n            }\n            vertices = new double[4*maxVertices];\n            for (int i=0; i=0 && vertexIndex=0) {\n                vertices[4*vertexIndex + (groupCode/10-1)] = toReal(groupValue);\n            }\n        } else if (groupCode==42 && vertexIndex=0) {\n            vertices[4*vertexIndex + 3] = toReal(groupValue);\n        }\n        return true;\n    }\n    return false;\n}", "func_hash": 66825183138389317029314964036422106221, "file_name": "dl_dxf.cpp", "file_hash": 181081005270076491555487324786328968837, "cwe": ["CWE-191"], "cve": "CVE-2021-21897", "cve_desc": "A code execution vulnerability exists in the DL_Dxf::handleLWPolylineData functionality of Ribbonsoft dxflib 3.17.0. A specially-crafted .dxf file can lead to a heap buffer overflow. An attacker can provide a malicious file to trigger this vulnerability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-21897"}
{"idx": 206781, "project": "linux", "commit_id": "ea8569194b43f0f01f0a84c689388542c7254a1f", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=ea8569194b43f0f01f0a84c689388542c7254a1f", "commit_message": "udf: Restore i_lenAlloc when inode expansion fails\n\nWhen we fail to expand inode from inline format to a normal format, we\nrestore inode to contain the original inline formatting but we forgot to\nset i_lenAlloc back. The mismatch between i_lenAlloc and i_size was then\ncausing further problems such as warnings and lost data down the line.\n\nReported-by: butt3rflyh4ck \nCC: stable@vger.kernel.org\nFixes: 7e49b6f2480c (\"udf: Convert UDF to new truncate calling sequence\")\nReviewed-by: Christoph Hellwig \nSigned-off-by: Jan Kara ", "target": 1, "func": "int udf_expand_file_adinicb(struct inode *inode)\n{\n\tstruct page *page;\n\tchar *kaddr;\n\tstruct udf_inode_info *iinfo = UDF_I(inode);\n\tint err;\n\n\tWARN_ON_ONCE(!inode_is_locked(inode));\n\tif (!iinfo->i_lenAlloc) {\n\t\tif (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))\n\t\t\tiinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;\n\t\telse\n\t\t\tiinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;\n\t\t/* from now on we have normal address_space methods */\n\t\tinode->i_data.a_ops = &udf_aops;\n\t\tup_write(&iinfo->i_data_sem);\n\t\tmark_inode_dirty(inode);\n\t\treturn 0;\n\t}\n\t/*\n\t * Release i_data_sem so that we can lock a page - page lock ranks\n\t * above i_data_sem. i_mutex still protects us against file changes.\n\t */\n\tup_write(&iinfo->i_data_sem);\n\n\tpage = find_or_create_page(inode->i_mapping, 0, GFP_NOFS);\n\tif (!page)\n\t\treturn -ENOMEM;\n\n\tif (!PageUptodate(page)) {\n\t\tkaddr = kmap_atomic(page);\n\t\tmemset(kaddr + iinfo->i_lenAlloc, 0x00,\n\t\t       PAGE_SIZE - iinfo->i_lenAlloc);\n\t\tmemcpy(kaddr, iinfo->i_data + iinfo->i_lenEAttr,\n\t\t\tiinfo->i_lenAlloc);\n\t\tflush_dcache_page(page);\n\t\tSetPageUptodate(page);\n\t\tkunmap_atomic(kaddr);\n\t}\n\tdown_write(&iinfo->i_data_sem);\n\tmemset(iinfo->i_data + iinfo->i_lenEAttr, 0x00,\n\t       iinfo->i_lenAlloc);\n\tiinfo->i_lenAlloc = 0;\n\tif (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))\n\t\tiinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;\n\telse\n\t\tiinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;\n\t/* from now on we have normal address_space methods */\n\tinode->i_data.a_ops = &udf_aops;\n\tset_page_dirty(page);\n\tunlock_page(page);\n\tup_write(&iinfo->i_data_sem);\n\terr = filemap_fdatawrite(inode->i_mapping);\n\tif (err) {\n\t\t/* Restore everything back so that we don't lose data... */\n\t\tlock_page(page);\n\t\tdown_write(&iinfo->i_data_sem);\n\t\tkaddr = kmap_atomic(page);\n\t\tmemcpy(iinfo->i_data + iinfo->i_lenEAttr, kaddr, inode->i_size);\n\t\tkunmap_atomic(kaddr);\n\t\tunlock_page(page);\n\t\tiinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB;\n\t\tinode->i_data.a_ops = &udf_adinicb_aops;\n\t\tup_write(&iinfo->i_data_sem);\n\t}\n\tput_page(page);\n\tmark_inode_dirty(inode);\n\n\treturn err;\n}", "func_hash": 151977926301006306483685572008692883310, "file_name": "inode.c", "file_hash": 299509065903875732825474013259696803505, "cwe": ["CWE-476"], "cve": "CVE-2022-0617", "cve_desc": "A flaw null pointer dereference in the Linux kernel UDF file system functionality was found in the way user triggers udf_file_write_iter function for the malicious UDF image. A local user could use this flaw to crash the system. Actual from Linux kernel 4.2-rc1 till 5.17-rc2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0617"}
{"idx": 386750, "project": "linux", "commit_id": "ea8569194b43f0f01f0a84c689388542c7254a1f", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=ea8569194b43f0f01f0a84c689388542c7254a1f", "commit_message": "udf: Restore i_lenAlloc when inode expansion fails\n\nWhen we fail to expand inode from inline format to a normal format, we\nrestore inode to contain the original inline formatting but we forgot to\nset i_lenAlloc back. The mismatch between i_lenAlloc and i_size was then\ncausing further problems such as warnings and lost data down the line.\n\nReported-by: butt3rflyh4ck \nCC: stable@vger.kernel.org\nFixes: 7e49b6f2480c (\"udf: Convert UDF to new truncate calling sequence\")\nReviewed-by: Christoph Hellwig \nSigned-off-by: Jan Kara ", "target": 0, "func": "int udf_expand_file_adinicb(struct inode *inode)\n{\n\tstruct page *page;\n\tchar *kaddr;\n\tstruct udf_inode_info *iinfo = UDF_I(inode);\n\tint err;\n\n\tWARN_ON_ONCE(!inode_is_locked(inode));\n\tif (!iinfo->i_lenAlloc) {\n\t\tif (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))\n\t\t\tiinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;\n\t\telse\n\t\t\tiinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;\n\t\t/* from now on we have normal address_space methods */\n\t\tinode->i_data.a_ops = &udf_aops;\n\t\tup_write(&iinfo->i_data_sem);\n\t\tmark_inode_dirty(inode);\n\t\treturn 0;\n\t}\n\t/*\n\t * Release i_data_sem so that we can lock a page - page lock ranks\n\t * above i_data_sem. i_mutex still protects us against file changes.\n\t */\n\tup_write(&iinfo->i_data_sem);\n\n\tpage = find_or_create_page(inode->i_mapping, 0, GFP_NOFS);\n\tif (!page)\n\t\treturn -ENOMEM;\n\n\tif (!PageUptodate(page)) {\n\t\tkaddr = kmap_atomic(page);\n\t\tmemset(kaddr + iinfo->i_lenAlloc, 0x00,\n\t\t       PAGE_SIZE - iinfo->i_lenAlloc);\n\t\tmemcpy(kaddr, iinfo->i_data + iinfo->i_lenEAttr,\n\t\t\tiinfo->i_lenAlloc);\n\t\tflush_dcache_page(page);\n\t\tSetPageUptodate(page);\n\t\tkunmap_atomic(kaddr);\n\t}\n\tdown_write(&iinfo->i_data_sem);\n\tmemset(iinfo->i_data + iinfo->i_lenEAttr, 0x00,\n\t       iinfo->i_lenAlloc);\n\tiinfo->i_lenAlloc = 0;\n\tif (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))\n\t\tiinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;\n\telse\n\t\tiinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;\n\t/* from now on we have normal address_space methods */\n\tinode->i_data.a_ops = &udf_aops;\n\tset_page_dirty(page);\n\tunlock_page(page);\n\tup_write(&iinfo->i_data_sem);\n\terr = filemap_fdatawrite(inode->i_mapping);\n\tif (err) {\n\t\t/* Restore everything back so that we don't lose data... */\n\t\tlock_page(page);\n\t\tdown_write(&iinfo->i_data_sem);\n\t\tkaddr = kmap_atomic(page);\n\t\tmemcpy(iinfo->i_data + iinfo->i_lenEAttr, kaddr, inode->i_size);\n\t\tkunmap_atomic(kaddr);\n\t\tunlock_page(page);\n\t\tiinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB;\n\t\tinode->i_data.a_ops = &udf_adinicb_aops;\n\t\tiinfo->i_lenAlloc = inode->i_size;\n\t\tup_write(&iinfo->i_data_sem);\n\t}\n\tput_page(page);\n\tmark_inode_dirty(inode);\n\n\treturn err;\n}", "func_hash": 191954099261759057406602593964899861240, "file_name": "inode.c", "file_hash": 50770462585650222153062698584720679665, "cwe": ["CWE-476"], "cve": "CVE-2022-0617", "cve_desc": "A flaw null pointer dereference in the Linux kernel UDF file system functionality was found in the way user triggers udf_file_write_iter function for the malicious UDF image. A local user could use this flaw to crash the system. Actual from Linux kernel 4.2-rc1 till 5.17-rc2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0617"}
{"idx": 206815, "project": "ImageMagick", "commit_id": "c111ed9b035532c2c81ea569f2d22fded9517287", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/c111ed9b035532c2c81ea569f2d22fded9517287", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1540", "target": 1, "func": "static MagickBooleanType SetGrayscaleImage(Image *image,\n  ExceptionInfo *exception)\n{\n  CacheView\n    *image_view;\n\n  MagickBooleanType\n    status;\n\n  PixelInfo\n    *colormap;\n\n  register ssize_t\n    i;\n\n  ssize_t\n    *colormap_index,\n    j,\n    y;\n\n  assert(image != (Image *) NULL);\n  assert(image->signature == MagickCoreSignature);\n  if (image->type != GrayscaleType)\n    (void) TransformImageColorspace(image,GRAYColorspace,exception);\n  if (image->storage_class == PseudoClass)\n    colormap_index=(ssize_t *) AcquireQuantumMemory(image->colors+1,\n      sizeof(*colormap_index));\n  else\n    colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize+1,\n      sizeof(*colormap_index));\n  if (colormap_index == (ssize_t *) NULL)\n    ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n      image->filename);\n  if (image->storage_class != PseudoClass)\n    {\n      (void) memset(colormap_index,(-1),MaxColormapSize*\n        sizeof(*colormap_index));\n      if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)\n        {\n          colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);\n          ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n            image->filename);\n        }\n      image->colors=0;\n      status=MagickTrue;\n      image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n      #pragma omp parallel for schedule(static) shared(status) \\\n        magick_number_threads(image,image,image->rows,1)\n#endif\n      for (y=0; y < (ssize_t) image->rows; y++)\n      {\n        register Quantum\n          *magick_restrict q;\n\n        register ssize_t\n          x;\n\n        if (status == MagickFalse)\n          continue;\n        q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n          exception);\n        if (q == (Quantum *) NULL)\n          {\n            status=MagickFalse;\n            continue;\n          }\n        for (x=0; x < (ssize_t) image->columns; x++)\n        {\n          register size_t\n            intensity;\n\n          intensity=ScaleQuantumToMap(GetPixelRed(image,q));\n          if (colormap_index[intensity] < 0)\n            {\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n              #pragma omp critical (MagickCore_SetGrayscaleImage)\n#endif\n              if (colormap_index[intensity] < 0)\n                {\n                  colormap_index[intensity]=(ssize_t) image->colors;\n                  image->colormap[image->colors].red=(double)\n                    GetPixelRed(image,q);\n                  image->colormap[image->colors].green=(double)\n                    GetPixelGreen(image,q);\n                  image->colormap[image->colors].blue=(double)\n                    GetPixelBlue(image,q);\n                  image->colors++;\n               }\n            }\n          SetPixelIndex(image,(Quantum) colormap_index[intensity],q);\n          q+=GetPixelChannels(image);\n        }\n        if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n          status=MagickFalse;\n      }\n      image_view=DestroyCacheView(image_view);\n    }\n  for (i=0; i < (ssize_t) image->colors; i++)\n    image->colormap[i].alpha=(double) i;\n  qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),\n    IntensityCompare);\n  colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));\n  if (colormap == (PixelInfo *) NULL)\n    {\n      colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);\n      ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n        image->filename);\n    }\n  j=0;\n  colormap[j]=image->colormap[0];\n  for (i=0; i < (ssize_t) image->colors; i++)\n  {\n    if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)\n      {\n        j++;\n        colormap[j]=image->colormap[i];\n      }\n    colormap_index[(ssize_t) image->colormap[i].alpha]=j;\n  }\n  image->colors=(size_t) (j+1);\n  image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);\n  image->colormap=colormap;\n  status=MagickTrue;\n  image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n  #pragma omp parallel for schedule(static) shared(status) \\\n    magick_number_threads(image,image,image->rows,1)\n#endif\n  for (y=0; y < (ssize_t) image->rows; y++)\n  {\n    register Quantum\n      *magick_restrict q;\n\n    register ssize_t\n      x;\n\n    if (status == MagickFalse)\n      continue;\n    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);\n    if (q == (Quantum *) NULL)\n      {\n        status=MagickFalse;\n        continue;\n      }\n    for (x=0; x < (ssize_t) image->columns; x++)\n    {\n      SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(\n        GetPixelIndex(image,q))],q);\n      q+=GetPixelChannels(image);\n    }\n    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n      status=MagickFalse;\n  }\n  image_view=DestroyCacheView(image_view);\n  colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);\n  image->type=GrayscaleType;\n  if (SetImageMonochrome(image,exception) != MagickFalse)\n    image->type=BilevelType;\n  return(status);\n}", "func_hash": 31139316036408574839827699821440311605, "file_name": "quantize.c", "file_hash": 6776316156649379334956322163459365152, "cwe": ["CWE-125"], "cve": "CVE-2019-11598", "cve_desc": "In ImageMagick 7.0.8-40 Q16, there is a heap-based buffer over-read in the function WritePNMImage of coders/pnm.c, which allows an attacker to cause a denial of service or possibly information disclosure via a crafted image file. This is related to SetGrayscaleImage in MagickCore/quantize.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-11598"}
{"idx": 387149, "project": "ImageMagick", "commit_id": "c111ed9b035532c2c81ea569f2d22fded9517287", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/c111ed9b035532c2c81ea569f2d22fded9517287", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1540", "target": 0, "func": "static MagickBooleanType SetGrayscaleImage(Image *image,\n  ExceptionInfo *exception)\n{\n  CacheView\n    *image_view;\n\n  MagickBooleanType\n    status;\n\n  PixelInfo\n    *colormap;\n\n  register ssize_t\n    i;\n\n  ssize_t\n    *colormap_index,\n    j,\n    y;\n\n  assert(image != (Image *) NULL);\n  assert(image->signature == MagickCoreSignature);\n  if (image->type != GrayscaleType)\n    (void) TransformImageColorspace(image,GRAYColorspace,exception);\n  if (image->storage_class == PseudoClass)\n    colormap_index=(ssize_t *) AcquireQuantumMemory(MagickMax(image->colors+1,\n      MaxMap),sizeof(*colormap_index));\n  else\n    colormap_index=(ssize_t *) AcquireQuantumMemory(MagickMax(MaxColormapSize+1,\n      MaxMap),sizeof(*colormap_index));\n  if (colormap_index == (ssize_t *) NULL)\n    ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n      image->filename);\n  if (image->storage_class != PseudoClass)\n    {\n      (void) memset(colormap_index,(-1),MaxColormapSize*\n        sizeof(*colormap_index));\n      if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)\n        {\n          colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);\n          ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n            image->filename);\n        }\n      image->colors=0;\n      status=MagickTrue;\n      image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n      #pragma omp parallel for schedule(static) shared(status) \\\n        magick_number_threads(image,image,image->rows,1)\n#endif\n      for (y=0; y < (ssize_t) image->rows; y++)\n      {\n        register Quantum\n          *magick_restrict q;\n\n        register ssize_t\n          x;\n\n        if (status == MagickFalse)\n          continue;\n        q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n          exception);\n        if (q == (Quantum *) NULL)\n          {\n            status=MagickFalse;\n            continue;\n          }\n        for (x=0; x < (ssize_t) image->columns; x++)\n        {\n          register size_t\n            intensity;\n\n          intensity=ScaleQuantumToMap(GetPixelRed(image,q));\n          if (colormap_index[intensity] < 0)\n            {\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n              #pragma omp critical (MagickCore_SetGrayscaleImage)\n#endif\n              if (colormap_index[intensity] < 0)\n                {\n                  colormap_index[intensity]=(ssize_t) image->colors;\n                  image->colormap[image->colors].red=(double)\n                    GetPixelRed(image,q);\n                  image->colormap[image->colors].green=(double)\n                    GetPixelGreen(image,q);\n                  image->colormap[image->colors].blue=(double)\n                    GetPixelBlue(image,q);\n                  image->colors++;\n               }\n            }\n          SetPixelIndex(image,(Quantum) colormap_index[intensity],q);\n          q+=GetPixelChannels(image);\n        }\n        if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n          status=MagickFalse;\n      }\n      image_view=DestroyCacheView(image_view);\n    }\n  for (i=0; i < (ssize_t) image->colors; i++)\n    image->colormap[i].alpha=(double) i;\n  qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),\n    IntensityCompare);\n  colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));\n  if (colormap == (PixelInfo *) NULL)\n    {\n      colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);\n      ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n        image->filename);\n    }\n  j=0;\n  colormap[j]=image->colormap[0];\n  for (i=0; i < (ssize_t) image->colors; i++)\n  {\n    if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)\n      {\n        j++;\n        colormap[j]=image->colormap[i];\n      }\n    colormap_index[(ssize_t) image->colormap[i].alpha]=j;\n  }\n  image->colors=(size_t) (j+1);\n  image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);\n  image->colormap=colormap;\n  status=MagickTrue;\n  image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n  #pragma omp parallel for schedule(static) shared(status) \\\n    magick_number_threads(image,image,image->rows,1)\n#endif\n  for (y=0; y < (ssize_t) image->rows; y++)\n  {\n    register Quantum\n      *magick_restrict q;\n\n    register ssize_t\n      x;\n\n    if (status == MagickFalse)\n      continue;\n    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);\n    if (q == (Quantum *) NULL)\n      {\n        status=MagickFalse;\n        continue;\n      }\n    for (x=0; x < (ssize_t) image->columns; x++)\n    {\n      SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(\n        GetPixelIndex(image,q))],q);\n      q+=GetPixelChannels(image);\n    }\n    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n      status=MagickFalse;\n  }\n  image_view=DestroyCacheView(image_view);\n  colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);\n  image->type=GrayscaleType;\n  if (SetImageMonochrome(image,exception) != MagickFalse)\n    image->type=BilevelType;\n  return(status);\n}", "func_hash": 185597478640915810926254287356895046975, "file_name": "quantize.c", "file_hash": 90832018031567136939378750944649283392, "cwe": ["CWE-125"], "cve": "CVE-2019-11598", "cve_desc": "In ImageMagick 7.0.8-40 Q16, there is a heap-based buffer over-read in the function WritePNMImage of coders/pnm.c, which allows an attacker to cause a denial of service or possibly information disclosure via a crafted image file. This is related to SetGrayscaleImage in MagickCore/quantize.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-11598"}
{"idx": 206845, "project": "linux", "commit_id": "5934d9a0383619c14df91af8fd76261dc3de2f5f", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/5934d9a0383619c14df91af8fd76261dc3de2f5f", "commit_message": "ALSA: control: Re-order bounds checking in get_ctl_id_hash()\n\nThese two checks are in the reverse order so it might read one element\nbeyond the end of the array.  First check if the \"i\" is within bounds\nbefore using it.\n\nFixes: 6ab55ec0a938 (\"ALSA: control: Fix an out-of-bounds bug in get_ctl_id_hash()\")\nSigned-off-by: Dan Carpenter \nLink: https://lore.kernel.org/r/YwjgNh/gkG1hH7po@kili\nSigned-off-by: Takashi Iwai ", "target": 1, "func": "static unsigned long get_ctl_id_hash(const struct snd_ctl_elem_id *id)\n{\n\tint i;\n\tunsigned long h;\n\n\th = id->iface;\n\th = MULTIPLIER * h + id->device;\n\th = MULTIPLIER * h + id->subdevice;\n\tfor (i = 0; id->name[i] && i < SNDRV_CTL_ELEM_ID_NAME_MAXLEN; i++)\n\t\th = MULTIPLIER * h + id->name[i];\n\th = MULTIPLIER * h + id->index;\n\th &= LONG_MAX;\n\treturn h;\n}", "func_hash": 131319443934908040237061712028017051028, "file_name": "control.c", "file_hash": 255950300769870224716949641453203743368, "cwe": ["CWE-125"], "cve": "CVE-2022-3170", "cve_desc": "An out-of-bounds access issue was found in the Linux kernel sound subsystem. It could occur when the 'id->name' provided by the user did not end with '\\0'. A privileged local user could pass a specially crafted name through ioctl() interface and crash the system or potentially escalate their privileges on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3170"}
{"idx": 387593, "project": "linux", "commit_id": "5934d9a0383619c14df91af8fd76261dc3de2f5f", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/5934d9a0383619c14df91af8fd76261dc3de2f5f", "commit_message": "ALSA: control: Re-order bounds checking in get_ctl_id_hash()\n\nThese two checks are in the reverse order so it might read one element\nbeyond the end of the array.  First check if the \"i\" is within bounds\nbefore using it.\n\nFixes: 6ab55ec0a938 (\"ALSA: control: Fix an out-of-bounds bug in get_ctl_id_hash()\")\nSigned-off-by: Dan Carpenter \nLink: https://lore.kernel.org/r/YwjgNh/gkG1hH7po@kili\nSigned-off-by: Takashi Iwai ", "target": 0, "func": "static unsigned long get_ctl_id_hash(const struct snd_ctl_elem_id *id)\n{\n\tint i;\n\tunsigned long h;\n\n\th = id->iface;\n\th = MULTIPLIER * h + id->device;\n\th = MULTIPLIER * h + id->subdevice;\n\tfor (i = 0; i < SNDRV_CTL_ELEM_ID_NAME_MAXLEN && id->name[i]; i++)\n\t\th = MULTIPLIER * h + id->name[i];\n\th = MULTIPLIER * h + id->index;\n\th &= LONG_MAX;\n\treturn h;\n}", "func_hash": 34537843047622620480136251678937271731, "file_name": "control.c", "file_hash": 333017582912688268799367809880673073354, "cwe": ["CWE-125"], "cve": "CVE-2022-3170", "cve_desc": "An out-of-bounds access issue was found in the Linux kernel sound subsystem. It could occur when the 'id->name' provided by the user did not end with '\\0'. A privileged local user could pass a specially crafted name through ioctl() interface and crash the system or potentially escalate their privileges on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3170"}
{"idx": 206942, "project": "vim", "commit_id": "1e56bda9048a9625bce6e660938c834c5c15b07d", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/1e56bda9048a9625bce6e660938c834c5c15b07d", "commit_message": "patch 9.0.0104: going beyond allocated memory when evaluating string constant\n\nProblem:    Going beyond allocated memory when evaluating string constant.\nSolution:   Properly skip over  form.", "target": 1, "func": "eval_string(char_u **arg, typval_T *rettv, int evaluate, int interpolate)\n{\n    char_u\t*p;\n    char_u\t*end;\n    int\t\textra = interpolate ? 1 : 0;\n    int\t\toff = interpolate ? 0 : 1;\n    int\t\tlen;\n\n    // Find the end of the string, skipping backslashed characters.\n    for (p = *arg + off; *p != NUL && *p != '\"'; MB_PTR_ADV(p))\n    {\n\tif (*p == '\\\\' && p[1] != NUL)\n\t{\n\t    ++p;\n\t    // A \"\\\" form occupies at least 4 characters, and produces up\n\t    // to 9 characters (6 for the char and 3 for a modifier):\n\t    // reserve space for 5 extra.\n\t    if (*p == '<')\n\t\textra += 5;\n\t}\n\telse if (interpolate && (*p == '{' || *p == '}'))\n\t{\n\t    if (*p == '{' && p[1] != '{') // start of expression\n\t\tbreak;\n\t    ++p;\n\t    if (p[-1] == '}' && *p != '}') // single '}' is an error\n\t    {\n\t\tsemsg(_(e_stray_closing_curly_str), *arg);\n\t\treturn FAIL;\n\t    }\n\t    --extra;  // \"{{\" becomes \"{\", \"}}\" becomes \"}\"\n\t}\n    }\n\n    if (*p != '\"' && !(interpolate && *p == '{'))\n    {\n\tsemsg(_(e_missing_double_quote_str), *arg);\n\treturn FAIL;\n    }\n\n    // If only parsing, set *arg and return here\n    if (!evaluate)\n    {\n\t*arg = p + off;\n\treturn OK;\n    }\n\n    // Copy the string into allocated memory, handling backslashed\n    // characters.\n    rettv->v_type = VAR_STRING;\n    len = (int)(p - *arg + extra);\n    rettv->vval.v_string = alloc(len);\n    if (rettv->vval.v_string == NULL)\n\treturn FAIL;\n    end = rettv->vval.v_string;\n\n    for (p = *arg + off; *p != NUL && *p != '\"'; )\n    {\n\tif (*p == '\\\\')\n\t{\n\t    switch (*++p)\n\t    {\n\t\tcase 'b': *end++ = BS; ++p; break;\n\t\tcase 'e': *end++ = ESC; ++p; break;\n\t\tcase 'f': *end++ = FF; ++p; break;\n\t\tcase 'n': *end++ = NL; ++p; break;\n\t\tcase 'r': *end++ = CAR; ++p; break;\n\t\tcase 't': *end++ = TAB; ++p; break;\n\n\t\tcase 'X': // hex: \"\\x1\", \"\\x12\"\n\t\tcase 'x':\n\t\tcase 'u': // Unicode: \"\\u0023\"\n\t\tcase 'U':\n\t\t\t  if (vim_isxdigit(p[1]))\n\t\t\t  {\n\t\t\t      int\tn, nr;\n\t\t\t      int\tc = toupper(*p);\n\n\t\t\t      if (c == 'X')\n\t\t\t\t  n = 2;\n\t\t\t      else if (*p == 'u')\n\t\t\t\t  n = 4;\n\t\t\t      else\n\t\t\t\t  n = 8;\n\t\t\t      nr = 0;\n\t\t\t      while (--n >= 0 && vim_isxdigit(p[1]))\n\t\t\t      {\n\t\t\t\t  ++p;\n\t\t\t\t  nr = (nr << 4) + hex2nr(*p);\n\t\t\t      }\n\t\t\t      ++p;\n\t\t\t      // For \"\\u\" store the number according to\n\t\t\t      // 'encoding'.\n\t\t\t      if (c != 'X')\n\t\t\t\t  end += (*mb_char2bytes)(nr, end);\n\t\t\t      else\n\t\t\t\t  *end++ = nr;\n\t\t\t  }\n\t\t\t  break;\n\n\t\t\t  // octal: \"\\1\", \"\\12\", \"\\123\"\n\t\tcase '0':\n\t\tcase '1':\n\t\tcase '2':\n\t\tcase '3':\n\t\tcase '4':\n\t\tcase '5':\n\t\tcase '6':\n\t\tcase '7': *end = *p++ - '0';\n\t\t\t  if (*p >= '0' && *p <= '7')\n\t\t\t  {\n\t\t\t      *end = (*end << 3) + *p++ - '0';\n\t\t\t      if (*p >= '0' && *p <= '7')\n\t\t\t\t  *end = (*end << 3) + *p++ - '0';\n\t\t\t  }\n\t\t\t  ++end;\n\t\t\t  break;\n\n\t\t\t  // Special key, e.g.: \"\\\"\n\t\tcase '<':\n\t\t\t  {\n\t\t\t      int flags = FSK_KEYCODE | FSK_IN_STRING;\n\n\t\t\t      if (p[1] != '*')\n\t\t\t\t  flags |= FSK_SIMPLIFY;\n\t\t\t      extra = trans_special(&p, end, flags, FALSE, NULL);\n\t\t\t      if (extra != 0)\n\t\t\t      {\n\t\t\t\t  end += extra;\n\t\t\t\t  if (end >= rettv->vval.v_string + len)\n\t\t\t\t      iemsg(\"eval_string() used more space than allocated\");\n\t\t\t\t  break;\n\t\t\t      }\n\t\t\t  }\n\t\t\t  // FALLTHROUGH\n\n\t\tdefault: MB_COPY_CHAR(p, end);\n\t\t\t  break;\n\t    }\n\t}\n\telse\n\t{\n\t    if (interpolate && (*p == '{' || *p == '}'))\n\t    {\n\t\tif (*p == '{' && p[1] != '{') // start of expression\n\t\t    break;\n\t\t++p;  // reduce \"{{\" to \"{\" and \"}}\" to \"}\"\n\t    }\n\t    MB_COPY_CHAR(p, end);\n\t}\n    }\n    *end = NUL;\n    if (*p == '\"' && !interpolate)\n\t++p;\n    *arg = p;\n\n    return OK;\n}", "func_hash": 338220226163490913152834959718974208239, "file_name": "typval.c", "file_hash": 328531951922388475683903891036611129511, "cwe": ["CWE-125"], "cve": "CVE-2022-2580", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0102.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2580"}
{"idx": 389676, "project": "vim", "commit_id": "1e56bda9048a9625bce6e660938c834c5c15b07d", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/1e56bda9048a9625bce6e660938c834c5c15b07d", "commit_message": "patch 9.0.0104: going beyond allocated memory when evaluating string constant\n\nProblem:    Going beyond allocated memory when evaluating string constant.\nSolution:   Properly skip over  form.", "target": 0, "func": "eval_string(char_u **arg, typval_T *rettv, int evaluate, int interpolate)\n{\n    char_u\t*p;\n    char_u\t*end;\n    int\t\textra = interpolate ? 1 : 0;\n    int\t\toff = interpolate ? 0 : 1;\n    int\t\tlen;\n\n    // Find the end of the string, skipping backslashed characters.\n    for (p = *arg + off; *p != NUL && *p != '\"'; MB_PTR_ADV(p))\n    {\n\tif (*p == '\\\\' && p[1] != NUL)\n\t{\n\t    ++p;\n\t    // A \"\\\" form occupies at least 4 characters, and produces up\n\t    // to 9 characters (6 for the char and 3 for a modifier):\n\t    // reserve space for 5 extra.\n\t    if (*p == '<')\n\t    {\n\t\tint\t\tmodifiers = 0;\n\t\tint\t\tflags = FSK_KEYCODE | FSK_IN_STRING;\n\n\t\textra += 5;\n\n\t\t// Skip to the '>' to avoid using '{' inside for string\n\t\t// interpolation.\n\t\tif (p[1] != '*')\n\t\t    flags |= FSK_SIMPLIFY;\n\t\tif (find_special_key(&p, &modifiers, flags, NULL) != 0)\n\t\t    --p;  // leave \"p\" on the \">\"\n\t    }\n\t}\n\telse if (interpolate && (*p == '{' || *p == '}'))\n\t{\n\t    if (*p == '{' && p[1] != '{') // start of expression\n\t\tbreak;\n\t    ++p;\n\t    if (p[-1] == '}' && *p != '}') // single '}' is an error\n\t    {\n\t\tsemsg(_(e_stray_closing_curly_str), *arg);\n\t\treturn FAIL;\n\t    }\n\t    --extra;  // \"{{\" becomes \"{\", \"}}\" becomes \"}\"\n\t}\n    }\n\n    if (*p != '\"' && !(interpolate && *p == '{'))\n    {\n\tsemsg(_(e_missing_double_quote_str), *arg);\n\treturn FAIL;\n    }\n\n    // If only parsing, set *arg and return here\n    if (!evaluate)\n    {\n\t*arg = p + off;\n\treturn OK;\n    }\n\n    // Copy the string into allocated memory, handling backslashed\n    // characters.\n    rettv->v_type = VAR_STRING;\n    len = (int)(p - *arg + extra);\n    rettv->vval.v_string = alloc(len);\n    if (rettv->vval.v_string == NULL)\n\treturn FAIL;\n    end = rettv->vval.v_string;\n\n    for (p = *arg + off; *p != NUL && *p != '\"'; )\n    {\n\tif (*p == '\\\\')\n\t{\n\t    switch (*++p)\n\t    {\n\t\tcase 'b': *end++ = BS; ++p; break;\n\t\tcase 'e': *end++ = ESC; ++p; break;\n\t\tcase 'f': *end++ = FF; ++p; break;\n\t\tcase 'n': *end++ = NL; ++p; break;\n\t\tcase 'r': *end++ = CAR; ++p; break;\n\t\tcase 't': *end++ = TAB; ++p; break;\n\n\t\tcase 'X': // hex: \"\\x1\", \"\\x12\"\n\t\tcase 'x':\n\t\tcase 'u': // Unicode: \"\\u0023\"\n\t\tcase 'U':\n\t\t\t  if (vim_isxdigit(p[1]))\n\t\t\t  {\n\t\t\t      int\tn, nr;\n\t\t\t      int\tc = toupper(*p);\n\n\t\t\t      if (c == 'X')\n\t\t\t\t  n = 2;\n\t\t\t      else if (*p == 'u')\n\t\t\t\t  n = 4;\n\t\t\t      else\n\t\t\t\t  n = 8;\n\t\t\t      nr = 0;\n\t\t\t      while (--n >= 0 && vim_isxdigit(p[1]))\n\t\t\t      {\n\t\t\t\t  ++p;\n\t\t\t\t  nr = (nr << 4) + hex2nr(*p);\n\t\t\t      }\n\t\t\t      ++p;\n\t\t\t      // For \"\\u\" store the number according to\n\t\t\t      // 'encoding'.\n\t\t\t      if (c != 'X')\n\t\t\t\t  end += (*mb_char2bytes)(nr, end);\n\t\t\t      else\n\t\t\t\t  *end++ = nr;\n\t\t\t  }\n\t\t\t  break;\n\n\t\t\t  // octal: \"\\1\", \"\\12\", \"\\123\"\n\t\tcase '0':\n\t\tcase '1':\n\t\tcase '2':\n\t\tcase '3':\n\t\tcase '4':\n\t\tcase '5':\n\t\tcase '6':\n\t\tcase '7': *end = *p++ - '0';\n\t\t\t  if (*p >= '0' && *p <= '7')\n\t\t\t  {\n\t\t\t      *end = (*end << 3) + *p++ - '0';\n\t\t\t      if (*p >= '0' && *p <= '7')\n\t\t\t\t  *end = (*end << 3) + *p++ - '0';\n\t\t\t  }\n\t\t\t  ++end;\n\t\t\t  break;\n\n\t\t\t  // Special key, e.g.: \"\\\"\n\t\tcase '<':\n\t\t\t  {\n\t\t\t      int flags = FSK_KEYCODE | FSK_IN_STRING;\n\n\t\t\t      if (p[1] != '*')\n\t\t\t\t  flags |= FSK_SIMPLIFY;\n\t\t\t      extra = trans_special(&p, end, flags, FALSE, NULL);\n\t\t\t      if (extra != 0)\n\t\t\t      {\n\t\t\t\t  end += extra;\n\t\t\t\t  if (end >= rettv->vval.v_string + len)\n\t\t\t\t      iemsg(\"eval_string() used more space than allocated\");\n\t\t\t\t  break;\n\t\t\t      }\n\t\t\t  }\n\t\t\t  // FALLTHROUGH\n\n\t\tdefault: MB_COPY_CHAR(p, end);\n\t\t\t  break;\n\t    }\n\t}\n\telse\n\t{\n\t    if (interpolate && (*p == '{' || *p == '}'))\n\t    {\n\t\tif (*p == '{' && p[1] != '{') // start of expression\n\t\t    break;\n\t\t++p;  // reduce \"{{\" to \"{\" and \"}}\" to \"}\"\n\t    }\n\t    MB_COPY_CHAR(p, end);\n\t}\n    }\n    *end = NUL;\n    if (*p == '\"' && !interpolate)\n\t++p;\n    *arg = p;\n\n    return OK;\n}", "func_hash": 300144927032379821054071112406007573706, "file_name": "typval.c", "file_hash": 264686639878036499427248365468285871356, "cwe": ["CWE-125"], "cve": "CVE-2022-2580", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0102.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2580"}
{"idx": 206946, "project": "jasper", "commit_id": "d99636fad60629785efd1ef72da772a8ef68f54c", "project_url": "https://github.com/mdadams/jasper", "commit_url": "https://github.com/jasper-software/jasper/commit/d99636fad60629785efd1ef72da772a8ef68f54c", "commit_message": "fix memory leaks in function cmdopts_parse", "target": 1, "func": "cmdopts_t *cmdopts_parse(int argc, char **argv)\n{\n\tenum {\n\t\tCMDOPT_HELP = 0,\n\t\tCMDOPT_VERBOSE,\n\t\tCMDOPT_QUIET,\n\t\tCMDOPT_INFILE,\n\t\tCMDOPT_INFMT,\n\t\tCMDOPT_INOPT,\n\t\tCMDOPT_OUTFILE,\n\t\tCMDOPT_OUTFMT,\n\t\tCMDOPT_OUTOPT,\n\t\tCMDOPT_VERSION,\n\t\tCMDOPT_DEBUG,\n\t\tCMDOPT_CMPTNO,\n\t\tCMDOPT_SRGB,\n\t\tCMDOPT_MAXMEM,\n\t\tCMDOPT_LIST_ENABLED_CODECS,\n\t\tCMDOPT_LIST_ALL_CODECS,\n\t\tCMDOPT_ENABLE_FORMAT,\n\t\tCMDOPT_ENABLE_ALL_FORMATS,\n\t};\n\n\tstatic const jas_opt_t cmdoptions[] = {\n\t\t{CMDOPT_HELP, \"help\", 0},\n\t\t{CMDOPT_VERBOSE, \"verbose\", 0},\n\t\t{CMDOPT_QUIET, \"quiet\", 0},\n\t\t{CMDOPT_QUIET, \"q\", 0},\n\t\t{CMDOPT_INFILE, \"input\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INFILE, \"f\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INFMT, \"input-format\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INFMT, \"t\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INOPT, \"input-option\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INOPT, \"o\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTFILE, \"output\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTFILE, \"F\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTFMT, \"output-format\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTFMT, \"T\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTOPT, \"output-option\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTOPT, \"O\", JAS_OPT_HASARG},\n\t\t{CMDOPT_VERSION, \"version\", 0},\n\t\t{CMDOPT_DEBUG, \"debug-level\", JAS_OPT_HASARG},\n\t\t{CMDOPT_CMPTNO, \"cmptno\", JAS_OPT_HASARG},\n\t\t{CMDOPT_SRGB, \"force-srgb\", 0},\n\t\t{CMDOPT_SRGB, \"S\", 0},\n\t\t{CMDOPT_MAXMEM, \"memory-limit\", JAS_OPT_HASARG},\n\t\t{CMDOPT_LIST_ENABLED_CODECS, \"list-enabled-formats\", 0},\n\t\t{CMDOPT_LIST_ALL_CODECS, \"list-all-formats\", 0},\n\t\t{CMDOPT_ENABLE_FORMAT, \"enable-format\", JAS_OPT_HASARG},\n\t\t{CMDOPT_ENABLE_ALL_FORMATS, \"enable-all-formats\", 0},\n\t\t{-1, 0, 0}\n\t};\n\n\tcmdopts_t *cmdopts;\n\tint c;\n\n\tif (!(cmdopts = malloc(sizeof(cmdopts_t)))) {\n\t\tfprintf(stderr, \"error: insufficient memory\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tcmdopts->infile = 0;\n\tcmdopts->infmt = -1;\n\tcmdopts->infmt_str = 0;\n\tcmdopts->inopts = 0;\n\tcmdopts->inoptsbuf[0] = '\\0';\n\tcmdopts->outfile = 0;\n\tcmdopts->outfmt = -1;\n\tcmdopts->outfmt_str = 0;\n\tcmdopts->outopts = 0;\n\tcmdopts->outoptsbuf[0] = '\\0';\n\tcmdopts->verbose = 0;\n\tcmdopts->version = 0;\n\tcmdopts->cmptno = -1;\n\tcmdopts->debug = 0;\n\tcmdopts->srgb = 0;\n\tcmdopts->list_codecs = 0;\n\tcmdopts->list_codecs_all = 0;\n\tcmdopts->help = 0;\n\tcmdopts->max_mem = get_default_max_mem_usage();\n\tcmdopts->enable_format = 0;\n\tcmdopts->enable_all_formats = 0;\n\n\twhile ((c = jas_getopt(argc, argv, cmdoptions)) != EOF) {\n\t\tswitch (c) {\n\t\tcase CMDOPT_HELP:\n\t\t\tcmdopts->help = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_VERBOSE:\n\t\t\tcmdopts->verbose = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_QUIET:\n\t\t\tcmdopts->verbose = -1;\n\t\t\tbreak;\n\t\tcase CMDOPT_VERSION:\n\t\t\tcmdopts->version = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_LIST_ENABLED_CODECS:\n\t\t\tcmdopts->list_codecs = 1;\n\t\t\tcmdopts->list_codecs_all = 0;\n\t\t\tbreak;\n\t\tcase CMDOPT_LIST_ALL_CODECS:\n\t\t\tcmdopts->list_codecs = 1;\n\t\t\tcmdopts->list_codecs_all = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_DEBUG:\n\t\t\tcmdopts->debug = atoi(jas_optarg);\n\t\t\tbreak;\n\t\tcase CMDOPT_INFILE:\n\t\t\tcmdopts->infile = jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_INFMT:\n\t\t\tcmdopts->infmt_str= jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_INOPT:\n\t\t\taddopt(cmdopts->inoptsbuf, OPTSMAX, jas_optarg);\n\t\t\tcmdopts->inopts = cmdopts->inoptsbuf;\n\t\t\tbreak;\n\t\tcase CMDOPT_OUTFILE:\n\t\t\tcmdopts->outfile = jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_OUTFMT:\n\t\t\tcmdopts->outfmt_str = jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_OUTOPT:\n\t\t\taddopt(cmdopts->outoptsbuf, OPTSMAX, jas_optarg);\n\t\t\tcmdopts->outopts = cmdopts->outoptsbuf;\n\t\t\tbreak;\n\t\tcase CMDOPT_CMPTNO:\n\t\t\tcmdopts->cmptno = atoi(jas_optarg);\n\t\t\tbreak;\n\t\tcase CMDOPT_SRGB:\n\t\t\tcmdopts->srgb = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_MAXMEM:\n\t\t\tcmdopts->max_mem = strtoull(jas_optarg, 0, 10);\n\t\t\tbreak;\n\t\tcase CMDOPT_ENABLE_FORMAT:\n\t\t\tcmdopts->enable_format = jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_ENABLE_ALL_FORMATS:\n\t\t\tcmdopts->enable_all_formats = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbadusage();\n\t\t\tbreak;\n\t\t}\n\t}\n\n\twhile (jas_optind < argc) {\n\t\tfprintf(stderr,\n\t\t  \"warning: ignoring bogus command line argument %s\\n\",\n\t\t  argv[jas_optind]);\n\t\t++jas_optind;\n\t}\n\n\tif (cmdopts->version || cmdopts->list_codecs || cmdopts->help) {\n\t\tgoto done;\n\t}\n\n\tif (!cmdopts->outfmt_str && !cmdopts->outfile) {\n\t\tfprintf(stderr, \"error: cannot determine output format\\n\");\n\t\tbadusage();\n\t}\n\ndone:\n\treturn cmdopts;\n}", "func_hash": 93181291511681804073691200897709901657, "file_name": "jasper.c", "file_hash": 221565924886298462326836957771233686713, "cwe": ["CWE-703"], "cve": "CVE-2022-2963", "cve_desc": "A vulnerability found in jasper. This security vulnerability happens because of a memory leak bug in function cmdopts_parse that can cause a crash or segmentation fault.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2963"}
{"idx": 389760, "project": "jasper", "commit_id": "d99636fad60629785efd1ef72da772a8ef68f54c", "project_url": "https://github.com/mdadams/jasper", "commit_url": "https://github.com/jasper-software/jasper/commit/d99636fad60629785efd1ef72da772a8ef68f54c", "commit_message": "fix memory leaks in function cmdopts_parse", "target": 0, "func": "cmdopts_t *cmdopts_parse(int argc, char **argv)\n{\n\tenum {\n\t\tCMDOPT_HELP = 0,\n\t\tCMDOPT_VERBOSE,\n\t\tCMDOPT_QUIET,\n\t\tCMDOPT_INFILE,\n\t\tCMDOPT_INFMT,\n\t\tCMDOPT_INOPT,\n\t\tCMDOPT_OUTFILE,\n\t\tCMDOPT_OUTFMT,\n\t\tCMDOPT_OUTOPT,\n\t\tCMDOPT_VERSION,\n\t\tCMDOPT_DEBUG,\n\t\tCMDOPT_CMPTNO,\n\t\tCMDOPT_SRGB,\n\t\tCMDOPT_MAXMEM,\n\t\tCMDOPT_LIST_ENABLED_CODECS,\n\t\tCMDOPT_LIST_ALL_CODECS,\n\t\tCMDOPT_ENABLE_FORMAT,\n\t\tCMDOPT_ENABLE_ALL_FORMATS,\n\t};\n\n\tstatic const jas_opt_t cmdoptions[] = {\n\t\t{CMDOPT_HELP, \"help\", 0},\n\t\t{CMDOPT_VERBOSE, \"verbose\", 0},\n\t\t{CMDOPT_QUIET, \"quiet\", 0},\n\t\t{CMDOPT_QUIET, \"q\", 0},\n\t\t{CMDOPT_INFILE, \"input\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INFILE, \"f\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INFMT, \"input-format\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INFMT, \"t\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INOPT, \"input-option\", JAS_OPT_HASARG},\n\t\t{CMDOPT_INOPT, \"o\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTFILE, \"output\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTFILE, \"F\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTFMT, \"output-format\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTFMT, \"T\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTOPT, \"output-option\", JAS_OPT_HASARG},\n\t\t{CMDOPT_OUTOPT, \"O\", JAS_OPT_HASARG},\n\t\t{CMDOPT_VERSION, \"version\", 0},\n\t\t{CMDOPT_DEBUG, \"debug-level\", JAS_OPT_HASARG},\n\t\t{CMDOPT_CMPTNO, \"cmptno\", JAS_OPT_HASARG},\n\t\t{CMDOPT_SRGB, \"force-srgb\", 0},\n\t\t{CMDOPT_SRGB, \"S\", 0},\n\t\t{CMDOPT_MAXMEM, \"memory-limit\", JAS_OPT_HASARG},\n\t\t{CMDOPT_LIST_ENABLED_CODECS, \"list-enabled-formats\", 0},\n\t\t{CMDOPT_LIST_ALL_CODECS, \"list-all-formats\", 0},\n\t\t{CMDOPT_ENABLE_FORMAT, \"enable-format\", JAS_OPT_HASARG},\n\t\t{CMDOPT_ENABLE_ALL_FORMATS, \"enable-all-formats\", 0},\n\t\t{-1, 0, 0}\n\t};\n\n\tcmdopts_t *cmdopts;\n\tint c;\n\n\tif (!(cmdopts = malloc(sizeof(cmdopts_t)))) {\n\t\tfprintf(stderr, \"error: insufficient memory\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tcmdopts->infile = 0;\n\tcmdopts->infmt = -1;\n\tcmdopts->infmt_str = 0;\n\tcmdopts->inopts = 0;\n\tcmdopts->inoptsbuf[0] = '\\0';\n\tcmdopts->outfile = 0;\n\tcmdopts->outfmt = -1;\n\tcmdopts->outfmt_str = 0;\n\tcmdopts->outopts = 0;\n\tcmdopts->outoptsbuf[0] = '\\0';\n\tcmdopts->verbose = 0;\n\tcmdopts->version = 0;\n\tcmdopts->cmptno = -1;\n\tcmdopts->debug = 0;\n\tcmdopts->srgb = 0;\n\tcmdopts->list_codecs = 0;\n\tcmdopts->list_codecs_all = 0;\n\tcmdopts->help = 0;\n\tcmdopts->max_mem = get_default_max_mem_usage();\n\tcmdopts->enable_format = 0;\n\tcmdopts->enable_all_formats = 0;\n\n\twhile ((c = jas_getopt(argc, argv, cmdoptions)) != EOF) {\n\t\tswitch (c) {\n\t\tcase CMDOPT_HELP:\n\t\t\tcmdopts->help = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_VERBOSE:\n\t\t\tcmdopts->verbose = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_QUIET:\n\t\t\tcmdopts->verbose = -1;\n\t\t\tbreak;\n\t\tcase CMDOPT_VERSION:\n\t\t\tcmdopts->version = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_LIST_ENABLED_CODECS:\n\t\t\tcmdopts->list_codecs = 1;\n\t\t\tcmdopts->list_codecs_all = 0;\n\t\t\tbreak;\n\t\tcase CMDOPT_LIST_ALL_CODECS:\n\t\t\tcmdopts->list_codecs = 1;\n\t\t\tcmdopts->list_codecs_all = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_DEBUG:\n\t\t\tcmdopts->debug = atoi(jas_optarg);\n\t\t\tbreak;\n\t\tcase CMDOPT_INFILE:\n\t\t\tcmdopts->infile = jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_INFMT:\n\t\t\tcmdopts->infmt_str= jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_INOPT:\n\t\t\taddopt(cmdopts->inoptsbuf, OPTSMAX, jas_optarg);\n\t\t\tcmdopts->inopts = cmdopts->inoptsbuf;\n\t\t\tbreak;\n\t\tcase CMDOPT_OUTFILE:\n\t\t\tcmdopts->outfile = jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_OUTFMT:\n\t\t\tcmdopts->outfmt_str = jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_OUTOPT:\n\t\t\taddopt(cmdopts->outoptsbuf, OPTSMAX, jas_optarg);\n\t\t\tcmdopts->outopts = cmdopts->outoptsbuf;\n\t\t\tbreak;\n\t\tcase CMDOPT_CMPTNO:\n\t\t\tcmdopts->cmptno = atoi(jas_optarg);\n\t\t\tbreak;\n\t\tcase CMDOPT_SRGB:\n\t\t\tcmdopts->srgb = 1;\n\t\t\tbreak;\n\t\tcase CMDOPT_MAXMEM:\n\t\t\tcmdopts->max_mem = strtoull(jas_optarg, 0, 10);\n\t\t\tbreak;\n\t\tcase CMDOPT_ENABLE_FORMAT:\n\t\t\tcmdopts->enable_format = jas_optarg;\n\t\t\tbreak;\n\t\tcase CMDOPT_ENABLE_ALL_FORMATS:\n\t\t\tcmdopts->enable_all_formats = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcmdopts_destroy(cmdopts);\n\t\t\tbadusage();\n\t\t\tbreak;\n\t\t}\n\t}\n\n\twhile (jas_optind < argc) {\n\t\tfprintf(stderr,\n\t\t  \"warning: ignoring bogus command line argument %s\\n\",\n\t\t  argv[jas_optind]);\n\t\t++jas_optind;\n\t}\n\n\tif (cmdopts->version || cmdopts->list_codecs || cmdopts->help) {\n\t\tgoto done;\n\t}\n\n\tif (!cmdopts->outfmt_str && !cmdopts->outfile) {\n\t\tfprintf(stderr, \"error: cannot determine output format\\n\");\n\t\tcmdopts_destroy(cmdopts);\n\t\tbadusage();\n\t}\n\ndone:\n\treturn cmdopts;\n}", "func_hash": 102932853856682606703676466444383538610, "file_name": "jasper.c", "file_hash": 43318189901043805005058339060588403940, "cwe": ["CWE-703"], "cve": "CVE-2022-2963", "cve_desc": "A vulnerability found in jasper. This security vulnerability happens because of a memory leak bug in function cmdopts_parse that can cause a crash or segmentation fault.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2963"}
{"idx": 207068, "project": "linux", "commit_id": "cc7a0bb058b85ea03db87169c60c7cfdd5d34678", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=cc7a0bb058b85ea03db87169c60c7cfdd5d34678", "commit_message": "PCI: rpadlpar: Fix potential drc_name corruption in store functions\n\nBoth add_slot_store() and remove_slot_store() try to fix up the\ndrc_name copied from the store buffer by placing a NUL terminator at\nnbyte + 1 or in place of a '\\n' if present. However, the static buffer\nthat we copy the drc_name data into is not zeroed and can contain\nanything past the n-th byte.\n\nThis is problematic if a '\\n' byte appears in that buffer after nbytes\nand the string copied into the store buffer was not NUL terminated to\nstart with as the strchr() search for a '\\n' byte will mark this\nincorrectly as the end of the drc_name string resulting in a drc_name\nstring that contains garbage data after the n-th byte.\n\nAdditionally it will cause us to overwrite that '\\n' byte on the stack\nwith NUL, potentially corrupting data on the stack.\n\nThe following debugging shows an example of the drmgr utility writing\n\"PHB 4543\" to the add_slot sysfs attribute, but add_slot_store()\nlogging a corrupted string value.\n\n  drmgr: drmgr: -c phb -a -s PHB 4543 -d 1\n  add_slot_store: drc_name = PHB 4543\u00b0|<82>!, rc = -19\n\nFix this by using strscpy() instead of memcpy() to ensure the string\nis NUL terminated when copied into the static drc_name buffer.\nFurther, since the string is now NUL terminated the code only needs to\nchange '\\n' to '\\0' when present.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Tyrel Datwyler \n[mpe: Reformat change log and add mention of possible stack corruption]\nSigned-off-by: Michael Ellerman \nLink: https://lore.kernel.org/r/20210315214821.452959-1-tyreld@linux.ibm.com", "target": 1, "func": "static ssize_t remove_slot_store(struct kobject *kobj,\n\t\t\t\t struct kobj_attribute *attr,\n\t\t\t\t const char *buf, size_t nbytes)\n{\n\tchar drc_name[MAX_DRC_NAME_LEN];\n\tint rc;\n\tchar *end;\n\n\tif (nbytes >= MAX_DRC_NAME_LEN)\n\t\treturn 0;\n\n\tmemcpy(drc_name, buf, nbytes);\n\n\tend = strchr(drc_name, '\\n');\n\tif (!end)\n\t\tend = &drc_name[nbytes];\n\t*end = '\\0';\n\n\trc = dlpar_remove_slot(drc_name);\n\tif (rc)\n\t\treturn rc;\n\n\treturn nbytes;\n}", "func_hash": 237293762490436147707541740545065202667, "file_name": "rpadlpar_sysfs.c", "file_hash": 143265511624763705093739678134289779335, "cwe": ["CWE-120"], "cve": "CVE-2021-28972", "cve_desc": "In drivers/pci/hotplug/rpadlpar_sysfs.c in the Linux kernel through 5.11.8, the RPA PCI Hotplug driver has a user-tolerable buffer overflow when writing a new device name to the driver from userspace, allowing userspace to write data to the kernel stack frame directly. This occurs because add_slot_store and remove_slot_store mishandle drc_name '\\0' termination, aka CID-cc7a0bb058b8.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28972"}
{"idx": 391627, "project": "linux", "commit_id": "cc7a0bb058b85ea03db87169c60c7cfdd5d34678", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=cc7a0bb058b85ea03db87169c60c7cfdd5d34678", "commit_message": "PCI: rpadlpar: Fix potential drc_name corruption in store functions\n\nBoth add_slot_store() and remove_slot_store() try to fix up the\ndrc_name copied from the store buffer by placing a NUL terminator at\nnbyte + 1 or in place of a '\\n' if present. However, the static buffer\nthat we copy the drc_name data into is not zeroed and can contain\nanything past the n-th byte.\n\nThis is problematic if a '\\n' byte appears in that buffer after nbytes\nand the string copied into the store buffer was not NUL terminated to\nstart with as the strchr() search for a '\\n' byte will mark this\nincorrectly as the end of the drc_name string resulting in a drc_name\nstring that contains garbage data after the n-th byte.\n\nAdditionally it will cause us to overwrite that '\\n' byte on the stack\nwith NUL, potentially corrupting data on the stack.\n\nThe following debugging shows an example of the drmgr utility writing\n\"PHB 4543\" to the add_slot sysfs attribute, but add_slot_store()\nlogging a corrupted string value.\n\n  drmgr: drmgr: -c phb -a -s PHB 4543 -d 1\n  add_slot_store: drc_name = PHB 4543\u00b0|<82>!, rc = -19\n\nFix this by using strscpy() instead of memcpy() to ensure the string\nis NUL terminated when copied into the static drc_name buffer.\nFurther, since the string is now NUL terminated the code only needs to\nchange '\\n' to '\\0' when present.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Tyrel Datwyler \n[mpe: Reformat change log and add mention of possible stack corruption]\nSigned-off-by: Michael Ellerman \nLink: https://lore.kernel.org/r/20210315214821.452959-1-tyreld@linux.ibm.com", "target": 0, "func": "static ssize_t remove_slot_store(struct kobject *kobj,\n\t\t\t\t struct kobj_attribute *attr,\n\t\t\t\t const char *buf, size_t nbytes)\n{\n\tchar drc_name[MAX_DRC_NAME_LEN];\n\tint rc;\n\tchar *end;\n\n\tif (nbytes >= MAX_DRC_NAME_LEN)\n\t\treturn 0;\n\n\tstrscpy(drc_name, buf, nbytes + 1);\n\n\tend = strchr(drc_name, '\\n');\n\tif (end)\n\t\t*end = '\\0';\n\n\trc = dlpar_remove_slot(drc_name);\n\tif (rc)\n\t\treturn rc;\n\n\treturn nbytes;\n}", "func_hash": 228561592734793467772177551896912743936, "file_name": "rpadlpar_sysfs.c", "file_hash": 21668029196687947173345261458760783896, "cwe": ["CWE-120"], "cve": "CVE-2021-28972", "cve_desc": "In drivers/pci/hotplug/rpadlpar_sysfs.c in the Linux kernel through 5.11.8, the RPA PCI Hotplug driver has a user-tolerable buffer overflow when writing a new device name to the driver from userspace, allowing userspace to write data to the kernel stack frame directly. This occurs because add_slot_store and remove_slot_store mishandle drc_name '\\0' termination, aka CID-cc7a0bb058b8.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28972"}
{"idx": 207069, "project": "linux", "commit_id": "cc7a0bb058b85ea03db87169c60c7cfdd5d34678", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=cc7a0bb058b85ea03db87169c60c7cfdd5d34678", "commit_message": "PCI: rpadlpar: Fix potential drc_name corruption in store functions\n\nBoth add_slot_store() and remove_slot_store() try to fix up the\ndrc_name copied from the store buffer by placing a NUL terminator at\nnbyte + 1 or in place of a '\\n' if present. However, the static buffer\nthat we copy the drc_name data into is not zeroed and can contain\nanything past the n-th byte.\n\nThis is problematic if a '\\n' byte appears in that buffer after nbytes\nand the string copied into the store buffer was not NUL terminated to\nstart with as the strchr() search for a '\\n' byte will mark this\nincorrectly as the end of the drc_name string resulting in a drc_name\nstring that contains garbage data after the n-th byte.\n\nAdditionally it will cause us to overwrite that '\\n' byte on the stack\nwith NUL, potentially corrupting data on the stack.\n\nThe following debugging shows an example of the drmgr utility writing\n\"PHB 4543\" to the add_slot sysfs attribute, but add_slot_store()\nlogging a corrupted string value.\n\n  drmgr: drmgr: -c phb -a -s PHB 4543 -d 1\n  add_slot_store: drc_name = PHB 4543\u00b0|<82>!, rc = -19\n\nFix this by using strscpy() instead of memcpy() to ensure the string\nis NUL terminated when copied into the static drc_name buffer.\nFurther, since the string is now NUL terminated the code only needs to\nchange '\\n' to '\\0' when present.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Tyrel Datwyler \n[mpe: Reformat change log and add mention of possible stack corruption]\nSigned-off-by: Michael Ellerman \nLink: https://lore.kernel.org/r/20210315214821.452959-1-tyreld@linux.ibm.com", "target": 1, "func": "static ssize_t add_slot_store(struct kobject *kobj, struct kobj_attribute *attr,\n\t\t\t      const char *buf, size_t nbytes)\n{\n\tchar drc_name[MAX_DRC_NAME_LEN];\n\tchar *end;\n\tint rc;\n\n\tif (nbytes >= MAX_DRC_NAME_LEN)\n\t\treturn 0;\n\n\tmemcpy(drc_name, buf, nbytes);\n\n\tend = strchr(drc_name, '\\n');\n\tif (!end)\n\t\tend = &drc_name[nbytes];\n\t*end = '\\0';\n\n\trc = dlpar_add_slot(drc_name);\n\tif (rc)\n\t\treturn rc;\n\n\treturn nbytes;\n}", "func_hash": 262261814389997886159936729256803084500, "file_name": "rpadlpar_sysfs.c", "file_hash": 143265511624763705093739678134289779335, "cwe": ["CWE-120"], "cve": "CVE-2021-28972", "cve_desc": "In drivers/pci/hotplug/rpadlpar_sysfs.c in the Linux kernel through 5.11.8, the RPA PCI Hotplug driver has a user-tolerable buffer overflow when writing a new device name to the driver from userspace, allowing userspace to write data to the kernel stack frame directly. This occurs because add_slot_store and remove_slot_store mishandle drc_name '\\0' termination, aka CID-cc7a0bb058b8.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28972"}
{"idx": 391628, "project": "linux", "commit_id": "cc7a0bb058b85ea03db87169c60c7cfdd5d34678", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=cc7a0bb058b85ea03db87169c60c7cfdd5d34678", "commit_message": "PCI: rpadlpar: Fix potential drc_name corruption in store functions\n\nBoth add_slot_store() and remove_slot_store() try to fix up the\ndrc_name copied from the store buffer by placing a NUL terminator at\nnbyte + 1 or in place of a '\\n' if present. However, the static buffer\nthat we copy the drc_name data into is not zeroed and can contain\nanything past the n-th byte.\n\nThis is problematic if a '\\n' byte appears in that buffer after nbytes\nand the string copied into the store buffer was not NUL terminated to\nstart with as the strchr() search for a '\\n' byte will mark this\nincorrectly as the end of the drc_name string resulting in a drc_name\nstring that contains garbage data after the n-th byte.\n\nAdditionally it will cause us to overwrite that '\\n' byte on the stack\nwith NUL, potentially corrupting data on the stack.\n\nThe following debugging shows an example of the drmgr utility writing\n\"PHB 4543\" to the add_slot sysfs attribute, but add_slot_store()\nlogging a corrupted string value.\n\n  drmgr: drmgr: -c phb -a -s PHB 4543 -d 1\n  add_slot_store: drc_name = PHB 4543\u00b0|<82>!, rc = -19\n\nFix this by using strscpy() instead of memcpy() to ensure the string\nis NUL terminated when copied into the static drc_name buffer.\nFurther, since the string is now NUL terminated the code only needs to\nchange '\\n' to '\\0' when present.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Tyrel Datwyler \n[mpe: Reformat change log and add mention of possible stack corruption]\nSigned-off-by: Michael Ellerman \nLink: https://lore.kernel.org/r/20210315214821.452959-1-tyreld@linux.ibm.com", "target": 0, "func": "static ssize_t add_slot_store(struct kobject *kobj, struct kobj_attribute *attr,\n\t\t\t      const char *buf, size_t nbytes)\n{\n\tchar drc_name[MAX_DRC_NAME_LEN];\n\tchar *end;\n\tint rc;\n\n\tif (nbytes >= MAX_DRC_NAME_LEN)\n\t\treturn 0;\n\n\tstrscpy(drc_name, buf, nbytes + 1);\n\n\tend = strchr(drc_name, '\\n');\n\tif (end)\n\t\t*end = '\\0';\n\n\trc = dlpar_add_slot(drc_name);\n\tif (rc)\n\t\treturn rc;\n\n\treturn nbytes;\n}", "func_hash": 228230730882908285016023798985921663046, "file_name": "rpadlpar_sysfs.c", "file_hash": 21668029196687947173345261458760783896, "cwe": ["CWE-120"], "cve": "CVE-2021-28972", "cve_desc": "In drivers/pci/hotplug/rpadlpar_sysfs.c in the Linux kernel through 5.11.8, the RPA PCI Hotplug driver has a user-tolerable buffer overflow when writing a new device name to the driver from userspace, allowing userspace to write data to the kernel stack frame directly. This occurs because add_slot_store and remove_slot_store mishandle drc_name '\\0' termination, aka CID-cc7a0bb058b8.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-28972"}
{"idx": 207150, "project": "squirrel", "commit_id": "a6413aa690e0bdfef648c68693349a7b878fe60d", "project_url": "https://github.com/albertodemichelis/squirrel", "commit_url": "https://github.com/albertodemichelis/squirrel/commit/a6413aa690e0bdfef648c68693349a7b878fe60d", "commit_message": "fix in thread.call", "target": 1, "func": "static SQInteger thread_call(HSQUIRRELVM v)\n{\n    SQObjectPtr o = stack_get(v,1);\n    if(sq_type(o) == OT_THREAD) {\n        SQInteger nparams = sq_gettop(v);\n        _thread(o)->Push(_thread(o)->_roottable);\n        for(SQInteger i = 2; i<(nparams+1); i++)\n            sq_move(_thread(o),v,i);\n        if(SQ_SUCCEEDED(sq_call(_thread(o),nparams,SQTrue,SQTrue))) {\n            sq_move(v,_thread(o),-1);\n            sq_pop(_thread(o),1);\n            return 1;\n        }\n        v->_lasterror = _thread(o)->_lasterror;\n        return SQ_ERROR;\n    }\n    return sq_throwerror(v,_SC(\"wrong parameter\"));\n}", "func_hash": 39783972208477930534182111058478291044, "file_name": "sqbaselib.cpp", "file_hash": 22214130882110251892898581176850711195, "cwe": ["CWE-703"], "cve": "CVE-2022-30292", "cve_desc": "Heap-based buffer overflow in sqbaselib.cpp in SQUIRREL 3.2 due to lack of a certain sq_reservestack call.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-30292"}
{"idx": 393528, "project": "squirrel", "commit_id": "a6413aa690e0bdfef648c68693349a7b878fe60d", "project_url": "https://github.com/albertodemichelis/squirrel", "commit_url": "https://github.com/albertodemichelis/squirrel/commit/a6413aa690e0bdfef648c68693349a7b878fe60d", "commit_message": "fix in thread.call", "target": 0, "func": "static SQInteger thread_call(HSQUIRRELVM v)\n{\n    SQObjectPtr o = stack_get(v,1);\n    if(sq_type(o) == OT_THREAD) {\n        SQInteger nparams = sq_gettop(v);\n        sq_reservestack(_thread(o), nparams + 3);\n        _thread(o)->Push(_thread(o)->_roottable);\n        for(SQInteger i = 2; i<(nparams+1); i++)\n            sq_move(_thread(o),v,i);\n        if(SQ_SUCCEEDED(sq_call(_thread(o),nparams,SQTrue,SQTrue))) {\n            sq_move(v,_thread(o),-1);\n            sq_pop(_thread(o),1);\n            return 1;\n        }\n        v->_lasterror = _thread(o)->_lasterror;\n        return SQ_ERROR;\n    }\n    return sq_throwerror(v,_SC(\"wrong parameter\"));\n}", "func_hash": 185870701968227218426869749475686341047, "file_name": "sqbaselib.cpp", "file_hash": 167918424394936848193603192917033144376, "cwe": ["CWE-703"], "cve": "CVE-2022-30292", "cve_desc": "Heap-based buffer overflow in sqbaselib.cpp in SQUIRREL 3.2 due to lack of a certain sq_reservestack call.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-30292"}
{"idx": 207461, "project": "autotrace", "commit_id": "e96bffadc25ff0ba0e10745f8012efcc5f920ea9", "project_url": "https://github.com/autotrace/autotrace", "commit_url": "https://github.com/autotrace/autotrace/commit/e96bffadc25ff0ba0e10745f8012efcc5f920ea9", "commit_message": "input-bmp: Increase header buffer in some cases\n\nSigned-off-by: Peter Lemenkov ", "target": 1, "func": "at_bitmap input_bmp_reader(gchar * filename, at_input_opts_type * opts, at_msg_func msg_func, gpointer msg_data, gpointer user_data)\n{\n  FILE *fd;\n  unsigned char buffer[64];\n  int ColormapSize, rowbytes, Maps;\n  gboolean Grey = FALSE;\n  unsigned char ColorMap[256][3];\n  at_bitmap image = at_bitmap_init(0, 0, 0, 1);\n  unsigned char *image_storage;\n  at_exception_type exp = at_exception_new(msg_func, msg_data);\n  char magick[2];\n  Bitmap_Channel masks[4];\n\n  fd = fopen(filename, \"rb\");\n\n  if (!fd) {\n    LOG(\"Can't open \\\"%s\\\"\\n\", filename);\n    at_exception_fatal(&exp, \"bmp: cannot open input file\");\n    goto cleanup;\n  }\n\n  /* It is a File. Now is it a Bitmap? Read the shortest possible header. */\n\n  if (!ReadOK(fd, magick, 2) ||\n\t  !(!strncmp(magick, \"BA\", 2) ||\n\t\t  !strncmp(magick, \"BM\", 2) ||\n\t\t  !strncmp(magick, \"IC\", 2) ||\n\t\t  !strncmp(magick, \"PT\", 2) ||\n\t\t  !strncmp(magick, \"CI\", 2) ||\n\t\t  !strncmp(magick, \"CP\", 2)))\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  while (!strncmp(magick, \"BA\", 2))\n  {\n\t  if (!ReadOK(fd, buffer, 12))\n\t  {\n\t\t  LOG(\"%s is not a valid BMP file\", filename);\n\t\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t\t  goto cleanup;\n\t  }\n\n\t  if (!ReadOK(fd, magick, 2))\n\t  {\n\t\t  LOG(\"%s is not a valid BMP file\", filename);\n\t\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t\t  goto cleanup;\n\t  }\n  }\n\n  if (!ReadOK(fd, buffer, 12))////\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  /* bring them to the right byteorder. Not too nice, but it should work */\n\n  Bitmap_File_Head.bfSize = ToL(&buffer[0x00]);\n  Bitmap_File_Head.zzHotX = ToS(&buffer[0x04]);\n  Bitmap_File_Head.zzHotY = ToS(&buffer[0x06]);\n  Bitmap_File_Head.bfOffs = ToL(&buffer[0x08]);\n\n  if (!ReadOK(fd, buffer, 4))\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  Bitmap_File_Head.biSize = ToL(&buffer[0x00]);\n\n  /* What kind of bitmap is it? */\n\n  if (Bitmap_File_Head.biSize == 12) {  /* OS/2 1.x ? */\n    if (!ReadOK(fd, buffer, 8)) {\n      LOG(\"Error reading BMP file header\\n\");\n      at_exception_fatal(&exp, \"Error reading BMP file header\");\n      goto cleanup;\n    }\n\n    Bitmap_Head.biWidth = ToS(&buffer[0x00]); /* 12 */\n    Bitmap_Head.biHeight = ToS(&buffer[0x02]);  /* 14 */\n    Bitmap_Head.biPlanes = ToS(&buffer[0x04]);  /* 16 */\n    Bitmap_Head.biBitCnt = ToS(&buffer[0x06]);  /* 18 */\n    Bitmap_Head.biCompr = 0;\n    Bitmap_Head.biSizeIm = 0;\n    Bitmap_Head.biXPels = Bitmap_Head.biYPels = 0;\n    Bitmap_Head.biClrUsed = 0;\n    Bitmap_Head.biClrImp = 0;\n    Bitmap_Head.masks[0] = 0;\n    Bitmap_Head.masks[1] = 0;\n    Bitmap_Head.masks[2] = 0;\n    Bitmap_Head.masks[3] = 0;\n\n    memset(masks, 0, sizeof(masks));\n    Maps = 3;\n\n  } else if (Bitmap_File_Head.biSize == 40) { /* Windows 3.x */\n    if (!ReadOK(fd, buffer, 36))\n    {\n      LOG (\"Error reading BMP file header\\n\");\n      at_exception_fatal(&exp, \"Error reading BMP file header\");\n      goto cleanup;\n    }\n          \n\n    Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */\n    Bitmap_Head.biHeight = ToL(&buffer[0x04]);  /* 16 */\n    Bitmap_Head.biPlanes = ToS(&buffer[0x08]);  /* 1A */\n    Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);  /* 1C */\n    Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */\n    Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);  /* 22 */\n    Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */\n    Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */\n    Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */\n    Bitmap_Head.biClrImp = ToL(&buffer[0x20]);  /* 32 */\n    Bitmap_Head.masks[0] = 0;\n    Bitmap_Head.masks[1] = 0;\n    Bitmap_Head.masks[2] = 0;\n    Bitmap_Head.masks[3] = 0;\n\n    Maps = 4;\n    memset(masks, 0, sizeof(masks));\n\n    if (Bitmap_Head.biCompr == BI_BITFIELDS)\n      {\n\tif (!ReadOK(fd, buffer, 3 * sizeof(unsigned long)))\n\t  {\n\t    LOG(\"Error reading BMP file header\\n\");\n\t    at_exception_fatal(&exp, \"Error reading BMP file header\");\n\t    goto cleanup;\n\t  }\n\n\tBitmap_Head.masks[0] = ToL(&buffer[0x00]);\n\tBitmap_Head.masks[1] = ToL(&buffer[0x04]);\n\tBitmap_Head.masks[2] = ToL(&buffer[0x08]);\n\n\tReadChannelMasks(&Bitmap_Head.masks[0], masks, 3);\n      }\n    else if (Bitmap_Head.biCompr == BI_RGB)\n      {\n\tsetMasksDefault(Bitmap_Head.biBitCnt, masks);\n      }\n    else if ((Bitmap_Head.biCompr != BI_RLE4) &&\n\t     (Bitmap_Head.biCompr != BI_RLE8))\n      {\n\t/* BI_ALPHABITFIELDS, etc. */\n\tLOG(\"Unsupported compression in BMP file\\n\");\n\tat_exception_fatal(&exp, \"Unsupported compression in BMP file\");\n\tgoto cleanup;\n      }\n  }\n  else if (Bitmap_File_Head.biSize >= 56 &&\n\t   Bitmap_File_Head.biSize <= 64)\n  {\n    /* enhanced Windows format with bit masks */\n\n    if (!ReadOK (fd, buffer, Bitmap_File_Head.biSize - 4))\n    {\n\n      LOG(\"Error reading BMP file header\\n\");\n      at_exception_fatal(&exp, \"Error reading BMP file header\");\n      goto cleanup;\n    }\n\n    Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */\n    Bitmap_Head.biHeight = ToL(&buffer[0x04]);  /* 16 */\n    Bitmap_Head.biPlanes = ToS(&buffer[0x08]);  /* 1A */\n    Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);  /* 1C */\n    Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */\n    Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);  /* 22 */\n    Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */\n    Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */\n    Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */\n    Bitmap_Head.biClrImp = ToL(&buffer[0x20]);  /* 32 */\n    Bitmap_Head.masks[0] = ToL(&buffer[0x24]);       /* 36 */\n    Bitmap_Head.masks[1] = ToL(&buffer[0x28]);       /* 3A */\n    Bitmap_Head.masks[2] = ToL(&buffer[0x2C]);       /* 3E */\n    Bitmap_Head.masks[3] = ToL(&buffer[0x30]);       /* 42 */\n\n    Maps = 4;\n    ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);\n  }\n  else if (Bitmap_File_Head.biSize == 108 ||\n           Bitmap_File_Head.biSize == 124)\n  {\n    /* BMP Version 4 or 5 */\n\n    if (!ReadOK(fd, buffer, Bitmap_File_Head.biSize - 4))\n    {\n\t    LOG(\"Error reading BMP file header\\n\");\n\t    at_exception_fatal(&exp, \"Error reading BMP file header\");\n\t    goto cleanup;\n    }\n\n    Bitmap_Head.biWidth = ToL(&buffer[0x00]);\n    Bitmap_Head.biHeight = ToL(&buffer[0x04]);\n    Bitmap_Head.biPlanes = ToS(&buffer[0x08]);\n    Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);\n    Bitmap_Head.biCompr = ToL(&buffer[0x0C]);\n    Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);\n    Bitmap_Head.biXPels = ToL(&buffer[0x14]);\n    Bitmap_Head.biYPels = ToL(&buffer[0x18]);\n    Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]);\n    Bitmap_Head.biClrImp = ToL(&buffer[0x20]);\n    Bitmap_Head.masks[0] = ToL(&buffer[0x24]);\n    Bitmap_Head.masks[1] = ToL(&buffer[0x28]);\n    Bitmap_Head.masks[2] = ToL(&buffer[0x2C]);\n    Bitmap_Head.masks[3] = ToL(&buffer[0x30]);\n\n    Maps = 4;\n\n    if (Bitmap_Head.biCompr == BI_BITFIELDS)\n    {\n\t    ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);\n    }\n    else if (Bitmap_Head.biCompr == BI_RGB)\n    {\n\t    setMasksDefault(Bitmap_Head.biBitCnt, masks);\n    }\n  } else {\n    LOG(\"Error reading BMP file header\\n\");\n    at_exception_fatal(&exp, \"Error reading BMP file header\");\n    goto cleanup;\n  }\n\n  /* Valid options 1, 4, 8, 16, 24, 32 */\n  /* 16 is awful, we should probably shoot whoever invented it */\n\n  switch (Bitmap_Head.biBitCnt)\n  {\n  case 1:\n  case 2:\n  case 4:\n  case 8:\n  case 16:\n  case 24:\n  case 32:\n\t  break;\n  default:\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  /* There should be some colors used! */\n\n  ColormapSize = (Bitmap_File_Head.bfOffs - Bitmap_File_Head.biSize - 14) / Maps;\n\n  if ((Bitmap_Head.biClrUsed == 0) &&\n      (Bitmap_Head.biBitCnt <= 8))\n  {\n\t  ColormapSize = Bitmap_Head.biClrUsed = 1 << Bitmap_Head.biBitCnt;\n  }\n\n  if (ColormapSize > 256)\n    ColormapSize = 256;\n\n  /* Sanity checks */\n\n  if (Bitmap_Head.biHeight == 0 ||\n\t  Bitmap_Head.biWidth == 0)\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  /* biHeight may be negative, but -2147483648 is dangerous because:\n\t -2147483648 == -(-2147483648) */\n  if (Bitmap_Head.biWidth < 0 ||\n\t  Bitmap_Head.biHeight == -2147483648)\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  if (Bitmap_Head.biPlanes != 1)\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  if (Bitmap_Head.biClrUsed > 256 &&\n\t  Bitmap_Head.biBitCnt <= 8)\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  /* protect against integer overflows caused by malicious BMPs */\n  /* use divisions in comparisons to avoid type overflows */\n\n  if (((unsigned long)Bitmap_Head.biWidth) > (unsigned int)0x7fffffff / Bitmap_Head.biBitCnt ||\n\t  ((unsigned long)Bitmap_Head.biWidth) > ((unsigned int)0x7fffffff /abs(Bitmap_Head.biHeight)) / 4)\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  /* Windows and OS/2 declare filler so that rows are a multiple of\n   * word length (32 bits == 4 bytes)\n   */\n   \n  unsigned long overflowTest = Bitmap_Head.biWidth * Bitmap_Head.biBitCnt;\n  if (overflowTest / Bitmap_Head.biWidth != Bitmap_Head.biBitCnt) {\n    LOG(\"Error reading BMP file header. Width is too large\\n\");\n    at_exception_fatal(&exp, \"Error reading BMP file header. Width is too large\");\n    goto cleanup;\n  }\n\n  rowbytes = ((Bitmap_Head.biWidth * Bitmap_Head.biBitCnt - 1) / 32) * 4 + 4;\n\n#ifdef DEBUG\n  printf(\"\\nSize: %u, Colors: %u, Bits: %u, Width: %u, Height: %u, Comp: %u, Zeile: %u\\n\", Bitmap_File_Head.bfSize, Bitmap_Head.biClrUsed, Bitmap_Head.biBitCnt, Bitmap_Head.biWidth, Bitmap_Head.biHeight, Bitmap_Head.biCompr, rowbytes);\n#endif\n\n\n  if (Bitmap_Head.biBitCnt <= 8)\n  {\n#ifdef DEBUG\n    printf(\"Colormap read\\n\");\n#endif\n\t  /* Get the Colormap */\n\t  if (!ReadColorMap(fd, ColorMap, ColormapSize, Maps, &Grey, &exp))\n\t\t  goto cleanup;\n  }\n\n  fseek(fd, Bitmap_File_Head.bfOffs, SEEK_SET);\n\n  /* Get the Image and return the ID or -1 on error */\n  image_storage = ReadImage(fd, \n\tBitmap_Head.biWidth, Bitmap_Head.biHeight,\n\tColorMap,\n        Bitmap_Head.biClrUsed,\n\tBitmap_Head.biBitCnt, Bitmap_Head.biCompr, rowbytes,\n        Grey,\n\tmasks,\n\t&exp);\n\n  image = at_bitmap_init(image_storage, (unsigned short)Bitmap_Head.biWidth, (unsigned short)Bitmap_Head.biHeight, Grey ? 1 : 3);\ncleanup:\n  fclose(fd);\n  return (image);\n}", "func_hash": 217805098145205715295086602544452101199, "file_name": "input-bmp.c", "file_hash": 38605146891124325135879659140059354528, "cwe": ["CWE-787"], "cve": "CVE-2022-32323", "cve_desc": "AutoTrace v0.40.0 was discovered to contain a heap overflow via the ReadImage function at input-bmp.c:660.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32323"}
{"idx": 397644, "project": "autotrace", "commit_id": "e96bffadc25ff0ba0e10745f8012efcc5f920ea9", "project_url": "https://github.com/autotrace/autotrace", "commit_url": "https://github.com/autotrace/autotrace/commit/e96bffadc25ff0ba0e10745f8012efcc5f920ea9", "commit_message": "input-bmp: Increase header buffer in some cases\n\nSigned-off-by: Peter Lemenkov ", "target": 0, "func": "at_bitmap input_bmp_reader(gchar * filename, at_input_opts_type * opts, at_msg_func msg_func, gpointer msg_data, gpointer user_data)\n{\n  FILE *fd;\n  unsigned char buffer[128];\n  int ColormapSize, rowbytes, Maps;\n  gboolean Grey = FALSE;\n  unsigned char ColorMap[256][3];\n  at_bitmap image = at_bitmap_init(0, 0, 0, 1);\n  unsigned char *image_storage;\n  at_exception_type exp = at_exception_new(msg_func, msg_data);\n  char magick[2];\n  Bitmap_Channel masks[4];\n\n  fd = fopen(filename, \"rb\");\n\n  if (!fd) {\n    LOG(\"Can't open \\\"%s\\\"\\n\", filename);\n    at_exception_fatal(&exp, \"bmp: cannot open input file\");\n    goto cleanup;\n  }\n\n  /* It is a File. Now is it a Bitmap? Read the shortest possible header. */\n\n  if (!ReadOK(fd, magick, 2) ||\n\t  !(!strncmp(magick, \"BA\", 2) ||\n\t\t  !strncmp(magick, \"BM\", 2) ||\n\t\t  !strncmp(magick, \"IC\", 2) ||\n\t\t  !strncmp(magick, \"PT\", 2) ||\n\t\t  !strncmp(magick, \"CI\", 2) ||\n\t\t  !strncmp(magick, \"CP\", 2)))\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  while (!strncmp(magick, \"BA\", 2))\n  {\n\t  if (!ReadOK(fd, buffer, 12))\n\t  {\n\t\t  LOG(\"%s is not a valid BMP file\", filename);\n\t\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t\t  goto cleanup;\n\t  }\n\n\t  if (!ReadOK(fd, magick, 2))\n\t  {\n\t\t  LOG(\"%s is not a valid BMP file\", filename);\n\t\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t\t  goto cleanup;\n\t  }\n  }\n\n  if (!ReadOK(fd, buffer, 12))////\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  /* bring them to the right byteorder. Not too nice, but it should work */\n\n  Bitmap_File_Head.bfSize = ToL(&buffer[0x00]);\n  Bitmap_File_Head.zzHotX = ToS(&buffer[0x04]);\n  Bitmap_File_Head.zzHotY = ToS(&buffer[0x06]);\n  Bitmap_File_Head.bfOffs = ToL(&buffer[0x08]);\n\n  if (!ReadOK(fd, buffer, 4))\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  Bitmap_File_Head.biSize = ToL(&buffer[0x00]);\n\n  /* What kind of bitmap is it? */\n\n  if (Bitmap_File_Head.biSize == 12) {  /* OS/2 1.x ? */\n    if (!ReadOK(fd, buffer, 8)) {\n      LOG(\"Error reading BMP file header\\n\");\n      at_exception_fatal(&exp, \"Error reading BMP file header\");\n      goto cleanup;\n    }\n\n    Bitmap_Head.biWidth = ToS(&buffer[0x00]); /* 12 */\n    Bitmap_Head.biHeight = ToS(&buffer[0x02]);  /* 14 */\n    Bitmap_Head.biPlanes = ToS(&buffer[0x04]);  /* 16 */\n    Bitmap_Head.biBitCnt = ToS(&buffer[0x06]);  /* 18 */\n    Bitmap_Head.biCompr = 0;\n    Bitmap_Head.biSizeIm = 0;\n    Bitmap_Head.biXPels = Bitmap_Head.biYPels = 0;\n    Bitmap_Head.biClrUsed = 0;\n    Bitmap_Head.biClrImp = 0;\n    Bitmap_Head.masks[0] = 0;\n    Bitmap_Head.masks[1] = 0;\n    Bitmap_Head.masks[2] = 0;\n    Bitmap_Head.masks[3] = 0;\n\n    memset(masks, 0, sizeof(masks));\n    Maps = 3;\n\n  } else if (Bitmap_File_Head.biSize == 40) { /* Windows 3.x */\n    if (!ReadOK(fd, buffer, 36))\n    {\n      LOG (\"Error reading BMP file header\\n\");\n      at_exception_fatal(&exp, \"Error reading BMP file header\");\n      goto cleanup;\n    }\n          \n\n    Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */\n    Bitmap_Head.biHeight = ToL(&buffer[0x04]);  /* 16 */\n    Bitmap_Head.biPlanes = ToS(&buffer[0x08]);  /* 1A */\n    Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);  /* 1C */\n    Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */\n    Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);  /* 22 */\n    Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */\n    Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */\n    Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */\n    Bitmap_Head.biClrImp = ToL(&buffer[0x20]);  /* 32 */\n    Bitmap_Head.masks[0] = 0;\n    Bitmap_Head.masks[1] = 0;\n    Bitmap_Head.masks[2] = 0;\n    Bitmap_Head.masks[3] = 0;\n\n    Maps = 4;\n    memset(masks, 0, sizeof(masks));\n\n    if (Bitmap_Head.biCompr == BI_BITFIELDS)\n      {\n\tif (!ReadOK(fd, buffer, 3 * sizeof(unsigned long)))\n\t  {\n\t    LOG(\"Error reading BMP file header\\n\");\n\t    at_exception_fatal(&exp, \"Error reading BMP file header\");\n\t    goto cleanup;\n\t  }\n\n\tBitmap_Head.masks[0] = ToL(&buffer[0x00]);\n\tBitmap_Head.masks[1] = ToL(&buffer[0x04]);\n\tBitmap_Head.masks[2] = ToL(&buffer[0x08]);\n\n\tReadChannelMasks(&Bitmap_Head.masks[0], masks, 3);\n      }\n    else if (Bitmap_Head.biCompr == BI_RGB)\n      {\n\tsetMasksDefault(Bitmap_Head.biBitCnt, masks);\n      }\n    else if ((Bitmap_Head.biCompr != BI_RLE4) &&\n\t     (Bitmap_Head.biCompr != BI_RLE8))\n      {\n\t/* BI_ALPHABITFIELDS, etc. */\n\tLOG(\"Unsupported compression in BMP file\\n\");\n\tat_exception_fatal(&exp, \"Unsupported compression in BMP file\");\n\tgoto cleanup;\n      }\n  }\n  else if (Bitmap_File_Head.biSize >= 56 &&\n\t   Bitmap_File_Head.biSize <= 64)\n  {\n    /* enhanced Windows format with bit masks */\n\n    if (!ReadOK (fd, buffer, Bitmap_File_Head.biSize - 4))\n    {\n\n      LOG(\"Error reading BMP file header\\n\");\n      at_exception_fatal(&exp, \"Error reading BMP file header\");\n      goto cleanup;\n    }\n\n    Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */\n    Bitmap_Head.biHeight = ToL(&buffer[0x04]);  /* 16 */\n    Bitmap_Head.biPlanes = ToS(&buffer[0x08]);  /* 1A */\n    Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);  /* 1C */\n    Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */\n    Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);  /* 22 */\n    Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */\n    Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */\n    Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */\n    Bitmap_Head.biClrImp = ToL(&buffer[0x20]);  /* 32 */\n    Bitmap_Head.masks[0] = ToL(&buffer[0x24]);       /* 36 */\n    Bitmap_Head.masks[1] = ToL(&buffer[0x28]);       /* 3A */\n    Bitmap_Head.masks[2] = ToL(&buffer[0x2C]);       /* 3E */\n    Bitmap_Head.masks[3] = ToL(&buffer[0x30]);       /* 42 */\n\n    Maps = 4;\n    ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);\n  }\n  else if (Bitmap_File_Head.biSize == 108 ||\n           Bitmap_File_Head.biSize == 124)\n  {\n    /* BMP Version 4 or 5 */\n\n    if (!ReadOK(fd, buffer, Bitmap_File_Head.biSize - 4))\n    {\n\t    LOG(\"Error reading BMP file header\\n\");\n\t    at_exception_fatal(&exp, \"Error reading BMP file header\");\n\t    goto cleanup;\n    }\n\n    Bitmap_Head.biWidth = ToL(&buffer[0x00]);\n    Bitmap_Head.biHeight = ToL(&buffer[0x04]);\n    Bitmap_Head.biPlanes = ToS(&buffer[0x08]);\n    Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);\n    Bitmap_Head.biCompr = ToL(&buffer[0x0C]);\n    Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);\n    Bitmap_Head.biXPels = ToL(&buffer[0x14]);\n    Bitmap_Head.biYPels = ToL(&buffer[0x18]);\n    Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]);\n    Bitmap_Head.biClrImp = ToL(&buffer[0x20]);\n    Bitmap_Head.masks[0] = ToL(&buffer[0x24]);\n    Bitmap_Head.masks[1] = ToL(&buffer[0x28]);\n    Bitmap_Head.masks[2] = ToL(&buffer[0x2C]);\n    Bitmap_Head.masks[3] = ToL(&buffer[0x30]);\n\n    Maps = 4;\n\n    if (Bitmap_Head.biCompr == BI_BITFIELDS)\n    {\n\t    ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);\n    }\n    else if (Bitmap_Head.biCompr == BI_RGB)\n    {\n\t    setMasksDefault(Bitmap_Head.biBitCnt, masks);\n    }\n  } else {\n    LOG(\"Error reading BMP file header\\n\");\n    at_exception_fatal(&exp, \"Error reading BMP file header\");\n    goto cleanup;\n  }\n\n  /* Valid options 1, 4, 8, 16, 24, 32 */\n  /* 16 is awful, we should probably shoot whoever invented it */\n\n  switch (Bitmap_Head.biBitCnt)\n  {\n  case 1:\n  case 2:\n  case 4:\n  case 8:\n  case 16:\n  case 24:\n  case 32:\n\t  break;\n  default:\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  /* There should be some colors used! */\n\n  ColormapSize = (Bitmap_File_Head.bfOffs - Bitmap_File_Head.biSize - 14) / Maps;\n\n  if ((Bitmap_Head.biClrUsed == 0) &&\n      (Bitmap_Head.biBitCnt <= 8))\n  {\n\t  ColormapSize = Bitmap_Head.biClrUsed = 1 << Bitmap_Head.biBitCnt;\n  }\n\n  if (ColormapSize > 256)\n    ColormapSize = 256;\n\n  /* Sanity checks */\n\n  if (Bitmap_Head.biHeight == 0 ||\n\t  Bitmap_Head.biWidth == 0)\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  /* biHeight may be negative, but -2147483648 is dangerous because:\n\t -2147483648 == -(-2147483648) */\n  if (Bitmap_Head.biWidth < 0 ||\n\t  Bitmap_Head.biHeight == -2147483648)\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  if (Bitmap_Head.biPlanes != 1)\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  if (Bitmap_Head.biClrUsed > 256 &&\n\t  Bitmap_Head.biBitCnt <= 8)\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  /* protect against integer overflows caused by malicious BMPs */\n  /* use divisions in comparisons to avoid type overflows */\n\n  if (((unsigned long)Bitmap_Head.biWidth) > (unsigned int)0x7fffffff / Bitmap_Head.biBitCnt ||\n\t  ((unsigned long)Bitmap_Head.biWidth) > ((unsigned int)0x7fffffff /abs(Bitmap_Head.biHeight)) / 4)\n  {\n\t  LOG(\"%s is not a valid BMP file\", filename);\n\t  at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t  goto cleanup;\n  }\n\n  /* Windows and OS/2 declare filler so that rows are a multiple of\n   * word length (32 bits == 4 bytes)\n   */\n   \n  unsigned long overflowTest = Bitmap_Head.biWidth * Bitmap_Head.biBitCnt;\n  if (overflowTest / Bitmap_Head.biWidth != Bitmap_Head.biBitCnt) {\n    LOG(\"Error reading BMP file header. Width is too large\\n\");\n    at_exception_fatal(&exp, \"Error reading BMP file header. Width is too large\");\n    goto cleanup;\n  }\n\n  rowbytes = ((Bitmap_Head.biWidth * Bitmap_Head.biBitCnt - 1) / 32) * 4 + 4;\n\n#ifdef DEBUG\n  printf(\"\\nSize: %u, Colors: %u, Bits: %u, Width: %u, Height: %u, Comp: %u, Zeile: %u\\n\", Bitmap_File_Head.bfSize, Bitmap_Head.biClrUsed, Bitmap_Head.biBitCnt, Bitmap_Head.biWidth, Bitmap_Head.biHeight, Bitmap_Head.biCompr, rowbytes);\n#endif\n\n\n  if (Bitmap_Head.biBitCnt <= 8)\n  {\n#ifdef DEBUG\n    printf(\"Colormap read\\n\");\n#endif\n\t  /* Get the Colormap */\n\t  if (!ReadColorMap(fd, ColorMap, ColormapSize, Maps, &Grey, &exp))\n\t\t  goto cleanup;\n  }\n\n  fseek(fd, Bitmap_File_Head.bfOffs, SEEK_SET);\n\n  /* Get the Image and return the ID or -1 on error */\n  image_storage = ReadImage(fd, \n\tBitmap_Head.biWidth, Bitmap_Head.biHeight,\n\tColorMap,\n        Bitmap_Head.biClrUsed,\n\tBitmap_Head.biBitCnt, Bitmap_Head.biCompr, rowbytes,\n        Grey,\n\tmasks,\n\t&exp);\n\n  image = at_bitmap_init(image_storage, (unsigned short)Bitmap_Head.biWidth, (unsigned short)Bitmap_Head.biHeight, Grey ? 1 : 3);\ncleanup:\n  fclose(fd);\n  return (image);\n}", "func_hash": 18153038985911000449594893666433988306, "file_name": "input-bmp.c", "file_hash": 29852375577809733693857999744439179756, "cwe": ["CWE-787"], "cve": "CVE-2022-32323", "cve_desc": "AutoTrace v0.40.0 was discovered to contain a heap overflow via the ReadImage function at input-bmp.c:660.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-32323"}
{"idx": 207520, "project": "rizin", "commit_id": "aa6917772d2f32e5a7daab25a46c72df0b5ea406", "project_url": "https://github.com/rizinorg/rizin", "commit_url": "https://github.com/rizinorg/rizin/commit/aa6917772d2f32e5a7daab25a46c72df0b5ea406", "commit_message": "Fix oob write for dwarf with abbrev with count 0 (Fix #2083) (#2086)", "target": 1, "func": "static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RzBinDwarfDebugInfo *info, RzBinDwarfAbbrevDecl *abbrev,\n\tRzBinDwarfCompUnitHdr *hdr, RzBinDwarfDie *die, const ut8 *debug_str, size_t debug_str_len, bool big_endian) {\n\tsize_t i;\n\tconst char *comp_dir = NULL;\n\tut64 line_info_offset = UT64_MAX;\n\tfor (i = 0; i < abbrev->count - 1; i++) {\n\t\tmemset(&die->attr_values[i], 0, sizeof(die->attr_values[i]));\n\n\t\tbuf = parse_attr_value(buf, buf_end - buf, &abbrev->defs[i],\n\t\t\t&die->attr_values[i], hdr, debug_str, debug_str_len, big_endian);\n\n\t\tRzBinDwarfAttrValue *attribute = &die->attr_values[i];\n\n\t\tif (attribute->attr_name == DW_AT_comp_dir && (attribute->attr_form == DW_FORM_strp || attribute->attr_form == DW_FORM_string) && attribute->string.content) {\n\t\t\tcomp_dir = attribute->string.content;\n\t\t}\n\t\tif (attribute->attr_name == DW_AT_stmt_list) {\n\t\t\tif (attribute->kind == DW_AT_KIND_CONSTANT) {\n\t\t\t\tline_info_offset = attribute->uconstant;\n\t\t\t} else if (attribute->kind == DW_AT_KIND_REFERENCE) {\n\t\t\t\tline_info_offset = attribute->reference;\n\t\t\t}\n\t\t}\n\t\tdie->count++;\n\t}\n\n\t// If this is a compilation unit dir attribute, we want to cache it so the line info parsing\n\t// which will need this info can quickly look it up.\n\tif (comp_dir && line_info_offset != UT64_MAX) {\n\t\tchar *name = strdup(comp_dir);\n\t\tif (name) {\n\t\t\tif (!ht_up_insert(info->line_info_offset_comp_dir, line_info_offset, name)) {\n\t\t\t\tfree(name);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn buf;\n}", "func_hash": 26636529307671690704479532140631853142, "file_name": "dwarf.c", "file_hash": 327051726619513035208543664099881519843, "cwe": ["CWE-787"], "cve": "CVE-2021-43814", "cve_desc": "Rizin is a UNIX-like reverse engineering framework and command-line toolset. In versions up to and including 0.3.1 there is a heap-based out of bounds write in parse_die() when reversing an AMD64 ELF binary with DWARF debug info. When a malicious AMD64 ELF binary is opened by a victim user, Rizin may crash or execute unintended actions. No workaround are known and users are advised to upgrade.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43814"}
{"idx": 398518, "project": "rizin", "commit_id": "aa6917772d2f32e5a7daab25a46c72df0b5ea406", "project_url": "https://github.com/rizinorg/rizin", "commit_url": "https://github.com/rizinorg/rizin/commit/aa6917772d2f32e5a7daab25a46c72df0b5ea406", "commit_message": "Fix oob write for dwarf with abbrev with count 0 (Fix #2083) (#2086)", "target": 0, "func": "static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RzBinDwarfDebugInfo *info, RzBinDwarfAbbrevDecl *abbrev,\n\tRzBinDwarfCompUnitHdr *hdr, RzBinDwarfDie *die, const ut8 *debug_str, size_t debug_str_len, bool big_endian) {\n\tsize_t i;\n\tconst char *comp_dir = NULL;\n\tut64 line_info_offset = UT64_MAX;\n\tif (abbrev->count) {\n\t\tfor (i = 0; i < abbrev->count - 1; i++) {\n\t\t\tmemset(&die->attr_values[i], 0, sizeof(die->attr_values[i]));\n\n\t\t\tbuf = parse_attr_value(buf, buf_end - buf, &abbrev->defs[i],\n\t\t\t\t&die->attr_values[i], hdr, debug_str, debug_str_len, big_endian);\n\n\t\t\tRzBinDwarfAttrValue *attribute = &die->attr_values[i];\n\n\t\t\tif (attribute->attr_name == DW_AT_comp_dir && (attribute->attr_form == DW_FORM_strp || attribute->attr_form == DW_FORM_string) && attribute->string.content) {\n\t\t\t\tcomp_dir = attribute->string.content;\n\t\t\t}\n\t\t\tif (attribute->attr_name == DW_AT_stmt_list) {\n\t\t\t\tif (attribute->kind == DW_AT_KIND_CONSTANT) {\n\t\t\t\t\tline_info_offset = attribute->uconstant;\n\t\t\t\t} else if (attribute->kind == DW_AT_KIND_REFERENCE) {\n\t\t\t\t\tline_info_offset = attribute->reference;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdie->count++;\n\t\t}\n\t}\n\n\t// If this is a compilation unit dir attribute, we want to cache it so the line info parsing\n\t// which will need this info can quickly look it up.\n\tif (comp_dir && line_info_offset != UT64_MAX) {\n\t\tchar *name = strdup(comp_dir);\n\t\tif (name) {\n\t\t\tif (!ht_up_insert(info->line_info_offset_comp_dir, line_info_offset, name)) {\n\t\t\t\tfree(name);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn buf;\n}", "func_hash": 51977580595649091612975538237343950990, "file_name": "dwarf.c", "file_hash": 92035029709372705681125485016113687180, "cwe": ["CWE-787"], "cve": "CVE-2021-43814", "cve_desc": "Rizin is a UNIX-like reverse engineering framework and command-line toolset. In versions up to and including 0.3.1 there is a heap-based out of bounds write in parse_die() when reversing an AMD64 ELF binary with DWARF debug info. When a malicious AMD64 ELF binary is opened by a victim user, Rizin may crash or execute unintended actions. No workaround are known and users are advised to upgrade.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43814"}
{"idx": 207700, "project": "EternalTerminal", "commit_id": "900348bb8bc96e1c7ba4888ac8480f643c43d3c3", "project_url": "https://github.com/MisterTea/EternalTerminal", "commit_url": "https://github.com/MisterTea/EternalTerminal/commit/900348bb8bc96e1c7ba4888ac8480f643c43d3c3", "commit_message": "red fixes (#468)\n\n* red fixes\n\n* remove magic number", "target": 1, "func": "TerminalUserInfo UserTerminalRouter::getInfoForId(const string &id) {\n  auto it = idInfoMap.find(id);\n  if (it == idInfoMap.end()) {\n    STFATAL << \" Tried to read from an id that no longer exists\";\n  }\n  return it->second;\n}", "func_hash": 65652485071667159611859578809507103310, "file_name": "UserTerminalRouter.cpp", "file_hash": 95512591738948248593704083286692164926, "cwe": ["CWE-362"], "cve": "CVE-2022-24950", "cve_desc": "A race condition exists in Eternal Terminal prior to version 6.2.0 that allows an authenticated attacker to hijack other users' SSH authorization socket, enabling the attacker to login to other systems as the targeted users. The bug is in UserTerminalRouter::getInfoForId().", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24950"}
{"idx": 400109, "project": "EternalTerminal", "commit_id": "900348bb8bc96e1c7ba4888ac8480f643c43d3c3", "project_url": "https://github.com/MisterTea/EternalTerminal", "commit_url": "https://github.com/MisterTea/EternalTerminal/commit/900348bb8bc96e1c7ba4888ac8480f643c43d3c3", "commit_message": "red fixes (#468)\n\n* red fixes\n\n* remove magic number", "target": 0, "func": "TerminalUserInfo UserTerminalRouter::getInfoForId(const string &id) {\n  lock_guard guard(routerMutex);\n  auto it = idInfoMap.find(id);\n  if (it == idInfoMap.end()) {\n    STFATAL << \" Tried to read from an id that no longer exists\";\n  }\n  return it->second;\n}", "func_hash": 194538535842091525230611933768280108618, "file_name": "UserTerminalRouter.cpp", "file_hash": 33756077495418666193931642880316711781, "cwe": ["CWE-362"], "cve": "CVE-2022-24950", "cve_desc": "A race condition exists in Eternal Terminal prior to version 6.2.0 that allows an authenticated attacker to hijack other users' SSH authorization socket, enabling the attacker to login to other systems as the targeted users. The bug is in UserTerminalRouter::getInfoForId().", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24950"}
{"idx": 207703, "project": "EternalTerminal", "commit_id": "900348bb8bc96e1c7ba4888ac8480f643c43d3c3", "project_url": "https://github.com/MisterTea/EternalTerminal", "commit_url": "https://github.com/MisterTea/EternalTerminal/commit/900348bb8bc96e1c7ba4888ac8480f643c43d3c3", "commit_message": "red fixes (#468)\n\n* red fixes\n\n* remove magic number", "target": 1, "func": "set PipeSocketHandler::listen(const SocketEndpoint& endpoint) {\n  lock_guard guard(globalMutex);\n\n  string pipePath = endpoint.name();\n  if (pipeServerSockets.find(pipePath) != pipeServerSockets.end()) {\n    throw runtime_error(\"Tried to listen twice on the same path\");\n  }\n\n  sockaddr_un local;\n\n  int fd = socket(AF_UNIX, SOCK_STREAM, 0);\n  FATAL_FAIL(fd);\n  initServerSocket(fd);\n  local.sun_family = AF_UNIX; /* local is declared before socket() ^ */\n  strcpy(local.sun_path, pipePath.c_str());\n  unlink(local.sun_path);\n\n  FATAL_FAIL(::bind(fd, (struct sockaddr*)&local, sizeof(sockaddr_un)));\n  ::listen(fd, 5);\n#ifndef WIN32\n  FATAL_FAIL(::chmod(local.sun_path, S_IRUSR | S_IWUSR | S_IXUSR));\n#endif\n\n  pipeServerSockets[pipePath] = set({fd});\n  return pipeServerSockets[pipePath];\n}", "func_hash": 148534117660985776148799839801292812152, "file_name": "PipeSocketHandler.cpp", "file_hash": 83158573064577402992437694952965778259, "cwe": ["CWE-362"], "cve": "CVE-2022-24950", "cve_desc": "A race condition exists in Eternal Terminal prior to version 6.2.0 that allows an authenticated attacker to hijack other users' SSH authorization socket, enabling the attacker to login to other systems as the targeted users. The bug is in UserTerminalRouter::getInfoForId().", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24950"}
{"idx": 400103, "project": "EternalTerminal", "commit_id": "900348bb8bc96e1c7ba4888ac8480f643c43d3c3", "project_url": "https://github.com/MisterTea/EternalTerminal", "commit_url": "https://github.com/MisterTea/EternalTerminal/commit/900348bb8bc96e1c7ba4888ac8480f643c43d3c3", "commit_message": "red fixes (#468)\n\n* red fixes\n\n* remove magic number", "target": 0, "func": "set PipeSocketHandler::listen(const SocketEndpoint& endpoint) {\n  lock_guard guard(globalMutex);\n\n  string pipePath = endpoint.name();\n  if (pipeServerSockets.find(pipePath) != pipeServerSockets.end()) {\n    throw runtime_error(\"Tried to listen twice on the same path\");\n  }\n\n  sockaddr_un local;\n\n  int fd = socket(AF_UNIX, SOCK_STREAM, 0);\n  FATAL_FAIL(fd);\n  initServerSocket(fd);\n  local.sun_family = AF_UNIX; /* local is declared before socket() ^ */\n  strncpy(local.sun_path, pipePath.c_str(), sizeof(local.sun_path));\n  unlink(local.sun_path);\n\n  FATAL_FAIL(::bind(fd, (struct sockaddr*)&local, sizeof(sockaddr_un)));\n  ::listen(fd, 5);\n#ifndef WIN32\n  FATAL_FAIL(::chmod(local.sun_path, S_IRUSR | S_IWUSR | S_IXUSR));\n#endif\n\n  pipeServerSockets[pipePath] = set({fd});\n  return pipeServerSockets[pipePath];\n}", "func_hash": 36125659257824603505725557266857282888, "file_name": "PipeSocketHandler.cpp", "file_hash": 231978839420872719355627255082595640778, "cwe": ["CWE-362"], "cve": "CVE-2022-24950", "cve_desc": "A race condition exists in Eternal Terminal prior to version 6.2.0 that allows an authenticated attacker to hijack other users' SSH authorization socket, enabling the attacker to login to other systems as the targeted users. The bug is in UserTerminalRouter::getInfoForId().", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24950"}
{"idx": 207719, "project": "vim", "commit_id": "e98c88c44c308edaea5994b8ad4363e65030968c", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/e98c88c44c308edaea5994b8ad4363e65030968c", "commit_message": "patch 9.0.0218: reading before the start of the line\n\nProblem:    Reading before the start of the line.\nSolution:   When displaying \"$\" check the column is not negative.", "target": 1, "func": "display_dollar(colnr_T col)\n{\n    colnr_T save_col;\n\n    if (!redrawing())\n\treturn;\n\n    cursor_off();\n    save_col = curwin->w_cursor.col;\n    curwin->w_cursor.col = col;\n    if (has_mbyte)\n    {\n\tchar_u *p;\n\n\t// If on the last byte of a multi-byte move to the first byte.\n\tp = ml_get_curline();\n\tcurwin->w_cursor.col -= (*mb_head_off)(p, p + col);\n    }\n    curs_columns(FALSE);\t    // recompute w_wrow and w_wcol\n    if (curwin->w_wcol < curwin->w_width)\n    {\n\tedit_putchar('$', FALSE);\n\tdollar_vcol = curwin->w_virtcol;\n    }\n    curwin->w_cursor.col = save_col;\n}", "func_hash": 56781688432244503822784219524894149055, "file_name": "edit.c", "file_hash": 251788010034679613424556948955874474953, "cwe": ["CWE-787"], "cve": "CVE-2022-2845", "cve_desc": "Improper Validation of Specified Quantity in Input in GitHub repository vim/vim prior to 9.0.0218.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2845"}
{"idx": 400409, "project": "vim", "commit_id": "e98c88c44c308edaea5994b8ad4363e65030968c", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/e98c88c44c308edaea5994b8ad4363e65030968c", "commit_message": "patch 9.0.0218: reading before the start of the line\n\nProblem:    Reading before the start of the line.\nSolution:   When displaying \"$\" check the column is not negative.", "target": 0, "func": "display_dollar(colnr_T col_arg)\n{\n    colnr_T col = col_arg < 0 ? 0 : col_arg;\n    colnr_T save_col;\n\n    if (!redrawing())\n\treturn;\n\n    cursor_off();\n    save_col = curwin->w_cursor.col;\n    curwin->w_cursor.col = col;\n    if (has_mbyte)\n    {\n\tchar_u *p;\n\n\t// If on the last byte of a multi-byte move to the first byte.\n\tp = ml_get_curline();\n\tcurwin->w_cursor.col -= (*mb_head_off)(p, p + col);\n    }\n    curs_columns(FALSE);\t    // recompute w_wrow and w_wcol\n    if (curwin->w_wcol < curwin->w_width)\n    {\n\tedit_putchar('$', FALSE);\n\tdollar_vcol = curwin->w_virtcol;\n    }\n    curwin->w_cursor.col = save_col;\n}", "func_hash": 125832747032800290670744012264167596321, "file_name": "edit.c", "file_hash": 91657375912486719968624749742093008286, "cwe": ["CWE-787"], "cve": "CVE-2022-2845", "cve_desc": "Improper Validation of Specified Quantity in Input in GitHub repository vim/vim prior to 9.0.0218.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2845"}
{"idx": 207753, "project": "linux", "commit_id": "9d2231c5d74e13b2a0546fee6737ee4446017903", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/9d2231c5d74e13b2a0546fee6737ee4446017903", "commit_message": "lib/iov_iter: initialize \"flags\" in new pipe_buffer\n\nThe functions copy_page_to_iter_pipe() and push_pipe() can both\nallocate a new pipe_buffer, but the \"flags\" member initializer is\nmissing.\n\nFixes: 241699cd72a8 (\"new iov_iter flavour: pipe-backed\")\nTo: Alexander Viro \nTo: linux-fsdevel@vger.kernel.org\nTo: linux-kernel@vger.kernel.org\nCc: stable@vger.kernel.org\nSigned-off-by: Max Kellermann \nSigned-off-by: Al Viro ", "target": 1, "func": "static size_t copy_page_to_iter_pipe(struct page *page, size_t offset, size_t bytes,\n\t\t\t struct iov_iter *i)\n{\n\tstruct pipe_inode_info *pipe = i->pipe;\n\tstruct pipe_buffer *buf;\n\tunsigned int p_tail = pipe->tail;\n\tunsigned int p_mask = pipe->ring_size - 1;\n\tunsigned int i_head = i->head;\n\tsize_t off;\n\n\tif (unlikely(bytes > i->count))\n\t\tbytes = i->count;\n\n\tif (unlikely(!bytes))\n\t\treturn 0;\n\n\tif (!sanity(i))\n\t\treturn 0;\n\n\toff = i->iov_offset;\n\tbuf = &pipe->bufs[i_head & p_mask];\n\tif (off) {\n\t\tif (offset == off && buf->page == page) {\n\t\t\t/* merge with the last one */\n\t\t\tbuf->len += bytes;\n\t\t\ti->iov_offset += bytes;\n\t\t\tgoto out;\n\t\t}\n\t\ti_head++;\n\t\tbuf = &pipe->bufs[i_head & p_mask];\n\t}\n\tif (pipe_full(i_head, p_tail, pipe->max_usage))\n\t\treturn 0;\n\n\tbuf->ops = &page_cache_pipe_buf_ops;\n\tget_page(page);\n\tbuf->page = page;\n\tbuf->offset = offset;\n\tbuf->len = bytes;\n\n\tpipe->head = i_head + 1;\n\ti->iov_offset = offset + bytes;\n\ti->head = i_head;\nout:\n\ti->count -= bytes;\n\treturn bytes;\n}", "func_hash": 167718514506109094299086513897213873936, "file_name": "iov_iter.c", "file_hash": 181499146794090302160100800341530380411, "cwe": ["CWE-284"], "cve": "CVE-2022-0847", "cve_desc": "A flaw was found in the way the \"flags\" member of the new pipe buffer structure was lacking proper initialization in copy_page_to_iter_pipe and push_pipe functions in the Linux kernel and could thus contain stale values. An unprivileged local user could use this flaw to write to pages in the page cache backed by read only files and as such escalate their privileges on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0847"}
{"idx": 400735, "project": "linux", "commit_id": "9d2231c5d74e13b2a0546fee6737ee4446017903", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/9d2231c5d74e13b2a0546fee6737ee4446017903", "commit_message": "lib/iov_iter: initialize \"flags\" in new pipe_buffer\n\nThe functions copy_page_to_iter_pipe() and push_pipe() can both\nallocate a new pipe_buffer, but the \"flags\" member initializer is\nmissing.\n\nFixes: 241699cd72a8 (\"new iov_iter flavour: pipe-backed\")\nTo: Alexander Viro \nTo: linux-fsdevel@vger.kernel.org\nTo: linux-kernel@vger.kernel.org\nCc: stable@vger.kernel.org\nSigned-off-by: Max Kellermann \nSigned-off-by: Al Viro ", "target": 0, "func": "static size_t copy_page_to_iter_pipe(struct page *page, size_t offset, size_t bytes,\n\t\t\t struct iov_iter *i)\n{\n\tstruct pipe_inode_info *pipe = i->pipe;\n\tstruct pipe_buffer *buf;\n\tunsigned int p_tail = pipe->tail;\n\tunsigned int p_mask = pipe->ring_size - 1;\n\tunsigned int i_head = i->head;\n\tsize_t off;\n\n\tif (unlikely(bytes > i->count))\n\t\tbytes = i->count;\n\n\tif (unlikely(!bytes))\n\t\treturn 0;\n\n\tif (!sanity(i))\n\t\treturn 0;\n\n\toff = i->iov_offset;\n\tbuf = &pipe->bufs[i_head & p_mask];\n\tif (off) {\n\t\tif (offset == off && buf->page == page) {\n\t\t\t/* merge with the last one */\n\t\t\tbuf->len += bytes;\n\t\t\ti->iov_offset += bytes;\n\t\t\tgoto out;\n\t\t}\n\t\ti_head++;\n\t\tbuf = &pipe->bufs[i_head & p_mask];\n\t}\n\tif (pipe_full(i_head, p_tail, pipe->max_usage))\n\t\treturn 0;\n\n\tbuf->ops = &page_cache_pipe_buf_ops;\n\tbuf->flags = 0;\n\tget_page(page);\n\tbuf->page = page;\n\tbuf->offset = offset;\n\tbuf->len = bytes;\n\n\tpipe->head = i_head + 1;\n\ti->iov_offset = offset + bytes;\n\ti->head = i_head;\nout:\n\ti->count -= bytes;\n\treturn bytes;\n}", "func_hash": 254624609360113587487306617570895393083, "file_name": "iov_iter.c", "file_hash": 158086795761237639591506235503715650431, "cwe": ["CWE-284"], "cve": "CVE-2022-0847", "cve_desc": "A flaw was found in the way the \"flags\" member of the new pipe buffer structure was lacking proper initialization in copy_page_to_iter_pipe and push_pipe functions in the Linux kernel and could thus contain stale values. An unprivileged local user could use this flaw to write to pages in the page cache backed by read only files and as such escalate their privileges on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0847"}
{"idx": 207754, "project": "linux", "commit_id": "9d2231c5d74e13b2a0546fee6737ee4446017903", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/9d2231c5d74e13b2a0546fee6737ee4446017903", "commit_message": "lib/iov_iter: initialize \"flags\" in new pipe_buffer\n\nThe functions copy_page_to_iter_pipe() and push_pipe() can both\nallocate a new pipe_buffer, but the \"flags\" member initializer is\nmissing.\n\nFixes: 241699cd72a8 (\"new iov_iter flavour: pipe-backed\")\nTo: Alexander Viro \nTo: linux-fsdevel@vger.kernel.org\nTo: linux-kernel@vger.kernel.org\nCc: stable@vger.kernel.org\nSigned-off-by: Max Kellermann \nSigned-off-by: Al Viro ", "target": 1, "func": "static size_t push_pipe(struct iov_iter *i, size_t size,\n\t\t\tint *iter_headp, size_t *offp)\n{\n\tstruct pipe_inode_info *pipe = i->pipe;\n\tunsigned int p_tail = pipe->tail;\n\tunsigned int p_mask = pipe->ring_size - 1;\n\tunsigned int iter_head;\n\tsize_t off;\n\tssize_t left;\n\n\tif (unlikely(size > i->count))\n\t\tsize = i->count;\n\tif (unlikely(!size))\n\t\treturn 0;\n\n\tleft = size;\n\tdata_start(i, &iter_head, &off);\n\t*iter_headp = iter_head;\n\t*offp = off;\n\tif (off) {\n\t\tleft -= PAGE_SIZE - off;\n\t\tif (left <= 0) {\n\t\t\tpipe->bufs[iter_head & p_mask].len += size;\n\t\t\treturn size;\n\t\t}\n\t\tpipe->bufs[iter_head & p_mask].len = PAGE_SIZE;\n\t\titer_head++;\n\t}\n\twhile (!pipe_full(iter_head, p_tail, pipe->max_usage)) {\n\t\tstruct pipe_buffer *buf = &pipe->bufs[iter_head & p_mask];\n\t\tstruct page *page = alloc_page(GFP_USER);\n\t\tif (!page)\n\t\t\tbreak;\n\n\t\tbuf->ops = &default_pipe_buf_ops;\n\t\tbuf->page = page;\n\t\tbuf->offset = 0;\n\t\tbuf->len = min_t(ssize_t, left, PAGE_SIZE);\n\t\tleft -= buf->len;\n\t\titer_head++;\n\t\tpipe->head = iter_head;\n\n\t\tif (left == 0)\n\t\t\treturn size;\n\t}\n\treturn size - left;\n}", "func_hash": 298985660493874547228624767727586322810, "file_name": "iov_iter.c", "file_hash": 181499146794090302160100800341530380411, "cwe": ["CWE-284"], "cve": "CVE-2022-0847", "cve_desc": "A flaw was found in the way the \"flags\" member of the new pipe buffer structure was lacking proper initialization in copy_page_to_iter_pipe and push_pipe functions in the Linux kernel and could thus contain stale values. An unprivileged local user could use this flaw to write to pages in the page cache backed by read only files and as such escalate their privileges on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0847"}
{"idx": 400743, "project": "linux", "commit_id": "9d2231c5d74e13b2a0546fee6737ee4446017903", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/9d2231c5d74e13b2a0546fee6737ee4446017903", "commit_message": "lib/iov_iter: initialize \"flags\" in new pipe_buffer\n\nThe functions copy_page_to_iter_pipe() and push_pipe() can both\nallocate a new pipe_buffer, but the \"flags\" member initializer is\nmissing.\n\nFixes: 241699cd72a8 (\"new iov_iter flavour: pipe-backed\")\nTo: Alexander Viro \nTo: linux-fsdevel@vger.kernel.org\nTo: linux-kernel@vger.kernel.org\nCc: stable@vger.kernel.org\nSigned-off-by: Max Kellermann \nSigned-off-by: Al Viro ", "target": 0, "func": "static size_t push_pipe(struct iov_iter *i, size_t size,\n\t\t\tint *iter_headp, size_t *offp)\n{\n\tstruct pipe_inode_info *pipe = i->pipe;\n\tunsigned int p_tail = pipe->tail;\n\tunsigned int p_mask = pipe->ring_size - 1;\n\tunsigned int iter_head;\n\tsize_t off;\n\tssize_t left;\n\n\tif (unlikely(size > i->count))\n\t\tsize = i->count;\n\tif (unlikely(!size))\n\t\treturn 0;\n\n\tleft = size;\n\tdata_start(i, &iter_head, &off);\n\t*iter_headp = iter_head;\n\t*offp = off;\n\tif (off) {\n\t\tleft -= PAGE_SIZE - off;\n\t\tif (left <= 0) {\n\t\t\tpipe->bufs[iter_head & p_mask].len += size;\n\t\t\treturn size;\n\t\t}\n\t\tpipe->bufs[iter_head & p_mask].len = PAGE_SIZE;\n\t\titer_head++;\n\t}\n\twhile (!pipe_full(iter_head, p_tail, pipe->max_usage)) {\n\t\tstruct pipe_buffer *buf = &pipe->bufs[iter_head & p_mask];\n\t\tstruct page *page = alloc_page(GFP_USER);\n\t\tif (!page)\n\t\t\tbreak;\n\n\t\tbuf->ops = &default_pipe_buf_ops;\n\t\tbuf->flags = 0;\n\t\tbuf->page = page;\n\t\tbuf->offset = 0;\n\t\tbuf->len = min_t(ssize_t, left, PAGE_SIZE);\n\t\tleft -= buf->len;\n\t\titer_head++;\n\t\tpipe->head = iter_head;\n\n\t\tif (left == 0)\n\t\t\treturn size;\n\t}\n\treturn size - left;\n}", "func_hash": 276660368195834134822998399913502516107, "file_name": "iov_iter.c", "file_hash": 158086795761237639591506235503715650431, "cwe": ["CWE-284"], "cve": "CVE-2022-0847", "cve_desc": "A flaw was found in the way the \"flags\" member of the new pipe buffer structure was lacking proper initialization in copy_page_to_iter_pipe and push_pipe functions in the Linux kernel and could thus contain stale values. An unprivileged local user could use this flaw to write to pages in the page cache backed by read only files and as such escalate their privileges on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0847"}
{"idx": 207755, "project": "php-src", "commit_id": "095cbc48a8f0090f3b0abc6155f2b61943c9eafb", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commitdiff;h=095cbc48a8f0090f3b0abc6155f2b61943c9eafb", "commit_message": "Fix segfault in older versions of OpenSSL (before 0.9.8i)", "target": 1, "func": "PHP_FUNCTION(openssl_encrypt)\n{\n\tzend_bool raw_output = 0;\n\tchar *data, *method, *password, *iv = \"\";\n\tint data_len, method_len, password_len, iv_len = 0, max_iv_len;\n\tconst EVP_CIPHER *cipher_type;\n\tEVP_CIPHER_CTX cipher_ctx;\n\tint i, outlen, keylen;\n\tunsigned char *outbuf, *key;\n\tzend_bool free_iv;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"sss|bs\", &data, &data_len, &method, &method_len, &password, &password_len, &raw_output, &iv, &iv_len) == FAILURE) {\n\t\treturn;\n\t}\n\tcipher_type = EVP_get_cipherbyname(method);\n\tif (!cipher_type) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Unknown cipher algorithm\");\n\t\tRETURN_FALSE;\n\t}\n\n\tkeylen = EVP_CIPHER_key_length(cipher_type);\n\tif (keylen > password_len) {\n\t\tkey = emalloc(keylen);\n\t\tmemset(key, 0, keylen);\n\t\tmemcpy(key, password, password_len);\n\t} else {\n\t\tkey = (unsigned char*)password;\n\t}\n\n\tmax_iv_len = EVP_CIPHER_iv_length(cipher_type);\n\tif (iv_len <= 0 && max_iv_len > 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Using an empty Initialization Vector (iv) is potentially insecure and not recommended\");\n\t}\n\tfree_iv = php_openssl_validate_iv(&iv, &iv_len, max_iv_len TSRMLS_CC);\n\n\toutlen = data_len + EVP_CIPHER_block_size(cipher_type);\n\toutbuf = emalloc(outlen + 1);\n\n\tEVP_EncryptInit(&cipher_ctx, cipher_type, NULL, NULL);\n\tif (password_len > keylen) {\n\t\tEVP_CIPHER_CTX_set_key_length(&cipher_ctx, password_len);\n\t}\n\tEVP_EncryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv);\n\tEVP_EncryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len);\n\toutlen = i;\n\tif (EVP_EncryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) {\n\t\toutlen += i;\n\t\tif (raw_output) {\n\t\t\toutbuf[outlen] = '\\0';\n\t\t\tRETVAL_STRINGL((char *)outbuf, outlen, 0);\n\t\t} else {\n\t\t\tint base64_str_len;\n\t\t\tchar *base64_str;\n\n\t\t\tbase64_str = (char*)php_base64_encode(outbuf, outlen, &base64_str_len);\n\t\t\tefree(outbuf);\n\t\t\tRETVAL_STRINGL(base64_str, base64_str_len, 0);\n\t\t}\n\t} else {\n\t\tefree(outbuf);\n\t\tRETVAL_FALSE;\n\t}\n\tif (key != (unsigned char*)password) {\n\t\tefree(key);\n\t}\n\tif (free_iv) {\n\t\tefree(iv);\n\t}\n\tEVP_CIPHER_CTX_cleanup(&cipher_ctx);\n}", "func_hash": 90779826180799829793304692194705605906, "file_name": "openssl.c", "file_hash": 64204082198714090575154286576472678758, "cwe": ["CWE-200"], "cve": "CVE-2012-6113", "cve_desc": "The openssl_encrypt function in ext/openssl/openssl.c in PHP 5.3.9 through 5.3.13 does not initialize a certain variable, which allows remote attackers to obtain sensitive information from process memory by providing zero bytes of input data.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2012-6113"}
{"idx": 400779, "project": "php-src", "commit_id": "095cbc48a8f0090f3b0abc6155f2b61943c9eafb", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commitdiff;h=095cbc48a8f0090f3b0abc6155f2b61943c9eafb", "commit_message": "Fix segfault in older versions of OpenSSL (before 0.9.8i)", "target": 0, "func": "PHP_FUNCTION(openssl_decrypt)\n{\n\tzend_bool raw_input = 0;\n\tchar *data, *method, *password, *iv = \"\";\n\tint data_len, method_len, password_len, iv_len = 0;\n\tconst EVP_CIPHER *cipher_type;\n\tEVP_CIPHER_CTX cipher_ctx;\n\tint i, outlen, keylen;\n\tunsigned char *outbuf, *key;\n\tint base64_str_len;\n\tchar *base64_str = NULL;\n\tzend_bool free_iv;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"sss|bs\", &data, &data_len, &method, &method_len, &password, &password_len, &raw_input, &iv, &iv_len) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (!method_len) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Unknown cipher algorithm\");\n\t\tRETURN_FALSE;\n\t}\n\n\tcipher_type = EVP_get_cipherbyname(method);\n\tif (!cipher_type) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Unknown cipher algorithm\");\n\t\tRETURN_FALSE;\n\t}\n\n\tif (!raw_input) {\n\t\tbase64_str = (char*)php_base64_decode((unsigned char*)data, data_len, &base64_str_len);\n\t\tdata_len = base64_str_len;\n\t\tdata = base64_str;\n\t}\n\n\tkeylen = EVP_CIPHER_key_length(cipher_type);\n\tif (keylen > password_len) {\n\t\tkey = emalloc(keylen);\n\t\tmemset(key, 0, keylen);\n\t\tmemcpy(key, password, password_len);\n\t} else {\n\t\tkey = (unsigned char*)password;\n\t}\n\n\tfree_iv = php_openssl_validate_iv(&iv, &iv_len, EVP_CIPHER_iv_length(cipher_type) TSRMLS_CC);\n\n\toutlen = data_len + EVP_CIPHER_block_size(cipher_type);\n\toutbuf = emalloc(outlen + 1);\n\n\tEVP_DecryptInit(&cipher_ctx, cipher_type, NULL, NULL);\n\tif (password_len > keylen) {\n\t\tEVP_CIPHER_CTX_set_key_length(&cipher_ctx, password_len);\n\t}\n\tEVP_DecryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv);\n\tEVP_DecryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len);\n\toutlen = i;\n\tif (EVP_DecryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) {\n\t\toutlen += i;\n\t\toutbuf[outlen] = '\\0';\n\t\tRETVAL_STRINGL((char *)outbuf, outlen, 0);\n\t} else {\n\t\tefree(outbuf);\n\t\tRETVAL_FALSE;\n\t}\n\tif (key != (unsigned char*)password) {\n\t\tefree(key);\n\t}\n\tif (free_iv) {\n\t\tefree(iv);\n\t}\n\tif (base64_str) {\n\t\tefree(base64_str);\n\t}\n \tEVP_CIPHER_CTX_cleanup(&cipher_ctx);\n}", "func_hash": 39006034581830174999253498846151645941, "file_name": "openssl.c", "file_hash": 57276947425832893910697869677062470849, "cwe": ["CWE-200"], "cve": "CVE-2012-6113", "cve_desc": "The openssl_encrypt function in ext/openssl/openssl.c in PHP 5.3.9 through 5.3.13 does not initialize a certain variable, which allows remote attackers to obtain sensitive information from process memory by providing zero bytes of input data.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2012-6113"}
{"idx": 207780, "project": "radare2", "commit_id": "2b77b277d67ce061ee6ef839e7139ebc2103c1e3", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/2b77b277d67ce061ee6ef839e7139ebc2103c1e3", "commit_message": "Fix oobread in dyldcache ##crash\n\n* Reported by @hdthky via huntr.dev\n* Reproducers: poc1\n* BountyID: 8ae2c61a-2220-47a5-bfe8-fe6d41ab1f82", "target": 1, "func": "static RList *create_cache_bins(RBinFile *bf, RDyldCache *cache) {\n\tRList *bins = r_list_newf ((RListFree)free_bin);\n\tut16 *depArray = NULL;\n\tcache_imgxtr_t *extras = NULL;\n\tif (!bins) {\n\t\treturn NULL;\n\t}\n\n\tchar *target_libs = NULL;\n\tRList *target_lib_names = NULL;\n\tint *deps = NULL;\n\ttarget_libs = r_sys_getenv (\"R_DYLDCACHE_FILTER\");\n\tif (target_libs) {\n\t\ttarget_lib_names = r_str_split_list (target_libs, \":\", 0);\n\t\tif (!target_lib_names) {\n\t\t\tr_list_free (bins);\n\t\t\treturn NULL;\n\t\t}\n\t\tdeps = R_NEWS0 (int, cache->hdr->imagesCount);\n\t\tif (!deps) {\n\t\t\tr_list_free (bins);\n\t\t\tr_list_free (target_lib_names);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\tut32 i;\n\tfor (i = 0; i < cache->n_hdr; i++) {\n\t\tcache_hdr_t *hdr = &cache->hdr[i];\n\t\tut64 hdr_offset = cache->hdr_offset[i];\n\t\tut32 maps_index = cache->maps_index[i];\n\t\tcache_img_t *img = read_cache_images (cache->buf, hdr, hdr_offset);\n\t\tif (!img) {\n\t\t\tgoto next;\n\t\t}\n\n\t\tut32 j;\n\t\tif (target_libs) {\n\t\t\tHtPU *path_to_idx = NULL;\n\t\t\tif (cache->accel) {\n\t\t\t\tdepArray = R_NEWS0 (ut16, cache->accel->depListCount);\n\t\t\t\tif (!depArray) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\n\t\t\t\tif (r_buf_fread_at (cache->buf, cache->accel->depListOffset, (ut8*) depArray, \"s\", cache->accel->depListCount) != cache->accel->depListCount * 2) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\n\t\t\t\textras = read_cache_imgextra (cache->buf, hdr, cache->accel);\n\t\t\t\tif (!extras) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpath_to_idx = create_path_to_index (cache->buf, img, hdr);\n\t\t\t}\n\n\t\t\tfor (j = 0; j < hdr->imagesCount; j++) {\n\t\t\t\tbool printing = !deps[j];\n\t\t\t\tchar *lib_name = get_lib_name (cache->buf, &img[j]);\n\t\t\t\tif (!lib_name) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (strstr (lib_name, \"libobjc.A.dylib\")) {\n\t\t\t\t\tdeps[j]++;\n\t\t\t\t}\n\t\t\t\tif (!r_list_find (target_lib_names, lib_name, string_contains)) {\n\t\t\t\t\tR_FREE (lib_name);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (printing) {\n\t\t\t\t\teprintf (\"FILTER: %s\\n\", lib_name);\n\t\t\t\t}\n\t\t\t\tR_FREE (lib_name);\n\t\t\t\tdeps[j]++;\n\n\t\t\t\tif (extras && depArray) {\n\t\t\t\t\tut32 k;\n\t\t\t\t\tfor (k = extras[j].dependentsStartArrayIndex; depArray[k] != 0xffff; k++) {\n\t\t\t\t\t\tut16 dep_index = depArray[k] & 0x7fff;\n\t\t\t\t\t\tdeps[dep_index]++;\n\n\t\t\t\t\t\tchar *dep_name = get_lib_name (cache->buf, &img[dep_index]);\n\t\t\t\t\t\tif (!dep_name) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (printing) {\n\t\t\t\t\t\t\teprintf (\"-> %s\\n\", dep_name);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfree (dep_name);\n\t\t\t\t\t}\n\t\t\t\t} else if (path_to_idx) {\n\t\t\t\t\tcarve_deps_at_address (cache, img, path_to_idx, img[j].address, deps, printing);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tht_pu_free (path_to_idx);\n\t\t\tR_FREE (depArray);\n\t\t\tR_FREE (extras);\n\t\t}\n\n\t\tfor (j = 0; j < hdr->imagesCount; j++) {\n\t\t\tif (deps && !deps[j]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tut64 pa = va2pa (img[j].address, hdr->mappingCount, &cache->maps[maps_index], cache->buf, 0, NULL, NULL);\n\t\t\tif (pa == UT64_MAX) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tut8 magicbytes[4];\n\t\t\tr_buf_read_at (cache->buf, pa, magicbytes, 4);\n\t\t\tint magic = r_read_le32 (magicbytes);\n\t\t\tswitch (magic) {\n\t\t\tcase MH_MAGIC_64:\n\t\t\t{\n\t\t\t\tchar file[256];\n\t\t\t\tRDyldBinImage *bin = R_NEW0 (RDyldBinImage);\n\t\t\t\tif (!bin) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\t\t\t\tbin->header_at = pa;\n\t\t\t\tbin->hdr_offset = hdr_offset;\n\t\t\t\tbin->symbols_off = resolve_symbols_off (cache, pa);\n\t\t\t\tbin->va = img[j].address;\n\t\t\t\tif (r_buf_read_at (cache->buf, img[j].pathFileOffset, (ut8*) &file, sizeof (file)) == sizeof (file)) {\n\t\t\t\t\tfile[255] = 0;\n\t\t\t\t\tchar *last_slash = strrchr (file, '/');\n\t\t\t\t\tif (last_slash && *last_slash) {\n\t\t\t\t\t\tif (last_slash > file) {\n\t\t\t\t\t\t\tchar *scan = last_slash - 1;\n\t\t\t\t\t\t\twhile (scan > file && *scan != '/') {\n\t\t\t\t\t\t\t\tscan--;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (*scan == '/') {\n\t\t\t\t\t\t\t\tbin->file = strdup (scan + 1);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbin->file = strdup (last_slash + 1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tbin->file = strdup (last_slash + 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbin->file = strdup (file);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tr_list_append (bins, bin);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\teprintf (\"Unknown sub-bin\\n\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\nnext:\n\t\tR_FREE (depArray);\n\t\tR_FREE (extras);\n\t\tR_FREE (img);\n\t}\n\tif (r_list_empty (bins)) {\n\t\tr_list_free (bins);\n\t\tbins = NULL;\n\t}\n\tR_FREE (deps);\n\tR_FREE (target_libs);\n\tr_list_free (target_lib_names);\n\treturn bins;\n}", "func_hash": 174827048480806807337685920262304563052, "file_name": "None", "file_hash": null, "cwe": ["CWE-703"], "cve": "CVE-2022-1244", "cve_desc": "heap-buffer-overflow in GitHub repository radareorg/radare2 prior to 5.6.8. This vulnerability is capable of inducing denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1244"}
{"idx": 401034, "project": "radare2", "commit_id": "2b77b277d67ce061ee6ef839e7139ebc2103c1e3", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/2b77b277d67ce061ee6ef839e7139ebc2103c1e3", "commit_message": "Fix oobread in dyldcache ##crash\n\n* Reported by @hdthky via huntr.dev\n* Reproducers: poc1\n* BountyID: 8ae2c61a-2220-47a5-bfe8-fe6d41ab1f82", "target": 0, "func": "static RList *create_cache_bins(RBinFile *bf, RDyldCache *cache) {\n\tRList *bins = r_list_newf ((RListFree)free_bin);\n\tut16 *depArray = NULL;\n\tcache_imgxtr_t *extras = NULL;\n\tif (!bins) {\n\t\treturn NULL;\n\t}\n\n\tchar *target_libs = NULL;\n\tRList *target_lib_names = NULL;\n\tint *deps = NULL;\n\ttarget_libs = r_sys_getenv (\"R_DYLDCACHE_FILTER\");\n\tif (target_libs) {\n\t\ttarget_lib_names = r_str_split_list (target_libs, \":\", 0);\n\t\tif (!target_lib_names) {\n\t\t\tr_list_free (bins);\n\t\t\treturn NULL;\n\t\t}\n\t\tdeps = R_NEWS0 (int, cache->hdr->imagesCount);\n\t\tif (!deps) {\n\t\t\tr_list_free (bins);\n\t\t\tr_list_free (target_lib_names);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\tut32 i;\n\tfor (i = 0; i < cache->n_hdr; i++) {\n\t\tcache_hdr_t *hdr = &cache->hdr[i];\n\t\tut64 hdr_offset = cache->hdr_offset[i];\n\t\tut32 maps_index = cache->maps_index[i];\n\t\tcache_img_t *img = read_cache_images (cache->buf, hdr, hdr_offset);\n\t\tif (!img) {\n\t\t\tgoto next;\n\t\t}\n\n\t\tut32 j;\n\t\tif (target_libs) {\n\t\t\tHtPU *path_to_idx = NULL;\n\t\t\tif (cache->accel) {\n\t\t\t\tdepArray = R_NEWS0 (ut16, cache->accel->depListCount);\n\t\t\t\tif (!depArray) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\n\t\t\t\tif (r_buf_fread_at (cache->buf, cache->accel->depListOffset, (ut8*) depArray, \"s\", cache->accel->depListCount) != cache->accel->depListCount * 2) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\n\t\t\t\textras = read_cache_imgextra (cache->buf, hdr, cache->accel);\n\t\t\t\tif (!extras) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpath_to_idx = create_path_to_index (cache->buf, img, hdr);\n\t\t\t}\n\n\t\t\tfor (j = 0; j < hdr->imagesCount; j++) {\n\t\t\t\tbool printing = !deps[j];\n\t\t\t\tchar *lib_name = get_lib_name (cache->buf, &img[j]);\n\t\t\t\tif (!lib_name) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (strstr (lib_name, \"libobjc.A.dylib\")) {\n\t\t\t\t\tdeps[j]++;\n\t\t\t\t}\n\t\t\t\tif (!r_list_find (target_lib_names, lib_name, string_contains)) {\n\t\t\t\t\tR_FREE (lib_name);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (printing) {\n\t\t\t\t\teprintf (\"FILTER: %s\\n\", lib_name);\n\t\t\t\t}\n\t\t\t\tR_FREE (lib_name);\n\t\t\t\tdeps[j]++;\n\n\t\t\t\tif (extras && depArray) {\n\t\t\t\t\tut32 k;\n\t\t\t\t\tfor (k = extras[j].dependentsStartArrayIndex; depArray[k] != 0xffff; k++) {\n\t\t\t\t\t\tut16 dep_index = depArray[k] & 0x7fff;\n\t\t\t\t\t\tdeps[dep_index]++;\n\n\t\t\t\t\t\tchar *dep_name = get_lib_name (cache->buf, &img[dep_index]);\n\t\t\t\t\t\tif (!dep_name) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (printing) {\n\t\t\t\t\t\t\teprintf (\"-> %s\\n\", dep_name);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfree (dep_name);\n\t\t\t\t\t}\n\t\t\t\t} else if (path_to_idx) {\n\t\t\t\t\tcarve_deps_at_address (cache, img, path_to_idx, img[j].address, deps, printing);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tht_pu_free (path_to_idx);\n\t\t\tR_FREE (depArray);\n\t\t\tR_FREE (extras);\n\t\t}\n\n\t\tfor (j = 0; j < hdr->imagesCount; j++) {\n\t\t\tif (deps && !deps[j]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// ut64 pa = va2pa (img[j].address, hdr->mappingCount, &cache->maps[maps_index], cache->buf, 0, NULL, NULL);\n\t\t\tut64 pa = va2pa (img[j].address, cache->n_maps, &cache->maps[maps_index], cache->buf, 0, NULL, NULL);\n\t\t\tif (pa == UT64_MAX) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tut8 magicbytes[4];\n\t\t\tr_buf_read_at (cache->buf, pa, magicbytes, 4);\n\t\t\tint magic = r_read_le32 (magicbytes);\n\t\t\tswitch (magic) {\n\t\t\tcase MH_MAGIC_64:\n\t\t\t{\n\t\t\t\tchar file[256];\n\t\t\t\tRDyldBinImage *bin = R_NEW0 (RDyldBinImage);\n\t\t\t\tif (!bin) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\t\t\t\tbin->header_at = pa;\n\t\t\t\tbin->hdr_offset = hdr_offset;\n\t\t\t\tbin->symbols_off = resolve_symbols_off (cache, pa);\n\t\t\t\tbin->va = img[j].address;\n\t\t\t\tif (r_buf_read_at (cache->buf, img[j].pathFileOffset, (ut8*) &file, sizeof (file)) == sizeof (file)) {\n\t\t\t\t\tfile[255] = 0;\n\t\t\t\t\tchar *last_slash = strrchr (file, '/');\n\t\t\t\t\tif (last_slash && *last_slash) {\n\t\t\t\t\t\tif (last_slash > file) {\n\t\t\t\t\t\t\tchar *scan = last_slash - 1;\n\t\t\t\t\t\t\twhile (scan > file && *scan != '/') {\n\t\t\t\t\t\t\t\tscan--;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (*scan == '/') {\n\t\t\t\t\t\t\t\tbin->file = strdup (scan + 1);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbin->file = strdup (last_slash + 1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tbin->file = strdup (last_slash + 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbin->file = strdup (file);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tr_list_append (bins, bin);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\teprintf (\"Unknown sub-bin\\n\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\nnext:\n\t\tR_FREE (depArray);\n\t\tR_FREE (extras);\n\t\tR_FREE (img);\n\t}\n\tif (r_list_empty (bins)) {\n\t\tr_list_free (bins);\n\t\tbins = NULL;\n\t}\n\tR_FREE (deps);\n\tR_FREE (target_libs);\n\tr_list_free (target_lib_names);\n\treturn bins;\n}", "func_hash": 125973238096905171890400385176953298313, "file_name": "None", "file_hash": null, "cwe": ["CWE-703"], "cve": "CVE-2022-1244", "cve_desc": "heap-buffer-overflow in GitHub repository radareorg/radare2 prior to 5.6.8. This vulnerability is capable of inducing denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1244"}
{"idx": 207803, "project": "linux", "commit_id": "f227e3ec3b5cad859ad15666874405e8c1bbc1d4", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/f227e3ec3b5cad859ad15666874405e8c1bbc1d4", "commit_message": "random32: update the net random state on interrupt and activity\n\nThis modifies the first 32 bits out of the 128 bits of a random CPU's\nnet_rand_state on interrupt or CPU activity to complicate remote\nobservations that could lead to guessing the network RNG's internal\nstate.\n\nNote that depending on some network devices' interrupt rate moderation\nor binding, this re-seeding might happen on every packet or even almost\nnever.\n\nIn addition, with NOHZ some CPUs might not even get timer interrupts,\nleaving their local state rarely updated, while they are running\nnetworked processes making use of the random state.  For this reason, we\nalso perform this update in update_process_times() in order to at least\nupdate the state when there is user or system activity, since it's the\nonly case we care about.\n\nReported-by: Amit Klein \nSuggested-by: Linus Torvalds \nCc: Eric Dumazet \nCc: \"Jason A. Donenfeld\" \nCc: Andy Lutomirski \nCc: Kees Cook \nCc: Thomas Gleixner \nCc: Peter Zijlstra \nCc: \nSigned-off-by: Willy Tarreau \nSigned-off-by: Linus Torvalds ", "target": 1, "func": "void add_interrupt_randomness(int irq, int irq_flags)\n{\n\tstruct entropy_store\t*r;\n\tstruct fast_pool\t*fast_pool = this_cpu_ptr(&irq_randomness);\n\tstruct pt_regs\t\t*regs = get_irq_regs();\n\tunsigned long\t\tnow = jiffies;\n\tcycles_t\t\tcycles = random_get_entropy();\n\t__u32\t\t\tc_high, j_high;\n\t__u64\t\t\tip;\n\tunsigned long\t\tseed;\n\tint\t\t\tcredit = 0;\n\n\tif (cycles == 0)\n\t\tcycles = get_reg(fast_pool, regs);\n\tc_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;\n\tj_high = (sizeof(now) > 4) ? now >> 32 : 0;\n\tfast_pool->pool[0] ^= cycles ^ j_high ^ irq;\n\tfast_pool->pool[1] ^= now ^ c_high;\n\tip = regs ? instruction_pointer(regs) : _RET_IP_;\n\tfast_pool->pool[2] ^= ip;\n\tfast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :\n\t\tget_reg(fast_pool, regs);\n\n\tfast_mix(fast_pool);\n\tadd_interrupt_bench(cycles);\n\n\tif (unlikely(crng_init == 0)) {\n\t\tif ((fast_pool->count >= 64) &&\n\t\t    crng_fast_load((char *) fast_pool->pool,\n\t\t\t\t   sizeof(fast_pool->pool))) {\n\t\t\tfast_pool->count = 0;\n\t\t\tfast_pool->last = now;\n\t\t}\n\t\treturn;\n\t}\n\n\tif ((fast_pool->count < 64) &&\n\t    !time_after(now, fast_pool->last + HZ))\n\t\treturn;\n\n\tr = &input_pool;\n\tif (!spin_trylock(&r->lock))\n\t\treturn;\n\n\tfast_pool->last = now;\n\t__mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));\n\n\t/*\n\t * If we have architectural seed generator, produce a seed and\n\t * add it to the pool.  For the sake of paranoia don't let the\n\t * architectural seed generator dominate the input from the\n\t * interrupt noise.\n\t */\n\tif (arch_get_random_seed_long(&seed)) {\n\t\t__mix_pool_bytes(r, &seed, sizeof(seed));\n\t\tcredit = 1;\n\t}\n\tspin_unlock(&r->lock);\n\n\tfast_pool->count = 0;\n\n\t/* award one bit for the contents of the fast pool */\n\tcredit_entropy_bits(r, credit + 1);\n}", "func_hash": 72986691588442626387015743278968252767, "file_name": "random.c", "file_hash": 239066926887312120799410704296303486044, "cwe": ["CWE-200"], "cve": "CVE-2020-16166", "cve_desc": "The Linux kernel through 5.7.11 allows remote attackers to make observations that help to obtain sensitive information about the internal state of the network RNG, aka CID-f227e3ec3b5c. This is related to drivers/char/random.c and kernel/time/timer.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16166"}
{"idx": 401579, "project": "linux", "commit_id": "f227e3ec3b5cad859ad15666874405e8c1bbc1d4", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/f227e3ec3b5cad859ad15666874405e8c1bbc1d4", "commit_message": "random32: update the net random state on interrupt and activity\n\nThis modifies the first 32 bits out of the 128 bits of a random CPU's\nnet_rand_state on interrupt or CPU activity to complicate remote\nobservations that could lead to guessing the network RNG's internal\nstate.\n\nNote that depending on some network devices' interrupt rate moderation\nor binding, this re-seeding might happen on every packet or even almost\nnever.\n\nIn addition, with NOHZ some CPUs might not even get timer interrupts,\nleaving their local state rarely updated, while they are running\nnetworked processes making use of the random state.  For this reason, we\nalso perform this update in update_process_times() in order to at least\nupdate the state when there is user or system activity, since it's the\nonly case we care about.\n\nReported-by: Amit Klein \nSuggested-by: Linus Torvalds \nCc: Eric Dumazet \nCc: \"Jason A. Donenfeld\" \nCc: Andy Lutomirski \nCc: Kees Cook \nCc: Thomas Gleixner \nCc: Peter Zijlstra \nCc: \nSigned-off-by: Willy Tarreau \nSigned-off-by: Linus Torvalds ", "target": 0, "func": "void add_interrupt_randomness(int irq, int irq_flags)\n{\n\tstruct entropy_store\t*r;\n\tstruct fast_pool\t*fast_pool = this_cpu_ptr(&irq_randomness);\n\tstruct pt_regs\t\t*regs = get_irq_regs();\n\tunsigned long\t\tnow = jiffies;\n\tcycles_t\t\tcycles = random_get_entropy();\n\t__u32\t\t\tc_high, j_high;\n\t__u64\t\t\tip;\n\tunsigned long\t\tseed;\n\tint\t\t\tcredit = 0;\n\n\tif (cycles == 0)\n\t\tcycles = get_reg(fast_pool, regs);\n\tc_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;\n\tj_high = (sizeof(now) > 4) ? now >> 32 : 0;\n\tfast_pool->pool[0] ^= cycles ^ j_high ^ irq;\n\tfast_pool->pool[1] ^= now ^ c_high;\n\tip = regs ? instruction_pointer(regs) : _RET_IP_;\n\tfast_pool->pool[2] ^= ip;\n\tfast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :\n\t\tget_reg(fast_pool, regs);\n\n\tfast_mix(fast_pool);\n\tadd_interrupt_bench(cycles);\n\tthis_cpu_add(net_rand_state.s1, fast_pool->pool[cycles & 3]);\n\n\tif (unlikely(crng_init == 0)) {\n\t\tif ((fast_pool->count >= 64) &&\n\t\t    crng_fast_load((char *) fast_pool->pool,\n\t\t\t\t   sizeof(fast_pool->pool))) {\n\t\t\tfast_pool->count = 0;\n\t\t\tfast_pool->last = now;\n\t\t}\n\t\treturn;\n\t}\n\n\tif ((fast_pool->count < 64) &&\n\t    !time_after(now, fast_pool->last + HZ))\n\t\treturn;\n\n\tr = &input_pool;\n\tif (!spin_trylock(&r->lock))\n\t\treturn;\n\n\tfast_pool->last = now;\n\t__mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));\n\n\t/*\n\t * If we have architectural seed generator, produce a seed and\n\t * add it to the pool.  For the sake of paranoia don't let the\n\t * architectural seed generator dominate the input from the\n\t * interrupt noise.\n\t */\n\tif (arch_get_random_seed_long(&seed)) {\n\t\t__mix_pool_bytes(r, &seed, sizeof(seed));\n\t\tcredit = 1;\n\t}\n\tspin_unlock(&r->lock);\n\n\tfast_pool->count = 0;\n\n\t/* award one bit for the contents of the fast pool */\n\tcredit_entropy_bits(r, credit + 1);\n}", "func_hash": 84995966578306698565240139293878155372, "file_name": "random.c", "file_hash": 208560159054698027072406931437153087485, "cwe": ["CWE-200"], "cve": "CVE-2020-16166", "cve_desc": "The Linux kernel through 5.7.11 allows remote attackers to make observations that help to obtain sensitive information about the internal state of the network RNG, aka CID-f227e3ec3b5c. This is related to drivers/char/random.c and kernel/time/timer.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16166"}
{"idx": 207804, "project": "linux", "commit_id": "f227e3ec3b5cad859ad15666874405e8c1bbc1d4", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/f227e3ec3b5cad859ad15666874405e8c1bbc1d4", "commit_message": "random32: update the net random state on interrupt and activity\n\nThis modifies the first 32 bits out of the 128 bits of a random CPU's\nnet_rand_state on interrupt or CPU activity to complicate remote\nobservations that could lead to guessing the network RNG's internal\nstate.\n\nNote that depending on some network devices' interrupt rate moderation\nor binding, this re-seeding might happen on every packet or even almost\nnever.\n\nIn addition, with NOHZ some CPUs might not even get timer interrupts,\nleaving their local state rarely updated, while they are running\nnetworked processes making use of the random state.  For this reason, we\nalso perform this update in update_process_times() in order to at least\nupdate the state when there is user or system activity, since it's the\nonly case we care about.\n\nReported-by: Amit Klein \nSuggested-by: Linus Torvalds \nCc: Eric Dumazet \nCc: \"Jason A. Donenfeld\" \nCc: Andy Lutomirski \nCc: Kees Cook \nCc: Thomas Gleixner \nCc: Peter Zijlstra \nCc: \nSigned-off-by: Willy Tarreau \nSigned-off-by: Linus Torvalds ", "target": 1, "func": "void update_process_times(int user_tick)\n{\n\tstruct task_struct *p = current;\n\n\t/* Note: this timer irq context must be accounted for as well. */\n\taccount_process_tick(p, user_tick);\n\trun_local_timers();\n\trcu_sched_clock_irq(user_tick);\n#ifdef CONFIG_IRQ_WORK\n\tif (in_irq())\n\t\tirq_work_tick();\n#endif\n\tscheduler_tick();\n\tif (IS_ENABLED(CONFIG_POSIX_TIMERS))\n\t\trun_posix_cpu_timers();\n}", "func_hash": 82612237012862358865324786376664956349, "file_name": "timer.c", "file_hash": 271218236065045560355591111071365801019, "cwe": ["CWE-200"], "cve": "CVE-2020-16166", "cve_desc": "The Linux kernel through 5.7.11 allows remote attackers to make observations that help to obtain sensitive information about the internal state of the network RNG, aka CID-f227e3ec3b5c. This is related to drivers/char/random.c and kernel/time/timer.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16166"}
{"idx": 401525, "project": "linux", "commit_id": "f227e3ec3b5cad859ad15666874405e8c1bbc1d4", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/f227e3ec3b5cad859ad15666874405e8c1bbc1d4", "commit_message": "random32: update the net random state on interrupt and activity\n\nThis modifies the first 32 bits out of the 128 bits of a random CPU's\nnet_rand_state on interrupt or CPU activity to complicate remote\nobservations that could lead to guessing the network RNG's internal\nstate.\n\nNote that depending on some network devices' interrupt rate moderation\nor binding, this re-seeding might happen on every packet or even almost\nnever.\n\nIn addition, with NOHZ some CPUs might not even get timer interrupts,\nleaving their local state rarely updated, while they are running\nnetworked processes making use of the random state.  For this reason, we\nalso perform this update in update_process_times() in order to at least\nupdate the state when there is user or system activity, since it's the\nonly case we care about.\n\nReported-by: Amit Klein \nSuggested-by: Linus Torvalds \nCc: Eric Dumazet \nCc: \"Jason A. Donenfeld\" \nCc: Andy Lutomirski \nCc: Kees Cook \nCc: Thomas Gleixner \nCc: Peter Zijlstra \nCc: \nSigned-off-by: Willy Tarreau \nSigned-off-by: Linus Torvalds ", "target": 0, "func": "void update_process_times(int user_tick)\n{\n\tstruct task_struct *p = current;\n\n\t/* Note: this timer irq context must be accounted for as well. */\n\taccount_process_tick(p, user_tick);\n\trun_local_timers();\n\trcu_sched_clock_irq(user_tick);\n#ifdef CONFIG_IRQ_WORK\n\tif (in_irq())\n\t\tirq_work_tick();\n#endif\n\tscheduler_tick();\n\tif (IS_ENABLED(CONFIG_POSIX_TIMERS))\n\t\trun_posix_cpu_timers();\n\n\t/* The current CPU might make use of net randoms without receiving IRQs\n\t * to renew them often enough. Let's update the net_rand_state from a\n\t * non-constant value that's not affine to the number of calls to make\n\t * sure it's updated when there's some activity (we don't care in idle).\n\t */\n\tthis_cpu_add(net_rand_state.s1, rol32(jiffies, 24) + user_tick);\n}", "func_hash": 311686403025993845778050249928014943417, "file_name": "timer.c", "file_hash": 222103336435375278106670191376448375228, "cwe": ["CWE-200"], "cve": "CVE-2020-16166", "cve_desc": "The Linux kernel through 5.7.11 allows remote attackers to make observations that help to obtain sensitive information about the internal state of the network RNG, aka CID-f227e3ec3b5c. This is related to drivers/char/random.c and kernel/time/timer.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16166"}
{"idx": 207990, "project": "pcre2", "commit_id": "03654e751e7f0700693526b67dfcadda6b42c9d0", "project_url": "https://github.com/PCRE2Project/pcre2", "commit_url": "https://github.com/PCRE2Project/pcre2/commit/03654e751e7f0700693526b67dfcadda6b42c9d0", "commit_message": "Fixed an issue affecting recursions in JIT", "target": 1, "func": "static int get_recurse_data_length(compiler_common *common, PCRE2_SPTR cc, PCRE2_SPTR ccend,\n  BOOL *needs_control_head, BOOL *has_quit, BOOL *has_accept)\n{\nint length = 1;\nint size;\nPCRE2_SPTR alternative;\nBOOL quit_found = FALSE;\nBOOL accept_found = FALSE;\nBOOL setsom_found = FALSE;\nBOOL setmark_found = FALSE;\nBOOL capture_last_found = FALSE;\nBOOL control_head_found = FALSE;\n\n#if defined DEBUG_FORCE_CONTROL_HEAD && DEBUG_FORCE_CONTROL_HEAD\nSLJIT_ASSERT(common->control_head_ptr != 0);\ncontrol_head_found = TRUE;\n#endif\n\n/* Calculate the sum of the private machine words. */\nwhile (cc < ccend)\n  {\n  size = 0;\n  switch(*cc)\n    {\n    case OP_SET_SOM:\n    SLJIT_ASSERT(common->has_set_som);\n    setsom_found = TRUE;\n    cc += 1;\n    break;\n\n    case OP_RECURSE:\n    if (common->has_set_som)\n      setsom_found = TRUE;\n    if (common->mark_ptr != 0)\n      setmark_found = TRUE;\n    if (common->capture_last_ptr != 0)\n      capture_last_found = TRUE;\n    cc += 1 + LINK_SIZE;\n    break;\n\n    case OP_KET:\n    if (PRIVATE_DATA(cc) != 0)\n      {\n      length++;\n      SLJIT_ASSERT(PRIVATE_DATA(cc + 1) != 0);\n      cc += PRIVATE_DATA(cc + 1);\n      }\n    cc += 1 + LINK_SIZE;\n    break;\n\n    case OP_ASSERT:\n    case OP_ASSERT_NOT:\n    case OP_ASSERTBACK:\n    case OP_ASSERTBACK_NOT:\n    case OP_ASSERT_NA:\n    case OP_ASSERTBACK_NA:\n    case OP_ONCE:\n    case OP_SCRIPT_RUN:\n    case OP_BRAPOS:\n    case OP_SBRA:\n    case OP_SBRAPOS:\n    case OP_SCOND:\n    length++;\n    SLJIT_ASSERT(PRIVATE_DATA(cc) != 0);\n    cc += 1 + LINK_SIZE;\n    break;\n\n    case OP_CBRA:\n    case OP_SCBRA:\n    length += 2;\n    if (common->capture_last_ptr != 0)\n      capture_last_found = TRUE;\n    if (common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] == 0)\n      length++;\n    cc += 1 + LINK_SIZE + IMM2_SIZE;\n    break;\n\n    case OP_CBRAPOS:\n    case OP_SCBRAPOS:\n    length += 2 + 2;\n    if (common->capture_last_ptr != 0)\n      capture_last_found = TRUE;\n    cc += 1 + LINK_SIZE + IMM2_SIZE;\n    break;\n\n    case OP_COND:\n    /* Might be a hidden SCOND. */\n    alternative = cc + GET(cc, 1);\n    if (*alternative == OP_KETRMAX || *alternative == OP_KETRMIN)\n      length++;\n    cc += 1 + LINK_SIZE;\n    break;\n\n    CASE_ITERATOR_PRIVATE_DATA_1\n    if (PRIVATE_DATA(cc) != 0)\n      length++;\n    cc += 2;\n#ifdef SUPPORT_UNICODE\n    if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);\n#endif\n    break;\n\n    CASE_ITERATOR_PRIVATE_DATA_2A\n    if (PRIVATE_DATA(cc) != 0)\n      length += 2;\n    cc += 2;\n#ifdef SUPPORT_UNICODE\n    if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);\n#endif\n    break;\n\n    CASE_ITERATOR_PRIVATE_DATA_2B\n    if (PRIVATE_DATA(cc) != 0)\n      length += 2;\n    cc += 2 + IMM2_SIZE;\n#ifdef SUPPORT_UNICODE\n    if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);\n#endif\n    break;\n\n    CASE_ITERATOR_TYPE_PRIVATE_DATA_1\n    if (PRIVATE_DATA(cc) != 0)\n      length++;\n    cc += 1;\n    break;\n\n    CASE_ITERATOR_TYPE_PRIVATE_DATA_2A\n    if (PRIVATE_DATA(cc) != 0)\n      length += 2;\n    cc += 1;\n    break;\n\n    CASE_ITERATOR_TYPE_PRIVATE_DATA_2B\n    if (PRIVATE_DATA(cc) != 0)\n      length += 2;\n    cc += 1 + IMM2_SIZE;\n    break;\n\n    case OP_CLASS:\n    case OP_NCLASS:\n#if defined SUPPORT_UNICODE || PCRE2_CODE_UNIT_WIDTH != 8\n    case OP_XCLASS:\n    size = (*cc == OP_XCLASS) ? GET(cc, 1) : 1 + 32 / (int)sizeof(PCRE2_UCHAR);\n#else\n    size = 1 + 32 / (int)sizeof(PCRE2_UCHAR);\n#endif\n    if (PRIVATE_DATA(cc) != 0)\n      length += get_class_iterator_size(cc + size);\n    cc += size;\n    break;\n\n    case OP_MARK:\n    case OP_COMMIT_ARG:\n    case OP_PRUNE_ARG:\n    case OP_THEN_ARG:\n    SLJIT_ASSERT(common->mark_ptr != 0);\n    if (!setmark_found)\n      setmark_found = TRUE;\n    if (common->control_head_ptr != 0)\n      control_head_found = TRUE;\n    if (*cc != OP_MARK)\n      quit_found = TRUE;\n\n    cc += 1 + 2 + cc[1];\n    break;\n\n    case OP_PRUNE:\n    case OP_SKIP:\n    case OP_COMMIT:\n    quit_found = TRUE;\n    cc++;\n    break;\n\n    case OP_SKIP_ARG:\n    quit_found = TRUE;\n    cc += 1 + 2 + cc[1];\n    break;\n\n    case OP_THEN:\n    SLJIT_ASSERT(common->control_head_ptr != 0);\n    quit_found = TRUE;\n    if (!control_head_found)\n      control_head_found = TRUE;\n    cc++;\n    break;\n\n    case OP_ACCEPT:\n    case OP_ASSERT_ACCEPT:\n    accept_found = TRUE;\n    cc++;\n    break;\n\n    default:\n    cc = next_opcode(common, cc);\n    SLJIT_ASSERT(cc != NULL);\n    break;\n    }\n  }\nSLJIT_ASSERT(cc == ccend);\n\nif (control_head_found)\n  length++;\nif (capture_last_found)\n  length++;\nif (quit_found)\n  {\n  if (setsom_found)\n    length++;\n  if (setmark_found)\n    length++;\n  }\n\n*needs_control_head = control_head_found;\n*has_quit = quit_found;\n*has_accept = accept_found;\nreturn length;\n}", "func_hash": 240126232931244050288328890875640372325, "file_name": "pcre2_jit_compile.c", "file_hash": 105541590302198799083513857874765354258, "cwe": ["CWE-703"], "cve": "CVE-2022-1587", "cve_desc": "An out-of-bounds read vulnerability was discovered in the PCRE2 library in the get_recurse_data_length() function of the pcre2_jit_compile.c file. This issue affects recursions in JIT-compiled regular expressions caused by duplicate data transfers.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1587"}
{"idx": 404192, "project": "pcre2", "commit_id": "03654e751e7f0700693526b67dfcadda6b42c9d0", "project_url": "https://github.com/PCRE2Project/pcre2", "commit_url": "https://github.com/PCRE2Project/pcre2/commit/03654e751e7f0700693526b67dfcadda6b42c9d0", "commit_message": "Fixed an issue affecting recursions in JIT", "target": 0, "func": "static int get_recurse_data_length(compiler_common *common, PCRE2_SPTR cc, PCRE2_SPTR ccend,\n  BOOL *needs_control_head, BOOL *has_quit, BOOL *has_accept)\n{\nint length = 1;\nint size, offset;\nPCRE2_SPTR alternative;\nBOOL quit_found = FALSE;\nBOOL accept_found = FALSE;\nBOOL setsom_found = FALSE;\nBOOL setmark_found = FALSE;\nBOOL control_head_found = FALSE;\n\nmemset(common->recurse_bitset, 0, common->recurse_bitset_size);\n\n#if defined DEBUG_FORCE_CONTROL_HEAD && DEBUG_FORCE_CONTROL_HEAD\nSLJIT_ASSERT(common->control_head_ptr != 0);\ncontrol_head_found = TRUE;\n#endif\n\n/* Calculate the sum of the private machine words. */\nwhile (cc < ccend)\n  {\n  size = 0;\n  switch(*cc)\n    {\n    case OP_SET_SOM:\n    SLJIT_ASSERT(common->has_set_som);\n    setsom_found = TRUE;\n    cc += 1;\n    break;\n\n    case OP_RECURSE:\n    if (common->has_set_som)\n      setsom_found = TRUE;\n    if (common->mark_ptr != 0)\n      setmark_found = TRUE;\n    if (common->capture_last_ptr != 0 && recurse_check_bit(common, common->capture_last_ptr))\n      length++;\n    cc += 1 + LINK_SIZE;\n    break;\n\n    case OP_KET:\n    offset = PRIVATE_DATA(cc);\n    if (offset != 0)\n      {\n      if (recurse_check_bit(common, offset))\n        length++;\n      SLJIT_ASSERT(PRIVATE_DATA(cc + 1) != 0);\n      cc += PRIVATE_DATA(cc + 1);\n      }\n    cc += 1 + LINK_SIZE;\n    break;\n\n    case OP_ASSERT:\n    case OP_ASSERT_NOT:\n    case OP_ASSERTBACK:\n    case OP_ASSERTBACK_NOT:\n    case OP_ASSERT_NA:\n    case OP_ASSERTBACK_NA:\n    case OP_ONCE:\n    case OP_SCRIPT_RUN:\n    case OP_BRAPOS:\n    case OP_SBRA:\n    case OP_SBRAPOS:\n    case OP_SCOND:\n    SLJIT_ASSERT(PRIVATE_DATA(cc) != 0);\n    if (recurse_check_bit(common, PRIVATE_DATA(cc)))\n      length++;\n    cc += 1 + LINK_SIZE;\n    break;\n\n    case OP_CBRA:\n    case OP_SCBRA:\n    offset = GET2(cc, 1 + LINK_SIZE);\n    if (recurse_check_bit(common, OVECTOR(offset << 1)))\n      {\n      SLJIT_ASSERT(recurse_check_bit(common, OVECTOR((offset << 1) + 1)));\n      length += 2;\n      }\n    if (common->optimized_cbracket[offset] == 0 && recurse_check_bit(common, OVECTOR_PRIV(offset)))\n      length++;\n    if (common->capture_last_ptr != 0 && recurse_check_bit(common, common->capture_last_ptr))\n      length++;\n    cc += 1 + LINK_SIZE + IMM2_SIZE;\n    break;\n\n    case OP_CBRAPOS:\n    case OP_SCBRAPOS:\n    offset = GET2(cc, 1 + LINK_SIZE);\n    if (recurse_check_bit(common, OVECTOR(offset << 1)))\n      {\n      SLJIT_ASSERT(recurse_check_bit(common, OVECTOR((offset << 1) + 1)));\n      length += 2;\n      }\n    if (recurse_check_bit(common, OVECTOR_PRIV(offset)))\n      length++;\n    if (recurse_check_bit(common, PRIVATE_DATA(cc)))\n      length++;\n    if (common->capture_last_ptr != 0 && recurse_check_bit(common, common->capture_last_ptr))\n      length++;\n    cc += 1 + LINK_SIZE + IMM2_SIZE;\n    break;\n\n    case OP_COND:\n    /* Might be a hidden SCOND. */\n    alternative = cc + GET(cc, 1);\n    if ((*alternative == OP_KETRMAX || *alternative == OP_KETRMIN) && recurse_check_bit(common, PRIVATE_DATA(cc)))\n      length++;\n    cc += 1 + LINK_SIZE;\n    break;\n\n    CASE_ITERATOR_PRIVATE_DATA_1\n    offset = PRIVATE_DATA(cc);\n    if (offset != 0 && recurse_check_bit(common, offset))\n      length++;\n    cc += 2;\n#ifdef SUPPORT_UNICODE\n    if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);\n#endif\n    break;\n\n    CASE_ITERATOR_PRIVATE_DATA_2A\n    offset = PRIVATE_DATA(cc);\n    if (offset != 0 && recurse_check_bit(common, offset))\n      {\n      SLJIT_ASSERT(recurse_check_bit(common, offset + sizeof(sljit_sw)));\n      length += 2;\n      }\n    cc += 2;\n#ifdef SUPPORT_UNICODE\n    if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);\n#endif\n    break;\n\n    CASE_ITERATOR_PRIVATE_DATA_2B\n    offset = PRIVATE_DATA(cc);\n    if (offset != 0 && recurse_check_bit(common, offset))\n      {\n      SLJIT_ASSERT(recurse_check_bit(common, offset + sizeof(sljit_sw)));\n      length += 2;\n      }\n    cc += 2 + IMM2_SIZE;\n#ifdef SUPPORT_UNICODE\n    if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);\n#endif\n    break;\n\n    CASE_ITERATOR_TYPE_PRIVATE_DATA_1\n    offset = PRIVATE_DATA(cc);\n    if (offset != 0 && recurse_check_bit(common, offset))\n      length++;\n    cc += 1;\n    break;\n\n    CASE_ITERATOR_TYPE_PRIVATE_DATA_2A\n    offset = PRIVATE_DATA(cc);\n    if (offset != 0 && recurse_check_bit(common, offset))\n      {\n      SLJIT_ASSERT(recurse_check_bit(common, offset + sizeof(sljit_sw)));\n      length += 2;\n      }\n    cc += 1;\n    break;\n\n    CASE_ITERATOR_TYPE_PRIVATE_DATA_2B\n    offset = PRIVATE_DATA(cc);\n    if (offset != 0 && recurse_check_bit(common, offset))\n      {\n      SLJIT_ASSERT(recurse_check_bit(common, offset + sizeof(sljit_sw)));\n      length += 2;\n      }\n    cc += 1 + IMM2_SIZE;\n    break;\n\n    case OP_CLASS:\n    case OP_NCLASS:\n#if defined SUPPORT_UNICODE || PCRE2_CODE_UNIT_WIDTH != 8\n    case OP_XCLASS:\n    size = (*cc == OP_XCLASS) ? GET(cc, 1) : 1 + 32 / (int)sizeof(PCRE2_UCHAR);\n#else\n    size = 1 + 32 / (int)sizeof(PCRE2_UCHAR);\n#endif\n\n    offset = PRIVATE_DATA(cc);\n    if (offset != 0 && recurse_check_bit(common, offset))\n      length += get_class_iterator_size(cc + size);\n    cc += size;\n    break;\n\n    case OP_MARK:\n    case OP_COMMIT_ARG:\n    case OP_PRUNE_ARG:\n    case OP_THEN_ARG:\n    SLJIT_ASSERT(common->mark_ptr != 0);\n    if (!setmark_found)\n      setmark_found = TRUE;\n    if (common->control_head_ptr != 0)\n      control_head_found = TRUE;\n    if (*cc != OP_MARK)\n      quit_found = TRUE;\n\n    cc += 1 + 2 + cc[1];\n    break;\n\n    case OP_PRUNE:\n    case OP_SKIP:\n    case OP_COMMIT:\n    quit_found = TRUE;\n    cc++;\n    break;\n\n    case OP_SKIP_ARG:\n    quit_found = TRUE;\n    cc += 1 + 2 + cc[1];\n    break;\n\n    case OP_THEN:\n    SLJIT_ASSERT(common->control_head_ptr != 0);\n    quit_found = TRUE;\n    control_head_found = TRUE;\n    cc++;\n    break;\n\n    case OP_ACCEPT:\n    case OP_ASSERT_ACCEPT:\n    accept_found = TRUE;\n    cc++;\n    break;\n\n    default:\n    cc = next_opcode(common, cc);\n    SLJIT_ASSERT(cc != NULL);\n    break;\n    }\n  }\nSLJIT_ASSERT(cc == ccend);\n\nif (control_head_found)\n  length++;\nif (quit_found)\n  {\n  if (setsom_found)\n    length++;\n  if (setmark_found)\n    length++;\n  }\n\n*needs_control_head = control_head_found;\n*has_quit = quit_found;\n*has_accept = accept_found;\nreturn length;\n}", "func_hash": 173942933444712771516446324481674462692, "file_name": "pcre2_jit_compile.c", "file_hash": 52374969195278947710795935639555031915, "cwe": ["CWE-703"], "cve": "CVE-2022-1587", "cve_desc": "An out-of-bounds read vulnerability was discovered in the PCRE2 library in the get_recurse_data_length() function of the pcre2_jit_compile.c file. This issue affects recursions in JIT-compiled regular expressions caused by duplicate data transfers.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1587"}
{"idx": 208107, "project": "linux", "commit_id": "f85daf0e725358be78dfd208dea5fd665d8cb901", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/f85daf0e725358be78dfd208dea5fd665d8cb901", "commit_message": "xfrm: xfrm_policy: fix a possible double xfrm_pols_put() in xfrm_bundle_lookup()\n\nxfrm_policy_lookup() will call xfrm_pol_hold_rcu() to get a refcount of\npols[0]. This refcount can be dropped in xfrm_expand_policies() when\nxfrm_expand_policies() return error. pols[0]'s refcount is balanced in\nhere. But xfrm_bundle_lookup() will also call xfrm_pols_put() with\nnum_pols == 1 to drop this refcount when xfrm_expand_policies() return\nerror.\n\nThis patch also fix an illegal address access. pols[0] will save a error\npoint when xfrm_policy_lookup fails. This lead to xfrm_pols_put to resolve\nan illegal address in xfrm_bundle_lookup's error path.\n\nFix these by setting num_pols = 0 in xfrm_expand_policies()'s error path.\n\nFixes: 80c802f3073e (\"xfrm: cache bundles instead of policies for outgoing flows\")\nSigned-off-by: Hangyu Hua \nSigned-off-by: Steffen Klassert ", "target": 1, "func": "static int xfrm_expand_policies(const struct flowi *fl, u16 family,\n\t\t\t\tstruct xfrm_policy **pols,\n\t\t\t\tint *num_pols, int *num_xfrms)\n{\n\tint i;\n\n\tif (*num_pols == 0 || !pols[0]) {\n\t\t*num_pols = 0;\n\t\t*num_xfrms = 0;\n\t\treturn 0;\n\t}\n\tif (IS_ERR(pols[0]))\n\t\treturn PTR_ERR(pols[0]);\n\n\t*num_xfrms = pols[0]->xfrm_nr;\n\n#ifdef CONFIG_XFRM_SUB_POLICY\n\tif (pols[0]->action == XFRM_POLICY_ALLOW &&\n\t    pols[0]->type != XFRM_POLICY_TYPE_MAIN) {\n\t\tpols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),\n\t\t\t\t\t\t    XFRM_POLICY_TYPE_MAIN,\n\t\t\t\t\t\t    fl, family,\n\t\t\t\t\t\t    XFRM_POLICY_OUT,\n\t\t\t\t\t\t    pols[0]->if_id);\n\t\tif (pols[1]) {\n\t\t\tif (IS_ERR(pols[1])) {\n\t\t\t\txfrm_pols_put(pols, *num_pols);\n\t\t\t\treturn PTR_ERR(pols[1]);\n\t\t\t}\n\t\t\t(*num_pols)++;\n\t\t\t(*num_xfrms) += pols[1]->xfrm_nr;\n\t\t}\n\t}\n#endif\n\tfor (i = 0; i < *num_pols; i++) {\n\t\tif (pols[i]->action != XFRM_POLICY_ALLOW) {\n\t\t\t*num_xfrms = -1;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn 0;\n\n}", "func_hash": 251684023315514826982518858194996142213, "file_name": "xfrm_policy.c", "file_hash": 240690312801703995044299112379503581676, "cwe": ["CWE-703"], "cve": "CVE-2022-36879", "cve_desc": "An issue was discovered in the Linux kernel through 5.18.14. xfrm_expand_policies in net/xfrm/xfrm_policy.c can cause a refcount to be dropped twice.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-36879"}
{"idx": 405333, "project": "linux", "commit_id": "f85daf0e725358be78dfd208dea5fd665d8cb901", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/f85daf0e725358be78dfd208dea5fd665d8cb901", "commit_message": "xfrm: xfrm_policy: fix a possible double xfrm_pols_put() in xfrm_bundle_lookup()\n\nxfrm_policy_lookup() will call xfrm_pol_hold_rcu() to get a refcount of\npols[0]. This refcount can be dropped in xfrm_expand_policies() when\nxfrm_expand_policies() return error. pols[0]'s refcount is balanced in\nhere. But xfrm_bundle_lookup() will also call xfrm_pols_put() with\nnum_pols == 1 to drop this refcount when xfrm_expand_policies() return\nerror.\n\nThis patch also fix an illegal address access. pols[0] will save a error\npoint when xfrm_policy_lookup fails. This lead to xfrm_pols_put to resolve\nan illegal address in xfrm_bundle_lookup's error path.\n\nFix these by setting num_pols = 0 in xfrm_expand_policies()'s error path.\n\nFixes: 80c802f3073e (\"xfrm: cache bundles instead of policies for outgoing flows\")\nSigned-off-by: Hangyu Hua \nSigned-off-by: Steffen Klassert ", "target": 0, "func": "static int xfrm_expand_policies(const struct flowi *fl, u16 family,\n\t\t\t\tstruct xfrm_policy **pols,\n\t\t\t\tint *num_pols, int *num_xfrms)\n{\n\tint i;\n\n\tif (*num_pols == 0 || !pols[0]) {\n\t\t*num_pols = 0;\n\t\t*num_xfrms = 0;\n\t\treturn 0;\n\t}\n\tif (IS_ERR(pols[0])) {\n\t\t*num_pols = 0;\n\t\treturn PTR_ERR(pols[0]);\n\t}\n\n\t*num_xfrms = pols[0]->xfrm_nr;\n\n#ifdef CONFIG_XFRM_SUB_POLICY\n\tif (pols[0]->action == XFRM_POLICY_ALLOW &&\n\t    pols[0]->type != XFRM_POLICY_TYPE_MAIN) {\n\t\tpols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),\n\t\t\t\t\t\t    XFRM_POLICY_TYPE_MAIN,\n\t\t\t\t\t\t    fl, family,\n\t\t\t\t\t\t    XFRM_POLICY_OUT,\n\t\t\t\t\t\t    pols[0]->if_id);\n\t\tif (pols[1]) {\n\t\t\tif (IS_ERR(pols[1])) {\n\t\t\t\txfrm_pols_put(pols, *num_pols);\n\t\t\t\t*num_pols = 0;\n\t\t\t\treturn PTR_ERR(pols[1]);\n\t\t\t}\n\t\t\t(*num_pols)++;\n\t\t\t(*num_xfrms) += pols[1]->xfrm_nr;\n\t\t}\n\t}\n#endif\n\tfor (i = 0; i < *num_pols; i++) {\n\t\tif (pols[i]->action != XFRM_POLICY_ALLOW) {\n\t\t\t*num_xfrms = -1;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn 0;\n\n}", "func_hash": 29732626654088535700777069321150029090, "file_name": "xfrm_policy.c", "file_hash": 264724924246430289692801756816591917107, "cwe": ["CWE-703"], "cve": "CVE-2022-36879", "cve_desc": "An issue was discovered in the Linux kernel through 5.18.14. xfrm_expand_policies in net/xfrm/xfrm_policy.c can cause a refcount to be dropped twice.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-36879"}
{"idx": 208115, "project": "linux", "commit_id": "d0d62baa7f505bd4c59cd169692ff07ec49dde37", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/d0d62baa7f505bd4c59cd169692ff07ec49dde37", "commit_message": "net: xilinx_emaclite: Do not print real IOMEM pointer\n\nPrinting kernel pointers is discouraged because they might leak kernel\nmemory layout.  This fixes smatch warning:\n\ndrivers/net/ethernet/xilinx/xilinx_emaclite.c:1191 xemaclite_of_probe() warn:\n argument 4 to %08lX specifier is cast from pointer\n\nSigned-off-by: YueHaibing \nSigned-off-by: David S. Miller ", "target": 1, "func": "static int xemaclite_of_probe(struct platform_device *ofdev)\n{\n\tstruct resource *res;\n\tstruct net_device *ndev = NULL;\n\tstruct net_local *lp = NULL;\n\tstruct device *dev = &ofdev->dev;\n\n\tint rc = 0;\n\n\tdev_info(dev, \"Device Tree Probing\\n\");\n\n\t/* Create an ethernet device instance */\n\tndev = alloc_etherdev(sizeof(struct net_local));\n\tif (!ndev)\n\t\treturn -ENOMEM;\n\n\tdev_set_drvdata(dev, ndev);\n\tSET_NETDEV_DEV(ndev, &ofdev->dev);\n\n\tlp = netdev_priv(ndev);\n\tlp->ndev = ndev;\n\n\t/* Get IRQ for the device */\n\tres = platform_get_resource(ofdev, IORESOURCE_IRQ, 0);\n\tif (!res) {\n\t\tdev_err(dev, \"no IRQ found\\n\");\n\t\trc = -ENXIO;\n\t\tgoto error;\n\t}\n\n\tndev->irq = res->start;\n\n\tres = platform_get_resource(ofdev, IORESOURCE_MEM, 0);\n\tlp->base_addr = devm_ioremap_resource(&ofdev->dev, res);\n\tif (IS_ERR(lp->base_addr)) {\n\t\trc = PTR_ERR(lp->base_addr);\n\t\tgoto error;\n\t}\n\n\tndev->mem_start = res->start;\n\tndev->mem_end = res->end;\n\n\tspin_lock_init(&lp->reset_lock);\n\tlp->next_tx_buf_to_use = 0x0;\n\tlp->next_rx_buf_to_use = 0x0;\n\tlp->tx_ping_pong = get_bool(ofdev, \"xlnx,tx-ping-pong\");\n\tlp->rx_ping_pong = get_bool(ofdev, \"xlnx,rx-ping-pong\");\n\n\trc = of_get_mac_address(ofdev->dev.of_node, ndev->dev_addr);\n\tif (rc) {\n\t\tdev_warn(dev, \"No MAC address found, using random\\n\");\n\t\teth_hw_addr_random(ndev);\n\t}\n\n\t/* Clear the Tx CSR's in case this is a restart */\n\txemaclite_writel(0, lp->base_addr + XEL_TSR_OFFSET);\n\txemaclite_writel(0, lp->base_addr + XEL_BUFFER_OFFSET + XEL_TSR_OFFSET);\n\n\t/* Set the MAC address in the EmacLite device */\n\txemaclite_update_address(lp, ndev->dev_addr);\n\n\tlp->phy_node = of_parse_phandle(ofdev->dev.of_node, \"phy-handle\", 0);\n\txemaclite_mdio_setup(lp, &ofdev->dev);\n\n\tdev_info(dev, \"MAC address is now %pM\\n\", ndev->dev_addr);\n\n\tndev->netdev_ops = &xemaclite_netdev_ops;\n\tndev->ethtool_ops = &xemaclite_ethtool_ops;\n\tndev->flags &= ~IFF_MULTICAST;\n\tndev->watchdog_timeo = TX_TIMEOUT;\n\n\t/* Finally, register the device */\n\trc = register_netdev(ndev);\n\tif (rc) {\n\t\tdev_err(dev,\n\t\t\t\"Cannot register network device, aborting\\n\");\n\t\tgoto error;\n\t}\n\n\tdev_info(dev,\n\t\t \"Xilinx EmacLite at 0x%08lX mapped to 0x%08lX, irq=%d\\n\",\n\t\t (unsigned long __force)ndev->mem_start,\n\t\t (unsigned long __force)lp->base_addr, ndev->irq);\n\treturn 0;\n\nerror:\n\tfree_netdev(ndev);\n\treturn rc;\n}", "func_hash": 7539144956808128275181130217400039273, "file_name": "xilinx_emaclite.c", "file_hash": 195328153780575985681144288401844286686, "cwe": ["CWE-703"], "cve": "CVE-2021-38205", "cve_desc": "drivers/net/ethernet/xilinx/xilinx_emaclite.c in the Linux kernel before 5.13.3 makes it easier for attackers to defeat an ASLR protection mechanism because it prints a kernel pointer (i.e., the real IOMEM pointer).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-38205"}
{"idx": 405698, "project": "linux", "commit_id": "d0d62baa7f505bd4c59cd169692ff07ec49dde37", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/d0d62baa7f505bd4c59cd169692ff07ec49dde37", "commit_message": "net: xilinx_emaclite: Do not print real IOMEM pointer\n\nPrinting kernel pointers is discouraged because they might leak kernel\nmemory layout.  This fixes smatch warning:\n\ndrivers/net/ethernet/xilinx/xilinx_emaclite.c:1191 xemaclite_of_probe() warn:\n argument 4 to %08lX specifier is cast from pointer\n\nSigned-off-by: YueHaibing \nSigned-off-by: David S. Miller ", "target": 0, "func": "static int xemaclite_of_probe(struct platform_device *ofdev)\n{\n\tstruct resource *res;\n\tstruct net_device *ndev = NULL;\n\tstruct net_local *lp = NULL;\n\tstruct device *dev = &ofdev->dev;\n\n\tint rc = 0;\n\n\tdev_info(dev, \"Device Tree Probing\\n\");\n\n\t/* Create an ethernet device instance */\n\tndev = alloc_etherdev(sizeof(struct net_local));\n\tif (!ndev)\n\t\treturn -ENOMEM;\n\n\tdev_set_drvdata(dev, ndev);\n\tSET_NETDEV_DEV(ndev, &ofdev->dev);\n\n\tlp = netdev_priv(ndev);\n\tlp->ndev = ndev;\n\n\t/* Get IRQ for the device */\n\tres = platform_get_resource(ofdev, IORESOURCE_IRQ, 0);\n\tif (!res) {\n\t\tdev_err(dev, \"no IRQ found\\n\");\n\t\trc = -ENXIO;\n\t\tgoto error;\n\t}\n\n\tndev->irq = res->start;\n\n\tres = platform_get_resource(ofdev, IORESOURCE_MEM, 0);\n\tlp->base_addr = devm_ioremap_resource(&ofdev->dev, res);\n\tif (IS_ERR(lp->base_addr)) {\n\t\trc = PTR_ERR(lp->base_addr);\n\t\tgoto error;\n\t}\n\n\tndev->mem_start = res->start;\n\tndev->mem_end = res->end;\n\n\tspin_lock_init(&lp->reset_lock);\n\tlp->next_tx_buf_to_use = 0x0;\n\tlp->next_rx_buf_to_use = 0x0;\n\tlp->tx_ping_pong = get_bool(ofdev, \"xlnx,tx-ping-pong\");\n\tlp->rx_ping_pong = get_bool(ofdev, \"xlnx,rx-ping-pong\");\n\n\trc = of_get_mac_address(ofdev->dev.of_node, ndev->dev_addr);\n\tif (rc) {\n\t\tdev_warn(dev, \"No MAC address found, using random\\n\");\n\t\teth_hw_addr_random(ndev);\n\t}\n\n\t/* Clear the Tx CSR's in case this is a restart */\n\txemaclite_writel(0, lp->base_addr + XEL_TSR_OFFSET);\n\txemaclite_writel(0, lp->base_addr + XEL_BUFFER_OFFSET + XEL_TSR_OFFSET);\n\n\t/* Set the MAC address in the EmacLite device */\n\txemaclite_update_address(lp, ndev->dev_addr);\n\n\tlp->phy_node = of_parse_phandle(ofdev->dev.of_node, \"phy-handle\", 0);\n\txemaclite_mdio_setup(lp, &ofdev->dev);\n\n\tdev_info(dev, \"MAC address is now %pM\\n\", ndev->dev_addr);\n\n\tndev->netdev_ops = &xemaclite_netdev_ops;\n\tndev->ethtool_ops = &xemaclite_ethtool_ops;\n\tndev->flags &= ~IFF_MULTICAST;\n\tndev->watchdog_timeo = TX_TIMEOUT;\n\n\t/* Finally, register the device */\n\trc = register_netdev(ndev);\n\tif (rc) {\n\t\tdev_err(dev,\n\t\t\t\"Cannot register network device, aborting\\n\");\n\t\tgoto error;\n\t}\n\n\tdev_info(dev,\n\t\t \"Xilinx EmacLite at 0x%08lX mapped to 0x%p, irq=%d\\n\",\n\t\t (unsigned long __force)ndev->mem_start, lp->base_addr, ndev->irq);\n\treturn 0;\n\nerror:\n\tfree_netdev(ndev);\n\treturn rc;\n}", "func_hash": 304374419764415204432847844541033449466, "file_name": "xilinx_emaclite.c", "file_hash": 308517377946216969047380117029804691833, "cwe": ["CWE-703"], "cve": "CVE-2021-38205", "cve_desc": "drivers/net/ethernet/xilinx/xilinx_emaclite.c in the Linux kernel before 5.13.3 makes it easier for attackers to defeat an ASLR protection mechanism because it prints a kernel pointer (i.e., the real IOMEM pointer).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-38205"}
{"idx": 208140, "project": "util-linux", "commit_id": "5ebbc3865d1e53ef42e5f121c41faab23dd59075", "project_url": "https://github.com/karelzak/util-linux", "commit_url": "http://git.kernel.org/?p=utils/util-linux/util-linux.git;a=commit;h=5ebbc3865d1e53ef42e5f121c41faab23dd59075", "commit_message": "mount: sanitize paths from non-root users\n\n $ mount /root/.ssh/../../dev/sda2\n mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot\n\nthis is too promiscuous. It seems better to ignore on command line\nspecified paths which are not resolve-able for non-root users.\n\nFixed version:\n\n  $ mount /root/.ssh/../../dev/sda2\n  mount: /root/.ssh/../../dev/sda2: Permission denied\n\n  $ mount /dev/sda2\n  mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot\n\nNote that this bug has no relation to mount(2) permissions evaluation\nin suid mode. The way how non-root user specifies paths on command\nline is completely irrelevant for comparison with fstab entries.\n\nSigned-off-by: Karel Zak ", "target": 1, "func": "int main(int argc, char **argv)\n{\n\tint c, rc = MOUNT_EX_SUCCESS, all = 0, show_labels = 0;\n\tstruct libmnt_context *cxt;\n\tstruct libmnt_table *fstab = NULL;\n\tchar *srcbuf = NULL;\n\tchar *types = NULL;\n\tunsigned long oper = 0;\n\n\tenum {\n\t\tMOUNT_OPT_SHARED = CHAR_MAX + 1,\n\t\tMOUNT_OPT_SLAVE,\n\t\tMOUNT_OPT_PRIVATE,\n\t\tMOUNT_OPT_UNBINDABLE,\n\t\tMOUNT_OPT_RSHARED,\n\t\tMOUNT_OPT_RSLAVE,\n\t\tMOUNT_OPT_RPRIVATE,\n\t\tMOUNT_OPT_RUNBINDABLE,\n\t\tMOUNT_OPT_TARGET,\n\t\tMOUNT_OPT_SOURCE\n\t};\n\n\tstatic const struct option longopts[] = {\n\t\t{ \"all\", 0, 0, 'a' },\n\t\t{ \"fake\", 0, 0, 'f' },\n\t\t{ \"fstab\", 1, 0, 'T' },\n\t\t{ \"fork\", 0, 0, 'F' },\n\t\t{ \"help\", 0, 0, 'h' },\n\t\t{ \"no-mtab\", 0, 0, 'n' },\n\t\t{ \"read-only\", 0, 0, 'r' },\n\t\t{ \"ro\", 0, 0, 'r' },\n\t\t{ \"verbose\", 0, 0, 'v' },\n\t\t{ \"version\", 0, 0, 'V' },\n\t\t{ \"read-write\", 0, 0, 'w' },\n\t\t{ \"rw\", 0, 0, 'w' },\n\t\t{ \"options\", 1, 0, 'o' },\n\t\t{ \"test-opts\", 1, 0, 'O' },\n\t\t{ \"pass-fd\", 1, 0, 'p' },\n\t\t{ \"types\", 1, 0, 't' },\n\t\t{ \"uuid\", 1, 0, 'U' },\n\t\t{ \"label\", 1, 0, 'L'},\n\t\t{ \"bind\", 0, 0, 'B' },\n\t\t{ \"move\", 0, 0, 'M' },\n\t\t{ \"rbind\", 0, 0, 'R' },\n\t\t{ \"make-shared\", 0, 0, MOUNT_OPT_SHARED },\n\t\t{ \"make-slave\", 0, 0, MOUNT_OPT_SLAVE },\n\t\t{ \"make-private\", 0, 0, MOUNT_OPT_PRIVATE },\n\t\t{ \"make-unbindable\", 0, 0, MOUNT_OPT_UNBINDABLE },\n\t\t{ \"make-rshared\", 0, 0, MOUNT_OPT_RSHARED },\n\t\t{ \"make-rslave\", 0, 0, MOUNT_OPT_RSLAVE },\n\t\t{ \"make-rprivate\", 0, 0, MOUNT_OPT_RPRIVATE },\n\t\t{ \"make-runbindable\", 0, 0, MOUNT_OPT_RUNBINDABLE },\n\t\t{ \"no-canonicalize\", 0, 0, 'c' },\n\t\t{ \"internal-only\", 0, 0, 'i' },\n\t\t{ \"show-labels\", 0, 0, 'l' },\n\t\t{ \"target\", 1, 0, MOUNT_OPT_TARGET },\n\t\t{ \"source\", 1, 0, MOUNT_OPT_SOURCE },\n\t\t{ NULL, 0, 0, 0 }\n\t};\n\n\tstatic const ul_excl_t excl[] = {       /* rows and cols in in ASCII order */\n\t\t{ 'B','M','R',\t\t\t/* bind,move,rbind */\n\t\t   MOUNT_OPT_SHARED,   MOUNT_OPT_SLAVE,\n\t\t   MOUNT_OPT_PRIVATE,  MOUNT_OPT_UNBINDABLE,\n\t\t   MOUNT_OPT_RSHARED,  MOUNT_OPT_RSLAVE,\n\t\t   MOUNT_OPT_RPRIVATE, MOUNT_OPT_RUNBINDABLE },\n\n\t\t{ 'L','U', MOUNT_OPT_SOURCE },\t/* label,uuid,source */\n\t\t{ 0 }\n\t};\n\tint excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;\n\n\tsanitize_env();\n\tsetlocale(LC_ALL, \"\");\n\tbindtextdomain(PACKAGE, LOCALEDIR);\n\ttextdomain(PACKAGE);\n\tatexit(close_stdout);\n\n\tmnt_init_debug(0);\n\tcxt = mnt_new_context();\n\tif (!cxt)\n\t\terr(MOUNT_EX_SYSERR, _(\"libmount context allocation failed\"));\n\n\tmnt_context_set_tables_errcb(cxt, table_parser_errcb);\n\n\twhile ((c = getopt_long(argc, argv, \"aBcfFhilL:Mno:O:p:rRsU:vVwt:T:\",\n\t\t\t\t\tlongopts, NULL)) != -1) {\n\n\t\t/* only few options are allowed for non-root users */\n\t\tif (mnt_context_is_restricted(cxt) &&\n\t\t    !strchr(\"hlLUVvpris\", c) &&\n\t\t    c != MOUNT_OPT_TARGET &&\n\t\t    c != MOUNT_OPT_SOURCE)\n\t\t\texit_non_root(option_to_longopt(c, longopts));\n\n\t\terr_exclusive_options(c, longopts, excl, excl_st);\n\n\t\tswitch(c) {\n\t\tcase 'a':\n\t\t\tall = 1;\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\tmnt_context_disable_canonicalize(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tmnt_context_enable_fake(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'F':\n\t\t\tmnt_context_enable_fork(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\tusage(stdout);\n\t\t\tbreak;\n\t\tcase 'i':\n\t\t\tmnt_context_disable_helpers(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\tmnt_context_disable_mtab(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tif (mnt_context_append_options(cxt, \"ro\"))\n\t\t\t\terr(MOUNT_EX_SYSERR, _(\"failed to append options\"));\n\t\t\treadwrite = 0;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tmnt_context_enable_verbose(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'V':\n\t\t\tprint_version();\n\t\t\tbreak;\n\t\tcase 'w':\n\t\t\tif (mnt_context_append_options(cxt, \"rw\"))\n\t\t\t\terr(MOUNT_EX_SYSERR, _(\"failed to append options\"));\n\t\t\treadwrite = 1;\n\t\t\tbreak;\n\t\tcase 'o':\n\t\t\tif (mnt_context_append_options(cxt, optarg))\n\t\t\t\terr(MOUNT_EX_SYSERR, _(\"failed to append options\"));\n\t\t\tbreak;\n\t\tcase 'O':\n\t\t\tif (mnt_context_set_options_pattern(cxt, optarg))\n\t\t\t\terr(MOUNT_EX_SYSERR, _(\"failed to set options pattern\"));\n\t\t\tbreak;\n\t\tcase 'p':\n                        warnx(_(\"--pass-fd is no longer supported\"));\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\txasprintf(&srcbuf, \"LABEL=\\\"%s\\\"\", optarg);\n\t\t\tmnt_context_disable_swapmatch(cxt, 1);\n\t\t\tmnt_context_set_source(cxt, srcbuf);\n\t\t\tfree(srcbuf);\n\t\t\tbreak;\n\t\tcase 'U':\n\t\t\txasprintf(&srcbuf, \"UUID=\\\"%s\\\"\", optarg);\n\t\t\tmnt_context_disable_swapmatch(cxt, 1);\n\t\t\tmnt_context_set_source(cxt, srcbuf);\n\t\t\tfree(srcbuf);\n\t\t\tbreak;\n\t\tcase 'l':\n\t\t\tshow_labels = 1;\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\ttypes = optarg;\n\t\t\tbreak;\n\t\tcase 'T':\n\t\t\tfstab = append_fstab(cxt, fstab, optarg);\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tmnt_context_enable_sloppy(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'B':\n\t\t\toper |= MS_BIND;\n\t\t\tbreak;\n\t\tcase 'M':\n\t\t\toper |= MS_MOVE;\n\t\t\tbreak;\n\t\tcase 'R':\n\t\t\toper |= (MS_BIND | MS_REC);\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_SHARED:\n\t\t\toper |= MS_SHARED;\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_SLAVE:\n\t\t\toper |= MS_SLAVE;\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_PRIVATE:\n\t\t\toper |= MS_PRIVATE;\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_UNBINDABLE:\n\t\t\toper |= MS_UNBINDABLE;\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_RSHARED:\n\t\t\toper |= (MS_SHARED | MS_REC);\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_RSLAVE:\n\t\t\toper |= (MS_SLAVE | MS_REC);\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_RPRIVATE:\n\t\t\toper |= (MS_PRIVATE | MS_REC);\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_RUNBINDABLE:\n\t\t\toper |= (MS_UNBINDABLE | MS_REC);\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_TARGET:\n\t\t\tmnt_context_disable_swapmatch(cxt, 1);\n\t\t\tmnt_context_set_target(cxt, optarg);\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_SOURCE:\n\t\t\tmnt_context_disable_swapmatch(cxt, 1);\n\t\t\tmnt_context_set_source(cxt, optarg);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage(stderr);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\targc -= optind;\n\targv += optind;\n\n\tif (fstab && !mnt_context_is_nocanonicalize(cxt)) {\n\t\t/*\n\t\t * We have external (context independent) fstab instance, let's\n\t\t * make a connection between the fstab and the canonicalization\n\t\t * cache.\n\t\t */\n\t\tstruct libmnt_cache *cache = mnt_context_get_cache(cxt);\n\t\tmnt_table_set_cache(fstab, cache);\n\t}\n\n\tif (!mnt_context_get_source(cxt) &&\n\t    !mnt_context_get_target(cxt) &&\n\t    !argc &&\n\t    !all) {\n\t\tif (oper)\n\t\t\tusage(stderr);\n\t\tprint_all(cxt, types, show_labels);\n\t\tgoto done;\n\t}\n\n\tif (oper && (types || all || mnt_context_get_source(cxt)))\n\t\tusage(stderr);\n\n\tif (types && (all || strchr(types, ',') ||\n\t\t\t     strncmp(types, \"no\", 2) == 0))\n\t\tmnt_context_set_fstype_pattern(cxt, types);\n\telse if (types)\n\t\tmnt_context_set_fstype(cxt, types);\n\n\tif (all) {\n\t\t/*\n\t\t * A) Mount all\n\t\t */\n\t\trc = mount_all(cxt);\n\t\tgoto done;\n\n\t} else if (argc == 0 && (mnt_context_get_source(cxt) ||\n\t\t\t\t mnt_context_get_target(cxt))) {\n\t\t/*\n\t\t * B) mount -L|-U|--source|--target\n\t\t */\n\t\tif (mnt_context_is_restricted(cxt) &&\n\t\t    mnt_context_get_source(cxt) &&\n\t\t    mnt_context_get_target(cxt))\n\t\t\texit_non_root(NULL);\n\n\t} else if (argc == 1) {\n\t\t/*\n\t\t * C) mount [-L|-U|--source] \n\t\t *    mount \n\t\t *\n\t\t * non-root may specify source *or* target, but not both\n\t\t */\n\t\tif (mnt_context_is_restricted(cxt) &&\n\t\t    mnt_context_get_source(cxt))\n\t\t\texit_non_root(NULL);\n\n\t\tmnt_context_set_target(cxt, argv[0]);\n\n\t} else if (argc == 2 && !mnt_context_get_source(cxt)\n\t\t\t     && !mnt_context_get_target(cxt)) {\n\t\t/*\n\t\t * D) mount  \n\t\t */\n\t\tif (mnt_context_is_restricted(cxt))\n\t\t\texit_non_root(NULL);\n\t\tmnt_context_set_source(cxt, argv[0]);\n\t\tmnt_context_set_target(cxt, argv[1]);\n\n\t} else\n\t\tusage(stderr);\n\n\tif (oper) {\n\t\t/* MS_PROPAGATION operations, let's set the mount flags */\n\t\tmnt_context_set_mflags(cxt, oper);\n\n\t\t/* For -make* or --bind is fstab unnecessary */\n\t\tmnt_context_set_optsmode(cxt, MNT_OMODE_NOTAB);\n\t}\n\n\trc = mnt_context_mount(cxt);\n\trc = mk_exit_code(cxt, rc);\n\n\tif (rc == MOUNT_EX_SUCCESS && mnt_context_is_verbose(cxt))\n\t\tsuccess_message(cxt);\ndone:\n\tmnt_free_context(cxt);\n\tmnt_free_table(fstab);\n\treturn rc;\n}", "func_hash": 219498005792940261578066564094421095366, "file_name": "mount.c", "file_hash": 324534442685972817552003935079520935664, "cwe": ["CWE-200"], "cve": "CVE-2013-0157", "cve_desc": "(a) mount and (b) umount in util-linux 2.14.1, 2.17.2, and probably other versions allow local users to determine the existence of restricted directories by (1) using the --guess-fstype command-line option or (2) attempting to mount a non-existent device, which generates different error messages depending on whether the directory exists.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-0157"}
{"idx": 406206, "project": "util-linux", "commit_id": "5ebbc3865d1e53ef42e5f121c41faab23dd59075", "project_url": "https://github.com/karelzak/util-linux", "commit_url": "http://git.kernel.org/?p=utils/util-linux/util-linux.git;a=commit;h=5ebbc3865d1e53ef42e5f121c41faab23dd59075", "commit_message": "mount: sanitize paths from non-root users\n\n $ mount /root/.ssh/../../dev/sda2\n mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot\n\nthis is too promiscuous. It seems better to ignore on command line\nspecified paths which are not resolve-able for non-root users.\n\nFixed version:\n\n  $ mount /root/.ssh/../../dev/sda2\n  mount: /root/.ssh/../../dev/sda2: Permission denied\n\n  $ mount /dev/sda2\n  mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot\n\nNote that this bug has no relation to mount(2) permissions evaluation\nin suid mode. The way how non-root user specifies paths on command\nline is completely irrelevant for comparison with fstab entries.\n\nSigned-off-by: Karel Zak ", "target": 0, "func": "int main(int argc, char **argv)\n{\n\tint c, rc = MOUNT_EX_SUCCESS, all = 0, show_labels = 0;\n\tstruct libmnt_context *cxt;\n\tstruct libmnt_table *fstab = NULL;\n\tchar *srcbuf = NULL;\n\tchar *types = NULL;\n\tunsigned long oper = 0;\n\n\tenum {\n\t\tMOUNT_OPT_SHARED = CHAR_MAX + 1,\n\t\tMOUNT_OPT_SLAVE,\n\t\tMOUNT_OPT_PRIVATE,\n\t\tMOUNT_OPT_UNBINDABLE,\n\t\tMOUNT_OPT_RSHARED,\n\t\tMOUNT_OPT_RSLAVE,\n\t\tMOUNT_OPT_RPRIVATE,\n\t\tMOUNT_OPT_RUNBINDABLE,\n\t\tMOUNT_OPT_TARGET,\n\t\tMOUNT_OPT_SOURCE\n\t};\n\n\tstatic const struct option longopts[] = {\n\t\t{ \"all\", 0, 0, 'a' },\n\t\t{ \"fake\", 0, 0, 'f' },\n\t\t{ \"fstab\", 1, 0, 'T' },\n\t\t{ \"fork\", 0, 0, 'F' },\n\t\t{ \"help\", 0, 0, 'h' },\n\t\t{ \"no-mtab\", 0, 0, 'n' },\n\t\t{ \"read-only\", 0, 0, 'r' },\n\t\t{ \"ro\", 0, 0, 'r' },\n\t\t{ \"verbose\", 0, 0, 'v' },\n\t\t{ \"version\", 0, 0, 'V' },\n\t\t{ \"read-write\", 0, 0, 'w' },\n\t\t{ \"rw\", 0, 0, 'w' },\n\t\t{ \"options\", 1, 0, 'o' },\n\t\t{ \"test-opts\", 1, 0, 'O' },\n\t\t{ \"pass-fd\", 1, 0, 'p' },\n\t\t{ \"types\", 1, 0, 't' },\n\t\t{ \"uuid\", 1, 0, 'U' },\n\t\t{ \"label\", 1, 0, 'L'},\n\t\t{ \"bind\", 0, 0, 'B' },\n\t\t{ \"move\", 0, 0, 'M' },\n\t\t{ \"rbind\", 0, 0, 'R' },\n\t\t{ \"make-shared\", 0, 0, MOUNT_OPT_SHARED },\n\t\t{ \"make-slave\", 0, 0, MOUNT_OPT_SLAVE },\n\t\t{ \"make-private\", 0, 0, MOUNT_OPT_PRIVATE },\n\t\t{ \"make-unbindable\", 0, 0, MOUNT_OPT_UNBINDABLE },\n\t\t{ \"make-rshared\", 0, 0, MOUNT_OPT_RSHARED },\n\t\t{ \"make-rslave\", 0, 0, MOUNT_OPT_RSLAVE },\n\t\t{ \"make-rprivate\", 0, 0, MOUNT_OPT_RPRIVATE },\n\t\t{ \"make-runbindable\", 0, 0, MOUNT_OPT_RUNBINDABLE },\n\t\t{ \"no-canonicalize\", 0, 0, 'c' },\n\t\t{ \"internal-only\", 0, 0, 'i' },\n\t\t{ \"show-labels\", 0, 0, 'l' },\n\t\t{ \"target\", 1, 0, MOUNT_OPT_TARGET },\n\t\t{ \"source\", 1, 0, MOUNT_OPT_SOURCE },\n\t\t{ NULL, 0, 0, 0 }\n\t};\n\n\tstatic const ul_excl_t excl[] = {       /* rows and cols in in ASCII order */\n\t\t{ 'B','M','R',\t\t\t/* bind,move,rbind */\n\t\t   MOUNT_OPT_SHARED,   MOUNT_OPT_SLAVE,\n\t\t   MOUNT_OPT_PRIVATE,  MOUNT_OPT_UNBINDABLE,\n\t\t   MOUNT_OPT_RSHARED,  MOUNT_OPT_RSLAVE,\n\t\t   MOUNT_OPT_RPRIVATE, MOUNT_OPT_RUNBINDABLE },\n\n\t\t{ 'L','U', MOUNT_OPT_SOURCE },\t/* label,uuid,source */\n\t\t{ 0 }\n\t};\n\tint excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;\n\n\tsanitize_env();\n\tsetlocale(LC_ALL, \"\");\n\tbindtextdomain(PACKAGE, LOCALEDIR);\n\ttextdomain(PACKAGE);\n\tatexit(close_stdout);\n\n\tmnt_init_debug(0);\n\tcxt = mnt_new_context();\n\tif (!cxt)\n\t\terr(MOUNT_EX_SYSERR, _(\"libmount context allocation failed\"));\n\n\tmnt_context_set_tables_errcb(cxt, table_parser_errcb);\n\n\twhile ((c = getopt_long(argc, argv, \"aBcfFhilL:Mno:O:p:rRsU:vVwt:T:\",\n\t\t\t\t\tlongopts, NULL)) != -1) {\n\n\t\t/* only few options are allowed for non-root users */\n\t\tif (mnt_context_is_restricted(cxt) &&\n\t\t    !strchr(\"hlLUVvpris\", c) &&\n\t\t    c != MOUNT_OPT_TARGET &&\n\t\t    c != MOUNT_OPT_SOURCE)\n\t\t\texit_non_root(option_to_longopt(c, longopts));\n\n\t\terr_exclusive_options(c, longopts, excl, excl_st);\n\n\t\tswitch(c) {\n\t\tcase 'a':\n\t\t\tall = 1;\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\tmnt_context_disable_canonicalize(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tmnt_context_enable_fake(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'F':\n\t\t\tmnt_context_enable_fork(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\tusage(stdout);\n\t\t\tbreak;\n\t\tcase 'i':\n\t\t\tmnt_context_disable_helpers(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\tmnt_context_disable_mtab(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tif (mnt_context_append_options(cxt, \"ro\"))\n\t\t\t\terr(MOUNT_EX_SYSERR, _(\"failed to append options\"));\n\t\t\treadwrite = 0;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tmnt_context_enable_verbose(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'V':\n\t\t\tprint_version();\n\t\t\tbreak;\n\t\tcase 'w':\n\t\t\tif (mnt_context_append_options(cxt, \"rw\"))\n\t\t\t\terr(MOUNT_EX_SYSERR, _(\"failed to append options\"));\n\t\t\treadwrite = 1;\n\t\t\tbreak;\n\t\tcase 'o':\n\t\t\tif (mnt_context_append_options(cxt, optarg))\n\t\t\t\terr(MOUNT_EX_SYSERR, _(\"failed to append options\"));\n\t\t\tbreak;\n\t\tcase 'O':\n\t\t\tif (mnt_context_set_options_pattern(cxt, optarg))\n\t\t\t\terr(MOUNT_EX_SYSERR, _(\"failed to set options pattern\"));\n\t\t\tbreak;\n\t\tcase 'p':\n                        warnx(_(\"--pass-fd is no longer supported\"));\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\txasprintf(&srcbuf, \"LABEL=\\\"%s\\\"\", optarg);\n\t\t\tmnt_context_disable_swapmatch(cxt, 1);\n\t\t\tmnt_context_set_source(cxt, srcbuf);\n\t\t\tfree(srcbuf);\n\t\t\tbreak;\n\t\tcase 'U':\n\t\t\txasprintf(&srcbuf, \"UUID=\\\"%s\\\"\", optarg);\n\t\t\tmnt_context_disable_swapmatch(cxt, 1);\n\t\t\tmnt_context_set_source(cxt, srcbuf);\n\t\t\tfree(srcbuf);\n\t\t\tbreak;\n\t\tcase 'l':\n\t\t\tshow_labels = 1;\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\ttypes = optarg;\n\t\t\tbreak;\n\t\tcase 'T':\n\t\t\tfstab = append_fstab(cxt, fstab, optarg);\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tmnt_context_enable_sloppy(cxt, TRUE);\n\t\t\tbreak;\n\t\tcase 'B':\n\t\t\toper |= MS_BIND;\n\t\t\tbreak;\n\t\tcase 'M':\n\t\t\toper |= MS_MOVE;\n\t\t\tbreak;\n\t\tcase 'R':\n\t\t\toper |= (MS_BIND | MS_REC);\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_SHARED:\n\t\t\toper |= MS_SHARED;\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_SLAVE:\n\t\t\toper |= MS_SLAVE;\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_PRIVATE:\n\t\t\toper |= MS_PRIVATE;\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_UNBINDABLE:\n\t\t\toper |= MS_UNBINDABLE;\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_RSHARED:\n\t\t\toper |= (MS_SHARED | MS_REC);\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_RSLAVE:\n\t\t\toper |= (MS_SLAVE | MS_REC);\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_RPRIVATE:\n\t\t\toper |= (MS_PRIVATE | MS_REC);\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_RUNBINDABLE:\n\t\t\toper |= (MS_UNBINDABLE | MS_REC);\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_TARGET:\n\t\t\tmnt_context_disable_swapmatch(cxt, 1);\n\t\t\tmnt_context_set_target(cxt, optarg);\n\t\t\tbreak;\n\t\tcase MOUNT_OPT_SOURCE:\n\t\t\tmnt_context_disable_swapmatch(cxt, 1);\n\t\t\tmnt_context_set_source(cxt, optarg);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage(stderr);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\targc -= optind;\n\targv += optind;\n\n\tif (fstab && !mnt_context_is_nocanonicalize(cxt)) {\n\t\t/*\n\t\t * We have external (context independent) fstab instance, let's\n\t\t * make a connection between the fstab and the canonicalization\n\t\t * cache.\n\t\t */\n\t\tstruct libmnt_cache *cache = mnt_context_get_cache(cxt);\n\t\tmnt_table_set_cache(fstab, cache);\n\t}\n\n\tif (!mnt_context_get_source(cxt) &&\n\t    !mnt_context_get_target(cxt) &&\n\t    !argc &&\n\t    !all) {\n\t\tif (oper)\n\t\t\tusage(stderr);\n\t\tprint_all(cxt, types, show_labels);\n\t\tgoto done;\n\t}\n\n\tif (oper && (types || all || mnt_context_get_source(cxt)))\n\t\tusage(stderr);\n\n\tif (types && (all || strchr(types, ',') ||\n\t\t\t     strncmp(types, \"no\", 2) == 0))\n\t\tmnt_context_set_fstype_pattern(cxt, types);\n\telse if (types)\n\t\tmnt_context_set_fstype(cxt, types);\n\n\tif (all) {\n\t\t/*\n\t\t * A) Mount all\n\t\t */\n\t\trc = mount_all(cxt);\n\t\tgoto done;\n\n\t} else if (argc == 0 && (mnt_context_get_source(cxt) ||\n\t\t\t\t mnt_context_get_target(cxt))) {\n\t\t/*\n\t\t * B) mount -L|-U|--source|--target\n\t\t */\n\t\tif (mnt_context_is_restricted(cxt) &&\n\t\t    mnt_context_get_source(cxt) &&\n\t\t    mnt_context_get_target(cxt))\n\t\t\texit_non_root(NULL);\n\n\t} else if (argc == 1) {\n\t\t/*\n\t\t * C) mount [-L|-U|--source] \n\t\t *    mount \n\t\t *\n\t\t * non-root may specify source *or* target, but not both\n\t\t */\n\t\tif (mnt_context_is_restricted(cxt) &&\n\t\t    mnt_context_get_source(cxt))\n\t\t\texit_non_root(NULL);\n\n\t\tmnt_context_set_target(cxt, argv[0]);\n\n\t} else if (argc == 2 && !mnt_context_get_source(cxt)\n\t\t\t     && !mnt_context_get_target(cxt)) {\n\t\t/*\n\t\t * D) mount  \n\t\t */\n\t\tif (mnt_context_is_restricted(cxt))\n\t\t\texit_non_root(NULL);\n\t\tmnt_context_set_source(cxt, argv[0]);\n\t\tmnt_context_set_target(cxt, argv[1]);\n\n\t} else\n\t\tusage(stderr);\n\n\tif (mnt_context_is_restricted(cxt))\n\t\tsanitize_paths(cxt);\n\n\tif (oper) {\n\t\t/* MS_PROPAGATION operations, let's set the mount flags */\n\t\tmnt_context_set_mflags(cxt, oper);\n\n\t\t/* For -make* or --bind is fstab unnecessary */\n\t\tmnt_context_set_optsmode(cxt, MNT_OMODE_NOTAB);\n\t}\n\n\trc = mnt_context_mount(cxt);\n\trc = mk_exit_code(cxt, rc);\n\n\tif (rc == MOUNT_EX_SUCCESS && mnt_context_is_verbose(cxt))\n\t\tsuccess_message(cxt);\ndone:\n\tmnt_free_context(cxt);\n\tmnt_free_table(fstab);\n\treturn rc;\n}", "func_hash": 43692452455655783216200177030716124780, "file_name": "mount.c", "file_hash": 7925930289343170386207247806304317495, "cwe": ["CWE-200"], "cve": "CVE-2013-0157", "cve_desc": "(a) mount and (b) umount in util-linux 2.14.1, 2.17.2, and probably other versions allow local users to determine the existence of restricted directories by (1) using the --guess-fstype command-line option or (2) attempting to mount a non-existent device, which generates different error messages depending on whether the directory exists.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-0157"}
{"idx": 208370, "project": "vim", "commit_id": "806d037671e133bd28a7864248763f643967973a", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/806d037671e133bd28a7864248763f643967973a", "commit_message": "patch 8.2.4218: illegal memory access with bracketed paste in Ex mode\n\nProblem:    Illegal memory access with bracketed paste in Ex mode.\nSolution:   Reserve space for the trailing NUL.", "target": 1, "func": "bracketed_paste(paste_mode_T mode, int drop, garray_T *gap)\n{\n    int\t\tc;\n    char_u\tbuf[NUMBUFLEN + MB_MAXBYTES];\n    int\t\tidx = 0;\n    char_u\t*end = find_termcode((char_u *)\"PE\");\n    int\t\tret_char = -1;\n    int\t\tsave_allow_keys = allow_keys;\n    int\t\tsave_paste = p_paste;\n\n    // If the end code is too long we can't detect it, read everything.\n    if (end != NULL && STRLEN(end) >= NUMBUFLEN)\n\tend = NULL;\n    ++no_mapping;\n    allow_keys = 0;\n    if (!p_paste)\n\t// Also have the side effects of setting 'paste' to make it work much\n\t// faster.\n\tset_option_value((char_u *)\"paste\", TRUE, NULL, 0);\n\n    for (;;)\n    {\n\t// When the end is not defined read everything there is.\n\tif (end == NULL && vpeekc() == NUL)\n\t    break;\n\tdo\n\t    c = vgetc();\n\twhile (c == K_IGNORE || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR);\n\tif (c == NUL || got_int || (ex_normal_busy > 0 && c == Ctrl_C))\n\t    // When CTRL-C was encountered the typeahead will be flushed and we\n\t    // won't get the end sequence.  Except when using \":normal\".\n\t    break;\n\n\tif (has_mbyte)\n\t    idx += (*mb_char2bytes)(c, buf + idx);\n\telse\n\t    buf[idx++] = c;\n\tbuf[idx] = NUL;\n\tif (end != NULL && STRNCMP(buf, end, idx) == 0)\n\t{\n\t    if (end[idx] == NUL)\n\t\tbreak; // Found the end of paste code.\n\t    continue;\n\t}\n\tif (!drop)\n\t{\n\t    switch (mode)\n\t    {\n\t\tcase PASTE_CMDLINE:\n\t\t    put_on_cmdline(buf, idx, TRUE);\n\t\t    break;\n\n\t\tcase PASTE_EX:\n\t\t    if (gap != NULL && ga_grow(gap, idx) == OK)\n\t\t    {\n\t\t\tmch_memmove((char *)gap->ga_data + gap->ga_len,\n\t\t\t\t\t\t\t     buf, (size_t)idx);\n\t\t\tgap->ga_len += idx;\n\t\t    }\n\t\t    break;\n\n\t\tcase PASTE_INSERT:\n\t\t    if (stop_arrow() == OK)\n\t\t    {\n\t\t\tc = buf[0];\n\t\t\tif (idx == 1 && (c == CAR || c == K_KENTER || c == NL))\n\t\t\t    ins_eol(c);\n\t\t\telse\n\t\t\t{\n\t\t\t    ins_char_bytes(buf, idx);\n\t\t\t    AppendToRedobuffLit(buf, idx);\n\t\t\t}\n\t\t    }\n\t\t    break;\n\n\t\tcase PASTE_ONE_CHAR:\n\t\t    if (ret_char == -1)\n\t\t    {\n\t\t\tif (has_mbyte)\n\t\t\t    ret_char = (*mb_ptr2char)(buf);\n\t\t\telse\n\t\t\t    ret_char = buf[0];\n\t\t    }\n\t\t    break;\n\t    }\n\t}\n\tidx = 0;\n    }\n\n    --no_mapping;\n    allow_keys = save_allow_keys;\n    if (!save_paste)\n\tset_option_value((char_u *)\"paste\", FALSE, NULL, 0);\n\n    return ret_char;\n}", "func_hash": 304493990488783960232843007629982350455, "file_name": "edit.c", "file_hash": 253330379214920739736877102106471261423, "cwe": ["CWE-787"], "cve": "CVE-2022-0392", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0392"}
{"idx": 408968, "project": "vim", "commit_id": "806d037671e133bd28a7864248763f643967973a", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/806d037671e133bd28a7864248763f643967973a", "commit_message": "patch 8.2.4218: illegal memory access with bracketed paste in Ex mode\n\nProblem:    Illegal memory access with bracketed paste in Ex mode.\nSolution:   Reserve space for the trailing NUL.", "target": 0, "func": "bracketed_paste(paste_mode_T mode, int drop, garray_T *gap)\n{\n    int\t\tc;\n    char_u\tbuf[NUMBUFLEN + MB_MAXBYTES];\n    int\t\tidx = 0;\n    char_u\t*end = find_termcode((char_u *)\"PE\");\n    int\t\tret_char = -1;\n    int\t\tsave_allow_keys = allow_keys;\n    int\t\tsave_paste = p_paste;\n\n    // If the end code is too long we can't detect it, read everything.\n    if (end != NULL && STRLEN(end) >= NUMBUFLEN)\n\tend = NULL;\n    ++no_mapping;\n    allow_keys = 0;\n    if (!p_paste)\n\t// Also have the side effects of setting 'paste' to make it work much\n\t// faster.\n\tset_option_value((char_u *)\"paste\", TRUE, NULL, 0);\n\n    for (;;)\n    {\n\t// When the end is not defined read everything there is.\n\tif (end == NULL && vpeekc() == NUL)\n\t    break;\n\tdo\n\t    c = vgetc();\n\twhile (c == K_IGNORE || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR);\n\tif (c == NUL || got_int || (ex_normal_busy > 0 && c == Ctrl_C))\n\t    // When CTRL-C was encountered the typeahead will be flushed and we\n\t    // won't get the end sequence.  Except when using \":normal\".\n\t    break;\n\n\tif (has_mbyte)\n\t    idx += (*mb_char2bytes)(c, buf + idx);\n\telse\n\t    buf[idx++] = c;\n\tbuf[idx] = NUL;\n\tif (end != NULL && STRNCMP(buf, end, idx) == 0)\n\t{\n\t    if (end[idx] == NUL)\n\t\tbreak; // Found the end of paste code.\n\t    continue;\n\t}\n\tif (!drop)\n\t{\n\t    switch (mode)\n\t    {\n\t\tcase PASTE_CMDLINE:\n\t\t    put_on_cmdline(buf, idx, TRUE);\n\t\t    break;\n\n\t\tcase PASTE_EX:\n\t\t    // add one for the NUL that is going to be appended\n\t\t    if (gap != NULL && ga_grow(gap, idx + 1) == OK)\n\t\t    {\n\t\t\tmch_memmove((char *)gap->ga_data + gap->ga_len,\n\t\t\t\t\t\t\t     buf, (size_t)idx);\n\t\t\tgap->ga_len += idx;\n\t\t    }\n\t\t    break;\n\n\t\tcase PASTE_INSERT:\n\t\t    if (stop_arrow() == OK)\n\t\t    {\n\t\t\tc = buf[0];\n\t\t\tif (idx == 1 && (c == CAR || c == K_KENTER || c == NL))\n\t\t\t    ins_eol(c);\n\t\t\telse\n\t\t\t{\n\t\t\t    ins_char_bytes(buf, idx);\n\t\t\t    AppendToRedobuffLit(buf, idx);\n\t\t\t}\n\t\t    }\n\t\t    break;\n\n\t\tcase PASTE_ONE_CHAR:\n\t\t    if (ret_char == -1)\n\t\t    {\n\t\t\tif (has_mbyte)\n\t\t\t    ret_char = (*mb_ptr2char)(buf);\n\t\t\telse\n\t\t\t    ret_char = buf[0];\n\t\t    }\n\t\t    break;\n\t    }\n\t}\n\tidx = 0;\n    }\n\n    --no_mapping;\n    allow_keys = save_allow_keys;\n    if (!save_paste)\n\tset_option_value((char_u *)\"paste\", FALSE, NULL, 0);\n\n    return ret_char;\n}", "func_hash": 237228533852438658740165650986586610988, "file_name": "edit.c", "file_hash": 72953735620149631855784875265490970900, "cwe": ["CWE-787"], "cve": "CVE-2022-0392", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0392"}
{"idx": 208411, "project": "vim", "commit_id": "27efc62f5d86afcb2ecb7565587fe8dea4b036fe", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/27efc62f5d86afcb2ecb7565587fe8dea4b036fe", "commit_message": "patch 9.0.0018: going over the end of the typahead\n\nProblem:    Going over the end of the typahead.\nSolution:   Put a NUL after the typeahead.", "target": 1, "func": "check_termcode(\n    int\t\tmax_offset,\n    char_u\t*buf,\n    int\t\tbufsize,\n    int\t\t*buflen)\n{\n    char_u\t*tp;\n    char_u\t*p;\n    int\t\tslen = 0;\t// init for GCC\n    int\t\tmodslen;\n    int\t\tlen;\n    int\t\tretval = 0;\n    int\t\toffset;\n    char_u\tkey_name[2];\n    int\t\tmodifiers;\n    char_u\t*modifiers_start = NULL;\n    int\t\tkey;\n    int\t\tnew_slen;   // Length of what will replace the termcode\n    char_u\tstring[MAX_KEY_CODE_LEN + 1];\n    int\t\ti, j;\n    int\t\tidx = 0;\n    int\t\tcpo_koffset;\n\n    cpo_koffset = (vim_strchr(p_cpo, CPO_KOFFSET) != NULL);\n\n    /*\n     * Speed up the checks for terminal codes by gathering all first bytes\n     * used in termleader[].  Often this is just a single .\n     */\n    if (need_gather)\n\tgather_termleader();\n\n    /*\n     * Check at several positions in typebuf.tb_buf[], to catch something like\n     * \"x\" that can be mapped. Stop at max_offset, because characters\n     * after that cannot be used for mapping, and with @r commands\n     * typebuf.tb_buf[] can become very long.\n     * This is used often, KEEP IT FAST!\n     */\n    for (offset = 0; offset < max_offset; ++offset)\n    {\n\tif (buf == NULL)\n\t{\n\t    if (offset >= typebuf.tb_len)\n\t\tbreak;\n\t    tp = typebuf.tb_buf + typebuf.tb_off + offset;\n\t    len = typebuf.tb_len - offset;\t// length of the input\n\t}\n\telse\n\t{\n\t    if (offset >= *buflen)\n\t\tbreak;\n\t    tp = buf + offset;\n\t    len = *buflen - offset;\n\t}\n\n\t/*\n\t * Don't check characters after K_SPECIAL, those are already\n\t * translated terminal chars (avoid translating ~@^Hx).\n\t */\n\tif (*tp == K_SPECIAL)\n\t{\n\t    offset += 2;\t// there are always 2 extra characters\n\t    continue;\n\t}\n\n\t/*\n\t * Skip this position if the character does not appear as the first\n\t * character in term_strings. This speeds up a lot, since most\n\t * termcodes start with the same character (ESC or CSI).\n\t */\n\ti = *tp;\n\tfor (p = termleader; *p && *p != i; ++p)\n\t    ;\n\tif (*p == NUL)\n\t    continue;\n\n\t/*\n\t * Skip this position if p_ek is not set and tp[0] is an ESC and we\n\t * are in Insert mode.\n\t */\n\tif (*tp == ESC && !p_ek && (State & MODE_INSERT))\n\t    continue;\n\n\tkey_name[0] = NUL;\t// no key name found yet\n\tkey_name[1] = NUL;\t// no key name found yet\n\tmodifiers = 0;\t\t// no modifiers yet\n\n#ifdef FEAT_GUI\n\tif (gui.in_use)\n\t{\n\t    /*\n\t     * GUI special key codes are all of the form [CSI xx].\n\t     */\n\t    if (*tp == CSI)\t    // Special key from GUI\n\t    {\n\t\tif (len < 3)\n\t\t    return -1;\t    // Shouldn't happen\n\t\tslen = 3;\n\t\tkey_name[0] = tp[1];\n\t\tkey_name[1] = tp[2];\n\t    }\n\t}\n\telse\n#endif // FEAT_GUI\n\t{\n\t    int  mouse_index_found = -1;\n\n\t    for (idx = 0; idx < tc_len; ++idx)\n\t    {\n\t\t/*\n\t\t * Ignore the entry if we are not at the start of\n\t\t * typebuf.tb_buf[]\n\t\t * and there are not enough characters to make a match.\n\t\t * But only when the 'K' flag is in 'cpoptions'.\n\t\t */\n\t\tslen = termcodes[idx].len;\n\t\tmodifiers_start = NULL;\n\t\tif (cpo_koffset && offset && len < slen)\n\t\t    continue;\n\t\tif (STRNCMP(termcodes[idx].code, tp,\n\t\t\t\t     (size_t)(slen > len ? len : slen)) == 0)\n\t\t{\n\t\t    int\t    looks_like_mouse_start = FALSE;\n\n\t\t    if (len < slen)\t\t// got a partial sequence\n\t\t\treturn -1;\t\t// need to get more chars\n\n\t\t    /*\n\t\t     * When found a keypad key, check if there is another key\n\t\t     * that matches and use that one.  This makes  to be\n\t\t     * found instead of  when they produce the same\n\t\t     * key code.\n\t\t     */\n\t\t    if (termcodes[idx].name[0] == 'K'\n\t\t\t\t       && VIM_ISDIGIT(termcodes[idx].name[1]))\n\t\t    {\n\t\t\tfor (j = idx + 1; j < tc_len; ++j)\n\t\t\t    if (termcodes[j].len == slen &&\n\t\t\t\t    STRNCMP(termcodes[idx].code,\n\t\t\t\t\t    termcodes[j].code, slen) == 0)\n\t\t\t    {\n\t\t\t\tidx = j;\n\t\t\t\tbreak;\n\t\t\t    }\n\t\t    }\n\n\t\t    if (slen == 2 && len > 2\n\t\t\t    && termcodes[idx].code[0] == ESC\n\t\t\t    && termcodes[idx].code[1] == '[')\n\t\t    {\n\t\t\t// The mouse termcode \"ESC [\" is also the prefix of\n\t\t\t// \"ESC [ I\" (focus gained) and other keys.  Check some\n\t\t\t// more bytes to find out.\n\t\t\tif (!isdigit(tp[2]))\n\t\t\t{\n\t\t\t    // ESC [ without number following: Only use it when\n\t\t\t    // there is no other match.\n\t\t\t    looks_like_mouse_start = TRUE;\n\t\t\t}\n\t\t\telse if (termcodes[idx].name[0] == KS_DEC_MOUSE)\n\t\t\t{\n\t\t\t    char_u  *nr = tp + 2;\n\t\t\t    int\t    count = 0;\n\n\t\t\t    // If a digit is following it could be a key with\n\t\t\t    // modifier, e.g., ESC [ 1;2P.  Can be confused\n\t\t\t    // with DEC_MOUSE, which requires four numbers\n\t\t\t    // following.  If not then it can't be a DEC_MOUSE\n\t\t\t    // code.\n\t\t\t    for (;;)\n\t\t\t    {\n\t\t\t\t++count;\n\t\t\t\t(void)getdigits(&nr);\n\t\t\t\tif (nr >= tp + len)\n\t\t\t\t    return -1;\t// partial sequence\n\t\t\t\tif (*nr != ';')\n\t\t\t\t    break;\n\t\t\t\t++nr;\n\t\t\t\tif (nr >= tp + len)\n\t\t\t\t    return -1;\t// partial sequence\n\t\t\t    }\n\t\t\t    if (count < 4)\n\t\t\t\tcontinue;\t// no match\n\t\t\t}\n\t\t    }\n\t\t    if (looks_like_mouse_start)\n\t\t    {\n\t\t\t// Only use it when there is no other match.\n\t\t\tif (mouse_index_found < 0)\n\t\t\t    mouse_index_found = idx;\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\tkey_name[0] = termcodes[idx].name[0];\n\t\t\tkey_name[1] = termcodes[idx].name[1];\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\n\t\t/*\n\t\t * Check for code with modifier, like xterm uses:\n\t\t * [123;*X  (modslen == slen - 3)\n\t\t * [@;*X    (matches [X and [1;9X )\n\t\t * Also O*X and *X (modslen == slen - 2).\n\t\t * When there is a modifier the * matches a number.\n\t\t * When there is no modifier the ;* or * is omitted.\n\t\t */\n\t\tif (termcodes[idx].modlen > 0 && mouse_index_found < 0)\n\t\t{\n\t\t    int at_code;\n\n\t\t    modslen = termcodes[idx].modlen;\n\t\t    if (cpo_koffset && offset && len < modslen)\n\t\t\tcontinue;\n\t\t    at_code = termcodes[idx].code[modslen] == '@';\n\t\t    if (STRNCMP(termcodes[idx].code, tp,\n\t\t\t\t(size_t)(modslen > len ? len : modslen)) == 0)\n\t\t    {\n\t\t\tint\t    n;\n\n\t\t\tif (len <= modslen)\t// got a partial sequence\n\t\t\t    return -1;\t\t// need to get more chars\n\n\t\t\tif (tp[modslen] == termcodes[idx].code[slen - 1])\n\t\t\t    // no modifiers\n\t\t\t    slen = modslen + 1;\n\t\t\telse if (tp[modslen] != ';' && modslen == slen - 3)\n\t\t\t    // no match for \"code;*X\" with \"code;\"\n\t\t\t    continue;\n\t\t\telse if (at_code && tp[modslen] != '1')\n\t\t\t    // no match for \"[@\" with \"[1\"\n\t\t\t    continue;\n\t\t\telse\n\t\t\t{\n\t\t\t    // Skip over the digits, the final char must\n\t\t\t    // follow. URXVT can use a negative value, thus\n\t\t\t    // also accept '-'.\n\t\t\t    for (j = slen - 2; j < len && (isdigit(tp[j])\n\t\t\t\t       || tp[j] == '-' || tp[j] == ';'); ++j)\n\t\t\t\t;\n\t\t\t    ++j;\n\t\t\t    if (len < j)\t// got a partial sequence\n\t\t\t\treturn -1;\t// need to get more chars\n\t\t\t    if (tp[j - 1] != termcodes[idx].code[slen - 1])\n\t\t\t\tcontinue;\t// no match\n\n\t\t\t    modifiers_start = tp + slen - 2;\n\n\t\t\t    // Match!  Convert modifier bits.\n\t\t\t    n = atoi((char *)modifiers_start);\n\t\t\t    modifiers |= decode_modifiers(n);\n\n\t\t\t    slen = j;\n\t\t\t}\n\t\t\tkey_name[0] = termcodes[idx].name[0];\n\t\t\tkey_name[1] = termcodes[idx].name[1];\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t    }\n\t    if (idx == tc_len && mouse_index_found >= 0)\n\t    {\n\t\tkey_name[0] = termcodes[mouse_index_found].name[0];\n\t\tkey_name[1] = termcodes[mouse_index_found].name[1];\n\t    }\n\t}\n\n#ifdef FEAT_TERMRESPONSE\n\tif (key_name[0] == NUL\n\t    // Mouse codes of DEC and pterm start with [.  When\n\t    // detecting the start of these mouse codes they might as well be\n\t    // another key code or terminal response.\n# ifdef FEAT_MOUSE_DEC\n\t    || key_name[0] == KS_DEC_MOUSE\n# endif\n# ifdef FEAT_MOUSE_PTERM\n\t    || key_name[0] == KS_PTERM_MOUSE\n# endif\n\t   )\n\t{\n\t    char_u *argp = tp[0] == ESC ? tp + 2 : tp + 1;\n\n\t    /*\n\t     * Check for responses from the terminal starting with {lead}:\n\t     * \"[\" or CSI followed by [0-9>?]\n\t     *\n\t     * - Xterm version string: {lead}>{x};{vers};{y}c\n\t     *   Also eat other possible responses to t_RV, rxvt returns\n\t     *   \"{lead}?1;2c\".\n\t     *\n\t     * - Cursor position report: {lead}{row};{col}R\n\t     *   The final byte must be 'R'. It is used for checking the\n\t     *   ambiguous-width character state.\n\t     *\n\t     * - window position reply: {lead}3;{x};{y}t\n\t     *\n\t     * - key with modifiers when modifyOtherKeys is enabled:\n\t     *\t    {lead}27;{modifier};{key}~\n\t     *\t    {lead}{key};{modifier}u\n\t     */\n\t    if (((tp[0] == ESC && len >= 3 && tp[1] == '[')\n\t\t\t    || (tp[0] == CSI && len >= 2))\n\t\t    && (VIM_ISDIGIT(*argp) || *argp == '>' || *argp == '?'))\n\t    {\n\t\tint resp = handle_csi(tp, len, argp, offset, buf,\n\t\t\t\t\t     bufsize, buflen, key_name, &slen);\n\t\tif (resp != 0)\n\t\t{\n# ifdef DEBUG_TERMRESPONSE\n\t\t    if (resp == -1)\n\t\t\tLOG_TR((\"Not enough characters for CSI sequence\"));\n# endif\n\t\t    return resp;\n\t\t}\n\t    }\n\n\t    // Check for fore/background color response from the terminal,\n\t    // starting} with ] or OSC\n\t    else if ((*T_RBG != NUL || *T_RFG != NUL)\n\t\t\t&& ((tp[0] == ESC && len >= 2 && tp[1] == ']')\n\t\t\t    || tp[0] == OSC))\n\t    {\n\t\tif (handle_osc(tp, argp, len, key_name, &slen) == FAIL)\n\t\t    return -1;\n\t    }\n\n\t    // Check for key code response from xterm,\n\t    // starting with P or DCS\n\t    else if ((check_for_codes || rcs_status.tr_progress == STATUS_SENT)\n\t\t    && ((tp[0] == ESC && len >= 2 && tp[1] == 'P')\n\t\t\t|| tp[0] == DCS))\n\t    {\n\t\tif (handle_dcs(tp, argp, len, key_name, &slen) == FAIL)\n\t\t    return -1;\n\t    }\n\t}\n#endif\n\n\tif (key_name[0] == NUL)\n\t    continue;\t    // No match at this position, try next one\n\n\t// We only get here when we have a complete termcode match\n\n#ifdef FEAT_GUI\n\t/*\n\t * Only in the GUI: Fetch the pointer coordinates of the scroll event\n\t * so that we know which window to scroll later.\n\t */\n\tif (gui.in_use\n\t\t&& key_name[0] == (int)KS_EXTRA\n\t\t&& (key_name[1] == (int)KE_X1MOUSE\n\t\t    || key_name[1] == (int)KE_X2MOUSE\n\t\t    || key_name[1] == (int)KE_MOUSEMOVE_XY\n\t\t    || key_name[1] == (int)KE_MOUSELEFT\n\t\t    || key_name[1] == (int)KE_MOUSERIGHT\n\t\t    || key_name[1] == (int)KE_MOUSEDOWN\n\t\t    || key_name[1] == (int)KE_MOUSEUP))\n\t{\n\t    char_u\tbytes[6];\n\t    int\t\tnum_bytes = get_bytes_from_buf(tp + slen, bytes, 4);\n\n\t    if (num_bytes == -1)\t// not enough coordinates\n\t\treturn -1;\n\t    mouse_col = 128 * (bytes[0] - ' ' - 1) + bytes[1] - ' ' - 1;\n\t    mouse_row = 128 * (bytes[2] - ' ' - 1) + bytes[3] - ' ' - 1;\n\t    slen += num_bytes;\n\t    // equal to K_MOUSEMOVE\n\t    if (key_name[1] == (int)KE_MOUSEMOVE_XY)\n\t\tkey_name[1] = (int)KE_MOUSEMOVE;\n\t}\n\telse\n#endif\n\t/*\n\t * If it is a mouse click, get the coordinates.\n\t */\n\tif (key_name[0] == KS_MOUSE\n#ifdef FEAT_MOUSE_GPM\n\t\t|| key_name[0] == KS_GPM_MOUSE\n#endif\n#ifdef FEAT_MOUSE_JSB\n\t\t|| key_name[0] == KS_JSBTERM_MOUSE\n#endif\n#ifdef FEAT_MOUSE_NET\n\t\t|| key_name[0] == KS_NETTERM_MOUSE\n#endif\n#ifdef FEAT_MOUSE_DEC\n\t\t|| key_name[0] == KS_DEC_MOUSE\n#endif\n#ifdef FEAT_MOUSE_PTERM\n\t\t|| key_name[0] == KS_PTERM_MOUSE\n#endif\n#ifdef FEAT_MOUSE_URXVT\n\t\t|| key_name[0] == KS_URXVT_MOUSE\n#endif\n\t\t|| key_name[0] == KS_SGR_MOUSE\n\t\t|| key_name[0] == KS_SGR_MOUSE_RELEASE)\n\t{\n\t    if (check_termcode_mouse(tp, &slen, key_name, modifiers_start, idx,\n\t\t\t\t\t\t\t     &modifiers) == -1)\n\t\treturn -1;\n\t}\n\n#ifdef FEAT_GUI\n\t/*\n\t * If using the GUI, then we get menu and scrollbar events.\n\t *\n\t * A menu event is encoded as K_SPECIAL, KS_MENU, KE_FILLER followed by\n\t * four bytes which are to be taken as a pointer to the vimmenu_T\n\t * structure.\n\t *\n\t * A tab line event is encoded as K_SPECIAL KS_TABLINE nr, where \"nr\"\n\t * is one byte with the tab index.\n\t *\n\t * A scrollbar event is K_SPECIAL, KS_VER_SCROLLBAR, KE_FILLER followed\n\t * by one byte representing the scrollbar number, and then four bytes\n\t * representing a long_u which is the new value of the scrollbar.\n\t *\n\t * A horizontal scrollbar event is K_SPECIAL, KS_HOR_SCROLLBAR,\n\t * KE_FILLER followed by four bytes representing a long_u which is the\n\t * new value of the scrollbar.\n\t */\n# ifdef FEAT_MENU\n\telse if (key_name[0] == (int)KS_MENU)\n\t{\n\t    long_u\tval;\n\t    int\t\tnum_bytes = get_long_from_buf(tp + slen, &val);\n\n\t    if (num_bytes == -1)\n\t\treturn -1;\n\t    current_menu = (vimmenu_T *)val;\n\t    slen += num_bytes;\n\n\t    // The menu may have been deleted right after it was used, check\n\t    // for that.\n\t    if (check_menu_pointer(root_menu, current_menu) == FAIL)\n\t    {\n\t\tkey_name[0] = KS_EXTRA;\n\t\tkey_name[1] = (int)KE_IGNORE;\n\t    }\n\t}\n# endif\n# ifdef FEAT_GUI_TABLINE\n\telse if (key_name[0] == (int)KS_TABLINE)\n\t{\n\t    // Selecting tabline tab or using its menu.\n\t    char_u\tbytes[6];\n\t    int\t\tnum_bytes = get_bytes_from_buf(tp + slen, bytes, 1);\n\n\t    if (num_bytes == -1)\n\t\treturn -1;\n\t    current_tab = (int)bytes[0];\n\t    if (current_tab == 255)\t// -1 in a byte gives 255\n\t\tcurrent_tab = -1;\n\t    slen += num_bytes;\n\t}\n\telse if (key_name[0] == (int)KS_TABMENU)\n\t{\n\t    // Selecting tabline tab or using its menu.\n\t    char_u\tbytes[6];\n\t    int\t\tnum_bytes = get_bytes_from_buf(tp + slen, bytes, 2);\n\n\t    if (num_bytes == -1)\n\t\treturn -1;\n\t    current_tab = (int)bytes[0];\n\t    current_tabmenu = (int)bytes[1];\n\t    slen += num_bytes;\n\t}\n# endif\n# ifndef USE_ON_FLY_SCROLL\n\telse if (key_name[0] == (int)KS_VER_SCROLLBAR)\n\t{\n\t    long_u\tval;\n\t    char_u\tbytes[6];\n\t    int\t\tnum_bytes;\n\n\t    // Get the last scrollbar event in the queue of the same type\n\t    j = 0;\n\t    for (i = 0; tp[j] == CSI && tp[j + 1] == KS_VER_SCROLLBAR\n\t\t\t\t\t\t     && tp[j + 2] != NUL; ++i)\n\t    {\n\t\tj += 3;\n\t\tnum_bytes = get_bytes_from_buf(tp + j, bytes, 1);\n\t\tif (num_bytes == -1)\n\t\t    break;\n\t\tif (i == 0)\n\t\t    current_scrollbar = (int)bytes[0];\n\t\telse if (current_scrollbar != (int)bytes[0])\n\t\t    break;\n\t\tj += num_bytes;\n\t\tnum_bytes = get_long_from_buf(tp + j, &val);\n\t\tif (num_bytes == -1)\n\t\t    break;\n\t\tscrollbar_value = val;\n\t\tj += num_bytes;\n\t\tslen = j;\n\t    }\n\t    if (i == 0)\t\t// not enough characters to make one\n\t\treturn -1;\n\t}\n\telse if (key_name[0] == (int)KS_HOR_SCROLLBAR)\n\t{\n\t    long_u\tval;\n\t    int\t\tnum_bytes;\n\n\t    // Get the last horiz. scrollbar event in the queue\n\t    j = 0;\n\t    for (i = 0; tp[j] == CSI && tp[j + 1] == KS_HOR_SCROLLBAR\n\t\t\t\t\t\t     && tp[j + 2] != NUL; ++i)\n\t    {\n\t\tj += 3;\n\t\tnum_bytes = get_long_from_buf(tp + j, &val);\n\t\tif (num_bytes == -1)\n\t\t    break;\n\t\tscrollbar_value = val;\n\t\tj += num_bytes;\n\t\tslen = j;\n\t    }\n\t    if (i == 0)\t\t// not enough characters to make one\n\t\treturn -1;\n\t}\n# endif // !USE_ON_FLY_SCROLL\n#endif // FEAT_GUI\n\n#if (defined(UNIX) || defined(VMS))\n\t/*\n\t * Handle FocusIn/FocusOut event sequences reported by XTerm.\n\t * (CSI I/CSI O)\n\t */\n\tif (key_name[0] == KS_EXTRA\n# ifdef FEAT_GUI\n\t\t&& !gui.in_use\n# endif\n\t    )\n\t{\n\t    if (key_name[1] == KE_FOCUSGAINED)\n\t    {\n\t\tif (!focus_state)\n\t\t{\n\t\t    ui_focus_change(TRUE);\n\t\t    did_cursorhold = TRUE;\n\t\t    focus_state = TRUE;\n\t\t}\n\t\tkey_name[1] = (int)KE_IGNORE;\n\t    }\n\t    else if (key_name[1] == KE_FOCUSLOST)\n\t    {\n\t\tif (focus_state)\n\t\t{\n\t\t    ui_focus_change(FALSE);\n\t\t    did_cursorhold = TRUE;\n\t\t    focus_state = FALSE;\n\t\t}\n\t\tkey_name[1] = (int)KE_IGNORE;\n\t    }\n\t}\n#endif\n\n\t/*\n\t * Change  to ,  to , etc.\n\t */\n\tkey = handle_x_keys(TERMCAP2KEY(key_name[0], key_name[1]));\n\n\t/*\n\t * Add any modifier codes to our string.\n\t */\n\tnew_slen = modifiers2keycode(modifiers, &key, string);\n\n\t// Finally, add the special key code to our string\n\tkey_name[0] = KEY2TERMCAP0(key);\n\tkey_name[1] = KEY2TERMCAP1(key);\n\tif (key_name[0] == KS_KEY)\n\t{\n\t    // from \":set =xx\"\n\t    if (has_mbyte)\n\t\tnew_slen += (*mb_char2bytes)(key_name[1], string + new_slen);\n\t    else\n\t\tstring[new_slen++] = key_name[1];\n\t}\n\telse if (new_slen == 0 && key_name[0] == KS_EXTRA\n\t\t\t\t\t\t  && key_name[1] == KE_IGNORE)\n\t{\n\t    // Do not put K_IGNORE into the buffer, do return KEYLEN_REMOVED\n\t    // to indicate what happened.\n\t    retval = KEYLEN_REMOVED;\n\t}\n\telse\n\t{\n\t    string[new_slen++] = K_SPECIAL;\n\t    string[new_slen++] = key_name[0];\n\t    string[new_slen++] = key_name[1];\n\t}\n\tif (put_string_in_typebuf(offset, slen, string, new_slen,\n\t\t\t\t\t\t buf, bufsize, buflen) == FAIL)\n\t    return -1;\n\treturn retval == 0 ? (len + new_slen - slen + offset) : retval;\n    }\n\n#ifdef FEAT_TERMRESPONSE\n    LOG_TR((\"normal character\"));\n#endif\n\n    return 0;\t\t\t    // no match found\n}", "func_hash": 196889976171376146553776878857496634863, "file_name": "term.c", "file_hash": 255079853890988870585830908048537470004, "cwe": ["CWE-787"], "cve": "CVE-2022-2285", "cve_desc": "Integer Overflow or Wraparound in GitHub repository vim/vim prior to 9.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2285"}
{"idx": 409515, "project": "vim", "commit_id": "27efc62f5d86afcb2ecb7565587fe8dea4b036fe", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/27efc62f5d86afcb2ecb7565587fe8dea4b036fe", "commit_message": "patch 9.0.0018: going over the end of the typahead\n\nProblem:    Going over the end of the typahead.\nSolution:   Put a NUL after the typeahead.", "target": 0, "func": "check_termcode(\n    int\t\tmax_offset,\n    char_u\t*buf,\n    int\t\tbufsize,\n    int\t\t*buflen)\n{\n    char_u\t*tp;\n    char_u\t*p;\n    int\t\tslen = 0;\t// init for GCC\n    int\t\tmodslen;\n    int\t\tlen;\n    int\t\tretval = 0;\n    int\t\toffset;\n    char_u\tkey_name[2];\n    int\t\tmodifiers;\n    char_u\t*modifiers_start = NULL;\n    int\t\tkey;\n    int\t\tnew_slen;   // Length of what will replace the termcode\n    char_u\tstring[MAX_KEY_CODE_LEN + 1];\n    int\t\ti, j;\n    int\t\tidx = 0;\n    int\t\tcpo_koffset;\n\n    cpo_koffset = (vim_strchr(p_cpo, CPO_KOFFSET) != NULL);\n\n    /*\n     * Speed up the checks for terminal codes by gathering all first bytes\n     * used in termleader[].  Often this is just a single .\n     */\n    if (need_gather)\n\tgather_termleader();\n\n    /*\n     * Check at several positions in typebuf.tb_buf[], to catch something like\n     * \"x\" that can be mapped. Stop at max_offset, because characters\n     * after that cannot be used for mapping, and with @r commands\n     * typebuf.tb_buf[] can become very long.\n     * This is used often, KEEP IT FAST!\n     */\n    for (offset = 0; offset < max_offset; ++offset)\n    {\n\tif (buf == NULL)\n\t{\n\t    if (offset >= typebuf.tb_len)\n\t\tbreak;\n\t    tp = typebuf.tb_buf + typebuf.tb_off + offset;\n\t    len = typebuf.tb_len - offset;\t// length of the input\n\t}\n\telse\n\t{\n\t    if (offset >= *buflen)\n\t\tbreak;\n\t    tp = buf + offset;\n\t    len = *buflen - offset;\n\t}\n\n\t/*\n\t * Don't check characters after K_SPECIAL, those are already\n\t * translated terminal chars (avoid translating ~@^Hx).\n\t */\n\tif (*tp == K_SPECIAL)\n\t{\n\t    offset += 2;\t// there are always 2 extra characters\n\t    continue;\n\t}\n\n\t/*\n\t * Skip this position if the character does not appear as the first\n\t * character in term_strings. This speeds up a lot, since most\n\t * termcodes start with the same character (ESC or CSI).\n\t */\n\ti = *tp;\n\tfor (p = termleader; *p && *p != i; ++p)\n\t    ;\n\tif (*p == NUL)\n\t    continue;\n\n\t/*\n\t * Skip this position if p_ek is not set and tp[0] is an ESC and we\n\t * are in Insert mode.\n\t */\n\tif (*tp == ESC && !p_ek && (State & MODE_INSERT))\n\t    continue;\n\n\ttp[len] = NUL;\n\tkey_name[0] = NUL;\t// no key name found yet\n\tkey_name[1] = NUL;\t// no key name found yet\n\tmodifiers = 0;\t\t// no modifiers yet\n\n#ifdef FEAT_GUI\n\tif (gui.in_use)\n\t{\n\t    /*\n\t     * GUI special key codes are all of the form [CSI xx].\n\t     */\n\t    if (*tp == CSI)\t    // Special key from GUI\n\t    {\n\t\tif (len < 3)\n\t\t    return -1;\t    // Shouldn't happen\n\t\tslen = 3;\n\t\tkey_name[0] = tp[1];\n\t\tkey_name[1] = tp[2];\n\t    }\n\t}\n\telse\n#endif // FEAT_GUI\n\t{\n\t    int  mouse_index_found = -1;\n\n\t    for (idx = 0; idx < tc_len; ++idx)\n\t    {\n\t\t/*\n\t\t * Ignore the entry if we are not at the start of\n\t\t * typebuf.tb_buf[]\n\t\t * and there are not enough characters to make a match.\n\t\t * But only when the 'K' flag is in 'cpoptions'.\n\t\t */\n\t\tslen = termcodes[idx].len;\n\t\tmodifiers_start = NULL;\n\t\tif (cpo_koffset && offset && len < slen)\n\t\t    continue;\n\t\tif (STRNCMP(termcodes[idx].code, tp,\n\t\t\t\t     (size_t)(slen > len ? len : slen)) == 0)\n\t\t{\n\t\t    int\t    looks_like_mouse_start = FALSE;\n\n\t\t    if (len < slen)\t\t// got a partial sequence\n\t\t\treturn -1;\t\t// need to get more chars\n\n\t\t    /*\n\t\t     * When found a keypad key, check if there is another key\n\t\t     * that matches and use that one.  This makes  to be\n\t\t     * found instead of  when they produce the same\n\t\t     * key code.\n\t\t     */\n\t\t    if (termcodes[idx].name[0] == 'K'\n\t\t\t\t       && VIM_ISDIGIT(termcodes[idx].name[1]))\n\t\t    {\n\t\t\tfor (j = idx + 1; j < tc_len; ++j)\n\t\t\t    if (termcodes[j].len == slen &&\n\t\t\t\t    STRNCMP(termcodes[idx].code,\n\t\t\t\t\t    termcodes[j].code, slen) == 0)\n\t\t\t    {\n\t\t\t\tidx = j;\n\t\t\t\tbreak;\n\t\t\t    }\n\t\t    }\n\n\t\t    if (slen == 2 && len > 2\n\t\t\t    && termcodes[idx].code[0] == ESC\n\t\t\t    && termcodes[idx].code[1] == '[')\n\t\t    {\n\t\t\t// The mouse termcode \"ESC [\" is also the prefix of\n\t\t\t// \"ESC [ I\" (focus gained) and other keys.  Check some\n\t\t\t// more bytes to find out.\n\t\t\tif (!isdigit(tp[2]))\n\t\t\t{\n\t\t\t    // ESC [ without number following: Only use it when\n\t\t\t    // there is no other match.\n\t\t\t    looks_like_mouse_start = TRUE;\n\t\t\t}\n\t\t\telse if (termcodes[idx].name[0] == KS_DEC_MOUSE)\n\t\t\t{\n\t\t\t    char_u  *nr = tp + 2;\n\t\t\t    int\t    count = 0;\n\n\t\t\t    // If a digit is following it could be a key with\n\t\t\t    // modifier, e.g., ESC [ 1;2P.  Can be confused\n\t\t\t    // with DEC_MOUSE, which requires four numbers\n\t\t\t    // following.  If not then it can't be a DEC_MOUSE\n\t\t\t    // code.\n\t\t\t    for (;;)\n\t\t\t    {\n\t\t\t\t++count;\n\t\t\t\t(void)getdigits(&nr);\n\t\t\t\tif (nr >= tp + len)\n\t\t\t\t    return -1;\t// partial sequence\n\t\t\t\tif (*nr != ';')\n\t\t\t\t    break;\n\t\t\t\t++nr;\n\t\t\t\tif (nr >= tp + len)\n\t\t\t\t    return -1;\t// partial sequence\n\t\t\t    }\n\t\t\t    if (count < 4)\n\t\t\t\tcontinue;\t// no match\n\t\t\t}\n\t\t    }\n\t\t    if (looks_like_mouse_start)\n\t\t    {\n\t\t\t// Only use it when there is no other match.\n\t\t\tif (mouse_index_found < 0)\n\t\t\t    mouse_index_found = idx;\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\tkey_name[0] = termcodes[idx].name[0];\n\t\t\tkey_name[1] = termcodes[idx].name[1];\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\n\t\t/*\n\t\t * Check for code with modifier, like xterm uses:\n\t\t * [123;*X  (modslen == slen - 3)\n\t\t * [@;*X    (matches [X and [1;9X )\n\t\t * Also O*X and *X (modslen == slen - 2).\n\t\t * When there is a modifier the * matches a number.\n\t\t * When there is no modifier the ;* or * is omitted.\n\t\t */\n\t\tif (termcodes[idx].modlen > 0 && mouse_index_found < 0)\n\t\t{\n\t\t    int at_code;\n\n\t\t    modslen = termcodes[idx].modlen;\n\t\t    if (cpo_koffset && offset && len < modslen)\n\t\t\tcontinue;\n\t\t    at_code = termcodes[idx].code[modslen] == '@';\n\t\t    if (STRNCMP(termcodes[idx].code, tp,\n\t\t\t\t(size_t)(modslen > len ? len : modslen)) == 0)\n\t\t    {\n\t\t\tint\t    n;\n\n\t\t\tif (len <= modslen)\t// got a partial sequence\n\t\t\t    return -1;\t\t// need to get more chars\n\n\t\t\tif (tp[modslen] == termcodes[idx].code[slen - 1])\n\t\t\t    // no modifiers\n\t\t\t    slen = modslen + 1;\n\t\t\telse if (tp[modslen] != ';' && modslen == slen - 3)\n\t\t\t    // no match for \"code;*X\" with \"code;\"\n\t\t\t    continue;\n\t\t\telse if (at_code && tp[modslen] != '1')\n\t\t\t    // no match for \"[@\" with \"[1\"\n\t\t\t    continue;\n\t\t\telse\n\t\t\t{\n\t\t\t    // Skip over the digits, the final char must\n\t\t\t    // follow. URXVT can use a negative value, thus\n\t\t\t    // also accept '-'.\n\t\t\t    for (j = slen - 2; j < len && (isdigit(tp[j])\n\t\t\t\t       || tp[j] == '-' || tp[j] == ';'); ++j)\n\t\t\t\t;\n\t\t\t    ++j;\n\t\t\t    if (len < j)\t// got a partial sequence\n\t\t\t\treturn -1;\t// need to get more chars\n\t\t\t    if (tp[j - 1] != termcodes[idx].code[slen - 1])\n\t\t\t\tcontinue;\t// no match\n\n\t\t\t    modifiers_start = tp + slen - 2;\n\n\t\t\t    // Match!  Convert modifier bits.\n\t\t\t    n = atoi((char *)modifiers_start);\n\t\t\t    modifiers |= decode_modifiers(n);\n\n\t\t\t    slen = j;\n\t\t\t}\n\t\t\tkey_name[0] = termcodes[idx].name[0];\n\t\t\tkey_name[1] = termcodes[idx].name[1];\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t    }\n\t    if (idx == tc_len && mouse_index_found >= 0)\n\t    {\n\t\tkey_name[0] = termcodes[mouse_index_found].name[0];\n\t\tkey_name[1] = termcodes[mouse_index_found].name[1];\n\t    }\n\t}\n\n#ifdef FEAT_TERMRESPONSE\n\tif (key_name[0] == NUL\n\t    // Mouse codes of DEC and pterm start with [.  When\n\t    // detecting the start of these mouse codes they might as well be\n\t    // another key code or terminal response.\n# ifdef FEAT_MOUSE_DEC\n\t    || key_name[0] == KS_DEC_MOUSE\n# endif\n# ifdef FEAT_MOUSE_PTERM\n\t    || key_name[0] == KS_PTERM_MOUSE\n# endif\n\t   )\n\t{\n\t    char_u *argp = tp[0] == ESC ? tp + 2 : tp + 1;\n\n\t    /*\n\t     * Check for responses from the terminal starting with {lead}:\n\t     * \"[\" or CSI followed by [0-9>?]\n\t     *\n\t     * - Xterm version string: {lead}>{x};{vers};{y}c\n\t     *   Also eat other possible responses to t_RV, rxvt returns\n\t     *   \"{lead}?1;2c\".\n\t     *\n\t     * - Cursor position report: {lead}{row};{col}R\n\t     *   The final byte must be 'R'. It is used for checking the\n\t     *   ambiguous-width character state.\n\t     *\n\t     * - window position reply: {lead}3;{x};{y}t\n\t     *\n\t     * - key with modifiers when modifyOtherKeys is enabled:\n\t     *\t    {lead}27;{modifier};{key}~\n\t     *\t    {lead}{key};{modifier}u\n\t     */\n\t    if (((tp[0] == ESC && len >= 3 && tp[1] == '[')\n\t\t\t    || (tp[0] == CSI && len >= 2))\n\t\t    && (VIM_ISDIGIT(*argp) || *argp == '>' || *argp == '?'))\n\t    {\n\t\tint resp = handle_csi(tp, len, argp, offset, buf,\n\t\t\t\t\t     bufsize, buflen, key_name, &slen);\n\t\tif (resp != 0)\n\t\t{\n# ifdef DEBUG_TERMRESPONSE\n\t\t    if (resp == -1)\n\t\t\tLOG_TR((\"Not enough characters for CSI sequence\"));\n# endif\n\t\t    return resp;\n\t\t}\n\t    }\n\n\t    // Check for fore/background color response from the terminal,\n\t    // starting} with ] or OSC\n\t    else if ((*T_RBG != NUL || *T_RFG != NUL)\n\t\t\t&& ((tp[0] == ESC && len >= 2 && tp[1] == ']')\n\t\t\t    || tp[0] == OSC))\n\t    {\n\t\tif (handle_osc(tp, argp, len, key_name, &slen) == FAIL)\n\t\t    return -1;\n\t    }\n\n\t    // Check for key code response from xterm,\n\t    // starting with P or DCS\n\t    else if ((check_for_codes || rcs_status.tr_progress == STATUS_SENT)\n\t\t    && ((tp[0] == ESC && len >= 2 && tp[1] == 'P')\n\t\t\t|| tp[0] == DCS))\n\t    {\n\t\tif (handle_dcs(tp, argp, len, key_name, &slen) == FAIL)\n\t\t    return -1;\n\t    }\n\t}\n#endif\n\n\tif (key_name[0] == NUL)\n\t    continue;\t    // No match at this position, try next one\n\n\t// We only get here when we have a complete termcode match\n\n#ifdef FEAT_GUI\n\t/*\n\t * Only in the GUI: Fetch the pointer coordinates of the scroll event\n\t * so that we know which window to scroll later.\n\t */\n\tif (gui.in_use\n\t\t&& key_name[0] == (int)KS_EXTRA\n\t\t&& (key_name[1] == (int)KE_X1MOUSE\n\t\t    || key_name[1] == (int)KE_X2MOUSE\n\t\t    || key_name[1] == (int)KE_MOUSEMOVE_XY\n\t\t    || key_name[1] == (int)KE_MOUSELEFT\n\t\t    || key_name[1] == (int)KE_MOUSERIGHT\n\t\t    || key_name[1] == (int)KE_MOUSEDOWN\n\t\t    || key_name[1] == (int)KE_MOUSEUP))\n\t{\n\t    char_u\tbytes[6];\n\t    int\t\tnum_bytes = get_bytes_from_buf(tp + slen, bytes, 4);\n\n\t    if (num_bytes == -1)\t// not enough coordinates\n\t\treturn -1;\n\t    mouse_col = 128 * (bytes[0] - ' ' - 1) + bytes[1] - ' ' - 1;\n\t    mouse_row = 128 * (bytes[2] - ' ' - 1) + bytes[3] - ' ' - 1;\n\t    slen += num_bytes;\n\t    // equal to K_MOUSEMOVE\n\t    if (key_name[1] == (int)KE_MOUSEMOVE_XY)\n\t\tkey_name[1] = (int)KE_MOUSEMOVE;\n\t}\n\telse\n#endif\n\t/*\n\t * If it is a mouse click, get the coordinates.\n\t */\n\tif (key_name[0] == KS_MOUSE\n#ifdef FEAT_MOUSE_GPM\n\t\t|| key_name[0] == KS_GPM_MOUSE\n#endif\n#ifdef FEAT_MOUSE_JSB\n\t\t|| key_name[0] == KS_JSBTERM_MOUSE\n#endif\n#ifdef FEAT_MOUSE_NET\n\t\t|| key_name[0] == KS_NETTERM_MOUSE\n#endif\n#ifdef FEAT_MOUSE_DEC\n\t\t|| key_name[0] == KS_DEC_MOUSE\n#endif\n#ifdef FEAT_MOUSE_PTERM\n\t\t|| key_name[0] == KS_PTERM_MOUSE\n#endif\n#ifdef FEAT_MOUSE_URXVT\n\t\t|| key_name[0] == KS_URXVT_MOUSE\n#endif\n\t\t|| key_name[0] == KS_SGR_MOUSE\n\t\t|| key_name[0] == KS_SGR_MOUSE_RELEASE)\n\t{\n\t    if (check_termcode_mouse(tp, &slen, key_name, modifiers_start, idx,\n\t\t\t\t\t\t\t     &modifiers) == -1)\n\t\treturn -1;\n\t}\n\n#ifdef FEAT_GUI\n\t/*\n\t * If using the GUI, then we get menu and scrollbar events.\n\t *\n\t * A menu event is encoded as K_SPECIAL, KS_MENU, KE_FILLER followed by\n\t * four bytes which are to be taken as a pointer to the vimmenu_T\n\t * structure.\n\t *\n\t * A tab line event is encoded as K_SPECIAL KS_TABLINE nr, where \"nr\"\n\t * is one byte with the tab index.\n\t *\n\t * A scrollbar event is K_SPECIAL, KS_VER_SCROLLBAR, KE_FILLER followed\n\t * by one byte representing the scrollbar number, and then four bytes\n\t * representing a long_u which is the new value of the scrollbar.\n\t *\n\t * A horizontal scrollbar event is K_SPECIAL, KS_HOR_SCROLLBAR,\n\t * KE_FILLER followed by four bytes representing a long_u which is the\n\t * new value of the scrollbar.\n\t */\n# ifdef FEAT_MENU\n\telse if (key_name[0] == (int)KS_MENU)\n\t{\n\t    long_u\tval;\n\t    int\t\tnum_bytes = get_long_from_buf(tp + slen, &val);\n\n\t    if (num_bytes == -1)\n\t\treturn -1;\n\t    current_menu = (vimmenu_T *)val;\n\t    slen += num_bytes;\n\n\t    // The menu may have been deleted right after it was used, check\n\t    // for that.\n\t    if (check_menu_pointer(root_menu, current_menu) == FAIL)\n\t    {\n\t\tkey_name[0] = KS_EXTRA;\n\t\tkey_name[1] = (int)KE_IGNORE;\n\t    }\n\t}\n# endif\n# ifdef FEAT_GUI_TABLINE\n\telse if (key_name[0] == (int)KS_TABLINE)\n\t{\n\t    // Selecting tabline tab or using its menu.\n\t    char_u\tbytes[6];\n\t    int\t\tnum_bytes = get_bytes_from_buf(tp + slen, bytes, 1);\n\n\t    if (num_bytes == -1)\n\t\treturn -1;\n\t    current_tab = (int)bytes[0];\n\t    if (current_tab == 255)\t// -1 in a byte gives 255\n\t\tcurrent_tab = -1;\n\t    slen += num_bytes;\n\t}\n\telse if (key_name[0] == (int)KS_TABMENU)\n\t{\n\t    // Selecting tabline tab or using its menu.\n\t    char_u\tbytes[6];\n\t    int\t\tnum_bytes = get_bytes_from_buf(tp + slen, bytes, 2);\n\n\t    if (num_bytes == -1)\n\t\treturn -1;\n\t    current_tab = (int)bytes[0];\n\t    current_tabmenu = (int)bytes[1];\n\t    slen += num_bytes;\n\t}\n# endif\n# ifndef USE_ON_FLY_SCROLL\n\telse if (key_name[0] == (int)KS_VER_SCROLLBAR)\n\t{\n\t    long_u\tval;\n\t    char_u\tbytes[6];\n\t    int\t\tnum_bytes;\n\n\t    // Get the last scrollbar event in the queue of the same type\n\t    j = 0;\n\t    for (i = 0; tp[j] == CSI && tp[j + 1] == KS_VER_SCROLLBAR\n\t\t\t\t\t\t     && tp[j + 2] != NUL; ++i)\n\t    {\n\t\tj += 3;\n\t\tnum_bytes = get_bytes_from_buf(tp + j, bytes, 1);\n\t\tif (num_bytes == -1)\n\t\t    break;\n\t\tif (i == 0)\n\t\t    current_scrollbar = (int)bytes[0];\n\t\telse if (current_scrollbar != (int)bytes[0])\n\t\t    break;\n\t\tj += num_bytes;\n\t\tnum_bytes = get_long_from_buf(tp + j, &val);\n\t\tif (num_bytes == -1)\n\t\t    break;\n\t\tscrollbar_value = val;\n\t\tj += num_bytes;\n\t\tslen = j;\n\t    }\n\t    if (i == 0)\t\t// not enough characters to make one\n\t\treturn -1;\n\t}\n\telse if (key_name[0] == (int)KS_HOR_SCROLLBAR)\n\t{\n\t    long_u\tval;\n\t    int\t\tnum_bytes;\n\n\t    // Get the last horiz. scrollbar event in the queue\n\t    j = 0;\n\t    for (i = 0; tp[j] == CSI && tp[j + 1] == KS_HOR_SCROLLBAR\n\t\t\t\t\t\t     && tp[j + 2] != NUL; ++i)\n\t    {\n\t\tj += 3;\n\t\tnum_bytes = get_long_from_buf(tp + j, &val);\n\t\tif (num_bytes == -1)\n\t\t    break;\n\t\tscrollbar_value = val;\n\t\tj += num_bytes;\n\t\tslen = j;\n\t    }\n\t    if (i == 0)\t\t// not enough characters to make one\n\t\treturn -1;\n\t}\n# endif // !USE_ON_FLY_SCROLL\n#endif // FEAT_GUI\n\n#if (defined(UNIX) || defined(VMS))\n\t/*\n\t * Handle FocusIn/FocusOut event sequences reported by XTerm.\n\t * (CSI I/CSI O)\n\t */\n\tif (key_name[0] == KS_EXTRA\n# ifdef FEAT_GUI\n\t\t&& !gui.in_use\n# endif\n\t    )\n\t{\n\t    if (key_name[1] == KE_FOCUSGAINED)\n\t    {\n\t\tif (!focus_state)\n\t\t{\n\t\t    ui_focus_change(TRUE);\n\t\t    did_cursorhold = TRUE;\n\t\t    focus_state = TRUE;\n\t\t}\n\t\tkey_name[1] = (int)KE_IGNORE;\n\t    }\n\t    else if (key_name[1] == KE_FOCUSLOST)\n\t    {\n\t\tif (focus_state)\n\t\t{\n\t\t    ui_focus_change(FALSE);\n\t\t    did_cursorhold = TRUE;\n\t\t    focus_state = FALSE;\n\t\t}\n\t\tkey_name[1] = (int)KE_IGNORE;\n\t    }\n\t}\n#endif\n\n\t/*\n\t * Change  to ,  to , etc.\n\t */\n\tkey = handle_x_keys(TERMCAP2KEY(key_name[0], key_name[1]));\n\n\t/*\n\t * Add any modifier codes to our string.\n\t */\n\tnew_slen = modifiers2keycode(modifiers, &key, string);\n\n\t// Finally, add the special key code to our string\n\tkey_name[0] = KEY2TERMCAP0(key);\n\tkey_name[1] = KEY2TERMCAP1(key);\n\tif (key_name[0] == KS_KEY)\n\t{\n\t    // from \":set =xx\"\n\t    if (has_mbyte)\n\t\tnew_slen += (*mb_char2bytes)(key_name[1], string + new_slen);\n\t    else\n\t\tstring[new_slen++] = key_name[1];\n\t}\n\telse if (new_slen == 0 && key_name[0] == KS_EXTRA\n\t\t\t\t\t\t  && key_name[1] == KE_IGNORE)\n\t{\n\t    // Do not put K_IGNORE into the buffer, do return KEYLEN_REMOVED\n\t    // to indicate what happened.\n\t    retval = KEYLEN_REMOVED;\n\t}\n\telse\n\t{\n\t    string[new_slen++] = K_SPECIAL;\n\t    string[new_slen++] = key_name[0];\n\t    string[new_slen++] = key_name[1];\n\t}\n\tif (put_string_in_typebuf(offset, slen, string, new_slen,\n\t\t\t\t\t\t buf, bufsize, buflen) == FAIL)\n\t    return -1;\n\treturn retval == 0 ? (len + new_slen - slen + offset) : retval;\n    }\n\n#ifdef FEAT_TERMRESPONSE\n    LOG_TR((\"normal character\"));\n#endif\n\n    return 0;\t\t\t    // no match found\n}", "func_hash": 105354748681163651663383549655228844664, "file_name": "term.c", "file_hash": 113564079834188954277061754674630069521, "cwe": ["CWE-787"], "cve": "CVE-2022-2285", "cve_desc": "Integer Overflow or Wraparound in GitHub repository vim/vim prior to 9.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2285"}
{"idx": 208505, "project": "tor", "commit_id": "57e35ad3d91724882c345ac709666a551a977f0f", "project_url": "https://github.com/torproject/tor", "commit_url": "https://gitweb.torproject.org/tor.git/commitdiff/57e35ad3d91724882c345ac709666a551a977f0f", "commit_message": "Avoid possible segfault when handling networkstatus vote with bad flavor\n\nFix for 6530; fix on 0.2.2.6-alpha.", "target": 1, "func": "networkstatus_parse_vote_from_string(const char *s, const char **eos_out,\n                                     networkstatus_type_t ns_type)\n{\n  smartlist_t *tokens = smartlist_create();\n  smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;\n  networkstatus_voter_info_t *voter = NULL;\n  networkstatus_t *ns = NULL;\n  digests_t ns_digests;\n  const char *cert, *end_of_header, *end_of_footer, *s_dup = s;\n  directory_token_t *tok;\n  int ok;\n  struct in_addr in;\n  int i, inorder, n_signatures = 0;\n  memarea_t *area = NULL, *rs_area = NULL;\n  consensus_flavor_t flav = FLAV_NS;\n\n  tor_assert(s);\n\n  if (eos_out)\n    *eos_out = NULL;\n\n  if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {\n    log_warn(LD_DIR, \"Unable to compute digest of network-status\");\n    goto err;\n  }\n\n  area = memarea_new();\n  end_of_header = find_start_of_next_routerstatus(s);\n  if (tokenize_string(area, s, end_of_header, tokens,\n                      (ns_type == NS_TYPE_CONSENSUS) ?\n                      networkstatus_consensus_token_table :\n                      networkstatus_token_table, 0)) {\n    log_warn(LD_DIR, \"Error tokenizing network-status vote header\");\n    goto err;\n  }\n\n  ns = tor_malloc_zero(sizeof(networkstatus_t));\n  memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));\n\n  tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);\n  tor_assert(tok);\n  if (tok->n_args > 1) {\n    int flavor = networkstatus_parse_flavor_name(tok->args[1]);\n    if (flavor < 0) {\n      log_warn(LD_DIR, \"Can't parse document with unknown flavor %s\",\n               escaped(tok->args[2]));\n      goto err;\n    }\n    ns->flavor = flav = flavor;\n  }\n  if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {\n    log_warn(LD_DIR, \"Flavor found on non-consensus networkstatus.\");\n    goto err;\n  }\n\n  if (ns_type != NS_TYPE_CONSENSUS) {\n    const char *end_of_cert = NULL;\n    if (!(cert = strstr(s, \"\\ndir-key-certificate-version\")))\n      goto err;\n    ++cert;\n    ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);\n    if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)\n      goto err;\n  }\n\n  tok = find_by_keyword(tokens, K_VOTE_STATUS);\n  tor_assert(tok->n_args);\n  if (!strcmp(tok->args[0], \"vote\")) {\n    ns->type = NS_TYPE_VOTE;\n  } else if (!strcmp(tok->args[0], \"consensus\")) {\n    ns->type = NS_TYPE_CONSENSUS;\n  } else if (!strcmp(tok->args[0], \"opinion\")) {\n    ns->type = NS_TYPE_OPINION;\n  } else {\n    log_warn(LD_DIR, \"Unrecognized vote status %s in network-status\",\n             escaped(tok->args[0]));\n    goto err;\n  }\n  if (ns_type != ns->type) {\n    log_warn(LD_DIR, \"Got the wrong kind of v3 networkstatus.\");\n    goto err;\n  }\n\n  if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {\n    tok = find_by_keyword(tokens, K_PUBLISHED);\n    if (parse_iso_time(tok->args[0], &ns->published))\n      goto err;\n\n    ns->supported_methods = smartlist_create();\n    tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);\n    if (tok) {\n      for (i=0; i < tok->n_args; ++i)\n        smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));\n    } else {\n      smartlist_add(ns->supported_methods, tor_strdup(\"1\"));\n    }\n  } else {\n    tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);\n    if (tok) {\n      ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,\n                                                 &ok, NULL);\n      if (!ok)\n        goto err;\n    } else {\n      ns->consensus_method = 1;\n    }\n  }\n\n  tok = find_by_keyword(tokens, K_VALID_AFTER);\n  if (parse_iso_time(tok->args[0], &ns->valid_after))\n    goto err;\n\n  tok = find_by_keyword(tokens, K_FRESH_UNTIL);\n  if (parse_iso_time(tok->args[0], &ns->fresh_until))\n    goto err;\n\n  tok = find_by_keyword(tokens, K_VALID_UNTIL);\n  if (parse_iso_time(tok->args[0], &ns->valid_until))\n    goto err;\n\n  tok = find_by_keyword(tokens, K_VOTING_DELAY);\n  tor_assert(tok->n_args >= 2);\n  ns->vote_seconds =\n    (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);\n  if (!ok)\n    goto err;\n  ns->dist_seconds =\n    (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);\n  if (!ok)\n    goto err;\n  if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {\n    log_warn(LD_DIR, \"Vote/consensus freshness interval is too short\");\n    goto err;\n  }\n  if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {\n    log_warn(LD_DIR, \"Vote/consensus liveness interval is too short\");\n    goto err;\n  }\n  if (ns->vote_seconds < MIN_VOTE_SECONDS) {\n    log_warn(LD_DIR, \"Vote seconds is too short\");\n    goto err;\n  }\n  if (ns->dist_seconds < MIN_DIST_SECONDS) {\n    log_warn(LD_DIR, \"Dist seconds is too short\");\n    goto err;\n  }\n\n  if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {\n    ns->client_versions = tor_strdup(tok->args[0]);\n  }\n  if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {\n    ns->server_versions = tor_strdup(tok->args[0]);\n  }\n\n  tok = find_by_keyword(tokens, K_KNOWN_FLAGS);\n  ns->known_flags = smartlist_create();\n  inorder = 1;\n  for (i = 0; i < tok->n_args; ++i) {\n    smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));\n    if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {\n      log_warn(LD_DIR, \"%s >= %s\", tok->args[i-1], tok->args[i]);\n      inorder = 0;\n    }\n  }\n  if (!inorder) {\n    log_warn(LD_DIR, \"known-flags not in order\");\n    goto err;\n  }\n\n  tok = find_opt_by_keyword(tokens, K_PARAMS);\n  if (tok) {\n    inorder = 1;\n    ns->net_params = smartlist_create();\n    for (i = 0; i < tok->n_args; ++i) {\n      int ok=0;\n      char *eq = strchr(tok->args[i], '=');\n      if (!eq) {\n        log_warn(LD_DIR, \"Bad element '%s' in params\", escaped(tok->args[i]));\n        goto err;\n      }\n      tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);\n      if (!ok) {\n        log_warn(LD_DIR, \"Bad element '%s' in params\", escaped(tok->args[i]));\n        goto err;\n      }\n      if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {\n        log_warn(LD_DIR, \"%s >= %s\", tok->args[i-1], tok->args[i]);\n        inorder = 0;\n      }\n      smartlist_add(ns->net_params, tor_strdup(tok->args[i]));\n    }\n    if (!inorder) {\n      log_warn(LD_DIR, \"params not in order\");\n      goto err;\n    }\n  }\n\n  ns->voters = smartlist_create();\n\n  SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {\n    tok = _tok;\n    if (tok->tp == K_DIR_SOURCE) {\n      tor_assert(tok->n_args >= 6);\n\n      if (voter)\n        smartlist_add(ns->voters, voter);\n      voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));\n      voter->sigs = smartlist_create();\n      if (ns->type != NS_TYPE_CONSENSUS)\n        memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);\n\n      voter->nickname = tor_strdup(tok->args[0]);\n      if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||\n          base16_decode(voter->identity_digest, sizeof(voter->identity_digest),\n                        tok->args[1], HEX_DIGEST_LEN) < 0) {\n        log_warn(LD_DIR, \"Error decoding identity digest %s in \"\n                 \"network-status vote.\", escaped(tok->args[1]));\n        goto err;\n      }\n      if (ns->type != NS_TYPE_CONSENSUS &&\n          tor_memneq(ns->cert->cache_info.identity_digest,\n                 voter->identity_digest, DIGEST_LEN)) {\n        log_warn(LD_DIR,\"Mismatch between identities in certificate and vote\");\n        goto err;\n      }\n      voter->address = tor_strdup(tok->args[2]);\n      if (!tor_inet_aton(tok->args[3], &in)) {\n        log_warn(LD_DIR, \"Error decoding IP address %s in network-status.\",\n                 escaped(tok->args[3]));\n        goto err;\n      }\n      voter->addr = ntohl(in.s_addr);\n      voter->dir_port = (uint16_t)\n        tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);\n      if (!ok)\n        goto err;\n      voter->or_port = (uint16_t)\n        tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);\n      if (!ok)\n        goto err;\n    } else if (tok->tp == K_CONTACT) {\n      if (!voter || voter->contact) {\n        log_warn(LD_DIR, \"contact element is out of place.\");\n        goto err;\n      }\n      voter->contact = tor_strdup(tok->args[0]);\n    } else if (tok->tp == K_VOTE_DIGEST) {\n      tor_assert(ns->type == NS_TYPE_CONSENSUS);\n      tor_assert(tok->n_args >= 1);\n      if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {\n        log_warn(LD_DIR, \"vote-digest element is out of place.\");\n        goto err;\n      }\n      if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||\n        base16_decode(voter->vote_digest, sizeof(voter->vote_digest),\n                      tok->args[0], HEX_DIGEST_LEN) < 0) {\n        log_warn(LD_DIR, \"Error decoding vote digest %s in \"\n                 \"network-status consensus.\", escaped(tok->args[0]));\n        goto err;\n      }\n    }\n  } SMARTLIST_FOREACH_END(_tok);\n  if (voter) {\n    smartlist_add(ns->voters, voter);\n    voter = NULL;\n  }\n  if (smartlist_len(ns->voters) == 0) {\n    log_warn(LD_DIR, \"Missing dir-source elements in a vote networkstatus.\");\n    goto err;\n  } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {\n    log_warn(LD_DIR, \"Too many dir-source elements in a vote networkstatus.\");\n    goto err;\n  }\n\n  if (ns->type != NS_TYPE_CONSENSUS &&\n      (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {\n    int bad = 1;\n    if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {\n      networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);\n      if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,\n                        tok->args[0], HEX_DIGEST_LEN)<0)\n        bad = 1;\n      else\n        bad = 0;\n    }\n    if (bad) {\n      log_warn(LD_DIR, \"Invalid legacy key digest %s on vote.\",\n               escaped(tok->args[0]));\n    }\n  }\n\n  /* Parse routerstatus lines. */\n  rs_tokens = smartlist_create();\n  rs_area = memarea_new();\n  s = end_of_header;\n  ns->routerstatus_list = smartlist_create();\n\n  while (!strcmpstart(s, \"r \")) {\n    if (ns->type != NS_TYPE_CONSENSUS) {\n      vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));\n      if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,\n                                               rs, 0, 0))\n        smartlist_add(ns->routerstatus_list, rs);\n      else {\n        tor_free(rs->version);\n        tor_free(rs);\n      }\n    } else {\n      routerstatus_t *rs;\n      if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,\n                                                     NULL, NULL,\n                                                     ns->consensus_method,\n                                                     flav)))\n        smartlist_add(ns->routerstatus_list, rs);\n    }\n  }\n  for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {\n    routerstatus_t *rs1, *rs2;\n    if (ns->type != NS_TYPE_CONSENSUS) {\n      vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);\n      vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);\n      rs1 = &a->status; rs2 = &b->status;\n    } else {\n      rs1 = smartlist_get(ns->routerstatus_list, i-1);\n      rs2 = smartlist_get(ns->routerstatus_list, i);\n    }\n    if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)\n        >= 0) {\n      log_warn(LD_DIR, \"Vote networkstatus entries not sorted by identity \"\n               \"digest\");\n      goto err;\n    }\n  }\n\n  /* Parse footer; check signature. */\n  footer_tokens = smartlist_create();\n  if ((end_of_footer = strstr(s, \"\\nnetwork-status-version \")))\n    ++end_of_footer;\n  else\n    end_of_footer = s + strlen(s);\n  if (tokenize_string(area,s, end_of_footer, footer_tokens,\n                      networkstatus_vote_footer_token_table, 0)) {\n    log_warn(LD_DIR, \"Error tokenizing network-status vote footer.\");\n    goto err;\n  }\n\n  {\n    int found_sig = 0;\n    SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {\n      tok = _tok;\n      if (tok->tp == K_DIRECTORY_SIGNATURE)\n        found_sig = 1;\n      else if (found_sig) {\n        log_warn(LD_DIR, \"Extraneous token after first directory-signature\");\n        goto err;\n      }\n    } SMARTLIST_FOREACH_END(_tok);\n  }\n\n  if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {\n    if (tok != smartlist_get(footer_tokens, 0)) {\n      log_warn(LD_DIR, \"Misplaced directory-footer token\");\n      goto err;\n    }\n  }\n\n  tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);\n  if (tok) {\n    ns->weight_params = smartlist_create();\n    for (i = 0; i < tok->n_args; ++i) {\n      int ok=0;\n      char *eq = strchr(tok->args[i], '=');\n      if (!eq) {\n        log_warn(LD_DIR, \"Bad element '%s' in weight params\",\n                 escaped(tok->args[i]));\n        goto err;\n      }\n      tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);\n      if (!ok) {\n        log_warn(LD_DIR, \"Bad element '%s' in params\", escaped(tok->args[i]));\n        goto err;\n      }\n      smartlist_add(ns->weight_params, tor_strdup(tok->args[i]));\n    }\n  }\n\n  SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {\n    char declared_identity[DIGEST_LEN];\n    networkstatus_voter_info_t *v;\n    document_signature_t *sig;\n    const char *id_hexdigest = NULL;\n    const char *sk_hexdigest = NULL;\n    digest_algorithm_t alg = DIGEST_SHA1;\n    tok = _tok;\n    if (tok->tp != K_DIRECTORY_SIGNATURE)\n      continue;\n    tor_assert(tok->n_args >= 2);\n    if (tok->n_args == 2) {\n      id_hexdigest = tok->args[0];\n      sk_hexdigest = tok->args[1];\n    } else {\n      const char *algname = tok->args[0];\n      int a;\n      id_hexdigest = tok->args[1];\n      sk_hexdigest = tok->args[2];\n      a = crypto_digest_algorithm_parse_name(algname);\n      if (a<0) {\n        log_warn(LD_DIR, \"Unknown digest algorithm %s; skipping\",\n                 escaped(algname));\n        continue;\n      }\n      alg = a;\n    }\n\n    if (!tok->object_type ||\n        strcmp(tok->object_type, \"SIGNATURE\") ||\n        tok->object_size < 128 || tok->object_size > 512) {\n      log_warn(LD_DIR, \"Bad object type or length on directory-signature\");\n      goto err;\n    }\n\n    if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||\n        base16_decode(declared_identity, sizeof(declared_identity),\n                      id_hexdigest, HEX_DIGEST_LEN) < 0) {\n      log_warn(LD_DIR, \"Error decoding declared identity %s in \"\n               \"network-status vote.\", escaped(id_hexdigest));\n      goto err;\n    }\n    if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {\n      log_warn(LD_DIR, \"ID on signature on network-status vote does not match \"\n               \"any declared directory source.\");\n      goto err;\n    }\n    sig = tor_malloc_zero(sizeof(document_signature_t));\n    memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);\n    sig->alg = alg;\n    if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||\n        base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),\n                      sk_hexdigest, HEX_DIGEST_LEN) < 0) {\n      log_warn(LD_DIR, \"Error decoding declared signing key digest %s in \"\n               \"network-status vote.\", escaped(sk_hexdigest));\n      tor_free(sig);\n      goto err;\n    }\n\n    if (ns->type != NS_TYPE_CONSENSUS) {\n      if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,\n                 DIGEST_LEN)) {\n        log_warn(LD_DIR, \"Digest mismatch between declared and actual on \"\n                 \"network-status vote.\");\n        tor_free(sig);\n        goto err;\n      }\n    }\n\n    if (voter_get_sig_by_algorithm(v, sig->alg)) {\n      /* We already parsed a vote with this algorithm from this voter. Use the\n         first one. */\n      log_fn(LOG_PROTOCOL_WARN, LD_DIR, \"We received a networkstatus \"\n             \"that contains two votes from the same voter with the same \"\n             \"algorithm. Ignoring the second vote.\");\n      tor_free(sig);\n      continue;\n    }\n\n    if (ns->type != NS_TYPE_CONSENSUS) {\n      if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,\n                                tok, ns->cert->signing_key, 0,\n                                \"network-status vote\")) {\n        tor_free(sig);\n        goto err;\n      }\n      sig->good_signature = 1;\n    } else {\n      if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {\n        tor_free(sig);\n        goto err;\n      }\n      sig->signature = tor_memdup(tok->object_body, tok->object_size);\n      sig->signature_len = (int) tok->object_size;\n    }\n    smartlist_add(v->sigs, sig);\n\n    ++n_signatures;\n  } SMARTLIST_FOREACH_END(_tok);\n\n  if (! n_signatures) {\n    log_warn(LD_DIR, \"No signatures on networkstatus vote.\");\n    goto err;\n  } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {\n    log_warn(LD_DIR, \"Received more than one signature on a \"\n             \"network-status vote.\");\n    goto err;\n  }\n\n  if (eos_out)\n    *eos_out = end_of_footer;\n\n  goto done;\n err:\n  dump_desc(s_dup, \"v3 networkstatus\");\n  networkstatus_vote_free(ns);\n  ns = NULL;\n done:\n  if (tokens) {\n    SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));\n    smartlist_free(tokens);\n  }\n  if (voter) {\n    if (voter->sigs) {\n      SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,\n                        document_signature_free(sig));\n      smartlist_free(voter->sigs);\n    }\n    tor_free(voter->nickname);\n    tor_free(voter->address);\n    tor_free(voter->contact);\n    tor_free(voter);\n  }\n  if (rs_tokens) {\n    SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));\n    smartlist_free(rs_tokens);\n  }\n  if (footer_tokens) {\n    SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));\n    smartlist_free(footer_tokens);\n  }\n  if (area) {\n    DUMP_AREA(area, \"v3 networkstatus\");\n    memarea_drop_all(area);\n  }\n  if (rs_area)\n    memarea_drop_all(rs_area);\n\n  return ns;\n}", "func_hash": 297795787979009632344281497591388902899, "file_name": "routerparse.c", "file_hash": 22420103474128049345359193080521452725, "cwe": ["CWE-399"], "cve": "CVE-2012-3517", "cve_desc": "Use-after-free vulnerability in dns.c in Tor before 0.2.2.38 might allow remote attackers to cause a denial of service (daemon crash) via vectors related to failed DNS requests.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2012-3517"}
{"idx": 411896, "project": "tor", "commit_id": "57e35ad3d91724882c345ac709666a551a977f0f", "project_url": "https://github.com/torproject/tor", "commit_url": "https://gitweb.torproject.org/tor.git/commitdiff/57e35ad3d91724882c345ac709666a551a977f0f", "commit_message": "Avoid possible segfault when handling networkstatus vote with bad flavor\n\nFix for 6530; fix on 0.2.2.6-alpha.", "target": 0, "func": "networkstatus_parse_vote_from_string(const char *s, const char **eos_out,\n                                     networkstatus_type_t ns_type)\n{\n  smartlist_t *tokens = smartlist_create();\n  smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;\n  networkstatus_voter_info_t *voter = NULL;\n  networkstatus_t *ns = NULL;\n  digests_t ns_digests;\n  const char *cert, *end_of_header, *end_of_footer, *s_dup = s;\n  directory_token_t *tok;\n  int ok;\n  struct in_addr in;\n  int i, inorder, n_signatures = 0;\n  memarea_t *area = NULL, *rs_area = NULL;\n  consensus_flavor_t flav = FLAV_NS;\n\n  tor_assert(s);\n\n  if (eos_out)\n    *eos_out = NULL;\n\n  if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {\n    log_warn(LD_DIR, \"Unable to compute digest of network-status\");\n    goto err;\n  }\n\n  area = memarea_new();\n  end_of_header = find_start_of_next_routerstatus(s);\n  if (tokenize_string(area, s, end_of_header, tokens,\n                      (ns_type == NS_TYPE_CONSENSUS) ?\n                      networkstatus_consensus_token_table :\n                      networkstatus_token_table, 0)) {\n    log_warn(LD_DIR, \"Error tokenizing network-status vote header\");\n    goto err;\n  }\n\n  ns = tor_malloc_zero(sizeof(networkstatus_t));\n  memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));\n\n  tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);\n  tor_assert(tok);\n  if (tok->n_args > 1) {\n    int flavor = networkstatus_parse_flavor_name(tok->args[1]);\n    if (flavor < 0) {\n      log_warn(LD_DIR, \"Can't parse document with unknown flavor %s\",\n               escaped(tok->args[1]));\n      goto err;\n    }\n    ns->flavor = flav = flavor;\n  }\n  if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {\n    log_warn(LD_DIR, \"Flavor found on non-consensus networkstatus.\");\n    goto err;\n  }\n\n  if (ns_type != NS_TYPE_CONSENSUS) {\n    const char *end_of_cert = NULL;\n    if (!(cert = strstr(s, \"\\ndir-key-certificate-version\")))\n      goto err;\n    ++cert;\n    ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);\n    if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)\n      goto err;\n  }\n\n  tok = find_by_keyword(tokens, K_VOTE_STATUS);\n  tor_assert(tok->n_args);\n  if (!strcmp(tok->args[0], \"vote\")) {\n    ns->type = NS_TYPE_VOTE;\n  } else if (!strcmp(tok->args[0], \"consensus\")) {\n    ns->type = NS_TYPE_CONSENSUS;\n  } else if (!strcmp(tok->args[0], \"opinion\")) {\n    ns->type = NS_TYPE_OPINION;\n  } else {\n    log_warn(LD_DIR, \"Unrecognized vote status %s in network-status\",\n             escaped(tok->args[0]));\n    goto err;\n  }\n  if (ns_type != ns->type) {\n    log_warn(LD_DIR, \"Got the wrong kind of v3 networkstatus.\");\n    goto err;\n  }\n\n  if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {\n    tok = find_by_keyword(tokens, K_PUBLISHED);\n    if (parse_iso_time(tok->args[0], &ns->published))\n      goto err;\n\n    ns->supported_methods = smartlist_create();\n    tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);\n    if (tok) {\n      for (i=0; i < tok->n_args; ++i)\n        smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));\n    } else {\n      smartlist_add(ns->supported_methods, tor_strdup(\"1\"));\n    }\n  } else {\n    tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);\n    if (tok) {\n      ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,\n                                                 &ok, NULL);\n      if (!ok)\n        goto err;\n    } else {\n      ns->consensus_method = 1;\n    }\n  }\n\n  tok = find_by_keyword(tokens, K_VALID_AFTER);\n  if (parse_iso_time(tok->args[0], &ns->valid_after))\n    goto err;\n\n  tok = find_by_keyword(tokens, K_FRESH_UNTIL);\n  if (parse_iso_time(tok->args[0], &ns->fresh_until))\n    goto err;\n\n  tok = find_by_keyword(tokens, K_VALID_UNTIL);\n  if (parse_iso_time(tok->args[0], &ns->valid_until))\n    goto err;\n\n  tok = find_by_keyword(tokens, K_VOTING_DELAY);\n  tor_assert(tok->n_args >= 2);\n  ns->vote_seconds =\n    (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);\n  if (!ok)\n    goto err;\n  ns->dist_seconds =\n    (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);\n  if (!ok)\n    goto err;\n  if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {\n    log_warn(LD_DIR, \"Vote/consensus freshness interval is too short\");\n    goto err;\n  }\n  if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {\n    log_warn(LD_DIR, \"Vote/consensus liveness interval is too short\");\n    goto err;\n  }\n  if (ns->vote_seconds < MIN_VOTE_SECONDS) {\n    log_warn(LD_DIR, \"Vote seconds is too short\");\n    goto err;\n  }\n  if (ns->dist_seconds < MIN_DIST_SECONDS) {\n    log_warn(LD_DIR, \"Dist seconds is too short\");\n    goto err;\n  }\n\n  if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {\n    ns->client_versions = tor_strdup(tok->args[0]);\n  }\n  if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {\n    ns->server_versions = tor_strdup(tok->args[0]);\n  }\n\n  tok = find_by_keyword(tokens, K_KNOWN_FLAGS);\n  ns->known_flags = smartlist_create();\n  inorder = 1;\n  for (i = 0; i < tok->n_args; ++i) {\n    smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));\n    if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {\n      log_warn(LD_DIR, \"%s >= %s\", tok->args[i-1], tok->args[i]);\n      inorder = 0;\n    }\n  }\n  if (!inorder) {\n    log_warn(LD_DIR, \"known-flags not in order\");\n    goto err;\n  }\n\n  tok = find_opt_by_keyword(tokens, K_PARAMS);\n  if (tok) {\n    inorder = 1;\n    ns->net_params = smartlist_create();\n    for (i = 0; i < tok->n_args; ++i) {\n      int ok=0;\n      char *eq = strchr(tok->args[i], '=');\n      if (!eq) {\n        log_warn(LD_DIR, \"Bad element '%s' in params\", escaped(tok->args[i]));\n        goto err;\n      }\n      tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);\n      if (!ok) {\n        log_warn(LD_DIR, \"Bad element '%s' in params\", escaped(tok->args[i]));\n        goto err;\n      }\n      if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {\n        log_warn(LD_DIR, \"%s >= %s\", tok->args[i-1], tok->args[i]);\n        inorder = 0;\n      }\n      smartlist_add(ns->net_params, tor_strdup(tok->args[i]));\n    }\n    if (!inorder) {\n      log_warn(LD_DIR, \"params not in order\");\n      goto err;\n    }\n  }\n\n  ns->voters = smartlist_create();\n\n  SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {\n    tok = _tok;\n    if (tok->tp == K_DIR_SOURCE) {\n      tor_assert(tok->n_args >= 6);\n\n      if (voter)\n        smartlist_add(ns->voters, voter);\n      voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));\n      voter->sigs = smartlist_create();\n      if (ns->type != NS_TYPE_CONSENSUS)\n        memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);\n\n      voter->nickname = tor_strdup(tok->args[0]);\n      if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||\n          base16_decode(voter->identity_digest, sizeof(voter->identity_digest),\n                        tok->args[1], HEX_DIGEST_LEN) < 0) {\n        log_warn(LD_DIR, \"Error decoding identity digest %s in \"\n                 \"network-status vote.\", escaped(tok->args[1]));\n        goto err;\n      }\n      if (ns->type != NS_TYPE_CONSENSUS &&\n          tor_memneq(ns->cert->cache_info.identity_digest,\n                 voter->identity_digest, DIGEST_LEN)) {\n        log_warn(LD_DIR,\"Mismatch between identities in certificate and vote\");\n        goto err;\n      }\n      voter->address = tor_strdup(tok->args[2]);\n      if (!tor_inet_aton(tok->args[3], &in)) {\n        log_warn(LD_DIR, \"Error decoding IP address %s in network-status.\",\n                 escaped(tok->args[3]));\n        goto err;\n      }\n      voter->addr = ntohl(in.s_addr);\n      voter->dir_port = (uint16_t)\n        tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);\n      if (!ok)\n        goto err;\n      voter->or_port = (uint16_t)\n        tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);\n      if (!ok)\n        goto err;\n    } else if (tok->tp == K_CONTACT) {\n      if (!voter || voter->contact) {\n        log_warn(LD_DIR, \"contact element is out of place.\");\n        goto err;\n      }\n      voter->contact = tor_strdup(tok->args[0]);\n    } else if (tok->tp == K_VOTE_DIGEST) {\n      tor_assert(ns->type == NS_TYPE_CONSENSUS);\n      tor_assert(tok->n_args >= 1);\n      if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {\n        log_warn(LD_DIR, \"vote-digest element is out of place.\");\n        goto err;\n      }\n      if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||\n        base16_decode(voter->vote_digest, sizeof(voter->vote_digest),\n                      tok->args[0], HEX_DIGEST_LEN) < 0) {\n        log_warn(LD_DIR, \"Error decoding vote digest %s in \"\n                 \"network-status consensus.\", escaped(tok->args[0]));\n        goto err;\n      }\n    }\n  } SMARTLIST_FOREACH_END(_tok);\n  if (voter) {\n    smartlist_add(ns->voters, voter);\n    voter = NULL;\n  }\n  if (smartlist_len(ns->voters) == 0) {\n    log_warn(LD_DIR, \"Missing dir-source elements in a vote networkstatus.\");\n    goto err;\n  } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {\n    log_warn(LD_DIR, \"Too many dir-source elements in a vote networkstatus.\");\n    goto err;\n  }\n\n  if (ns->type != NS_TYPE_CONSENSUS &&\n      (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {\n    int bad = 1;\n    if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {\n      networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);\n      if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,\n                        tok->args[0], HEX_DIGEST_LEN)<0)\n        bad = 1;\n      else\n        bad = 0;\n    }\n    if (bad) {\n      log_warn(LD_DIR, \"Invalid legacy key digest %s on vote.\",\n               escaped(tok->args[0]));\n    }\n  }\n\n  /* Parse routerstatus lines. */\n  rs_tokens = smartlist_create();\n  rs_area = memarea_new();\n  s = end_of_header;\n  ns->routerstatus_list = smartlist_create();\n\n  while (!strcmpstart(s, \"r \")) {\n    if (ns->type != NS_TYPE_CONSENSUS) {\n      vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));\n      if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,\n                                               rs, 0, 0))\n        smartlist_add(ns->routerstatus_list, rs);\n      else {\n        tor_free(rs->version);\n        tor_free(rs);\n      }\n    } else {\n      routerstatus_t *rs;\n      if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,\n                                                     NULL, NULL,\n                                                     ns->consensus_method,\n                                                     flav)))\n        smartlist_add(ns->routerstatus_list, rs);\n    }\n  }\n  for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {\n    routerstatus_t *rs1, *rs2;\n    if (ns->type != NS_TYPE_CONSENSUS) {\n      vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);\n      vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);\n      rs1 = &a->status; rs2 = &b->status;\n    } else {\n      rs1 = smartlist_get(ns->routerstatus_list, i-1);\n      rs2 = smartlist_get(ns->routerstatus_list, i);\n    }\n    if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)\n        >= 0) {\n      log_warn(LD_DIR, \"Vote networkstatus entries not sorted by identity \"\n               \"digest\");\n      goto err;\n    }\n  }\n\n  /* Parse footer; check signature. */\n  footer_tokens = smartlist_create();\n  if ((end_of_footer = strstr(s, \"\\nnetwork-status-version \")))\n    ++end_of_footer;\n  else\n    end_of_footer = s + strlen(s);\n  if (tokenize_string(area,s, end_of_footer, footer_tokens,\n                      networkstatus_vote_footer_token_table, 0)) {\n    log_warn(LD_DIR, \"Error tokenizing network-status vote footer.\");\n    goto err;\n  }\n\n  {\n    int found_sig = 0;\n    SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {\n      tok = _tok;\n      if (tok->tp == K_DIRECTORY_SIGNATURE)\n        found_sig = 1;\n      else if (found_sig) {\n        log_warn(LD_DIR, \"Extraneous token after first directory-signature\");\n        goto err;\n      }\n    } SMARTLIST_FOREACH_END(_tok);\n  }\n\n  if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {\n    if (tok != smartlist_get(footer_tokens, 0)) {\n      log_warn(LD_DIR, \"Misplaced directory-footer token\");\n      goto err;\n    }\n  }\n\n  tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);\n  if (tok) {\n    ns->weight_params = smartlist_create();\n    for (i = 0; i < tok->n_args; ++i) {\n      int ok=0;\n      char *eq = strchr(tok->args[i], '=');\n      if (!eq) {\n        log_warn(LD_DIR, \"Bad element '%s' in weight params\",\n                 escaped(tok->args[i]));\n        goto err;\n      }\n      tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);\n      if (!ok) {\n        log_warn(LD_DIR, \"Bad element '%s' in params\", escaped(tok->args[i]));\n        goto err;\n      }\n      smartlist_add(ns->weight_params, tor_strdup(tok->args[i]));\n    }\n  }\n\n  SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {\n    char declared_identity[DIGEST_LEN];\n    networkstatus_voter_info_t *v;\n    document_signature_t *sig;\n    const char *id_hexdigest = NULL;\n    const char *sk_hexdigest = NULL;\n    digest_algorithm_t alg = DIGEST_SHA1;\n    tok = _tok;\n    if (tok->tp != K_DIRECTORY_SIGNATURE)\n      continue;\n    tor_assert(tok->n_args >= 2);\n    if (tok->n_args == 2) {\n      id_hexdigest = tok->args[0];\n      sk_hexdigest = tok->args[1];\n    } else {\n      const char *algname = tok->args[0];\n      int a;\n      id_hexdigest = tok->args[1];\n      sk_hexdigest = tok->args[2];\n      a = crypto_digest_algorithm_parse_name(algname);\n      if (a<0) {\n        log_warn(LD_DIR, \"Unknown digest algorithm %s; skipping\",\n                 escaped(algname));\n        continue;\n      }\n      alg = a;\n    }\n\n    if (!tok->object_type ||\n        strcmp(tok->object_type, \"SIGNATURE\") ||\n        tok->object_size < 128 || tok->object_size > 512) {\n      log_warn(LD_DIR, \"Bad object type or length on directory-signature\");\n      goto err;\n    }\n\n    if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||\n        base16_decode(declared_identity, sizeof(declared_identity),\n                      id_hexdigest, HEX_DIGEST_LEN) < 0) {\n      log_warn(LD_DIR, \"Error decoding declared identity %s in \"\n               \"network-status vote.\", escaped(id_hexdigest));\n      goto err;\n    }\n    if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {\n      log_warn(LD_DIR, \"ID on signature on network-status vote does not match \"\n               \"any declared directory source.\");\n      goto err;\n    }\n    sig = tor_malloc_zero(sizeof(document_signature_t));\n    memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);\n    sig->alg = alg;\n    if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||\n        base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),\n                      sk_hexdigest, HEX_DIGEST_LEN) < 0) {\n      log_warn(LD_DIR, \"Error decoding declared signing key digest %s in \"\n               \"network-status vote.\", escaped(sk_hexdigest));\n      tor_free(sig);\n      goto err;\n    }\n\n    if (ns->type != NS_TYPE_CONSENSUS) {\n      if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,\n                 DIGEST_LEN)) {\n        log_warn(LD_DIR, \"Digest mismatch between declared and actual on \"\n                 \"network-status vote.\");\n        tor_free(sig);\n        goto err;\n      }\n    }\n\n    if (voter_get_sig_by_algorithm(v, sig->alg)) {\n      /* We already parsed a vote with this algorithm from this voter. Use the\n         first one. */\n      log_fn(LOG_PROTOCOL_WARN, LD_DIR, \"We received a networkstatus \"\n             \"that contains two votes from the same voter with the same \"\n             \"algorithm. Ignoring the second vote.\");\n      tor_free(sig);\n      continue;\n    }\n\n    if (ns->type != NS_TYPE_CONSENSUS) {\n      if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,\n                                tok, ns->cert->signing_key, 0,\n                                \"network-status vote\")) {\n        tor_free(sig);\n        goto err;\n      }\n      sig->good_signature = 1;\n    } else {\n      if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {\n        tor_free(sig);\n        goto err;\n      }\n      sig->signature = tor_memdup(tok->object_body, tok->object_size);\n      sig->signature_len = (int) tok->object_size;\n    }\n    smartlist_add(v->sigs, sig);\n\n    ++n_signatures;\n  } SMARTLIST_FOREACH_END(_tok);\n\n  if (! n_signatures) {\n    log_warn(LD_DIR, \"No signatures on networkstatus vote.\");\n    goto err;\n  } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {\n    log_warn(LD_DIR, \"Received more than one signature on a \"\n             \"network-status vote.\");\n    goto err;\n  }\n\n  if (eos_out)\n    *eos_out = end_of_footer;\n\n  goto done;\n err:\n  dump_desc(s_dup, \"v3 networkstatus\");\n  networkstatus_vote_free(ns);\n  ns = NULL;\n done:\n  if (tokens) {\n    SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));\n    smartlist_free(tokens);\n  }\n  if (voter) {\n    if (voter->sigs) {\n      SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,\n                        document_signature_free(sig));\n      smartlist_free(voter->sigs);\n    }\n    tor_free(voter->nickname);\n    tor_free(voter->address);\n    tor_free(voter->contact);\n    tor_free(voter);\n  }\n  if (rs_tokens) {\n    SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));\n    smartlist_free(rs_tokens);\n  }\n  if (footer_tokens) {\n    SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));\n    smartlist_free(footer_tokens);\n  }\n  if (area) {\n    DUMP_AREA(area, \"v3 networkstatus\");\n    memarea_drop_all(area);\n  }\n  if (rs_area)\n    memarea_drop_all(rs_area);\n\n  return ns;\n}", "func_hash": 32476189085047846654485357461000169303, "file_name": "routerparse.c", "file_hash": 74078993205863755729749320619386018823, "cwe": ["CWE-399"], "cve": "CVE-2012-3517", "cve_desc": "Use-after-free vulnerability in dns.c in Tor before 0.2.2.38 might allow remote attackers to cause a denial of service (daemon crash) via vectors related to failed DNS requests.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2012-3517"}
{"idx": 208506, "project": "heimdal", "commit_id": "04171147948d0a3636bc6374181926f0fb2ec83a", "project_url": "https://github.com/heimdal/heimdal", "commit_url": "https://github.com/heimdal/heimdal/commit/04171147948d0a3636bc6374181926f0fb2ec83a", "commit_message": "kdc: validate sname in TGS-REQ\n\nIn tgs_build_reply(), validate the server name in the TGS-REQ is present before\ndereferencing.", "target": 1, "func": "tgs_build_reply(astgs_request_t priv,\n\t\thdb_entry_ex *krbtgt,\n\t\tkrb5_enctype krbtgt_etype,\n\t\tconst krb5_keyblock *replykey,\n\t\tint rk_is_subkey,\n\t\tkrb5_ticket *ticket,\n\t\tconst char **e_text,\n\t\tAuthorizationData **auth_data,\n\t\tconst struct sockaddr *from_addr)\n{\n    krb5_context context = priv->context;\n    krb5_kdc_configuration *config = priv->config;\n    KDC_REQ *req = &priv->req;\n    KDC_REQ_BODY *b = &priv->req.req_body;\n    const char *from = priv->from;\n    krb5_error_code ret, ret2;\n    krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL;\n    krb5_principal krbtgt_out_principal = NULL;\n    char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL;\n    hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL;\n    HDB *clientdb, *s4u2self_impersonated_clientdb;\n    krb5_realm ref_realm = NULL;\n    EncTicketPart *tgt = &ticket->ticket;\n    krb5_principals spp = NULL;\n    const EncryptionKey *ekey;\n    krb5_keyblock sessionkey;\n    krb5_kvno kvno;\n    krb5_data rspac;\n    const char *tgt_realm = /* Realm of TGT issuer */\n        krb5_principal_get_realm(context, krbtgt->entry.principal);\n    const char *our_realm = /* Realm of this KDC */\n        krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1);\n    char **capath = NULL;\n    size_t num_capath = 0;\n\n    hdb_entry_ex *krbtgt_out = NULL;\n\n    METHOD_DATA enc_pa_data;\n\n    PrincipalName *s;\n    Realm r;\n    EncTicketPart adtkt;\n    char opt_str[128];\n    int signedpath = 0;\n\n    Key *tkey_check;\n    Key *tkey_sign;\n    int flags = HDB_F_FOR_TGS_REQ;\n\n    memset(&sessionkey, 0, sizeof(sessionkey));\n    memset(&adtkt, 0, sizeof(adtkt));\n    krb5_data_zero(&rspac);\n    memset(&enc_pa_data, 0, sizeof(enc_pa_data));\n\n    s = b->sname;\n    r = b->realm;\n\n    /*\n     * The canonicalize KDC option is passed as a hint to the backend, but\n     * can typically be ignored. Per RFC 6806, names are not canonicalized\n     * in response to a TGS request (although we make an exception, see\n     * force-canonicalize below).\n     */\n    if (b->kdc_options.canonicalize)\n\tflags |= HDB_F_CANON;\n\n    if(b->kdc_options.enc_tkt_in_skey){\n\tTicket *t;\n\thdb_entry_ex *uu;\n\tkrb5_principal p;\n\tKey *uukey;\n\tkrb5uint32 second_kvno = 0;\n\tkrb5uint32 *kvno_ptr = NULL;\n\n\tif(b->additional_tickets == NULL ||\n\t   b->additional_tickets->len == 0){\n\t    ret = KRB5KDC_ERR_BADOPTION; /* ? */\n\t    kdc_log(context, config, 4,\n\t\t    \"No second ticket present in user-to-user request\");\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"No second ticket present in user-to-user request\");\n\t    goto out;\n\t}\n\tt = &b->additional_tickets->val[0];\n\tif(!get_krbtgt_realm(&t->sname)){\n\t    kdc_log(context, config, 4,\n\t\t    \"Additional ticket is not a ticket-granting ticket\");\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Additional ticket is not a ticket-granting ticket\");\n\t    ret = KRB5KDC_ERR_POLICY;\n\t    goto out;\n\t}\n\t_krb5_principalname2krb5_principal(context, &p, t->sname, t->realm);\n\tret = krb5_unparse_name(context, p, &tpn);\n\tif (ret)\n\t\tgoto out;\n\tif(t->enc_part.kvno){\n\t    second_kvno = *t->enc_part.kvno;\n\t    kvno_ptr = &second_kvno;\n\t}\n\tret = _kdc_db_fetch(context, config, p,\n\t\t\t    HDB_F_GET_KRBTGT, kvno_ptr,\n\t\t\t    NULL, &uu);\n\tkrb5_free_principal(context, p);\n\tif(ret){\n\t    if (ret == HDB_ERR_NOENTRY)\n\t\tret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"User-to-user service principal (TGS) unknown\");\n\t    goto out;\n\t}\n\tret = hdb_enctype2key(context, &uu->entry, NULL,\n\t\t\t      t->enc_part.etype, &uukey);\n\tif(ret){\n\t    _kdc_free_ent(context, uu);\n\t    ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"User-to-user enctype not supported\");\n\t    goto out;\n\t}\n\tret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0);\n\t_kdc_free_ent(context, uu);\n\tif(ret) {\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"User-to-user TGT decrypt failure\");\n\t    goto out;\n        }\n\n\tret = verify_flags(context, config, &adtkt, tpn);\n\tif (ret) {\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"User-to-user TGT expired or invalid\");\n\t    goto out;\n        }\n\n\ts = &adtkt.cname;\n\tr = adtkt.crealm;\n    }\n\n    _krb5_principalname2krb5_principal(context, &sp, *s, r);\n    ret = krb5_unparse_name(context, sp, &priv->sname);\n    if (ret)\n\tgoto out;\n    spn = priv->sname;\n    _krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm);\n    ret = krb5_unparse_name(context, cp, &priv->cname);\n    if (ret)\n\tgoto out;\n    cpn = priv->cname;\n    unparse_flags (KDCOptions2int(b->kdc_options),\n\t\t   asn1_KDCOptions_units(),\n\t\t   opt_str, sizeof(opt_str));\n    if(*opt_str)\n\tkdc_log(context, config, 4,\n\t\t\"TGS-REQ %s from %s for %s [%s]\",\n\t\tcpn, from, spn, opt_str);\n    else\n\tkdc_log(context, config, 4,\n\t\t\"TGS-REQ %s from %s for %s\", cpn, from, spn);\n\n    /*\n     * Fetch server\n     */\n\nserver_lookup:\n    ret = _kdc_db_fetch(context, config, sp,\n                        HDB_F_GET_SERVER | HDB_F_DELAY_NEW_KEYS | flags,\n\t\t\tNULL, NULL, &server);\n    priv->server = server;\n    if (ret == HDB_ERR_NOT_FOUND_HERE) {\n\tkdc_log(context, config, 5, \"target %s does not have secrets at this KDC, need to proxy\", spn);\n        _kdc_audit_addreason((kdc_request_t)priv, \"Target not found here\");\n\tgoto out;\n    } else if (ret == HDB_ERR_WRONG_REALM) {\n        free(ref_realm);\n\tref_realm = strdup(server->entry.principal->realm);\n\tif (ref_realm == NULL) {\n            ret = krb5_enomem(context);\n\t    goto out;\n\t}\n\n\tkdc_log(context, config, 4,\n\t\t\"Returning a referral to realm %s for \"\n\t\t\"server %s.\",\n\t\tref_realm, spn);\n\tkrb5_free_principal(context, sp);\n\tsp = NULL;\n\tret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,\n\t\t\t\t  ref_realm, NULL);\n\tif (ret)\n\t    goto out;\n\tfree(priv->sname);\n        priv->sname = NULL;\n\tret = krb5_unparse_name(context, sp, &priv->sname);\n\tif (ret)\n\t    goto out;\n\tspn = priv->sname;\n\n\tgoto server_lookup;\n    } else if (ret) {\n\tconst char *new_rlm, *msg;\n\tRealm req_rlm;\n\tkrb5_realm *realms;\n\n\tif ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) {\n            if (capath == NULL) {\n                /* With referalls, hierarchical capaths are always enabled */\n                ret2 = _krb5_find_capath(context, tgt->crealm, our_realm,\n                                         req_rlm, TRUE, &capath, &num_capath);\n                if (ret2) {\n                    ret = ret2;\n                    _kdc_audit_addreason((kdc_request_t)priv,\n                                         \"No trusted path from client realm to ours\");\n                    goto out;\n                }\n            }\n            new_rlm = num_capath > 0 ? capath[--num_capath] : NULL;\n            if (new_rlm) {\n                kdc_log(context, config, 5, \"krbtgt from %s via %s for \"\n                        \"realm %s not found, trying %s\", tgt->crealm,\n                        our_realm, req_rlm, new_rlm);\n\n                free(ref_realm);\n                ref_realm = strdup(new_rlm);\n                if (ref_realm == NULL) {\n                    ret = krb5_enomem(context);\n                    goto out;\n                }\n\n                krb5_free_principal(context, sp);\n                sp = NULL;\n                krb5_make_principal(context, &sp, r,\n                                    KRB5_TGS_NAME, ref_realm, NULL);\n                free(priv->sname);\n                priv->sname = NULL;\n                ret = krb5_unparse_name(context, sp, &priv->sname);\n                if (ret)\n                    goto out;\n                spn = priv->sname;\n                goto server_lookup;\n            }\n\t} else if (need_referral(context, config, &b->kdc_options, sp, &realms)) {\n\t    if (strcmp(realms[0], sp->realm) != 0) {\n\t\tkdc_log(context, config, 4,\n\t\t\t\"Returning a referral to realm %s for \"\n\t\t\t\"server %s that was not found\",\n\t\t\trealms[0], spn);\n\t\tkrb5_free_principal(context, sp);\n                sp = NULL;\n\t\tkrb5_make_principal(context, &sp, r, KRB5_TGS_NAME,\n\t\t\t\t    realms[0], NULL);\n\t\tfree(priv->sname);\n                priv->sname = NULL;\n\t\tret = krb5_unparse_name(context, sp, &priv->sname);\n\t\tif (ret) {\n\t\t    krb5_free_host_realm(context, realms);\n\t\t    goto out;\n\t\t}\n\t\tspn = priv->sname;\n\n                free(ref_realm);\n\t\tref_realm = strdup(realms[0]);\n\n\t\tkrb5_free_host_realm(context, realms);\n\t\tgoto server_lookup;\n\t    }\n\t    krb5_free_host_realm(context, realms);\n\t}\n\tmsg = krb5_get_error_message(context, ret);\n\tkdc_log(context, config, 3,\n\t\t\"Server not found in database: %s: %s\", spn, msg);\n\tkrb5_free_error_message(context, msg);\n\tif (ret == HDB_ERR_NOENTRY)\n\t    ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n        _kdc_audit_addreason((kdc_request_t)priv,\n                             \"Service principal unknown\");\n\tgoto out;\n    }\n\n    /*\n     * RFC 6806 notes that names MUST NOT be changed in the response to\n     * a TGS request. Hence we ignore the setting of the canonicalize\n     * KDC option. However, for legacy interoperability we do allow the\n     * backend to override this by setting the force-canonicalize HDB\n     * flag in the server entry.\n     */\n    if (server->entry.flags.force_canonicalize)\n\trsp = server->entry.principal;\n    else\n\trsp = sp;\n\n    /*\n     * Select enctype, return key and kvno.\n     */\n\n    {\n\tkrb5_enctype etype;\n\n\tif(b->kdc_options.enc_tkt_in_skey) {\n\t    size_t i;\n\t    ekey = &adtkt.key;\n\t    for(i = 0; i < b->etype.len; i++)\n\t\tif (b->etype.val[i] == adtkt.key.keytype)\n\t\t    break;\n\t    if(i == b->etype.len) {\n\t\tkdc_log(context, config, 4,\n\t\t\t\"Addition ticket have not matching etypes\");\n\t\tkrb5_clear_error_message(context);\n\t\tret = KRB5KDC_ERR_ETYPE_NOSUPP;\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"No matching enctypes for 2nd ticket\");\n\t\tgoto out;\n\t    }\n\t    etype = b->etype.val[i];\n\t    kvno = 0;\n\t} else {\n\t    Key *skey;\n\n\t    ret = _kdc_find_etype(priv, krb5_principal_is_krbtgt(context, sp)\n\t\t\t\t\t\t\t     ? KFE_IS_TGS : 0,\n\t\t\t\t  b->etype.val, b->etype.len, &etype, NULL,\n\t\t\t\t  NULL);\n\t    if(ret) {\n\t\tkdc_log(context, config, 4,\n\t\t\t\"Server (%s) has no support for etypes\", spn);\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"Enctype not supported\");\n\t\tgoto out;\n\t    }\n\t    ret = _kdc_get_preferred_key(context, config, server, spn,\n\t\t\t\t\t NULL, &skey);\n\t    if(ret) {\n\t\tkdc_log(context, config, 4,\n\t\t\t\"Server (%s) has no supported etypes\", spn);\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"Enctype not supported\");\n\t\tgoto out;\n\t    }\n\t    ekey = &skey->key;\n\t    kvno = server->entry.kvno;\n\t}\n\n\tret = krb5_generate_random_keyblock(context, etype, &sessionkey);\n\tif (ret)\n\t    goto out;\n    }\n\n    /*\n     * Check that service is in the same realm as the krbtgt. If it's\n     * not the same, it's someone that is using a uni-directional trust\n     * backward.\n     */\n\n    /*\n     * Validate authorization data\n     */\n\n    ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */\n\t\t\t  krbtgt_etype, &tkey_check);\n    if(ret) {\n\tkdc_log(context, config, 4,\n\t\t    \"Failed to find key for krbtgt PAC check\");\n        _kdc_audit_addreason((kdc_request_t)priv,\n                             \"No key for krbtgt PAC check\");\n\tgoto out;\n    }\n\n    /* \n     * Now refetch the primary krbtgt, and get the current kvno (the\n     * sign check may have been on an old kvno, and the server may\n     * have been an incoming trust)\n     */\n    \n    ret = krb5_make_principal(context,\n                              &krbtgt_out_principal,\n                              our_realm,\n                              KRB5_TGS_NAME,\n                              our_realm,\n                              NULL);\n    if (ret) {\n        kdc_log(context, config, 4,\n                \"Failed to make krbtgt principal name object for \"\n                \"authz-data signatures\");\n        goto out;\n    }\n    ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n);\n    if (ret) {\n        kdc_log(context, config, 4,\n                \"Failed to make krbtgt principal name object for \"\n                \"authz-data signatures\");\n        goto out;\n    }\n\n    ret = _kdc_db_fetch(context, config, krbtgt_out_principal,\n\t\t\tHDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out);\n    if (ret) {\n\tchar *ktpn = NULL;\n\tret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn);\n\tkdc_log(context, config, 4,\n\t\t\"No such principal %s (needed for authz-data signature keys) \"\n\t\t\"while processing TGS-REQ for service %s with krbtg %s\",\n\t\tkrbtgt_out_n, spn, (ret == 0) ? ktpn : \"\");\n\tfree(ktpn);\n\tret = KRB5KRB_AP_ERR_NOT_US;\n\tgoto out;\n    }\n\n    /* \n     * The first realm is the realm of the service, the second is\n     * krbtgt//@REALM component of the krbtgt DN the request was\n     * encrypted to.  The redirection via the krbtgt_out entry allows\n     * the DB to possibly correct the case of the realm (Samba4 does\n     * this) before the strcmp() \n     */\n    if (strcmp(krb5_principal_get_realm(context, server->entry.principal),\n\t       krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) {\n\tchar *ktpn;\n\tret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn);\n\tkdc_log(context, config, 4,\n\t\t\"Request with wrong krbtgt: %s\",\n\t\t(ret == 0) ? ktpn : \"\");\n\tif(ret == 0)\n\t    free(ktpn);\n\tret = KRB5KRB_AP_ERR_NOT_US;\n        _kdc_audit_addreason((kdc_request_t)priv, \"Request with wrong TGT\");\n\tgoto out;\n    }\n\n    ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n,\n\t\t\t\t NULL, &tkey_sign);\n    if (ret) {\n\tkdc_log(context, config, 4,\n\t\t    \"Failed to find key for krbtgt PAC signature\");\n        _kdc_audit_addreason((kdc_request_t)priv,\n                             \"Failed to find key for krbtgt PAC signature\");\n\tgoto out;\n    }\n    ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL,\n\t\t\t  tkey_sign->key.keytype, &tkey_sign);\n    if(ret) {\n\tkdc_log(context, config, 4,\n\t\t    \"Failed to find key for krbtgt PAC signature\");\n        _kdc_audit_addreason((kdc_request_t)priv,\n                             \"Failed to find key for krbtgt PAC signature\");\n\tgoto out;\n    }\n\n    {\n        krb5_data verified_cas;\n\n        /*\n         * If the client doesn't exist in the HDB but has a TGT and it's\n         * obtained with PKINIT then we assume it's a synthetic client -- that\n         * is, a client whose name was vouched for by a CA using a PKINIT SAN,\n         * but which doesn't exist in the HDB proper.  We'll allow such a\n         * client to do TGT requests even though normally we'd reject all\n         * clients that don't exist in the HDB.\n         */\n        ret = krb5_ticket_get_authorization_data_type(context, ticket,\n                                                      KRB5_AUTHDATA_INITIAL_VERIFIED_CAS,\n                                                      &verified_cas);\n        if (ret == 0) {\n            krb5_data_free(&verified_cas);\n            flags |= HDB_F_SYNTHETIC_OK;\n        }\n    }\n    ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags,\n\t\t\tNULL, &clientdb, &client);\n    flags &= ~HDB_F_SYNTHETIC_OK;\n    priv->client = client;\n    if(ret == HDB_ERR_NOT_FOUND_HERE) {\n\t/* This is OK, we are just trying to find out if they have\n\t * been disabled or deleted in the meantime, missing secrets\n\t * is OK */\n    } else if(ret){\n\tconst char *krbtgt_realm, *msg;\n\n\t/*\n\t * If the client belongs to the same realm as our krbtgt, it\n\t * should exist in the local database.\n\t *\n\t */\n\n\tkrbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal);\n\n\tif(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) {\n\t    if (ret == HDB_ERR_NOENTRY)\n\t\tret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;\n\t    kdc_log(context, config, 4, \"Client no longer in database: %s\",\n\t\t    cpn);\n            _kdc_audit_addreason((kdc_request_t)priv, \"Client no longer in HDB\");\n\t    goto out;\n\t}\n\n\tmsg = krb5_get_error_message(context, ret);\n\tkdc_log(context, config, 4, \"Client not found in database: %s\", msg);\n        _kdc_audit_addreason((kdc_request_t)priv, \"Client does not exist\");\n\tkrb5_free_error_message(context, msg);\n    } else if (ret == 0 &&\n               (client->entry.flags.invalid || !client->entry.flags.client)) {\n        _kdc_audit_addreason((kdc_request_t)priv, \"Client has invalid bit set\");\n        kdc_log(context, config, 4, \"Client has invalid bit set\");\n        ret = KRB5KDC_ERR_POLICY;\n        goto out;\n    }\n\n    ret = check_PAC(context, config, cp, NULL,\n\t\t    client, server, krbtgt,\n\t\t    &tkey_check->key,\n\t\t    ekey, &tkey_sign->key,\n\t\t    tgt, &rspac, &signedpath);\n    if (ret) {\n\tconst char *msg = krb5_get_error_message(context, ret);\n        _kdc_audit_addreason((kdc_request_t)priv, \"PAC check failed\");\n\tkdc_log(context, config, 4,\n\t\t\"Verify PAC failed for %s (%s) from %s with %s\",\n\t\tspn, cpn, from, msg);\n\tkrb5_free_error_message(context, msg);\n\tgoto out;\n    }\n\n    /* also check the krbtgt for signature */\n    ret = check_KRB5SignedPath(context,\n\t\t\t       config,\n\t\t\t       krbtgt,\n\t\t\t       cp,\n\t\t\t       tgt,\n\t\t\t       &spp,\n\t\t\t       &signedpath);\n    if (ret) {\n\tconst char *msg = krb5_get_error_message(context, ret);\n        _kdc_audit_addreason((kdc_request_t)priv, \"KRB5SignedPath check failed\");\n\tkdc_log(context, config, 4,\n\t\t\"KRB5SignedPath check failed for %s (%s) from %s with %s\",\n\t\tspn, cpn, from, msg);\n\tkrb5_free_error_message(context, msg);\n\tgoto out;\n    }\n\n    /*\n     * Process request\n     */\n\n    /* by default the tgt principal matches the client principal */\n    tp = cp;\n    tpn = cpn;\n\n    if (client) {\n\tconst PA_DATA *sdata;\n\tint i = 0;\n\n\tsdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER);\n\tif (sdata) {\n\t    struct astgs_request_desc imp_req;\n\t    krb5_crypto crypto;\n\t    krb5_data datack;\n\t    PA_S4U2Self self;\n\t    const char *str;\n\n\t    ret = decode_PA_S4U2Self(sdata->padata_value.data,\n\t\t\t\t     sdata->padata_value.length,\n\t\t\t\t     &self, NULL);\n\t    if (ret) {\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"Failed to decode PA-S4U2Self\");\n\t\tkdc_log(context, config, 4, \"Failed to decode PA-S4U2Self\");\n\t\tgoto out;\n\t    }\n\n\t    if (!krb5_checksum_is_keyed(context, self.cksum.cksumtype)) {\n\t\tfree_PA_S4U2Self(&self);\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"PA-S4U2Self with unkeyed checksum\");\n\t\tkdc_log(context, config, 4, \"Reject PA-S4U2Self with unkeyed checksum\");\n\t\tret = KRB5KRB_AP_ERR_INAPP_CKSUM;\n\t\tgoto out;\n\t    }\n\n\t    ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack);\n\t    if (ret)\n\t\tgoto out;\n\n\t    ret = krb5_crypto_init(context, &tgt->key, 0, &crypto);\n\t    if (ret) {\n\t\tconst char *msg = krb5_get_error_message(context, ret);\n\t\tfree_PA_S4U2Self(&self);\n\t\tkrb5_data_free(&datack);\n\t\tkdc_log(context, config, 4, \"krb5_crypto_init failed: %s\", msg);\n\t\tkrb5_free_error_message(context, msg);\n\t\tgoto out;\n\t    }\n\n\t    /* Allow HMAC_MD5 checksum with any key type */\n\t    if (self.cksum.cksumtype == CKSUMTYPE_HMAC_MD5) {\n\t\tstruct krb5_crypto_iov iov;\n\t\tunsigned char csdata[16];\n\t\tChecksum cs;\n\n\t\tcs.checksum.length = sizeof(csdata);\n\t\tcs.checksum.data = &csdata;\n\n\t\tiov.data.data = datack.data;\n\t\tiov.data.length = datack.length;\n\t\tiov.flags = KRB5_CRYPTO_TYPE_DATA;\n\n\t\tret = _krb5_HMAC_MD5_checksum(context, NULL, &crypto->key,\n\t\t\t\t\t      KRB5_KU_OTHER_CKSUM, &iov, 1,\n\t\t\t\t\t      &cs);\n\t\tif (ret == 0 &&\n\t\t    krb5_data_ct_cmp(&cs.checksum, &self.cksum.checksum) != 0)\n\t\t    ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;\n\t    }\n\t    else {\n\t\tret = krb5_verify_checksum(context,\n\t\t\t\t\t   crypto,\n\t\t\t\t\t   KRB5_KU_OTHER_CKSUM,\n\t\t\t\t\t   datack.data,\n\t\t\t\t\t   datack.length,\n\t\t\t\t\t   &self.cksum);\n\t    }\n\t    krb5_data_free(&datack);\n\t    krb5_crypto_destroy(context, crypto);\n\t    if (ret) {\n\t\tconst char *msg = krb5_get_error_message(context, ret);\n\t\tfree_PA_S4U2Self(&self);\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"S4U2Self checksum failed\");\n\t\tkdc_log(context, config, 4,\n\t\t\t\"krb5_verify_checksum failed for S4U2Self: %s\", msg);\n\t\tkrb5_free_error_message(context, msg);\n\t\tgoto out;\n\t    }\n\n\t    ret = _krb5_principalname2krb5_principal(context,\n\t\t\t\t\t\t     &tp,\n\t\t\t\t\t\t     self.name,\n\t\t\t\t\t\t     self.realm);\n\t    free_PA_S4U2Self(&self);\n\t    if (ret)\n\t\tgoto out;\n\n\t    ret = krb5_unparse_name(context, tp, &tpn);\n\t    if (ret)\n\t\tgoto out;\n\n            /*\n             * Note no HDB_F_SYNTHETIC_OK -- impersonating non-existent clients\n             * is probably not desirable!\n             */\n\t    ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags,\n\t\t\t\tNULL, &s4u2self_impersonated_clientdb,\n\t\t\t\t&s4u2self_impersonated_client);\n\t    if (ret) {\n\t\tconst char *msg;\n\n\t\t/*\n\t\t * If the client belongs to the same realm as our krbtgt, it\n\t\t * should exist in the local database.\n\t\t *\n\t\t */\n\n\t\tif (ret == HDB_ERR_NOENTRY)\n\t\t    ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;\n\t\tmsg = krb5_get_error_message(context, ret);\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"S4U2Self principal to impersonate not found\");\n\t\tkdc_log(context, config, 2,\n\t\t\t\"S4U2Self principal to impersonate %s not found in database: %s\",\n\t\t\ttpn, msg);\n\t\tkrb5_free_error_message(context, msg);\n\t\tgoto out;\n\t    }\n\n\t    /* Ignore require_pwchange and pw_end attributes (as Windows does),\n\t     * since S4U2Self is not password authentication. */\n\t    s4u2self_impersonated_client->entry.flags.require_pwchange = FALSE;\n\t    free(s4u2self_impersonated_client->entry.pw_end);\n\t    s4u2self_impersonated_client->entry.pw_end = NULL;\n\n\t    imp_req = *priv;\n\t    imp_req.client = s4u2self_impersonated_client;\n\t    imp_req.client_princ = tp;\n\n\t    ret = kdc_check_flags(&imp_req, FALSE);\n\t    if (ret)\n\t\tgoto out; /* kdc_check_flags() calls _kdc_audit_addreason() */\n\n\t    /* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */\n\t    if(rspac.data) {\n\t\tkrb5_pac p = NULL;\n\t\tkrb5_data_free(&rspac);\n\t\tret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p);\n\t\tif (ret) {\n                    _kdc_audit_addreason((kdc_request_t)priv,\n                                         \"KRB5SignedPath missing\");\n\t\t    kdc_log(context, config, 4, \"PAC generation failed for -- %s\",\n\t\t\t    tpn);\n\t\t    goto out;\n\t\t}\n\t\tif (p != NULL) {\n\t\t    ret = _krb5_pac_sign(context, p, ticket->ticket.authtime,\n\t\t\t\t\t s4u2self_impersonated_client->entry.principal,\n\t\t\t\t\t ekey, &tkey_sign->key,\n\t\t\t\t\t &rspac);\n\t\t    krb5_pac_free(context, p);\n\t\t    if (ret) {\n\t\t\tkdc_log(context, config, 4, \"PAC signing failed for -- %s\",\n\t\t\t\ttpn);\n\t\t\tgoto out;\n\t\t    }\n\t\t}\n\t    }\n\n\t    /*\n\t     * Check that service doing the impersonating is\n\t     * requesting a ticket to it-self.\n\t     */\n\t    ret = check_s4u2self(context, config, clientdb, client, sp);\n\t    if (ret) {\n\t\tkdc_log(context, config, 4, \"S4U2Self: %s is not allowed \"\n\t\t\t\"to impersonate to service \"\n\t\t\t\"(tried for user %s to service %s)\",\n\t\t\tcpn, tpn, spn);\n\t\tgoto out;\n\t    }\n\n\t    /*\n\t     * If the service isn't trusted for authentication to\n\t     * delegation or if the impersonate client is disallowed\n\t     * forwardable, remove the forwardable flag.\n\t     */\n\n\t    if (client->entry.flags.trusted_for_delegation &&\n\t\ts4u2self_impersonated_client->entry.flags.forwardable) {\n\t\tstr = \"[forwardable]\";\n\t    } else {\n\t\tb->kdc_options.forwardable = 0;\n\t\tstr = \"\";\n\t    }\n\t    kdc_log(context, config, 4, \"s4u2self %s impersonating %s to \"\n\t\t    \"service %s %s\", cpn, tpn, spn, str);\n\t}\n    }\n\n    /*\n     * Constrained delegation\n     */\n\n    if (client != NULL\n\t&& b->additional_tickets != NULL\n\t&& b->additional_tickets->len != 0\n\t&& b->kdc_options.cname_in_addl_tkt\n\t&& b->kdc_options.enc_tkt_in_skey == 0)\n    {\n\tint ad_signedpath = 0;\n\tKey *clientkey;\n\tTicket *t;\n\n\t/*\n\t * Require that the KDC have issued the service's krbtgt (not\n\t * self-issued ticket with kimpersonate(1).\n\t */\n\tif (!signedpath) {\n\t    ret = KRB5KDC_ERR_BADOPTION;\n            _kdc_audit_addreason((kdc_request_t)priv, \"KRB5SignedPath missing\");\n\t    kdc_log(context, config, 4,\n\t\t    \"Constrained delegation done on service ticket %s/%s\",\n\t\t    cpn, spn);\n\t    goto out;\n\t}\n\n\tt = &b->additional_tickets->val[0];\n\n\tret = hdb_enctype2key(context, &client->entry,\n\t\t\t      hdb_kvno2keys(context, &client->entry,\n\t\t\t\t\t    t->enc_part.kvno ? * t->enc_part.kvno : 0),\n\t\t\t      t->enc_part.etype, &clientkey);\n\tif(ret){\n\t    ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */\n\t    goto out;\n\t}\n\n\tret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0);\n\tif (ret) {\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Failed to decrypt constrained delegation ticket\");\n\t    kdc_log(context, config, 4,\n\t\t    \"failed to decrypt ticket for \"\n\t\t    \"constrained delegation from %s to %s \", cpn, spn);\n\t    goto out;\n\t}\n\n\tret = _krb5_principalname2krb5_principal(context,\n\t\t\t\t\t\t &tp,\n\t\t\t\t\t\t adtkt.cname,\n\t\t\t\t\t\t adtkt.crealm);\n\tif (ret)\n\t    goto out;\n\n\tret = krb5_unparse_name(context, tp, &tpn);\n\tif (ret)\n\t    goto out;\n\n        _kdc_audit_addkv((kdc_request_t)priv, 0, \"impersonatee\", \"%s\", tpn);\n\n\tret = _krb5_principalname2krb5_principal(context,\n\t\t\t\t\t\t &dp,\n\t\t\t\t\t\t t->sname,\n\t\t\t\t\t\t t->realm);\n\tif (ret)\n\t    goto out;\n\n\tret = krb5_unparse_name(context, dp, &dpn);\n\tif (ret)\n\t    goto out;\n\n\t/* check that ticket is valid */\n\tif (adtkt.flags.forwardable == 0) {\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Missing forwardable flag on ticket for constrained delegation\");\n\t    kdc_log(context, config, 4,\n\t\t    \"Missing forwardable flag on ticket for \"\n\t\t    \"constrained delegation from %s (%s) as %s to %s \",\n\t\t    cpn, dpn, tpn, spn);\n\t    ret = KRB5KDC_ERR_BADOPTION;\n\t    goto out;\n\t}\n\n\tret = check_constrained_delegation(context, config, clientdb,\n\t\t\t\t\t   client, server, sp);\n\tif (ret) {\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Constrained delegation not allowed\");\n\t    kdc_log(context, config, 4,\n\t\t    \"constrained delegation from %s (%s) as %s to %s not allowed\",\n\t\t    cpn, dpn, tpn, spn);\n\t    goto out;\n\t}\n\n\tret = verify_flags(context, config, &adtkt, tpn);\n\tif (ret) {\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Constrained delegation ticket expired or invalid\");\n\t    goto out;\n\t}\n\n\tkrb5_data_free(&rspac);\n\n\t/*\n\t * generate the PAC for the user.\n\t *\n\t * TODO: pass in t->sname and t->realm and build\n\t * a S4U_DELEGATION_INFO blob to the PAC.\n\t */\n\tret = check_PAC(context, config, tp, dp,\n\t\t\tclient, server, krbtgt,\n\t\t\t&clientkey->key,\n\t\t\tekey, &tkey_sign->key,\n\t\t\t&adtkt, &rspac, &ad_signedpath);\n\tif (ret) {\n\t    const char *msg = krb5_get_error_message(context, ret);\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Constrained delegation ticket PAC check failed\");\n\t    kdc_log(context, config, 4,\n\t\t    \"Verify delegated PAC failed to %s for client\"\n\t\t    \"%s (%s) as %s from %s with %s\",\n\t\t    spn, cpn, dpn, tpn, from, msg);\n\t    krb5_free_error_message(context, msg);\n\t    goto out;\n\t}\n\n\t/*\n\t * Check that the KDC issued the user's ticket.\n\t */\n\tret = check_KRB5SignedPath(context,\n\t\t\t\t   config,\n\t\t\t\t   krbtgt,\n\t\t\t\t   cp,\n\t\t\t\t   &adtkt,\n\t\t\t\t   NULL,\n\t\t\t\t   &ad_signedpath);\n\tif (ret) {\n\t    const char *msg = krb5_get_error_message(context, ret);\n\t    kdc_log(context, config, 4,\n\t\t    \"KRB5SignedPath check from service %s failed \"\n\t\t    \"for delegation to %s for client %s (%s)\"\n\t\t    \"from %s failed with %s\",\n\t\t    spn, tpn, dpn, cpn, from, msg);\n\t    krb5_free_error_message(context, msg);\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"KRB5SignedPath check failed\");\n\t    goto out;\n\t}\n\n\tif (!ad_signedpath) {\n\t    ret = KRB5KDC_ERR_BADOPTION;\n\t    kdc_log(context, config, 4,\n\t\t    \"Ticket not signed with PAC nor SignedPath service %s failed \"\n\t\t    \"for delegation to %s for client %s (%s)\"\n\t\t    \"from %s\",\n\t\t    spn, tpn, dpn, cpn, from);\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Constrained delegation ticket not signed\");\n\t    goto out;\n\t}\n\n\tkdc_log(context, config, 4, \"constrained delegation for %s \"\n\t\t\"from %s (%s) to %s\", tpn, cpn, dpn, spn);\n    }\n\n    /*\n     * Check flags\n     */\n\n    ret = kdc_check_flags(priv, FALSE);\n    if(ret)\n\tgoto out;\n\n    if((b->kdc_options.validate || b->kdc_options.renew) &&\n       !krb5_principal_compare(context,\n\t\t\t       krbtgt->entry.principal,\n\t\t\t       server->entry.principal)){\n        _kdc_audit_addreason((kdc_request_t)priv, \"Inconsistent request\");\n\tkdc_log(context, config, 4, \"Inconsistent request.\");\n\tret = KRB5KDC_ERR_SERVER_NOMATCH;\n\tgoto out;\n    }\n\n    /* check for valid set of addresses */\n    if (!_kdc_check_addresses(priv, tgt->caddr, from_addr)) {\n        if (config->check_ticket_addresses) {\n            ret = KRB5KRB_AP_ERR_BADADDR;\n            _kdc_audit_addkv((kdc_request_t)priv, 0, \"wrongaddr\", \"yes\");\n            kdc_log(context, config, 4, \"Request from wrong address\");\n            _kdc_audit_addreason((kdc_request_t)priv, \"Request from wrong address\");\n            goto out;\n        } else if (config->warn_ticket_addresses) {\n            _kdc_audit_addkv((kdc_request_t)priv, 0, \"wrongaddr\", \"yes\");\n        }\n    }\n\n    /* check local and per-principal anonymous ticket issuance policy */\n    if (is_anon_tgs_request_p(b, tgt)) {\n\tret = _kdc_check_anon_policy(priv);\n\tif (ret)\n\t    goto out;\n    }\n\n    /*\n     * If this is an referral, add server referral data to the\n     * auth_data reply .\n     */\n    if (ref_realm) {\n\tPA_DATA pa;\n\tkrb5_crypto crypto;\n\n\tkdc_log(context, config, 3,\n\t\t\"Adding server referral to %s\", ref_realm);\n\n\tret = krb5_crypto_init(context, &sessionkey, 0, &crypto);\n\tif (ret)\n\t    goto out;\n\n\tret = build_server_referral(context, config, crypto, ref_realm,\n\t\t\t\t    NULL, s, &pa.padata_value);\n\tkrb5_crypto_destroy(context, crypto);\n\tif (ret) {\n            _kdc_audit_addreason((kdc_request_t)priv, \"Referral build failed\");\n\t    kdc_log(context, config, 4,\n\t\t    \"Failed building server referral\");\n\t    goto out;\n\t}\n\tpa.padata_type = KRB5_PADATA_SERVER_REFERRAL;\n\n\tret = add_METHOD_DATA(&enc_pa_data, &pa);\n\tkrb5_data_free(&pa.padata_value);\n\tif (ret) {\n\t    kdc_log(context, config, 4,\n\t\t    \"Add server referral METHOD-DATA failed\");\n\t    goto out;\n\t}\n    }\n\n    /*\n     *\n     */\n\n    ret = tgs_make_reply(priv,\n\t\t\t tp,\n\t\t\t tgt,\n\t\t\t replykey,\n\t\t\t rk_is_subkey,\n\t\t\t ekey,\n\t\t\t &sessionkey,\n\t\t\t kvno,\n\t\t\t *auth_data,\n\t\t\t server,\n\t\t\t rsp,\n\t\t\t client,\n\t\t\t cp,\n                         tgt_realm,\n\t\t\t krbtgt_out,\n\t\t\t tkey_sign->key.keytype,\n\t\t\t spp,\n\t\t\t &rspac,\n\t\t\t &enc_pa_data);\n\nout:\n    if (tpn != cpn)\n\t    free(tpn);\n    free(dpn);\n    free(krbtgt_out_n);\n    _krb5_free_capath(context, capath);\n\n    krb5_data_free(&rspac);\n    krb5_free_keyblock_contents(context, &sessionkey);\n    if(krbtgt_out)\n\t_kdc_free_ent(context, krbtgt_out);\n    if(server)\n\t_kdc_free_ent(context, server);\n    if(client)\n\t_kdc_free_ent(context, client);\n    if(s4u2self_impersonated_client)\n\t_kdc_free_ent(context, s4u2self_impersonated_client);\n\n    if (tp && tp != cp)\n\tkrb5_free_principal(context, tp);\n    krb5_free_principal(context, cp);\n    krb5_free_principal(context, dp);\n    krb5_free_principal(context, sp);\n    krb5_free_principal(context, krbtgt_out_principal);\n    free(ref_realm);\n    free_METHOD_DATA(&enc_pa_data);\n\n    free_EncTicketPart(&adtkt);\n\n    return ret;\n}", "func_hash": 180711409541748394655723306760719102268, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2021-3671", "cve_desc": "A null pointer de-reference was found in the way samba kerberos server handled missing sname in TGS-REQ (Ticket Granting Server - Request). An authenticated user could use this flaw to crash the samba server.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3671"}
{"idx": 411926, "project": "heimdal", "commit_id": "04171147948d0a3636bc6374181926f0fb2ec83a", "project_url": "https://github.com/heimdal/heimdal", "commit_url": "https://github.com/heimdal/heimdal/commit/04171147948d0a3636bc6374181926f0fb2ec83a", "commit_message": "kdc: validate sname in TGS-REQ\n\nIn tgs_build_reply(), validate the server name in the TGS-REQ is present before\ndereferencing.", "target": 0, "func": "tgs_build_reply(astgs_request_t priv,\n\t\thdb_entry_ex *krbtgt,\n\t\tkrb5_enctype krbtgt_etype,\n\t\tconst krb5_keyblock *replykey,\n\t\tint rk_is_subkey,\n\t\tkrb5_ticket *ticket,\n\t\tconst char **e_text,\n\t\tAuthorizationData **auth_data,\n\t\tconst struct sockaddr *from_addr)\n{\n    krb5_context context = priv->context;\n    krb5_kdc_configuration *config = priv->config;\n    KDC_REQ *req = &priv->req;\n    KDC_REQ_BODY *b = &priv->req.req_body;\n    const char *from = priv->from;\n    krb5_error_code ret, ret2;\n    krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL;\n    krb5_principal krbtgt_out_principal = NULL;\n    char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL;\n    hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL;\n    HDB *clientdb, *s4u2self_impersonated_clientdb;\n    krb5_realm ref_realm = NULL;\n    EncTicketPart *tgt = &ticket->ticket;\n    krb5_principals spp = NULL;\n    const EncryptionKey *ekey;\n    krb5_keyblock sessionkey;\n    krb5_kvno kvno;\n    krb5_data rspac;\n    const char *tgt_realm = /* Realm of TGT issuer */\n        krb5_principal_get_realm(context, krbtgt->entry.principal);\n    const char *our_realm = /* Realm of this KDC */\n        krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1);\n    char **capath = NULL;\n    size_t num_capath = 0;\n\n    hdb_entry_ex *krbtgt_out = NULL;\n\n    METHOD_DATA enc_pa_data;\n\n    PrincipalName *s;\n    Realm r;\n    EncTicketPart adtkt;\n    char opt_str[128];\n    int signedpath = 0;\n\n    Key *tkey_check;\n    Key *tkey_sign;\n    int flags = HDB_F_FOR_TGS_REQ;\n\n    memset(&sessionkey, 0, sizeof(sessionkey));\n    memset(&adtkt, 0, sizeof(adtkt));\n    krb5_data_zero(&rspac);\n    memset(&enc_pa_data, 0, sizeof(enc_pa_data));\n\n    s = b->sname;\n    r = b->realm;\n\n    /*\n     * The canonicalize KDC option is passed as a hint to the backend, but\n     * can typically be ignored. Per RFC 6806, names are not canonicalized\n     * in response to a TGS request (although we make an exception, see\n     * force-canonicalize below).\n     */\n    if (b->kdc_options.canonicalize)\n\tflags |= HDB_F_CANON;\n\n    if(b->kdc_options.enc_tkt_in_skey){\n\tTicket *t;\n\thdb_entry_ex *uu;\n\tkrb5_principal p;\n\tKey *uukey;\n\tkrb5uint32 second_kvno = 0;\n\tkrb5uint32 *kvno_ptr = NULL;\n\n\tif(b->additional_tickets == NULL ||\n\t   b->additional_tickets->len == 0){\n\t    ret = KRB5KDC_ERR_BADOPTION; /* ? */\n\t    kdc_log(context, config, 4,\n\t\t    \"No second ticket present in user-to-user request\");\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"No second ticket present in user-to-user request\");\n\t    goto out;\n\t}\n\tt = &b->additional_tickets->val[0];\n\tif(!get_krbtgt_realm(&t->sname)){\n\t    kdc_log(context, config, 4,\n\t\t    \"Additional ticket is not a ticket-granting ticket\");\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Additional ticket is not a ticket-granting ticket\");\n\t    ret = KRB5KDC_ERR_POLICY;\n\t    goto out;\n\t}\n\t_krb5_principalname2krb5_principal(context, &p, t->sname, t->realm);\n\tret = krb5_unparse_name(context, p, &tpn);\n\tif (ret)\n\t\tgoto out;\n\tif(t->enc_part.kvno){\n\t    second_kvno = *t->enc_part.kvno;\n\t    kvno_ptr = &second_kvno;\n\t}\n\tret = _kdc_db_fetch(context, config, p,\n\t\t\t    HDB_F_GET_KRBTGT, kvno_ptr,\n\t\t\t    NULL, &uu);\n\tkrb5_free_principal(context, p);\n\tif(ret){\n\t    if (ret == HDB_ERR_NOENTRY)\n\t\tret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"User-to-user service principal (TGS) unknown\");\n\t    goto out;\n\t}\n\tret = hdb_enctype2key(context, &uu->entry, NULL,\n\t\t\t      t->enc_part.etype, &uukey);\n\tif(ret){\n\t    _kdc_free_ent(context, uu);\n\t    ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"User-to-user enctype not supported\");\n\t    goto out;\n\t}\n\tret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0);\n\t_kdc_free_ent(context, uu);\n\tif(ret) {\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"User-to-user TGT decrypt failure\");\n\t    goto out;\n        }\n\n\tret = verify_flags(context, config, &adtkt, tpn);\n\tif (ret) {\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"User-to-user TGT expired or invalid\");\n\t    goto out;\n        }\n\n\ts = &adtkt.cname;\n\tr = adtkt.crealm;\n    } else if (s == NULL) {\n\tret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n\t_kdc_set_e_text(r, \"No server in request\");\n\tgoto out;\n    }\n\n    _krb5_principalname2krb5_principal(context, &sp, *s, r);\n    ret = krb5_unparse_name(context, sp, &priv->sname);\n    if (ret)\n\tgoto out;\n    spn = priv->sname;\n    _krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm);\n    ret = krb5_unparse_name(context, cp, &priv->cname);\n    if (ret)\n\tgoto out;\n    cpn = priv->cname;\n    unparse_flags (KDCOptions2int(b->kdc_options),\n\t\t   asn1_KDCOptions_units(),\n\t\t   opt_str, sizeof(opt_str));\n    if(*opt_str)\n\tkdc_log(context, config, 4,\n\t\t\"TGS-REQ %s from %s for %s [%s]\",\n\t\tcpn, from, spn, opt_str);\n    else\n\tkdc_log(context, config, 4,\n\t\t\"TGS-REQ %s from %s for %s\", cpn, from, spn);\n\n    /*\n     * Fetch server\n     */\n\nserver_lookup:\n    ret = _kdc_db_fetch(context, config, sp,\n                        HDB_F_GET_SERVER | HDB_F_DELAY_NEW_KEYS | flags,\n\t\t\tNULL, NULL, &server);\n    priv->server = server;\n    if (ret == HDB_ERR_NOT_FOUND_HERE) {\n\tkdc_log(context, config, 5, \"target %s does not have secrets at this KDC, need to proxy\", spn);\n        _kdc_audit_addreason((kdc_request_t)priv, \"Target not found here\");\n\tgoto out;\n    } else if (ret == HDB_ERR_WRONG_REALM) {\n        free(ref_realm);\n\tref_realm = strdup(server->entry.principal->realm);\n\tif (ref_realm == NULL) {\n            ret = krb5_enomem(context);\n\t    goto out;\n\t}\n\n\tkdc_log(context, config, 4,\n\t\t\"Returning a referral to realm %s for \"\n\t\t\"server %s.\",\n\t\tref_realm, spn);\n\tkrb5_free_principal(context, sp);\n\tsp = NULL;\n\tret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,\n\t\t\t\t  ref_realm, NULL);\n\tif (ret)\n\t    goto out;\n\tfree(priv->sname);\n        priv->sname = NULL;\n\tret = krb5_unparse_name(context, sp, &priv->sname);\n\tif (ret)\n\t    goto out;\n\tspn = priv->sname;\n\n\tgoto server_lookup;\n    } else if (ret) {\n\tconst char *new_rlm, *msg;\n\tRealm req_rlm;\n\tkrb5_realm *realms;\n\n\tif ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) {\n            if (capath == NULL) {\n                /* With referalls, hierarchical capaths are always enabled */\n                ret2 = _krb5_find_capath(context, tgt->crealm, our_realm,\n                                         req_rlm, TRUE, &capath, &num_capath);\n                if (ret2) {\n                    ret = ret2;\n                    _kdc_audit_addreason((kdc_request_t)priv,\n                                         \"No trusted path from client realm to ours\");\n                    goto out;\n                }\n            }\n            new_rlm = num_capath > 0 ? capath[--num_capath] : NULL;\n            if (new_rlm) {\n                kdc_log(context, config, 5, \"krbtgt from %s via %s for \"\n                        \"realm %s not found, trying %s\", tgt->crealm,\n                        our_realm, req_rlm, new_rlm);\n\n                free(ref_realm);\n                ref_realm = strdup(new_rlm);\n                if (ref_realm == NULL) {\n                    ret = krb5_enomem(context);\n                    goto out;\n                }\n\n                krb5_free_principal(context, sp);\n                sp = NULL;\n                krb5_make_principal(context, &sp, r,\n                                    KRB5_TGS_NAME, ref_realm, NULL);\n                free(priv->sname);\n                priv->sname = NULL;\n                ret = krb5_unparse_name(context, sp, &priv->sname);\n                if (ret)\n                    goto out;\n                spn = priv->sname;\n                goto server_lookup;\n            }\n\t} else if (need_referral(context, config, &b->kdc_options, sp, &realms)) {\n\t    if (strcmp(realms[0], sp->realm) != 0) {\n\t\tkdc_log(context, config, 4,\n\t\t\t\"Returning a referral to realm %s for \"\n\t\t\t\"server %s that was not found\",\n\t\t\trealms[0], spn);\n\t\tkrb5_free_principal(context, sp);\n                sp = NULL;\n\t\tkrb5_make_principal(context, &sp, r, KRB5_TGS_NAME,\n\t\t\t\t    realms[0], NULL);\n\t\tfree(priv->sname);\n                priv->sname = NULL;\n\t\tret = krb5_unparse_name(context, sp, &priv->sname);\n\t\tif (ret) {\n\t\t    krb5_free_host_realm(context, realms);\n\t\t    goto out;\n\t\t}\n\t\tspn = priv->sname;\n\n                free(ref_realm);\n\t\tref_realm = strdup(realms[0]);\n\n\t\tkrb5_free_host_realm(context, realms);\n\t\tgoto server_lookup;\n\t    }\n\t    krb5_free_host_realm(context, realms);\n\t}\n\tmsg = krb5_get_error_message(context, ret);\n\tkdc_log(context, config, 3,\n\t\t\"Server not found in database: %s: %s\", spn, msg);\n\tkrb5_free_error_message(context, msg);\n\tif (ret == HDB_ERR_NOENTRY)\n\t    ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n        _kdc_audit_addreason((kdc_request_t)priv,\n                             \"Service principal unknown\");\n\tgoto out;\n    }\n\n    /*\n     * RFC 6806 notes that names MUST NOT be changed in the response to\n     * a TGS request. Hence we ignore the setting of the canonicalize\n     * KDC option. However, for legacy interoperability we do allow the\n     * backend to override this by setting the force-canonicalize HDB\n     * flag in the server entry.\n     */\n    if (server->entry.flags.force_canonicalize)\n\trsp = server->entry.principal;\n    else\n\trsp = sp;\n\n    /*\n     * Select enctype, return key and kvno.\n     */\n\n    {\n\tkrb5_enctype etype;\n\n\tif(b->kdc_options.enc_tkt_in_skey) {\n\t    size_t i;\n\t    ekey = &adtkt.key;\n\t    for(i = 0; i < b->etype.len; i++)\n\t\tif (b->etype.val[i] == adtkt.key.keytype)\n\t\t    break;\n\t    if(i == b->etype.len) {\n\t\tkdc_log(context, config, 4,\n\t\t\t\"Addition ticket have not matching etypes\");\n\t\tkrb5_clear_error_message(context);\n\t\tret = KRB5KDC_ERR_ETYPE_NOSUPP;\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"No matching enctypes for 2nd ticket\");\n\t\tgoto out;\n\t    }\n\t    etype = b->etype.val[i];\n\t    kvno = 0;\n\t} else {\n\t    Key *skey;\n\n\t    ret = _kdc_find_etype(priv, krb5_principal_is_krbtgt(context, sp)\n\t\t\t\t\t\t\t     ? KFE_IS_TGS : 0,\n\t\t\t\t  b->etype.val, b->etype.len, &etype, NULL,\n\t\t\t\t  NULL);\n\t    if(ret) {\n\t\tkdc_log(context, config, 4,\n\t\t\t\"Server (%s) has no support for etypes\", spn);\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"Enctype not supported\");\n\t\tgoto out;\n\t    }\n\t    ret = _kdc_get_preferred_key(context, config, server, spn,\n\t\t\t\t\t NULL, &skey);\n\t    if(ret) {\n\t\tkdc_log(context, config, 4,\n\t\t\t\"Server (%s) has no supported etypes\", spn);\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"Enctype not supported\");\n\t\tgoto out;\n\t    }\n\t    ekey = &skey->key;\n\t    kvno = server->entry.kvno;\n\t}\n\n\tret = krb5_generate_random_keyblock(context, etype, &sessionkey);\n\tif (ret)\n\t    goto out;\n    }\n\n    /*\n     * Check that service is in the same realm as the krbtgt. If it's\n     * not the same, it's someone that is using a uni-directional trust\n     * backward.\n     */\n\n    /*\n     * Validate authorization data\n     */\n\n    ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */\n\t\t\t  krbtgt_etype, &tkey_check);\n    if(ret) {\n\tkdc_log(context, config, 4,\n\t\t    \"Failed to find key for krbtgt PAC check\");\n        _kdc_audit_addreason((kdc_request_t)priv,\n                             \"No key for krbtgt PAC check\");\n\tgoto out;\n    }\n\n    /* \n     * Now refetch the primary krbtgt, and get the current kvno (the\n     * sign check may have been on an old kvno, and the server may\n     * have been an incoming trust)\n     */\n    \n    ret = krb5_make_principal(context,\n                              &krbtgt_out_principal,\n                              our_realm,\n                              KRB5_TGS_NAME,\n                              our_realm,\n                              NULL);\n    if (ret) {\n        kdc_log(context, config, 4,\n                \"Failed to make krbtgt principal name object for \"\n                \"authz-data signatures\");\n        goto out;\n    }\n    ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n);\n    if (ret) {\n        kdc_log(context, config, 4,\n                \"Failed to make krbtgt principal name object for \"\n                \"authz-data signatures\");\n        goto out;\n    }\n\n    ret = _kdc_db_fetch(context, config, krbtgt_out_principal,\n\t\t\tHDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out);\n    if (ret) {\n\tchar *ktpn = NULL;\n\tret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn);\n\tkdc_log(context, config, 4,\n\t\t\"No such principal %s (needed for authz-data signature keys) \"\n\t\t\"while processing TGS-REQ for service %s with krbtg %s\",\n\t\tkrbtgt_out_n, spn, (ret == 0) ? ktpn : \"\");\n\tfree(ktpn);\n\tret = KRB5KRB_AP_ERR_NOT_US;\n\tgoto out;\n    }\n\n    /* \n     * The first realm is the realm of the service, the second is\n     * krbtgt//@REALM component of the krbtgt DN the request was\n     * encrypted to.  The redirection via the krbtgt_out entry allows\n     * the DB to possibly correct the case of the realm (Samba4 does\n     * this) before the strcmp() \n     */\n    if (strcmp(krb5_principal_get_realm(context, server->entry.principal),\n\t       krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) {\n\tchar *ktpn;\n\tret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn);\n\tkdc_log(context, config, 4,\n\t\t\"Request with wrong krbtgt: %s\",\n\t\t(ret == 0) ? ktpn : \"\");\n\tif(ret == 0)\n\t    free(ktpn);\n\tret = KRB5KRB_AP_ERR_NOT_US;\n        _kdc_audit_addreason((kdc_request_t)priv, \"Request with wrong TGT\");\n\tgoto out;\n    }\n\n    ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n,\n\t\t\t\t NULL, &tkey_sign);\n    if (ret) {\n\tkdc_log(context, config, 4,\n\t\t    \"Failed to find key for krbtgt PAC signature\");\n        _kdc_audit_addreason((kdc_request_t)priv,\n                             \"Failed to find key for krbtgt PAC signature\");\n\tgoto out;\n    }\n    ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL,\n\t\t\t  tkey_sign->key.keytype, &tkey_sign);\n    if(ret) {\n\tkdc_log(context, config, 4,\n\t\t    \"Failed to find key for krbtgt PAC signature\");\n        _kdc_audit_addreason((kdc_request_t)priv,\n                             \"Failed to find key for krbtgt PAC signature\");\n\tgoto out;\n    }\n\n    {\n        krb5_data verified_cas;\n\n        /*\n         * If the client doesn't exist in the HDB but has a TGT and it's\n         * obtained with PKINIT then we assume it's a synthetic client -- that\n         * is, a client whose name was vouched for by a CA using a PKINIT SAN,\n         * but which doesn't exist in the HDB proper.  We'll allow such a\n         * client to do TGT requests even though normally we'd reject all\n         * clients that don't exist in the HDB.\n         */\n        ret = krb5_ticket_get_authorization_data_type(context, ticket,\n                                                      KRB5_AUTHDATA_INITIAL_VERIFIED_CAS,\n                                                      &verified_cas);\n        if (ret == 0) {\n            krb5_data_free(&verified_cas);\n            flags |= HDB_F_SYNTHETIC_OK;\n        }\n    }\n    ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags,\n\t\t\tNULL, &clientdb, &client);\n    flags &= ~HDB_F_SYNTHETIC_OK;\n    priv->client = client;\n    if(ret == HDB_ERR_NOT_FOUND_HERE) {\n\t/* This is OK, we are just trying to find out if they have\n\t * been disabled or deleted in the meantime, missing secrets\n\t * is OK */\n    } else if(ret){\n\tconst char *krbtgt_realm, *msg;\n\n\t/*\n\t * If the client belongs to the same realm as our krbtgt, it\n\t * should exist in the local database.\n\t *\n\t */\n\n\tkrbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal);\n\n\tif(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) {\n\t    if (ret == HDB_ERR_NOENTRY)\n\t\tret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;\n\t    kdc_log(context, config, 4, \"Client no longer in database: %s\",\n\t\t    cpn);\n            _kdc_audit_addreason((kdc_request_t)priv, \"Client no longer in HDB\");\n\t    goto out;\n\t}\n\n\tmsg = krb5_get_error_message(context, ret);\n\tkdc_log(context, config, 4, \"Client not found in database: %s\", msg);\n        _kdc_audit_addreason((kdc_request_t)priv, \"Client does not exist\");\n\tkrb5_free_error_message(context, msg);\n    } else if (ret == 0 &&\n               (client->entry.flags.invalid || !client->entry.flags.client)) {\n        _kdc_audit_addreason((kdc_request_t)priv, \"Client has invalid bit set\");\n        kdc_log(context, config, 4, \"Client has invalid bit set\");\n        ret = KRB5KDC_ERR_POLICY;\n        goto out;\n    }\n\n    ret = check_PAC(context, config, cp, NULL,\n\t\t    client, server, krbtgt,\n\t\t    &tkey_check->key,\n\t\t    ekey, &tkey_sign->key,\n\t\t    tgt, &rspac, &signedpath);\n    if (ret) {\n\tconst char *msg = krb5_get_error_message(context, ret);\n        _kdc_audit_addreason((kdc_request_t)priv, \"PAC check failed\");\n\tkdc_log(context, config, 4,\n\t\t\"Verify PAC failed for %s (%s) from %s with %s\",\n\t\tspn, cpn, from, msg);\n\tkrb5_free_error_message(context, msg);\n\tgoto out;\n    }\n\n    /* also check the krbtgt for signature */\n    ret = check_KRB5SignedPath(context,\n\t\t\t       config,\n\t\t\t       krbtgt,\n\t\t\t       cp,\n\t\t\t       tgt,\n\t\t\t       &spp,\n\t\t\t       &signedpath);\n    if (ret) {\n\tconst char *msg = krb5_get_error_message(context, ret);\n        _kdc_audit_addreason((kdc_request_t)priv, \"KRB5SignedPath check failed\");\n\tkdc_log(context, config, 4,\n\t\t\"KRB5SignedPath check failed for %s (%s) from %s with %s\",\n\t\tspn, cpn, from, msg);\n\tkrb5_free_error_message(context, msg);\n\tgoto out;\n    }\n\n    /*\n     * Process request\n     */\n\n    /* by default the tgt principal matches the client principal */\n    tp = cp;\n    tpn = cpn;\n\n    if (client) {\n\tconst PA_DATA *sdata;\n\tint i = 0;\n\n\tsdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER);\n\tif (sdata) {\n\t    struct astgs_request_desc imp_req;\n\t    krb5_crypto crypto;\n\t    krb5_data datack;\n\t    PA_S4U2Self self;\n\t    const char *str;\n\n\t    ret = decode_PA_S4U2Self(sdata->padata_value.data,\n\t\t\t\t     sdata->padata_value.length,\n\t\t\t\t     &self, NULL);\n\t    if (ret) {\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"Failed to decode PA-S4U2Self\");\n\t\tkdc_log(context, config, 4, \"Failed to decode PA-S4U2Self\");\n\t\tgoto out;\n\t    }\n\n\t    if (!krb5_checksum_is_keyed(context, self.cksum.cksumtype)) {\n\t\tfree_PA_S4U2Self(&self);\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"PA-S4U2Self with unkeyed checksum\");\n\t\tkdc_log(context, config, 4, \"Reject PA-S4U2Self with unkeyed checksum\");\n\t\tret = KRB5KRB_AP_ERR_INAPP_CKSUM;\n\t\tgoto out;\n\t    }\n\n\t    ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack);\n\t    if (ret)\n\t\tgoto out;\n\n\t    ret = krb5_crypto_init(context, &tgt->key, 0, &crypto);\n\t    if (ret) {\n\t\tconst char *msg = krb5_get_error_message(context, ret);\n\t\tfree_PA_S4U2Self(&self);\n\t\tkrb5_data_free(&datack);\n\t\tkdc_log(context, config, 4, \"krb5_crypto_init failed: %s\", msg);\n\t\tkrb5_free_error_message(context, msg);\n\t\tgoto out;\n\t    }\n\n\t    /* Allow HMAC_MD5 checksum with any key type */\n\t    if (self.cksum.cksumtype == CKSUMTYPE_HMAC_MD5) {\n\t\tstruct krb5_crypto_iov iov;\n\t\tunsigned char csdata[16];\n\t\tChecksum cs;\n\n\t\tcs.checksum.length = sizeof(csdata);\n\t\tcs.checksum.data = &csdata;\n\n\t\tiov.data.data = datack.data;\n\t\tiov.data.length = datack.length;\n\t\tiov.flags = KRB5_CRYPTO_TYPE_DATA;\n\n\t\tret = _krb5_HMAC_MD5_checksum(context, NULL, &crypto->key,\n\t\t\t\t\t      KRB5_KU_OTHER_CKSUM, &iov, 1,\n\t\t\t\t\t      &cs);\n\t\tif (ret == 0 &&\n\t\t    krb5_data_ct_cmp(&cs.checksum, &self.cksum.checksum) != 0)\n\t\t    ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;\n\t    }\n\t    else {\n\t\tret = krb5_verify_checksum(context,\n\t\t\t\t\t   crypto,\n\t\t\t\t\t   KRB5_KU_OTHER_CKSUM,\n\t\t\t\t\t   datack.data,\n\t\t\t\t\t   datack.length,\n\t\t\t\t\t   &self.cksum);\n\t    }\n\t    krb5_data_free(&datack);\n\t    krb5_crypto_destroy(context, crypto);\n\t    if (ret) {\n\t\tconst char *msg = krb5_get_error_message(context, ret);\n\t\tfree_PA_S4U2Self(&self);\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"S4U2Self checksum failed\");\n\t\tkdc_log(context, config, 4,\n\t\t\t\"krb5_verify_checksum failed for S4U2Self: %s\", msg);\n\t\tkrb5_free_error_message(context, msg);\n\t\tgoto out;\n\t    }\n\n\t    ret = _krb5_principalname2krb5_principal(context,\n\t\t\t\t\t\t     &tp,\n\t\t\t\t\t\t     self.name,\n\t\t\t\t\t\t     self.realm);\n\t    free_PA_S4U2Self(&self);\n\t    if (ret)\n\t\tgoto out;\n\n\t    ret = krb5_unparse_name(context, tp, &tpn);\n\t    if (ret)\n\t\tgoto out;\n\n            /*\n             * Note no HDB_F_SYNTHETIC_OK -- impersonating non-existent clients\n             * is probably not desirable!\n             */\n\t    ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags,\n\t\t\t\tNULL, &s4u2self_impersonated_clientdb,\n\t\t\t\t&s4u2self_impersonated_client);\n\t    if (ret) {\n\t\tconst char *msg;\n\n\t\t/*\n\t\t * If the client belongs to the same realm as our krbtgt, it\n\t\t * should exist in the local database.\n\t\t *\n\t\t */\n\n\t\tif (ret == HDB_ERR_NOENTRY)\n\t\t    ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;\n\t\tmsg = krb5_get_error_message(context, ret);\n                _kdc_audit_addreason((kdc_request_t)priv,\n                                     \"S4U2Self principal to impersonate not found\");\n\t\tkdc_log(context, config, 2,\n\t\t\t\"S4U2Self principal to impersonate %s not found in database: %s\",\n\t\t\ttpn, msg);\n\t\tkrb5_free_error_message(context, msg);\n\t\tgoto out;\n\t    }\n\n\t    /* Ignore require_pwchange and pw_end attributes (as Windows does),\n\t     * since S4U2Self is not password authentication. */\n\t    s4u2self_impersonated_client->entry.flags.require_pwchange = FALSE;\n\t    free(s4u2self_impersonated_client->entry.pw_end);\n\t    s4u2self_impersonated_client->entry.pw_end = NULL;\n\n\t    imp_req = *priv;\n\t    imp_req.client = s4u2self_impersonated_client;\n\t    imp_req.client_princ = tp;\n\n\t    ret = kdc_check_flags(&imp_req, FALSE);\n\t    if (ret)\n\t\tgoto out; /* kdc_check_flags() calls _kdc_audit_addreason() */\n\n\t    /* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */\n\t    if(rspac.data) {\n\t\tkrb5_pac p = NULL;\n\t\tkrb5_data_free(&rspac);\n\t\tret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p);\n\t\tif (ret) {\n                    _kdc_audit_addreason((kdc_request_t)priv,\n                                         \"KRB5SignedPath missing\");\n\t\t    kdc_log(context, config, 4, \"PAC generation failed for -- %s\",\n\t\t\t    tpn);\n\t\t    goto out;\n\t\t}\n\t\tif (p != NULL) {\n\t\t    ret = _krb5_pac_sign(context, p, ticket->ticket.authtime,\n\t\t\t\t\t s4u2self_impersonated_client->entry.principal,\n\t\t\t\t\t ekey, &tkey_sign->key,\n\t\t\t\t\t &rspac);\n\t\t    krb5_pac_free(context, p);\n\t\t    if (ret) {\n\t\t\tkdc_log(context, config, 4, \"PAC signing failed for -- %s\",\n\t\t\t\ttpn);\n\t\t\tgoto out;\n\t\t    }\n\t\t}\n\t    }\n\n\t    /*\n\t     * Check that service doing the impersonating is\n\t     * requesting a ticket to it-self.\n\t     */\n\t    ret = check_s4u2self(context, config, clientdb, client, sp);\n\t    if (ret) {\n\t\tkdc_log(context, config, 4, \"S4U2Self: %s is not allowed \"\n\t\t\t\"to impersonate to service \"\n\t\t\t\"(tried for user %s to service %s)\",\n\t\t\tcpn, tpn, spn);\n\t\tgoto out;\n\t    }\n\n\t    /*\n\t     * If the service isn't trusted for authentication to\n\t     * delegation or if the impersonate client is disallowed\n\t     * forwardable, remove the forwardable flag.\n\t     */\n\n\t    if (client->entry.flags.trusted_for_delegation &&\n\t\ts4u2self_impersonated_client->entry.flags.forwardable) {\n\t\tstr = \"[forwardable]\";\n\t    } else {\n\t\tb->kdc_options.forwardable = 0;\n\t\tstr = \"\";\n\t    }\n\t    kdc_log(context, config, 4, \"s4u2self %s impersonating %s to \"\n\t\t    \"service %s %s\", cpn, tpn, spn, str);\n\t}\n    }\n\n    /*\n     * Constrained delegation\n     */\n\n    if (client != NULL\n\t&& b->additional_tickets != NULL\n\t&& b->additional_tickets->len != 0\n\t&& b->kdc_options.cname_in_addl_tkt\n\t&& b->kdc_options.enc_tkt_in_skey == 0)\n    {\n\tint ad_signedpath = 0;\n\tKey *clientkey;\n\tTicket *t;\n\n\t/*\n\t * Require that the KDC have issued the service's krbtgt (not\n\t * self-issued ticket with kimpersonate(1).\n\t */\n\tif (!signedpath) {\n\t    ret = KRB5KDC_ERR_BADOPTION;\n            _kdc_audit_addreason((kdc_request_t)priv, \"KRB5SignedPath missing\");\n\t    kdc_log(context, config, 4,\n\t\t    \"Constrained delegation done on service ticket %s/%s\",\n\t\t    cpn, spn);\n\t    goto out;\n\t}\n\n\tt = &b->additional_tickets->val[0];\n\n\tret = hdb_enctype2key(context, &client->entry,\n\t\t\t      hdb_kvno2keys(context, &client->entry,\n\t\t\t\t\t    t->enc_part.kvno ? * t->enc_part.kvno : 0),\n\t\t\t      t->enc_part.etype, &clientkey);\n\tif(ret){\n\t    ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */\n\t    goto out;\n\t}\n\n\tret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0);\n\tif (ret) {\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Failed to decrypt constrained delegation ticket\");\n\t    kdc_log(context, config, 4,\n\t\t    \"failed to decrypt ticket for \"\n\t\t    \"constrained delegation from %s to %s \", cpn, spn);\n\t    goto out;\n\t}\n\n\tret = _krb5_principalname2krb5_principal(context,\n\t\t\t\t\t\t &tp,\n\t\t\t\t\t\t adtkt.cname,\n\t\t\t\t\t\t adtkt.crealm);\n\tif (ret)\n\t    goto out;\n\n\tret = krb5_unparse_name(context, tp, &tpn);\n\tif (ret)\n\t    goto out;\n\n        _kdc_audit_addkv((kdc_request_t)priv, 0, \"impersonatee\", \"%s\", tpn);\n\n\tret = _krb5_principalname2krb5_principal(context,\n\t\t\t\t\t\t &dp,\n\t\t\t\t\t\t t->sname,\n\t\t\t\t\t\t t->realm);\n\tif (ret)\n\t    goto out;\n\n\tret = krb5_unparse_name(context, dp, &dpn);\n\tif (ret)\n\t    goto out;\n\n\t/* check that ticket is valid */\n\tif (adtkt.flags.forwardable == 0) {\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Missing forwardable flag on ticket for constrained delegation\");\n\t    kdc_log(context, config, 4,\n\t\t    \"Missing forwardable flag on ticket for \"\n\t\t    \"constrained delegation from %s (%s) as %s to %s \",\n\t\t    cpn, dpn, tpn, spn);\n\t    ret = KRB5KDC_ERR_BADOPTION;\n\t    goto out;\n\t}\n\n\tret = check_constrained_delegation(context, config, clientdb,\n\t\t\t\t\t   client, server, sp);\n\tif (ret) {\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Constrained delegation not allowed\");\n\t    kdc_log(context, config, 4,\n\t\t    \"constrained delegation from %s (%s) as %s to %s not allowed\",\n\t\t    cpn, dpn, tpn, spn);\n\t    goto out;\n\t}\n\n\tret = verify_flags(context, config, &adtkt, tpn);\n\tif (ret) {\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Constrained delegation ticket expired or invalid\");\n\t    goto out;\n\t}\n\n\tkrb5_data_free(&rspac);\n\n\t/*\n\t * generate the PAC for the user.\n\t *\n\t * TODO: pass in t->sname and t->realm and build\n\t * a S4U_DELEGATION_INFO blob to the PAC.\n\t */\n\tret = check_PAC(context, config, tp, dp,\n\t\t\tclient, server, krbtgt,\n\t\t\t&clientkey->key,\n\t\t\tekey, &tkey_sign->key,\n\t\t\t&adtkt, &rspac, &ad_signedpath);\n\tif (ret) {\n\t    const char *msg = krb5_get_error_message(context, ret);\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Constrained delegation ticket PAC check failed\");\n\t    kdc_log(context, config, 4,\n\t\t    \"Verify delegated PAC failed to %s for client\"\n\t\t    \"%s (%s) as %s from %s with %s\",\n\t\t    spn, cpn, dpn, tpn, from, msg);\n\t    krb5_free_error_message(context, msg);\n\t    goto out;\n\t}\n\n\t/*\n\t * Check that the KDC issued the user's ticket.\n\t */\n\tret = check_KRB5SignedPath(context,\n\t\t\t\t   config,\n\t\t\t\t   krbtgt,\n\t\t\t\t   cp,\n\t\t\t\t   &adtkt,\n\t\t\t\t   NULL,\n\t\t\t\t   &ad_signedpath);\n\tif (ret) {\n\t    const char *msg = krb5_get_error_message(context, ret);\n\t    kdc_log(context, config, 4,\n\t\t    \"KRB5SignedPath check from service %s failed \"\n\t\t    \"for delegation to %s for client %s (%s)\"\n\t\t    \"from %s failed with %s\",\n\t\t    spn, tpn, dpn, cpn, from, msg);\n\t    krb5_free_error_message(context, msg);\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"KRB5SignedPath check failed\");\n\t    goto out;\n\t}\n\n\tif (!ad_signedpath) {\n\t    ret = KRB5KDC_ERR_BADOPTION;\n\t    kdc_log(context, config, 4,\n\t\t    \"Ticket not signed with PAC nor SignedPath service %s failed \"\n\t\t    \"for delegation to %s for client %s (%s)\"\n\t\t    \"from %s\",\n\t\t    spn, tpn, dpn, cpn, from);\n            _kdc_audit_addreason((kdc_request_t)priv,\n                                 \"Constrained delegation ticket not signed\");\n\t    goto out;\n\t}\n\n\tkdc_log(context, config, 4, \"constrained delegation for %s \"\n\t\t\"from %s (%s) to %s\", tpn, cpn, dpn, spn);\n    }\n\n    /*\n     * Check flags\n     */\n\n    ret = kdc_check_flags(priv, FALSE);\n    if(ret)\n\tgoto out;\n\n    if((b->kdc_options.validate || b->kdc_options.renew) &&\n       !krb5_principal_compare(context,\n\t\t\t       krbtgt->entry.principal,\n\t\t\t       server->entry.principal)){\n        _kdc_audit_addreason((kdc_request_t)priv, \"Inconsistent request\");\n\tkdc_log(context, config, 4, \"Inconsistent request.\");\n\tret = KRB5KDC_ERR_SERVER_NOMATCH;\n\tgoto out;\n    }\n\n    /* check for valid set of addresses */\n    if (!_kdc_check_addresses(priv, tgt->caddr, from_addr)) {\n        if (config->check_ticket_addresses) {\n            ret = KRB5KRB_AP_ERR_BADADDR;\n            _kdc_audit_addkv((kdc_request_t)priv, 0, \"wrongaddr\", \"yes\");\n            kdc_log(context, config, 4, \"Request from wrong address\");\n            _kdc_audit_addreason((kdc_request_t)priv, \"Request from wrong address\");\n            goto out;\n        } else if (config->warn_ticket_addresses) {\n            _kdc_audit_addkv((kdc_request_t)priv, 0, \"wrongaddr\", \"yes\");\n        }\n    }\n\n    /* check local and per-principal anonymous ticket issuance policy */\n    if (is_anon_tgs_request_p(b, tgt)) {\n\tret = _kdc_check_anon_policy(priv);\n\tif (ret)\n\t    goto out;\n    }\n\n    /*\n     * If this is an referral, add server referral data to the\n     * auth_data reply .\n     */\n    if (ref_realm) {\n\tPA_DATA pa;\n\tkrb5_crypto crypto;\n\n\tkdc_log(context, config, 3,\n\t\t\"Adding server referral to %s\", ref_realm);\n\n\tret = krb5_crypto_init(context, &sessionkey, 0, &crypto);\n\tif (ret)\n\t    goto out;\n\n\tret = build_server_referral(context, config, crypto, ref_realm,\n\t\t\t\t    NULL, s, &pa.padata_value);\n\tkrb5_crypto_destroy(context, crypto);\n\tif (ret) {\n            _kdc_audit_addreason((kdc_request_t)priv, \"Referral build failed\");\n\t    kdc_log(context, config, 4,\n\t\t    \"Failed building server referral\");\n\t    goto out;\n\t}\n\tpa.padata_type = KRB5_PADATA_SERVER_REFERRAL;\n\n\tret = add_METHOD_DATA(&enc_pa_data, &pa);\n\tkrb5_data_free(&pa.padata_value);\n\tif (ret) {\n\t    kdc_log(context, config, 4,\n\t\t    \"Add server referral METHOD-DATA failed\");\n\t    goto out;\n\t}\n    }\n\n    /*\n     *\n     */\n\n    ret = tgs_make_reply(priv,\n\t\t\t tp,\n\t\t\t tgt,\n\t\t\t replykey,\n\t\t\t rk_is_subkey,\n\t\t\t ekey,\n\t\t\t &sessionkey,\n\t\t\t kvno,\n\t\t\t *auth_data,\n\t\t\t server,\n\t\t\t rsp,\n\t\t\t client,\n\t\t\t cp,\n                         tgt_realm,\n\t\t\t krbtgt_out,\n\t\t\t tkey_sign->key.keytype,\n\t\t\t spp,\n\t\t\t &rspac,\n\t\t\t &enc_pa_data);\n\nout:\n    if (tpn != cpn)\n\t    free(tpn);\n    free(dpn);\n    free(krbtgt_out_n);\n    _krb5_free_capath(context, capath);\n\n    krb5_data_free(&rspac);\n    krb5_free_keyblock_contents(context, &sessionkey);\n    if(krbtgt_out)\n\t_kdc_free_ent(context, krbtgt_out);\n    if(server)\n\t_kdc_free_ent(context, server);\n    if(client)\n\t_kdc_free_ent(context, client);\n    if(s4u2self_impersonated_client)\n\t_kdc_free_ent(context, s4u2self_impersonated_client);\n\n    if (tp && tp != cp)\n\tkrb5_free_principal(context, tp);\n    krb5_free_principal(context, cp);\n    krb5_free_principal(context, dp);\n    krb5_free_principal(context, sp);\n    krb5_free_principal(context, krbtgt_out_principal);\n    free(ref_realm);\n    free_METHOD_DATA(&enc_pa_data);\n\n    free_EncTicketPart(&adtkt);\n\n    return ret;\n}", "func_hash": 196356477365064545945564048418819765006, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2021-3671", "cve_desc": "A null pointer de-reference was found in the way samba kerberos server handled missing sname in TGS-REQ (Ticket Granting Server - Request). An authenticated user could use this flaw to crash the samba server.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3671"}
{"idx": 208522, "project": "unbound", "commit_id": "02080f6b180232f43b77f403d0c038e9360a460f", "project_url": "https://github.com/NLnetLabs/unbound", "commit_url": "https://github.com/NLnetLabs/unbound/commit/02080f6b180232f43b77f403d0c038e9360a460f", "commit_message": "- Fix Integer Overflows in Size Calculations,\n  reported by X41 D-Sec.", "target": 1, "func": "dnsc_load_local_data(struct dnsc_env* dnscenv, struct config_file *cfg)\n{\n    size_t i, j;\n\t// Insert 'local-zone: \"2.dnscrypt-cert.example.com\" deny'\n    if(!cfg_str2list_insert(&cfg->local_zones,\n                            strdup(dnscenv->provider_name),\n                            strdup(\"deny\"))) {\n        log_err(\"Could not load dnscrypt local-zone: %s deny\",\n                dnscenv->provider_name);\n        return -1;\n    }\n\n    // Add local data entry of type:\n    // 2.dnscrypt-cert.example.com 86400 IN TXT \"DNSC......\"\n    for(i=0; isigned_certs_count; i++) {\n        const char *ttl_class_type = \" 86400 IN TXT \\\"\";\n        int rotated_cert = 0;\n\tuint32_t serial;\n\tuint16_t rrlen;\n\tchar* rr;\n        struct SignedCert *cert = dnscenv->signed_certs + i;\n\t\t// Check if the certificate is being rotated and should not be published\n        for(j=0; jrotated_certs_count; j++){\n            if(cert == dnscenv->rotated_certs[j]) {\n                rotated_cert = 1;\n                break;\n            }\n        }\n\t\tmemcpy(&serial, cert->serial, sizeof serial);\n\t\tserial = htonl(serial);\n        if(rotated_cert) {\n            verbose(VERB_OPS,\n                \"DNSCrypt: not adding cert with serial #%\"\n                PRIu32\n                \" to local-data as it is rotated\",\n                serial\n            );\n            continue;\n        }\n        rrlen = strlen(dnscenv->provider_name) +\n                         strlen(ttl_class_type) +\n                         4 * sizeof(struct SignedCert) + // worst case scenario\n                         1 + // trailing double quote\n                         1;\n        rr = malloc(rrlen);\n        if(!rr) {\n            log_err(\"Could not allocate memory\");\n            return -2;\n        }\n        snprintf(rr, rrlen - 1, \"%s 86400 IN TXT \\\"\", dnscenv->provider_name);\n        for(j=0; jlocal_data, strdup(rr));\n        free(rr);\n    }\n    return dnscenv->signed_certs_count;\n}", "func_hash": 44451332163685602086826854088983200257, "file_name": "dnscrypt.c", "file_hash": 338731906376917706393921999097571082291, "cwe": ["CWE-190"], "cve": "CVE-2019-25038", "cve_desc": "Unbound before 1.9.5 allows an integer overflow in a size calculation in dnscrypt/dnscrypt.c. NOTE: The vendor disputes that this is a vulnerability. Although the code may be vulnerable, a running Unbound installation cannot be remotely or locally exploited", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-25038"}
{"idx": 412117, "project": "unbound", "commit_id": "02080f6b180232f43b77f403d0c038e9360a460f", "project_url": "https://github.com/NLnetLabs/unbound", "commit_url": "https://github.com/NLnetLabs/unbound/commit/02080f6b180232f43b77f403d0c038e9360a460f", "commit_message": "- Fix Integer Overflows in Size Calculations,\n  reported by X41 D-Sec.", "target": 0, "func": "dnsc_load_local_data(struct dnsc_env* dnscenv, struct config_file *cfg)\n{\n    size_t i, j;\n\t// Insert 'local-zone: \"2.dnscrypt-cert.example.com\" deny'\n    if(!cfg_str2list_insert(&cfg->local_zones,\n                            strdup(dnscenv->provider_name),\n                            strdup(\"deny\"))) {\n        log_err(\"Could not load dnscrypt local-zone: %s deny\",\n                dnscenv->provider_name);\n        return -1;\n    }\n\n    // Add local data entry of type:\n    // 2.dnscrypt-cert.example.com 86400 IN TXT \"DNSC......\"\n    for(i=0; isigned_certs_count; i++) {\n        const char *ttl_class_type = \" 86400 IN TXT \\\"\";\n        int rotated_cert = 0;\n\tuint32_t serial;\n\tuint16_t rrlen;\n\tchar* rr;\n        struct SignedCert *cert = dnscenv->signed_certs + i;\n\t\t// Check if the certificate is being rotated and should not be published\n        for(j=0; jrotated_certs_count; j++){\n            if(cert == dnscenv->rotated_certs[j]) {\n                rotated_cert = 1;\n                break;\n            }\n        }\n\t\tmemcpy(&serial, cert->serial, sizeof serial);\n\t\tserial = htonl(serial);\n        if(rotated_cert) {\n            verbose(VERB_OPS,\n                \"DNSCrypt: not adding cert with serial #%\"\n                PRIu32\n                \" to local-data as it is rotated\",\n                serial\n            );\n            continue;\n        }\n\tif((unsigned)strlen(dnscenv->provider_name) >= (unsigned)0xffff0000) {\n\t\t/* guard against integer overflow in rrlen calculation */\n\t\tverbose(VERB_OPS, \"cert #%\" PRIu32 \" is too long\", serial);\n\t\tcontinue\n\t}\n        rrlen = strlen(dnscenv->provider_name) +\n                         strlen(ttl_class_type) +\n                         4 * sizeof(struct SignedCert) + // worst case scenario\n                         1 + // trailing double quote\n                         1;\n        rr = malloc(rrlen);\n        if(!rr) {\n            log_err(\"Could not allocate memory\");\n            return -2;\n        }\n        snprintf(rr, rrlen - 1, \"%s 86400 IN TXT \\\"\", dnscenv->provider_name);\n        for(j=0; jlocal_data, strdup(rr));\n        free(rr);\n    }\n    return dnscenv->signed_certs_count;\n}", "func_hash": 220864762997315196932796822660985000469, "file_name": "dnscrypt.c", "file_hash": 151631660973156645492009635074477412124, "cwe": ["CWE-190"], "cve": "CVE-2019-25038", "cve_desc": "Unbound before 1.9.5 allows an integer overflow in a size calculation in dnscrypt/dnscrypt.c. NOTE: The vendor disputes that this is a vulnerability. Although the code may be vulnerable, a running Unbound installation cannot be remotely or locally exploited", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-25038"}
{"idx": 208525, "project": "vim", "commit_id": "6046aded8da002b08d380db29de2ba0268b6616e", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/6046aded8da002b08d380db29de2ba0268b6616e", "commit_message": "patch 8.2.5148: invalid memory access when using expression on command line\n\nProblem:    Invalid memory access when using an expression on the command line.\nSolution:   Make sure the position does not go negative.", "target": 1, "func": "cmdline_insert_reg(int *gotesc UNUSED)\n{\n    int\t\ti;\n    int\t\tc;\n\n#ifdef USE_ON_FLY_SCROLL\n    dont_scroll = TRUE;\t// disallow scrolling here\n#endif\n    putcmdline('\"', TRUE);\n    ++no_mapping;\n    ++allow_keys;\n    i = c = plain_vgetc();\t// CTRL-R \n    if (i == Ctrl_O)\n\ti = Ctrl_R;\t\t// CTRL-R CTRL-O == CTRL-R CTRL-R\n    if (i == Ctrl_R)\n\tc = plain_vgetc();\t// CTRL-R CTRL-R \n    extra_char = NUL;\n    --no_mapping;\n    --allow_keys;\n#ifdef FEAT_EVAL\n    /*\n     * Insert the result of an expression.\n     * Need to save the current command line, to be able to enter\n     * a new one...\n     */\n    new_cmdpos = -1;\n    if (c == '=')\n    {\n\tif (ccline.cmdfirstc == '='  // can't do this recursively\n\t\t|| cmdline_star > 0) // or when typing a password\n\t{\n\t    beep_flush();\n\t    c = ESC;\n\t}\n\telse\n\t    c = get_expr_register();\n    }\n#endif\n    if (c != ESC)\t    // use ESC to cancel inserting register\n    {\n\tcmdline_paste(c, i == Ctrl_R, FALSE);\n\n#ifdef FEAT_EVAL\n\t// When there was a serious error abort getting the\n\t// command line.\n\tif (aborting())\n\t{\n\t    *gotesc = TRUE;  // will free ccline.cmdbuff after\n\t    // putting it in history\n\t    return GOTO_NORMAL_MODE;\n\t}\n#endif\n\tKeyTyped = FALSE;\t// Don't do p_wc completion.\n#ifdef FEAT_EVAL\n\tif (new_cmdpos >= 0)\n\t{\n\t    // set_cmdline_pos() was used\n\t    if (new_cmdpos > ccline.cmdlen)\n\t\tccline.cmdpos = ccline.cmdlen;\n\t    else\n\t\tccline.cmdpos = new_cmdpos;\n\t}\n#endif\n    }\n    // remove the double quote\n    redrawcmd();\n\n    // The text has been stuffed, the command line didn't change yet.\n    return CMDLINE_NOT_CHANGED;\n}", "func_hash": 167804329878727127060395714139665031179, "file_name": "ex_getln.c", "file_hash": 269509646770853684376504137864854849552, "cwe": ["CWE-787"], "cve": "CVE-2022-2175", "cve_desc": "Buffer Over-read in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2175"}
{"idx": 412190, "project": "vim", "commit_id": "6046aded8da002b08d380db29de2ba0268b6616e", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/6046aded8da002b08d380db29de2ba0268b6616e", "commit_message": "patch 8.2.5148: invalid memory access when using expression on command line\n\nProblem:    Invalid memory access when using an expression on the command line.\nSolution:   Make sure the position does not go negative.", "target": 0, "func": "cmdline_insert_reg(int *gotesc UNUSED)\n{\n    int\t\ti;\n    int\t\tc;\n    int\t\tsave_new_cmdpos = new_cmdpos;\n\n#ifdef USE_ON_FLY_SCROLL\n    dont_scroll = TRUE;\t// disallow scrolling here\n#endif\n    putcmdline('\"', TRUE);\n    ++no_mapping;\n    ++allow_keys;\n    i = c = plain_vgetc();\t// CTRL-R \n    if (i == Ctrl_O)\n\ti = Ctrl_R;\t\t// CTRL-R CTRL-O == CTRL-R CTRL-R\n    if (i == Ctrl_R)\n\tc = plain_vgetc();\t// CTRL-R CTRL-R \n    extra_char = NUL;\n    --no_mapping;\n    --allow_keys;\n#ifdef FEAT_EVAL\n    /*\n     * Insert the result of an expression.\n     */\n    new_cmdpos = -1;\n    if (c == '=')\n    {\n\tif (ccline.cmdfirstc == '='  // can't do this recursively\n\t\t|| cmdline_star > 0) // or when typing a password\n\t{\n\t    beep_flush();\n\t    c = ESC;\n\t}\n\telse\n\t    c = get_expr_register();\n    }\n#endif\n    if (c != ESC)\t    // use ESC to cancel inserting register\n    {\n\tcmdline_paste(c, i == Ctrl_R, FALSE);\n\n#ifdef FEAT_EVAL\n\t// When there was a serious error abort getting the\n\t// command line.\n\tif (aborting())\n\t{\n\t    *gotesc = TRUE;  // will free ccline.cmdbuff after\n\t    // putting it in history\n\t    return GOTO_NORMAL_MODE;\n\t}\n#endif\n\tKeyTyped = FALSE;\t// Don't do p_wc completion.\n#ifdef FEAT_EVAL\n\tif (new_cmdpos >= 0)\n\t{\n\t    // set_cmdline_pos() was used\n\t    if (new_cmdpos > ccline.cmdlen)\n\t\tccline.cmdpos = ccline.cmdlen;\n\t    else\n\t\tccline.cmdpos = new_cmdpos;\n\t}\n#endif\n    }\n    new_cmdpos = save_new_cmdpos;\n\n    // remove the double quote\n    redrawcmd();\n\n    // The text has been stuffed, the command line didn't change yet.\n    return CMDLINE_NOT_CHANGED;\n}", "func_hash": 5421090615610689574320991257810194043, "file_name": "ex_getln.c", "file_hash": 9575536184258751931455824501169284802, "cwe": ["CWE-787"], "cve": "CVE-2022-2175", "cve_desc": "Buffer Over-read in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2175"}
{"idx": 208535, "project": "rizin", "commit_id": "58926dffbe819fe9ebf5062f7130e026351cae01", "project_url": "https://github.com/rizinorg/rizin", "commit_url": "https://github.com/rizinorg/rizin/commit/58926dffbe819fe9ebf5062f7130e026351cae01", "commit_message": "fix #2964 - double-free in bin_qnx.c", "target": 1, "func": "static RzList *relocs(RzBinFile *bf) {\n\trz_return_val_if_fail(bf && bf->o, NULL);\n\tQnxObj *qo = bf->o->bin_obj;\n\treturn rz_list_clone(qo->fixups);\n}", "func_hash": 41829514855496977293704373413382810445, "file_name": "bin_qnx.c", "file_hash": 327448367050510652704729380638932181720, "cwe": ["CWE-415"], "cve": "CVE-2022-36043", "cve_desc": "Rizin is a UNIX-like reverse engineering framework and command-line toolset. Versions 0.4.0 and prior are vulnerable to a double free in bobj.c:rz_bin_reloc_storage_free() when freeing relocations generated from qnx binary plugin. A user opening a malicious qnx binary could be affected by this vulnerability, allowing an attacker to execute code on the user's machine. Commit number a3d50c1ea185f3f642f2d8180715f82d98840784 contains a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-36043"}
{"idx": 412332, "project": "rizin", "commit_id": "58926dffbe819fe9ebf5062f7130e026351cae01", "project_url": "https://github.com/rizinorg/rizin", "commit_url": "https://github.com/rizinorg/rizin/commit/58926dffbe819fe9ebf5062f7130e026351cae01", "commit_message": "fix #2964 - double-free in bin_qnx.c", "target": 0, "func": "static RzList *maps(RzBinFile *bf) {\n\trz_return_val_if_fail(bf && bf->o, NULL);\n\tQnxObj *qo = bf->o->bin_obj;\n\treturn rz_list_clone(qo->maps);\n}", "func_hash": 19242058764705601713784045996495740023, "file_name": "bin_qnx.c", "file_hash": 19463219798062548086589627833690645590, "cwe": ["CWE-415"], "cve": "CVE-2022-36043", "cve_desc": "Rizin is a UNIX-like reverse engineering framework and command-line toolset. Versions 0.4.0 and prior are vulnerable to a double free in bobj.c:rz_bin_reloc_storage_free() when freeing relocations generated from qnx binary plugin. A user opening a malicious qnx binary could be affected by this vulnerability, allowing an attacker to execute code on the user's machine. Commit number a3d50c1ea185f3f642f2d8180715f82d98840784 contains a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-36043"}
{"idx": 208654, "project": "php-src", "commit_id": "cab1c3b3708eead315e033359d07049b23b147a3", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=cab1c3b3708eead315e033359d07049b23b147a3", "commit_message": "Fixed bug #72479 - same as #72434", "target": 1, "func": "PHP_MINIT_FUNCTION(snmp)\n{\n\tnetsnmp_log_handler *logh;\n\tzend_class_entry ce, cex;\n\n\tle_snmp_session = zend_register_list_destructors_ex(php_snmp_session_destructor, NULL, PHP_SNMP_SESSION_RES_NAME, module_number);\n\n\tinit_snmp(\"snmpapp\");\n\n#ifdef NETSNMP_DS_LIB_DONT_PERSIST_STATE\n\t/* Prevent update of the snmpapp.conf file */\n\tnetsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PERSIST_STATE, 1);\n#endif\n\n\t/* Disable logging, use exit status'es and related variabled to detect errors */\n\tshutdown_snmp_logging();\n\tlogh = netsnmp_register_loghandler(NETSNMP_LOGHANDLER_NONE, LOG_ERR);\n\tif (logh) {\n\t\tlogh->pri_max = LOG_ERR;\n\t}\n\n\tmemcpy(&php_snmp_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));\n\tphp_snmp_object_handlers.read_property = php_snmp_read_property;\n\tphp_snmp_object_handlers.write_property = php_snmp_write_property;\n\tphp_snmp_object_handlers.has_property = php_snmp_has_property;\n\tphp_snmp_object_handlers.get_properties = php_snmp_get_properties;\n\n\t/* Register SNMP Class */\n\tINIT_CLASS_ENTRY(ce, \"SNMP\", php_snmp_class_methods);\n\tce.create_object = php_snmp_object_new;\n\tphp_snmp_object_handlers.clone_obj = NULL;\n\tphp_snmp_ce = zend_register_internal_class(&ce TSRMLS_CC);\n\n\t/* Register SNMP Class properties */\n\tzend_hash_init(&php_snmp_properties, 0, NULL, NULL, 1);\n\tPHP_SNMP_ADD_PROPERTIES(&php_snmp_properties, php_snmp_property_entries);\n\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_SUFFIX\",\tNETSNMP_OID_OUTPUT_SUFFIX,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_MODULE\",\tNETSNMP_OID_OUTPUT_MODULE,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_FULL\",\t\tNETSNMP_OID_OUTPUT_FULL,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_NUMERIC\",\tNETSNMP_OID_OUTPUT_NUMERIC,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_UCD\",\t\tNETSNMP_OID_OUTPUT_UCD,\t\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_NONE\",\t\tNETSNMP_OID_OUTPUT_NONE,\tCONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"SNMP_VALUE_LIBRARY\",\tSNMP_VALUE_LIBRARY,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_VALUE_PLAIN\",\tSNMP_VALUE_PLAIN,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_VALUE_OBJECT\",\tSNMP_VALUE_OBJECT,\tCONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"SNMP_BIT_STR\",\t\tASN_BIT_STR,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OCTET_STR\",\tASN_OCTET_STR,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OPAQUE\",\t\tASN_OPAQUE,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_NULL\",\t\tASN_NULL,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OBJECT_ID\",\tASN_OBJECT_ID,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_IPADDRESS\",\tASN_IPADDRESS,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_COUNTER\",\t\tASN_GAUGE,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_UNSIGNED\",\t\tASN_UNSIGNED,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_TIMETICKS\",\tASN_TIMETICKS,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_UINTEGER\",\t\tASN_UINTEGER,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_INTEGER\",\t\tASN_INTEGER,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_COUNTER64\",\tASN_COUNTER64,\tCONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"VERSION_1\",\t\t\tSNMP_VERSION_1);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"VERSION_2c\",\t\t\tSNMP_VERSION_2c);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"VERSION_2C\",\t\t\tSNMP_VERSION_2c);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"VERSION_3\",\t\t\tSNMP_VERSION_3);\n\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_NOERROR\",\t\t\tPHP_SNMP_ERRNO_NOERROR);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_ANY\",\t\t\tPHP_SNMP_ERRNO_ANY);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_GENERIC\",\t\t\tPHP_SNMP_ERRNO_GENERIC);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_TIMEOUT\",\t\t\tPHP_SNMP_ERRNO_TIMEOUT);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_ERROR_IN_REPLY\",\t\tPHP_SNMP_ERRNO_ERROR_IN_REPLY);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_OID_NOT_INCREASING\",\tPHP_SNMP_ERRNO_OID_NOT_INCREASING);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_OID_PARSING_ERROR\",\tPHP_SNMP_ERRNO_OID_PARSING_ERROR);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_MULTIPLE_SET_QUERIES\",\tPHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES);\n\n\t/* Register SNMPException class */\n\tINIT_CLASS_ENTRY(cex, \"SNMPException\", NULL);\n#ifdef HAVE_SPL\n\tphp_snmp_exception_ce = zend_register_internal_class_ex(&cex, spl_ce_RuntimeException, NULL TSRMLS_CC);\n#else\n\tphp_snmp_exception_ce = zend_register_internal_class_ex(&cex, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC);\n#endif\n\n\treturn SUCCESS;\n}", "func_hash": 67376393539603801542933710123087364670, "file_name": "snmp.c", "file_hash": 23932759773432740913613151934817775847, "cwe": ["CWE-416"], "cve": "CVE-2016-6295", "cve_desc": "ext/snmp/snmp.c in PHP before 5.5.38, 5.6.x before 5.6.24, and 7.x before 7.0.9 improperly interacts with the unserialize implementation and garbage collection, which allows remote attackers to cause a denial of service (use-after-free and application crash) or possibly have unspecified other impact via crafted serialized data, a related issue to CVE-2016-5773.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-6295"}
{"idx": 413339, "project": "php-src", "commit_id": "cab1c3b3708eead315e033359d07049b23b147a3", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=cab1c3b3708eead315e033359d07049b23b147a3", "commit_message": "Fixed bug #72479 - same as #72434", "target": 0, "func": "PHP_MINIT_FUNCTION(snmp)\n{\n\tnetsnmp_log_handler *logh;\n\tzend_class_entry ce, cex;\n\n\tle_snmp_session = zend_register_list_destructors_ex(php_snmp_session_destructor, NULL, PHP_SNMP_SESSION_RES_NAME, module_number);\n\n\tinit_snmp(\"snmpapp\");\n\n#ifdef NETSNMP_DS_LIB_DONT_PERSIST_STATE\n\t/* Prevent update of the snmpapp.conf file */\n\tnetsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PERSIST_STATE, 1);\n#endif\n\n\t/* Disable logging, use exit status'es and related variabled to detect errors */\n\tshutdown_snmp_logging();\n\tlogh = netsnmp_register_loghandler(NETSNMP_LOGHANDLER_NONE, LOG_ERR);\n\tif (logh) {\n\t\tlogh->pri_max = LOG_ERR;\n\t}\n\n\tmemcpy(&php_snmp_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));\n\tphp_snmp_object_handlers.read_property = php_snmp_read_property;\n\tphp_snmp_object_handlers.write_property = php_snmp_write_property;\n\tphp_snmp_object_handlers.has_property = php_snmp_has_property;\n\tphp_snmp_object_handlers.get_properties = php_snmp_get_properties;\n\tphp_snmp_object_handlers.get_gc = php_snmp_get_gc;\n\n\t/* Register SNMP Class */\n\tINIT_CLASS_ENTRY(ce, \"SNMP\", php_snmp_class_methods);\n\tce.create_object = php_snmp_object_new;\n\tphp_snmp_object_handlers.clone_obj = NULL;\n\tphp_snmp_ce = zend_register_internal_class(&ce TSRMLS_CC);\n\n\t/* Register SNMP Class properties */\n\tzend_hash_init(&php_snmp_properties, 0, NULL, NULL, 1);\n\tPHP_SNMP_ADD_PROPERTIES(&php_snmp_properties, php_snmp_property_entries);\n\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_SUFFIX\",\tNETSNMP_OID_OUTPUT_SUFFIX,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_MODULE\",\tNETSNMP_OID_OUTPUT_MODULE,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_FULL\",\t\tNETSNMP_OID_OUTPUT_FULL,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_NUMERIC\",\tNETSNMP_OID_OUTPUT_NUMERIC,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_UCD\",\t\tNETSNMP_OID_OUTPUT_UCD,\t\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OID_OUTPUT_NONE\",\t\tNETSNMP_OID_OUTPUT_NONE,\tCONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"SNMP_VALUE_LIBRARY\",\tSNMP_VALUE_LIBRARY,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_VALUE_PLAIN\",\tSNMP_VALUE_PLAIN,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_VALUE_OBJECT\",\tSNMP_VALUE_OBJECT,\tCONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_LONG_CONSTANT(\"SNMP_BIT_STR\",\t\tASN_BIT_STR,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OCTET_STR\",\tASN_OCTET_STR,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OPAQUE\",\t\tASN_OPAQUE,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_NULL\",\t\tASN_NULL,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_OBJECT_ID\",\tASN_OBJECT_ID,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_IPADDRESS\",\tASN_IPADDRESS,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_COUNTER\",\t\tASN_GAUGE,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_UNSIGNED\",\t\tASN_UNSIGNED,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_TIMETICKS\",\tASN_TIMETICKS,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_UINTEGER\",\t\tASN_UINTEGER,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_INTEGER\",\t\tASN_INTEGER,\tCONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"SNMP_COUNTER64\",\tASN_COUNTER64,\tCONST_CS | CONST_PERSISTENT);\n\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"VERSION_1\",\t\t\tSNMP_VERSION_1);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"VERSION_2c\",\t\t\tSNMP_VERSION_2c);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"VERSION_2C\",\t\t\tSNMP_VERSION_2c);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"VERSION_3\",\t\t\tSNMP_VERSION_3);\n\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_NOERROR\",\t\t\tPHP_SNMP_ERRNO_NOERROR);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_ANY\",\t\t\tPHP_SNMP_ERRNO_ANY);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_GENERIC\",\t\t\tPHP_SNMP_ERRNO_GENERIC);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_TIMEOUT\",\t\t\tPHP_SNMP_ERRNO_TIMEOUT);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_ERROR_IN_REPLY\",\t\tPHP_SNMP_ERRNO_ERROR_IN_REPLY);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_OID_NOT_INCREASING\",\tPHP_SNMP_ERRNO_OID_NOT_INCREASING);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_OID_PARSING_ERROR\",\tPHP_SNMP_ERRNO_OID_PARSING_ERROR);\n\tREGISTER_SNMP_CLASS_CONST_LONG(\"ERRNO_MULTIPLE_SET_QUERIES\",\tPHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES);\n\n\t/* Register SNMPException class */\n\tINIT_CLASS_ENTRY(cex, \"SNMPException\", NULL);\n#ifdef HAVE_SPL\n\tphp_snmp_exception_ce = zend_register_internal_class_ex(&cex, spl_ce_RuntimeException, NULL TSRMLS_CC);\n#else\n\tphp_snmp_exception_ce = zend_register_internal_class_ex(&cex, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC);\n#endif\n\n\treturn SUCCESS;\n}", "func_hash": 61841669860685177602281773654543637365, "file_name": "snmp.c", "file_hash": 195062314366498303509175847868002620782, "cwe": ["CWE-416"], "cve": "CVE-2016-6295", "cve_desc": "ext/snmp/snmp.c in PHP before 5.5.38, 5.6.x before 5.6.24, and 7.x before 7.0.9 improperly interacts with the unserialize implementation and garbage collection, which allows remote attackers to cause a denial of service (use-after-free and application crash) or possibly have unspecified other impact via crafted serialized data, a related issue to CVE-2016-5773.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-6295"}
{"idx": 208680, "project": "radare2", "commit_id": "10517e3ff0e609697eb8cde60ec8dc999ee5ea24", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/10517e3ff0e609697eb8cde60ec8dc999ee5ea24", "commit_message": "aaef on arm/thumb switches causes uaf ##crash\n\n* Reported by peacock-doris via huntr.dev\n* Reproducer: poc_uaf_r_reg_get", "target": 1, "func": "R_API void r_core_anal_esil(RCore *core, const char *str, const char *target) {\n\tbool cfg_anal_strings = r_config_get_i (core->config, \"anal.strings\");\n\tbool emu_lazy = r_config_get_i (core->config, \"emu.lazy\");\n\tbool gp_fixed = r_config_get_i (core->config, \"anal.gpfixed\");\n\tRAnalEsil *ESIL = core->anal->esil;\n\tut64 refptr = 0LL;\n\tconst char *pcname;\n\tRAnalOp op = R_EMPTY;\n\tut8 *buf = NULL;\n\tbool end_address_set = false;\n\tint iend;\n\tint minopsize = 4; // XXX this depends on asm->mininstrsize\n\tbool archIsArm = false;\n\tut64 addr = core->offset;\n\tut64 start = addr;\n\tut64 end = 0LL;\n\tut64 cur;\n\tif (esil_anal_stop || r_cons_is_breaked ()) {\n\t\t// faster ^C\n\t\treturn;\n\t}\n\n\tmycore = core;\n\tif (!strcmp (str, \"?\")) {\n\t\teprintf (\"Usage: aae[f] [len] [addr] - analyze refs in function, section or len bytes with esil\\n\");\n\t\teprintf (\"  aae $SS @ $S             - analyze the whole section\\n\");\n\t\teprintf (\"  aae $SS str.Hello @ $S   - find references for str.Hellow\\n\");\n\t\teprintf (\"  aaef                     - analyze functions discovered with esil\\n\");\n\t\treturn;\n\t}\n#define CHECKREF(x) ((refptr && (x) == refptr) || !refptr)\n\tif (target) {\n\t\tconst char *expr = r_str_trim_head_ro (target);\n\t\tif (*expr) {\n\t\t\trefptr = ntarget = r_num_math (core->num, expr);\n\t\t\tif (!refptr) {\n\t\t\t\tntarget = refptr = addr;\n\t\t\t}\n\t\t} else {\n\t\t\tntarget = UT64_MAX;\n\t\t\trefptr = 0LL;\n\t\t}\n\t} else {\n\t\tntarget = UT64_MAX;\n\t\trefptr = 0LL;\n\t}\n\tRAnalFunction *fcn = NULL;\n\tif (!strcmp (str, \"f\")) {\n\t\tfcn = r_anal_get_fcn_in (core->anal, core->offset, 0);\n\t\tif (fcn) {\n\t\t\tstart = r_anal_function_min_addr (fcn);\n\t\t\taddr = fcn->addr;\n\t\t\tend = r_anal_function_max_addr (fcn);\n\t\t\tend_address_set = true;\n\t\t}\n\t}\n\n\tif (!end_address_set) {\n\t\tif (str[0] == ' ') {\n\t\t\tend = addr + r_num_math (core->num, str + 1);\n\t\t} else {\n\t\t\tRIOMap *map = r_io_map_get_at (core->io, addr);\n\t\t\tif (map) {\n\t\t\t\tend = r_io_map_end (map);\n\t\t\t} else {\n\t\t\t\tend = addr + core->blocksize;\n\t\t\t}\n\t\t}\n\t}\n\n\tiend = end - start;\n\tif (iend < 0) {\n\t\treturn;\n\t}\n\tif (iend > MAX_SCAN_SIZE) {\n\t\teprintf (\"Warning: Not going to analyze 0x%08\"PFMT64x\" bytes.\\n\", (ut64)iend);\n\t\treturn;\n\t}\n\tbuf = malloc ((size_t)iend + 2);\n\tif (!buf) {\n\t\tperror (\"malloc\");\n\t\treturn;\n\t}\n\tesilbreak_last_read = UT64_MAX;\n\tr_io_read_at (core->io, start, buf, iend + 1);\n\tif (!ESIL) {\n\t\tr_core_cmd0 (core, \"aei\");\n\t\tESIL = core->anal->esil;\n\t\tif (!ESIL) {\n\t\t\teprintf (\"ESIL not initialized\\n\");\n\t\t\treturn;\n\t\t}\n\t\tr_core_cmd0 (core, \"aeim\");\n\t\tESIL = core->anal->esil;\n\t}\n\tconst char *spname = r_reg_get_name (core->anal->reg, R_REG_NAME_SP);\n\tif (!spname) {\n\t\teprintf (\"Error: No =SP defined in the reg profile.\\n\");\n\t\treturn;\n\t}\n\tEsilBreakCtx ctx = {\n\t\t&op,\n\t\tfcn,\n\t\tspname,\n\t\tr_reg_getv (core->anal->reg, spname)\n\t};\n\tESIL->cb.hook_reg_write = &esilbreak_reg_write;\n\t//this is necessary for the hook to read the id of analop\n\tESIL->user = &ctx;\n\tESIL->cb.hook_mem_read = &esilbreak_mem_read;\n\tESIL->cb.hook_mem_write = &esilbreak_mem_write;\n\n\tif (fcn && fcn->reg_save_area) {\n\t\tr_reg_setv (core->anal->reg, ctx.spname, ctx.initial_sp - fcn->reg_save_area);\n\t}\n\t//eprintf (\"Analyzing ESIL refs from 0x%\"PFMT64x\" - 0x%\"PFMT64x\"\\n\", addr, end);\n\t// TODO: backup/restore register state before/after analysis\n\tpcname = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);\n\tif (!pcname || !*pcname) {\n\t\teprintf (\"Cannot find program counter register in the current profile.\\n\");\n\t\treturn;\n\t}\n\tesil_anal_stop = false;\n\tr_cons_break_push (cccb, core);\n\n\tint arch = -1;\n\tif (!strcmp (core->anal->cur->arch, \"arm\")) {\n\t\tswitch (core->anal->cur->bits) {\n\t\tcase 64: arch = R2_ARCH_ARM64; break;\n\t\tcase 32: arch = R2_ARCH_ARM32; break;\n\t\tcase 16: arch = R2_ARCH_THUMB; break;\n\t\t}\n\t\tarchIsArm = true;\n\t}\n\n\tut64 gp = r_config_get_i (core->config, \"anal.gp\");\n\tconst char *gp_reg = NULL;\n\tif (!strcmp (core->anal->cur->arch, \"mips\")) {\n\t\tgp_reg = \"gp\";\n\t\tarch = R2_ARCH_MIPS;\n\t}\n\n\tconst char *sn = r_reg_get_name (core->anal->reg, R_REG_NAME_SN);\n\tif (!sn) {\n\t\teprintf (\"Warning: No SN reg alias for current architecture.\\n\");\n\t}\n\tr_reg_arena_push (core->anal->reg);\n\n\tIterCtx ictx = { start, end, fcn, NULL };\n\tsize_t i = addr - start;\n\tsize_t i_old = 0;\n\tdo {\n\t\tif (esil_anal_stop || r_cons_is_breaked ()) {\n\t\t\tbreak;\n\t\t}\n\t\tcur = start + i;\n\t\tif (!r_io_is_valid_offset (core->io, cur, 0)) {\n\t\t\tbreak;\n\t\t}\n#if 0\n\t\t// disabled because it causes some tests to fail\n\t\t{\n\t\t\tRPVector *list = r_meta_get_all_in (core->anal, cur, R_META_TYPE_ANY);\n\t\t\tvoid **it;\n\t\t\tr_pvector_foreach (list, it) {\n\t\t\t\tRIntervalNode *node = *it;\n\t\t\t\tRAnalMetaItem *meta = node->data;\n\t\t\t\tswitch (meta->type) {\n\t\t\t\tcase R_META_TYPE_DATA:\n\t\t\t\tcase R_META_TYPE_STRING:\n\t\t\t\tcase R_META_TYPE_FORMAT:\n#if 0\n\t\t\t\t\t{\n\t\t\t\t\t\tint msz = r_meta_get_size (core->anal, meta->type);\n\t\t\t\t\t\ti += (msz > 0)? msz: minopsize;\n\t\t\t\t\t}\n\t\t\t\t\tr_pvector_free (list);\n\t\t\t\t\tgoto loopback;\n#elif 0\n\t\t\t\t\t{\n\t\t\t\t\t\tint msz = r_meta_get_size (core->anal, meta->type);\n\t\t\t\t\t\ti += (msz > 0)? msz: minopsize;\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n#else\n\t\t\t\t\ti += 4;\n\t\t\t\t\tgoto repeat;\n#endif\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tr_pvector_free (list);\n\t\t}\n#endif\n\n\t\t/* realign address if needed */\n\t\tr_core_seek_arch_bits (core, cur);\n\t\tint opalign = core->anal->pcalign;\n\t\tif (opalign > 0) {\n\t\t\tcur -= (cur % opalign);\n\t\t}\n\n\t\tr_anal_op_fini (&op);\n\t\tr_asm_set_pc (core->rasm, cur);\n\t\ti_old = i;\n#if 1\n\t\tif (i > iend) {\n\t\t\tgoto repeat;\n\t\t}\n#endif\n\t\tif (!r_anal_op (core->anal, &op, cur, buf + i, iend - i, R_ANAL_OP_MASK_ESIL | R_ANAL_OP_MASK_VAL | R_ANAL_OP_MASK_HINT)) {\n\t\t\ti += minopsize - 1; //   XXX dupe in op.size below\n\t\t}\n\t\tif (op.type == R_ANAL_OP_TYPE_ILL || op.type == R_ANAL_OP_TYPE_UNK) {\n\t\t\t// i += 2\n\t\t\tr_anal_op_fini (&op);\n\t\t\tgoto repeat;\n\t\t}\n\t\t//we need to check again i because buf+i may goes beyond its boundaries\n\t\t//because of i+= minopsize - 1\n\t\tif (op.size < 1) {\n\t\t\ti += minopsize - 1;\n\t\t\tgoto repeat;\n\t\t}\n\t\tif (emu_lazy) {\n\t\t\tif (op.type & R_ANAL_OP_TYPE_REP) {\n\t\t\t\ti += op.size - 1;\n\t\t\t\tgoto repeat;\n\t\t\t}\n\t\t\tswitch (op.type & R_ANAL_OP_TYPE_MASK) {\n\t\t\tcase R_ANAL_OP_TYPE_JMP:\n\t\t\tcase R_ANAL_OP_TYPE_CJMP:\n\t\t\tcase R_ANAL_OP_TYPE_CALL:\n\t\t\tcase R_ANAL_OP_TYPE_RET:\n\t\t\tcase R_ANAL_OP_TYPE_ILL:\n\t\t\tcase R_ANAL_OP_TYPE_NOP:\n\t\t\tcase R_ANAL_OP_TYPE_UJMP:\n\t\t\tcase R_ANAL_OP_TYPE_IO:\n\t\t\tcase R_ANAL_OP_TYPE_LEAVE:\n\t\t\tcase R_ANAL_OP_TYPE_CRYPTO:\n\t\t\tcase R_ANAL_OP_TYPE_CPL:\n\t\t\tcase R_ANAL_OP_TYPE_SYNC:\n\t\t\tcase R_ANAL_OP_TYPE_SWI:\n\t\t\tcase R_ANAL_OP_TYPE_CMP:\n\t\t\tcase R_ANAL_OP_TYPE_ACMP:\n\t\t\tcase R_ANAL_OP_TYPE_NULL:\n\t\t\tcase R_ANAL_OP_TYPE_CSWI:\n\t\t\tcase R_ANAL_OP_TYPE_TRAP:\n\t\t\t\ti += op.size - 1;\n\t\t\t\tgoto repeat;\n\t\t\t//  those require write support\n\t\t\tcase R_ANAL_OP_TYPE_PUSH:\n\t\t\tcase R_ANAL_OP_TYPE_POP:\n\t\t\t\ti += op.size - 1;\n\t\t\t\tgoto repeat;\n\t\t\t}\n\t\t}\n\t\tif (sn && op.type == R_ANAL_OP_TYPE_SWI) {\n\t\t\tr_strf_buffer (64);\n\t\t\tr_flag_space_set (core->flags, R_FLAGS_FS_SYSCALLS);\n\t\t\tint snv = (arch == R2_ARCH_THUMB)? op.val: (int)r_reg_getv (core->anal->reg, sn);\n\t\t\tRSyscallItem *si = r_syscall_get (core->anal->syscall, snv, -1);\n\t\t\tif (si) {\n\t\t\t//\teprintf (\"0x%08\"PFMT64x\" SYSCALL %-4d %s\\n\", cur, snv, si->name);\n\t\t\t\tr_flag_set_next (core->flags, r_strf (\"syscall.%s\", si->name), cur, 1);\n\t\t\t} else {\n\t\t\t\t//todo were doing less filtering up top because we can't match against 80 on all platforms\n\t\t\t\t// might get too many of this path now..\n\t\t\t//\teprintf (\"0x%08\"PFMT64x\" SYSCALL %d\\n\", cur, snv);\n\t\t\t\tr_flag_set_next (core->flags, r_strf (\"syscall.%d\", snv), cur, 1);\n\t\t\t}\n\t\t\tr_flag_space_set (core->flags, NULL);\n\t\t\tr_syscall_item_free (si);\n\t\t}\n\t\tconst char *esilstr = R_STRBUF_SAFEGET (&op.esil);\n\t\ti += op.size - 1;\n\t\tif (R_STR_ISEMPTY (esilstr)) {\n\t\t\tgoto repeat;\n\t\t}\n\t\tr_anal_esil_set_pc (ESIL, cur);\n\t\tr_reg_setv (core->anal->reg, pcname, cur + op.size);\n\t\tif (gp_fixed && gp_reg) {\n\t\t\tr_reg_setv (core->anal->reg, gp_reg, gp);\n\t\t}\n\t\t(void)r_anal_esil_parse (ESIL, esilstr);\n\t\t// looks like ^C is handled by esil_parse !!!!\n\t\t//r_anal_esil_dumpstack (ESIL);\n\t\t//r_anal_esil_stack_free (ESIL);\n\t\tswitch (op.type) {\n\t\tcase R_ANAL_OP_TYPE_LEA:\n\t\t\t// arm64\n\t\t\tif (core->anal->cur && arch == R2_ARCH_ARM64) {\n\t\t\t\tif (CHECKREF (ESIL->cur)) {\n\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, ESIL->cur, R_ANAL_REF_TYPE_STRING);\n\t\t\t\t}\n\t\t\t} else if ((target && op.ptr == ntarget) || !target) {\n\t\t\t\tif (CHECKREF (ESIL->cur)) {\n\t\t\t\t\tif (op.ptr && r_io_is_valid_offset (core->io, op.ptr, !core->anal->opt.noncode)) {\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, op.ptr, R_ANAL_REF_TYPE_STRING);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, ESIL->cur, R_ANAL_REF_TYPE_STRING);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (cfg_anal_strings) {\n\t\t\t\tadd_string_ref (core, op.addr, op.ptr);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase R_ANAL_OP_TYPE_ADD:\n\t\t\t/* TODO: test if this is valid for other archs too */\n\t\t\tif (core->anal->cur && archIsArm) {\n\t\t\t\t/* This code is known to work on Thumb, ARM and ARM64 */\n\t\t\t\tut64 dst = ESIL->cur;\n\t\t\t\tif ((target && dst == ntarget) || !target) {\n\t\t\t\t\tif (CHECKREF (dst)) {\n\t\t\t\t\t\tint type = core_type_by_addr (core, dst); // R_ANAL_REF_TYPE_DATA;\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, type);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (cfg_anal_strings) {\n\t\t\t\t\tadd_string_ref (core, op.addr, dst);\n\t\t\t\t}\n\t\t\t} else if ((core->anal->bits == 32 && core->anal->cur && arch == R2_ARCH_MIPS)) {\n\t\t\t\tut64 dst = ESIL->cur;\n\t\t\t\tif (!op.src[0] || !op.src[0]->reg || !op.src[0]->reg->name) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!strcmp (op.src[0]->reg->name, \"sp\")) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!strcmp (op.src[0]->reg->name, \"zero\")) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ((target && dst == ntarget) || !target) {\n\t\t\t\t\tif (dst > 0xffff && op.src[1] && (dst & 0xffff) == (op.src[1]->imm & 0xffff) && myvalid (mycore->io, dst)) {\n\t\t\t\t\t\tRFlagItem *f;\n\t\t\t\t\t\tchar *str;\n\t\t\t\t\t\tif (CHECKREF (dst) || CHECKREF (cur)) {\n\t\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);\n\t\t\t\t\t\t\tif (cfg_anal_strings) {\n\t\t\t\t\t\t\t\tadd_string_ref (core, op.addr, dst);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ((f = r_core_flag_get_by_spaces (core->flags, dst))) {\n\t\t\t\t\t\t\t\tr_meta_set_string (core->anal, R_META_TYPE_COMMENT, cur, f->name);\n\t\t\t\t\t\t\t} else if ((str = is_string_at (mycore, dst, NULL))) {\n\t\t\t\t\t\t\t\tchar *str2 = r_str_newf (\"esilref: '%s'\", str);\n\t\t\t\t\t\t\t\t// HACK avoid format string inside string used later as format\n\t\t\t\t\t\t\t\t// string crashes disasm inside agf under some conditions.\n\t\t\t\t\t\t\t\t// https://github.com/radareorg/radare2/issues/6937\n\t\t\t\t\t\t\t\tr_str_replace_char (str2, '%', '&');\n\t\t\t\t\t\t\t\tr_meta_set_string (core->anal, R_META_TYPE_COMMENT, cur, str2);\n\t\t\t\t\t\t\t\tfree (str2);\n\t\t\t\t\t\t\t\tfree (str);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase R_ANAL_OP_TYPE_LOAD:\n\t\t\t{\n\t\t\t\tut64 dst = esilbreak_last_read;\n\t\t\t\tif (dst != UT64_MAX && CHECKREF (dst)) {\n\t\t\t\t\tif (myvalid (mycore->io, dst)) {\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);\n\t\t\t\t\t\tif (cfg_anal_strings) {\n\t\t\t\t\t\t\tadd_string_ref (core, op.addr, dst);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdst = esilbreak_last_data;\n\t\t\t\tif (dst != UT64_MAX && CHECKREF (dst)) {\n\t\t\t\t\tif (myvalid (mycore->io, dst)) {\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);\n\t\t\t\t\t\tif (cfg_anal_strings) {\n\t\t\t\t\t\t\tadd_string_ref (core, op.addr, dst);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase R_ANAL_OP_TYPE_JMP:\n\t\t\t{\n\t\t\t\tut64 dst = op.jump;\n\t\t\t\tif (CHECKREF (dst)) {\n\t\t\t\t\tif (myvalid (core->io, dst)) {\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_CODE);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase R_ANAL_OP_TYPE_CALL:\n\t\t\t{\n\t\t\t\tut64 dst = op.jump;\n\t\t\t\tif (CHECKREF (dst)) {\n\t\t\t\t\tif (myvalid (core->io, dst)) {\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_CALL);\n\t\t\t\t\t}\n\t\t\t\t\tESIL->old = cur + op.size;\n\t\t\t\t\tgetpcfromstack (core, ESIL);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase R_ANAL_OP_TYPE_UJMP:\n\t\tcase R_ANAL_OP_TYPE_UCALL:\n\t\tcase R_ANAL_OP_TYPE_ICALL:\n\t\tcase R_ANAL_OP_TYPE_RCALL:\n\t\tcase R_ANAL_OP_TYPE_IRCALL:\n\t\tcase R_ANAL_OP_TYPE_MJMP:\n\t\t\t{\n\t\t\t\tut64 dst = core->anal->esil->jump_target;\n\t\t\t\tif (dst == 0 || dst == UT64_MAX) {\n\t\t\t\t\tdst = r_reg_getv (core->anal->reg, pcname);\n\t\t\t\t}\n\t\t\t\tif (CHECKREF (dst)) {\n\t\t\t\t\tif (myvalid (core->io, dst)) {\n\t\t\t\t\t\tRAnalRefType ref =\n\t\t\t\t\t\t\t(op.type & R_ANAL_OP_TYPE_MASK) == R_ANAL_OP_TYPE_UCALL\n\t\t\t\t\t\t\t? R_ANAL_REF_TYPE_CALL\n\t\t\t\t\t\t\t: R_ANAL_REF_TYPE_CODE;\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, ref);\n\t\t\t\t\t\tr_core_anal_fcn (core, dst, UT64_MAX, R_ANAL_REF_TYPE_NULL, 1);\n// analyze function here\n#if 0\n\t\t\t\t\t\tif (op.type == R_ANAL_OP_TYPE_UCALL || op.type == R_ANAL_OP_TYPE_RCALL) {\n\t\t\t\t\t\t\teprintf (\"0x%08\"PFMT64x\"  RCALL TO %llx\\n\", cur, dst);\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tr_anal_esil_stack_free (ESIL);\nrepeat:\n\t\tif (!r_anal_get_block_at (core->anal, cur)) {\n\t\t\tsize_t fcn_i;\n\t\t\tfor (fcn_i = i_old + 1; fcn_i <= i; fcn_i++) {\n\t\t\t\tif (r_anal_get_function_at (core->anal, start + fcn_i)) {\n\t\t\t\t\ti = fcn_i - 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (i >= iend) {\n\t\t\tbreak;\n\t\t}\n\t} while (get_next_i (&ictx, &i));\n\tr_list_free (ictx.bbl);\n\tr_list_free (ictx.path);\n\tr_list_free (ictx.switch_path);\n\tfree (buf);\n\tESIL->cb.hook_mem_read = NULL;\n\tESIL->cb.hook_mem_write = NULL;\n\tESIL->cb.hook_reg_write = NULL;\n\tESIL->user = NULL;\n\tr_anal_op_fini (&op);\n\tr_cons_break_pop ();\n\t// restore register\n\tr_reg_arena_pop (core->anal->reg);\n}", "func_hash": 25949004488581343936391059714889689262, "file_name": "None", "file_hash": null, "cwe": ["CWE-416"], "cve": "CVE-2022-0849", "cve_desc": "Use After Free in r_reg_get_name_idx in GitHub repository radareorg/radare2 prior to 5.6.6.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0849"}
{"idx": 413623, "project": "radare2", "commit_id": "10517e3ff0e609697eb8cde60ec8dc999ee5ea24", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/10517e3ff0e609697eb8cde60ec8dc999ee5ea24", "commit_message": "aaef on arm/thumb switches causes uaf ##crash\n\n* Reported by peacock-doris via huntr.dev\n* Reproducer: poc_uaf_r_reg_get", "target": 0, "func": "R_API void r_core_anal_esil(RCore *core, const char *str, const char *target) {\n\tbool cfg_anal_strings = r_config_get_i (core->config, \"anal.strings\");\n\tbool emu_lazy = r_config_get_i (core->config, \"emu.lazy\");\n\tbool gp_fixed = r_config_get_i (core->config, \"anal.gpfixed\");\n\tRAnalEsil *ESIL = core->anal->esil;\n\tut64 refptr = 0LL;\n\tchar *pcname = NULL;\n\tRAnalOp op = R_EMPTY;\n\tut8 *buf = NULL;\n\tbool end_address_set = false;\n\tint iend;\n\tint minopsize = 4; // XXX this depends on asm->mininstrsize\n\tbool archIsArm = false;\n\tut64 addr = core->offset;\n\tut64 start = addr;\n\tut64 end = 0LL;\n\tut64 cur;\n\tif (esil_anal_stop || r_cons_is_breaked ()) {\n\t\t// faster ^C\n\t\treturn;\n\t}\n\n\tmycore = core;\n\tif (!strcmp (str, \"?\")) {\n\t\teprintf (\"Usage: aae[f] [len] [addr] - analyze refs in function, section or len bytes with esil\\n\");\n\t\teprintf (\"  aae $SS @ $S             - analyze the whole section\\n\");\n\t\teprintf (\"  aae $SS str.Hello @ $S   - find references for str.Hellow\\n\");\n\t\teprintf (\"  aaef                     - analyze functions discovered with esil\\n\");\n\t\treturn;\n\t}\n#define CHECKREF(x) ((refptr && (x) == refptr) || !refptr)\n\tif (target) {\n\t\tconst char *expr = r_str_trim_head_ro (target);\n\t\tif (*expr) {\n\t\t\trefptr = ntarget = r_num_math (core->num, expr);\n\t\t\tif (!refptr) {\n\t\t\t\tntarget = refptr = addr;\n\t\t\t}\n\t\t} else {\n\t\t\tntarget = UT64_MAX;\n\t\t\trefptr = 0LL;\n\t\t}\n\t} else {\n\t\tntarget = UT64_MAX;\n\t\trefptr = 0LL;\n\t}\n\tRAnalFunction *fcn = NULL;\n\tif (!strcmp (str, \"f\")) {\n\t\tfcn = r_anal_get_fcn_in (core->anal, core->offset, 0);\n\t\tif (fcn) {\n\t\t\tstart = r_anal_function_min_addr (fcn);\n\t\t\taddr = fcn->addr;\n\t\t\tend = r_anal_function_max_addr (fcn);\n\t\t\tend_address_set = true;\n\t\t}\n\t}\n\n\tif (!end_address_set) {\n\t\tif (str[0] == ' ') {\n\t\t\tend = addr + r_num_math (core->num, str + 1);\n\t\t} else {\n\t\t\tRIOMap *map = r_io_map_get_at (core->io, addr);\n\t\t\tif (map) {\n\t\t\t\tend = r_io_map_end (map);\n\t\t\t} else {\n\t\t\t\tend = addr + core->blocksize;\n\t\t\t}\n\t\t}\n\t}\n\n\tiend = end - start;\n\tif (iend < 0) {\n\t\treturn;\n\t}\n\tif (iend > MAX_SCAN_SIZE) {\n\t\teprintf (\"Warning: Not going to analyze 0x%08\"PFMT64x\" bytes.\\n\", (ut64)iend);\n\t\treturn;\n\t}\n\tbuf = malloc ((size_t)iend + 2);\n\tif (!buf) {\n\t\tperror (\"malloc\");\n\t\treturn;\n\t}\n\tesilbreak_last_read = UT64_MAX;\n\tr_io_read_at (core->io, start, buf, iend + 1);\n\tif (!ESIL) {\n\t\tr_core_cmd0 (core, \"aei\");\n\t\tESIL = core->anal->esil;\n\t\tif (!ESIL) {\n\t\t\teprintf (\"ESIL not initialized\\n\");\n\t\t\treturn;\n\t\t}\n\t\tr_core_cmd0 (core, \"aeim\");\n\t\tESIL = core->anal->esil;\n\t}\n\tconst char *kspname = r_reg_get_name (core->anal->reg, R_REG_NAME_SP);\n\tif (R_STR_ISEMPTY (kspname)) {\n\t\teprintf (\"Error: No =SP defined in the reg profile.\\n\");\n\t\treturn;\n\t}\n\tchar *spname = strdup (kspname);\n\tEsilBreakCtx ctx = {\n\t\t&op,\n\t\tfcn,\n\t\tspname,\n\t\tr_reg_getv (core->anal->reg, spname)\n\t};\n\tESIL->cb.hook_reg_write = &esilbreak_reg_write;\n\t//this is necessary for the hook to read the id of analop\n\tESIL->user = &ctx;\n\tESIL->cb.hook_mem_read = &esilbreak_mem_read;\n\tESIL->cb.hook_mem_write = &esilbreak_mem_write;\n\n\tif (fcn && fcn->reg_save_area) {\n\t\tr_reg_setv (core->anal->reg, ctx.spname, ctx.initial_sp - fcn->reg_save_area);\n\t}\n\t//eprintf (\"Analyzing ESIL refs from 0x%\"PFMT64x\" - 0x%\"PFMT64x\"\\n\", addr, end);\n\t// TODO: backup/restore register state before/after analysis\n\tconst char *kpcname = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);\n\tif (!kpcname || !*kpcname) {\n\t\teprintf (\"Cannot find program counter register in the current profile.\\n\");\n\t\treturn;\n\t}\n\tpcname = strdup (kpcname);\n\tesil_anal_stop = false;\n\tr_cons_break_push (cccb, core);\n\n\tint arch = -1;\n\tif (!strcmp (core->anal->cur->arch, \"arm\")) {\n\t\tswitch (core->anal->cur->bits) {\n\t\tcase 64: arch = R2_ARCH_ARM64; break;\n\t\tcase 32: arch = R2_ARCH_ARM32; break;\n\t\tcase 16: arch = R2_ARCH_THUMB; break;\n\t\t}\n\t\tarchIsArm = true;\n\t}\n\n\tut64 gp = r_config_get_i (core->config, \"anal.gp\");\n\tconst char *gp_reg = NULL;\n\tif (!strcmp (core->anal->cur->arch, \"mips\")) {\n\t\tgp_reg = \"gp\";\n\t\tarch = R2_ARCH_MIPS;\n\t}\n\n\tconst char *sn = r_reg_get_name (core->anal->reg, R_REG_NAME_SN);\n\tif (!sn) {\n\t\teprintf (\"Warning: No SN reg alias for current architecture.\\n\");\n\t}\n\tr_reg_arena_push (core->anal->reg);\n\n\tIterCtx ictx = { start, end, fcn, NULL };\n\tsize_t i = addr - start;\n\tsize_t i_old = 0;\n\tdo {\n\t\tif (esil_anal_stop || r_cons_is_breaked ()) {\n\t\t\tbreak;\n\t\t}\n\t\tcur = start + i;\n\t\tif (!r_io_is_valid_offset (core->io, cur, 0)) {\n\t\t\tbreak;\n\t\t}\n#if 0\n\t\t// disabled because it causes some tests to fail\n\t\t{\n\t\t\tRPVector *list = r_meta_get_all_in (core->anal, cur, R_META_TYPE_ANY);\n\t\t\tvoid **it;\n\t\t\tr_pvector_foreach (list, it) {\n\t\t\t\tRIntervalNode *node = *it;\n\t\t\t\tRAnalMetaItem *meta = node->data;\n\t\t\t\tswitch (meta->type) {\n\t\t\t\tcase R_META_TYPE_DATA:\n\t\t\t\tcase R_META_TYPE_STRING:\n\t\t\t\tcase R_META_TYPE_FORMAT:\n#if 0\n\t\t\t\t\t{\n\t\t\t\t\t\tint msz = r_meta_get_size (core->anal, meta->type);\n\t\t\t\t\t\ti += (msz > 0)? msz: minopsize;\n\t\t\t\t\t}\n\t\t\t\t\tr_pvector_free (list);\n\t\t\t\t\tgoto loopback;\n#elif 0\n\t\t\t\t\t{\n\t\t\t\t\t\tint msz = r_meta_get_size (core->anal, meta->type);\n\t\t\t\t\t\ti += (msz > 0)? msz: minopsize;\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n#else\n\t\t\t\t\ti += 4;\n\t\t\t\t\tgoto repeat;\n#endif\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tr_pvector_free (list);\n\t\t}\n#endif\n\n\t\t/* realign address if needed */\n\t\tr_core_seek_arch_bits (core, cur);\n\t\tint opalign = core->anal->pcalign;\n\t\tif (opalign > 0) {\n\t\t\tcur -= (cur % opalign);\n\t\t}\n\n\t\tr_anal_op_fini (&op);\n\t\tr_asm_set_pc (core->rasm, cur);\n\t\ti_old = i;\n\t\tif (i > iend) {\n\t\t\tgoto repeat;\n\t\t}\n\t\tif (!r_anal_op (core->anal, &op, cur, buf + i, iend - i, R_ANAL_OP_MASK_ESIL | R_ANAL_OP_MASK_VAL | R_ANAL_OP_MASK_HINT)) {\n\t\t\ti += minopsize - 1; //   XXX dupe in op.size below\n\t\t}\n\t\tif (op.type == R_ANAL_OP_TYPE_ILL || op.type == R_ANAL_OP_TYPE_UNK) {\n\t\t\t// i += 2\n\t\t\tr_anal_op_fini (&op);\n\t\t\tgoto repeat;\n\t\t}\n\t\t//we need to check again i because buf+i may goes beyond its boundaries\n\t\t//because of i+= minopsize - 1\n\t\tif (op.size < 1) {\n\t\t\ti += minopsize - 1;\n\t\t\tgoto repeat;\n\t\t}\n\t\tif (emu_lazy) {\n\t\t\tif (op.type & R_ANAL_OP_TYPE_REP) {\n\t\t\t\ti += op.size - 1;\n\t\t\t\tgoto repeat;\n\t\t\t}\n\t\t\tswitch (op.type & R_ANAL_OP_TYPE_MASK) {\n\t\t\tcase R_ANAL_OP_TYPE_JMP:\n\t\t\tcase R_ANAL_OP_TYPE_CJMP:\n\t\t\tcase R_ANAL_OP_TYPE_CALL:\n\t\t\tcase R_ANAL_OP_TYPE_RET:\n\t\t\tcase R_ANAL_OP_TYPE_ILL:\n\t\t\tcase R_ANAL_OP_TYPE_NOP:\n\t\t\tcase R_ANAL_OP_TYPE_UJMP:\n\t\t\tcase R_ANAL_OP_TYPE_IO:\n\t\t\tcase R_ANAL_OP_TYPE_LEAVE:\n\t\t\tcase R_ANAL_OP_TYPE_CRYPTO:\n\t\t\tcase R_ANAL_OP_TYPE_CPL:\n\t\t\tcase R_ANAL_OP_TYPE_SYNC:\n\t\t\tcase R_ANAL_OP_TYPE_SWI:\n\t\t\tcase R_ANAL_OP_TYPE_CMP:\n\t\t\tcase R_ANAL_OP_TYPE_ACMP:\n\t\t\tcase R_ANAL_OP_TYPE_NULL:\n\t\t\tcase R_ANAL_OP_TYPE_CSWI:\n\t\t\tcase R_ANAL_OP_TYPE_TRAP:\n\t\t\t\ti += op.size - 1;\n\t\t\t\tgoto repeat;\n\t\t\t//  those require write support\n\t\t\tcase R_ANAL_OP_TYPE_PUSH:\n\t\t\tcase R_ANAL_OP_TYPE_POP:\n\t\t\t\ti += op.size - 1;\n\t\t\t\tgoto repeat;\n\t\t\t}\n\t\t}\n\t\tif (sn && op.type == R_ANAL_OP_TYPE_SWI) {\n\t\t\tr_strf_buffer (64);\n\t\t\tr_flag_space_set (core->flags, R_FLAGS_FS_SYSCALLS);\n\t\t\tint snv = (arch == R2_ARCH_THUMB)? op.val: (int)r_reg_getv (core->anal->reg, sn);\n\t\t\tRSyscallItem *si = r_syscall_get (core->anal->syscall, snv, -1);\n\t\t\tif (si) {\n\t\t\t//\teprintf (\"0x%08\"PFMT64x\" SYSCALL %-4d %s\\n\", cur, snv, si->name);\n\t\t\t\tr_flag_set_next (core->flags, r_strf (\"syscall.%s\", si->name), cur, 1);\n\t\t\t} else {\n\t\t\t\t//todo were doing less filtering up top because we can't match against 80 on all platforms\n\t\t\t\t// might get too many of this path now..\n\t\t\t//\teprintf (\"0x%08\"PFMT64x\" SYSCALL %d\\n\", cur, snv);\n\t\t\t\tr_flag_set_next (core->flags, r_strf (\"syscall.%d\", snv), cur, 1);\n\t\t\t}\n\t\t\tr_flag_space_set (core->flags, NULL);\n\t\t\tr_syscall_item_free (si);\n\t\t}\n\t\tconst char *esilstr = R_STRBUF_SAFEGET (&op.esil);\n\t\ti += op.size - 1;\n\t\tif (R_STR_ISEMPTY (esilstr)) {\n\t\t\tgoto repeat;\n\t\t}\n\t\tr_anal_esil_set_pc (ESIL, cur);\n\t\tr_reg_setv (core->anal->reg, pcname, cur + op.size);\n\t\tif (gp_fixed && gp_reg) {\n\t\t\tr_reg_setv (core->anal->reg, gp_reg, gp);\n\t\t}\n\t\t(void)r_anal_esil_parse (ESIL, esilstr);\n\t\t// looks like ^C is handled by esil_parse !!!!\n\t\t//r_anal_esil_dumpstack (ESIL);\n\t\t//r_anal_esil_stack_free (ESIL);\n\t\tswitch (op.type) {\n\t\tcase R_ANAL_OP_TYPE_LEA:\n\t\t\t// arm64\n\t\t\tif (core->anal->cur && arch == R2_ARCH_ARM64) {\n\t\t\t\tif (CHECKREF (ESIL->cur)) {\n\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, ESIL->cur, R_ANAL_REF_TYPE_STRING);\n\t\t\t\t}\n\t\t\t} else if ((target && op.ptr == ntarget) || !target) {\n\t\t\t\tif (CHECKREF (ESIL->cur)) {\n\t\t\t\t\tif (op.ptr && r_io_is_valid_offset (core->io, op.ptr, !core->anal->opt.noncode)) {\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, op.ptr, R_ANAL_REF_TYPE_STRING);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, ESIL->cur, R_ANAL_REF_TYPE_STRING);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (cfg_anal_strings) {\n\t\t\t\tadd_string_ref (core, op.addr, op.ptr);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase R_ANAL_OP_TYPE_ADD:\n\t\t\t/* TODO: test if this is valid for other archs too */\n\t\t\tif (core->anal->cur && archIsArm) {\n\t\t\t\t/* This code is known to work on Thumb, ARM and ARM64 */\n\t\t\t\tut64 dst = ESIL->cur;\n\t\t\t\tif ((target && dst == ntarget) || !target) {\n\t\t\t\t\tif (CHECKREF (dst)) {\n\t\t\t\t\t\tint type = core_type_by_addr (core, dst); // R_ANAL_REF_TYPE_DATA;\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, type);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (cfg_anal_strings) {\n\t\t\t\t\tadd_string_ref (core, op.addr, dst);\n\t\t\t\t}\n\t\t\t} else if ((core->anal->bits == 32 && core->anal->cur && arch == R2_ARCH_MIPS)) {\n\t\t\t\tut64 dst = ESIL->cur;\n\t\t\t\tif (!op.src[0] || !op.src[0]->reg || !op.src[0]->reg->name) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!strcmp (op.src[0]->reg->name, \"sp\")) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!strcmp (op.src[0]->reg->name, \"zero\")) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ((target && dst == ntarget) || !target) {\n\t\t\t\t\tif (dst > 0xffff && op.src[1] && (dst & 0xffff) == (op.src[1]->imm & 0xffff) && myvalid (mycore->io, dst)) {\n\t\t\t\t\t\tRFlagItem *f;\n\t\t\t\t\t\tchar *str;\n\t\t\t\t\t\tif (CHECKREF (dst) || CHECKREF (cur)) {\n\t\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);\n\t\t\t\t\t\t\tif (cfg_anal_strings) {\n\t\t\t\t\t\t\t\tadd_string_ref (core, op.addr, dst);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ((f = r_core_flag_get_by_spaces (core->flags, dst))) {\n\t\t\t\t\t\t\t\tr_meta_set_string (core->anal, R_META_TYPE_COMMENT, cur, f->name);\n\t\t\t\t\t\t\t} else if ((str = is_string_at (mycore, dst, NULL))) {\n\t\t\t\t\t\t\t\tchar *str2 = r_str_newf (\"esilref: '%s'\", str);\n\t\t\t\t\t\t\t\t// HACK avoid format string inside string used later as format\n\t\t\t\t\t\t\t\t// string crashes disasm inside agf under some conditions.\n\t\t\t\t\t\t\t\t// https://github.com/radareorg/radare2/issues/6937\n\t\t\t\t\t\t\t\tr_str_replace_char (str2, '%', '&');\n\t\t\t\t\t\t\t\tr_meta_set_string (core->anal, R_META_TYPE_COMMENT, cur, str2);\n\t\t\t\t\t\t\t\tfree (str2);\n\t\t\t\t\t\t\t\tfree (str);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase R_ANAL_OP_TYPE_LOAD:\n\t\t\t{\n\t\t\t\tut64 dst = esilbreak_last_read;\n\t\t\t\tif (dst != UT64_MAX && CHECKREF (dst)) {\n\t\t\t\t\tif (myvalid (mycore->io, dst)) {\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);\n\t\t\t\t\t\tif (cfg_anal_strings) {\n\t\t\t\t\t\t\tadd_string_ref (core, op.addr, dst);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdst = esilbreak_last_data;\n\t\t\t\tif (dst != UT64_MAX && CHECKREF (dst)) {\n\t\t\t\t\tif (myvalid (mycore->io, dst)) {\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);\n\t\t\t\t\t\tif (cfg_anal_strings) {\n\t\t\t\t\t\t\tadd_string_ref (core, op.addr, dst);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase R_ANAL_OP_TYPE_JMP:\n\t\t\t{\n\t\t\t\tut64 dst = op.jump;\n\t\t\t\tif (CHECKREF (dst)) {\n\t\t\t\t\tif (myvalid (core->io, dst)) {\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_CODE);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase R_ANAL_OP_TYPE_CALL:\n\t\t\t{\n\t\t\t\tut64 dst = op.jump;\n\t\t\t\tif (CHECKREF (dst)) {\n\t\t\t\t\tif (myvalid (core->io, dst)) {\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_CALL);\n\t\t\t\t\t}\n\t\t\t\t\tESIL->old = cur + op.size;\n\t\t\t\t\tgetpcfromstack (core, ESIL);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase R_ANAL_OP_TYPE_UJMP:\n\t\tcase R_ANAL_OP_TYPE_UCALL:\n\t\tcase R_ANAL_OP_TYPE_ICALL:\n\t\tcase R_ANAL_OP_TYPE_RCALL:\n\t\tcase R_ANAL_OP_TYPE_IRCALL:\n\t\tcase R_ANAL_OP_TYPE_MJMP:\n\t\t\t{\n\t\t\t\tut64 dst = core->anal->esil->jump_target;\n\t\t\t\tif (dst == 0 || dst == UT64_MAX) {\n\t\t\t\t\tdst = r_reg_getv (core->anal->reg, pcname);\n\t\t\t\t}\n\t\t\t\tif (CHECKREF (dst)) {\n\t\t\t\t\tif (myvalid (core->io, dst)) {\n\t\t\t\t\t\tRAnalRefType ref =\n\t\t\t\t\t\t\t(op.type & R_ANAL_OP_TYPE_MASK) == R_ANAL_OP_TYPE_UCALL\n\t\t\t\t\t\t\t? R_ANAL_REF_TYPE_CALL\n\t\t\t\t\t\t\t: R_ANAL_REF_TYPE_CODE;\n\t\t\t\t\t\tr_anal_xrefs_set (core->anal, cur, dst, ref);\n\t\t\t\t\t\tr_core_anal_fcn (core, dst, UT64_MAX, R_ANAL_REF_TYPE_NULL, 1);\n// analyze function here\n#if 0\n\t\t\t\t\t\tif (op.type == R_ANAL_OP_TYPE_UCALL || op.type == R_ANAL_OP_TYPE_RCALL) {\n\t\t\t\t\t\t\teprintf (\"0x%08\"PFMT64x\"  RCALL TO %llx\\n\", cur, dst);\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tr_anal_esil_stack_free (ESIL);\nrepeat:\n\t\tif (!r_anal_get_block_at (core->anal, cur)) {\n\t\t\tsize_t fcn_i;\n\t\t\tfor (fcn_i = i_old + 1; fcn_i <= i; fcn_i++) {\n\t\t\t\tif (r_anal_get_function_at (core->anal, start + fcn_i)) {\n\t\t\t\t\ti = fcn_i - 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (i >= iend) {\n\t\t\tbreak;\n\t\t}\n\t} while (get_next_i (&ictx, &i));\n\tfree (pcname);\n\tfree (spname);\n\tr_list_free (ictx.bbl);\n\tr_list_free (ictx.path);\n\tr_list_free (ictx.switch_path);\n\tfree (buf);\n\tESIL->cb.hook_mem_read = NULL;\n\tESIL->cb.hook_mem_write = NULL;\n\tESIL->cb.hook_reg_write = NULL;\n\tESIL->user = NULL;\n\tr_anal_op_fini (&op);\n\tr_cons_break_pop ();\n\t// restore register\n\tr_reg_arena_pop (core->anal->reg);\n}", "func_hash": 238488437783667654322031890485445145764, "file_name": "None", "file_hash": null, "cwe": ["CWE-416"], "cve": "CVE-2022-0849", "cve_desc": "Use After Free in r_reg_get_name_idx in GitHub repository radareorg/radare2 prior to 5.6.6.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0849"}
{"idx": 208912, "project": "vim", "commit_id": "1c3dd8ddcba63c1af5112e567215b3cec2de11d0", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/1c3dd8ddcba63c1af5112e567215b3cec2de11d0", "commit_message": "patch 9.0.0490: using freed memory with cmdwin and BufEnter autocmd\n\nProblem:    Using freed memory with cmdwin and BufEnter autocmd.\nSolution:   Make sure pointer to b_p_iminsert is still valid.", "target": 1, "func": "getcmdline_int(\n    int\t\tfirstc,\n    long\tcount UNUSED,\t// only used for incremental search\n    int\t\tindent,\t\t// indent for inside conditionals\n    int\t\tclear_ccline)\t// clear ccline first\n{\n    static int\tdepth = 0;\t    // call depth\n    int\t\tc;\n    int\t\ti;\n    int\t\tj;\n    int\t\tgotesc = FALSE;\t\t// TRUE when  just typed\n    int\t\tdo_abbr;\t\t// when TRUE check for abbr.\n    char_u\t*lookfor = NULL;\t// string to match\n    int\t\thiscnt;\t\t\t// current history line in use\n    int\t\thistype;\t\t// history type to be used\n#ifdef FEAT_SEARCH_EXTRA\n    incsearch_state_T\tis_state;\n#endif\n    int\t\tdid_wild_list = FALSE;\t// did wild_list() recently\n    int\t\twim_index = 0;\t\t// index in wim_flags[]\n    int\t\tres;\n    int\t\tsave_msg_scroll = msg_scroll;\n    int\t\tsave_State = State;\t// remember State when called\n    int\t\tsome_key_typed = FALSE;\t// one of the keys was typed\n    // mouse drag and release events are ignored, unless they are\n    // preceded with a mouse down event\n    int\t\tignore_drag_release = TRUE;\n#ifdef FEAT_EVAL\n    int\t\tbreak_ctrl_c = FALSE;\n#endif\n    expand_T\txpc;\n    long\t*b_im_ptr = NULL;\n    cmdline_info_T save_ccline;\n    int\t\tdid_save_ccline = FALSE;\n    int\t\tcmdline_type;\n    int\t\twild_type;\n\n    // one recursion level deeper\n    ++depth;\n\n    if (ccline.cmdbuff != NULL)\n    {\n\t// Being called recursively.  Since ccline is global, we need to save\n\t// the current buffer and restore it when returning.\n\tsave_cmdline(&save_ccline);\n\tdid_save_ccline = TRUE;\n    }\n    if (clear_ccline)\n\tCLEAR_FIELD(ccline);\n\n#ifdef FEAT_EVAL\n    if (firstc == -1)\n    {\n\tfirstc = NUL;\n\tbreak_ctrl_c = TRUE;\n    }\n#endif\n#ifdef FEAT_RIGHTLEFT\n    // start without Hebrew mapping for a command line\n    if (firstc == ':' || firstc == '=' || firstc == '>')\n\tcmd_hkmap = 0;\n#endif\n\n#ifdef FEAT_SEARCH_EXTRA\n    init_incsearch_state(&is_state);\n#endif\n\n    if (init_ccline(firstc, indent) != OK)\n\tgoto theend;\t// out of memory\n\n    if (depth == 50)\n    {\n\t// Somehow got into a loop recursively calling getcmdline(), bail out.\n\temsg(_(e_command_too_recursive));\n\tgoto theend;\n    }\n\n    ExpandInit(&xpc);\n    ccline.xpc = &xpc;\n\n#ifdef FEAT_RIGHTLEFT\n    if (curwin->w_p_rl && *curwin->w_p_rlc == 's'\n\t\t\t\t\t  && (firstc == '/' || firstc == '?'))\n\tcmdmsg_rl = TRUE;\n    else\n\tcmdmsg_rl = FALSE;\n#endif\n\n    redir_off = TRUE;\t\t// don't redirect the typed command\n    if (!cmd_silent)\n    {\n\ti = msg_scrolled;\n\tmsg_scrolled = 0;\t\t// avoid wait_return() message\n\tgotocmdline(TRUE);\n\tmsg_scrolled += i;\n\tredrawcmdprompt();\t\t// draw prompt or indent\n\tset_cmdspos();\n    }\n    xpc.xp_context = EXPAND_NOTHING;\n    xpc.xp_backslash = XP_BS_NONE;\n#ifndef BACKSLASH_IN_FILENAME\n    xpc.xp_shell = FALSE;\n#endif\n\n#if defined(FEAT_EVAL)\n    if (ccline.input_fn)\n    {\n\txpc.xp_context = ccline.xp_context;\n\txpc.xp_pattern = ccline.cmdbuff;\n\txpc.xp_arg = ccline.xp_arg;\n    }\n#endif\n\n    /*\n     * Avoid scrolling when called by a recursive do_cmdline(), e.g. when\n     * doing \":@0\" when register 0 doesn't contain a CR.\n     */\n    msg_scroll = FALSE;\n\n    State = MODE_CMDLINE;\n\n    if (firstc == '/' || firstc == '?' || firstc == '@')\n    {\n\t// Use \":lmap\" mappings for search pattern and input().\n\tif (curbuf->b_p_imsearch == B_IMODE_USE_INSERT)\n\t    b_im_ptr = &curbuf->b_p_iminsert;\n\telse\n\t    b_im_ptr = &curbuf->b_p_imsearch;\n\tif (*b_im_ptr == B_IMODE_LMAP)\n\t    State |= MODE_LANGMAP;\n#ifdef HAVE_INPUT_METHOD\n\tim_set_active(*b_im_ptr == B_IMODE_IM);\n#endif\n    }\n#ifdef HAVE_INPUT_METHOD\n    else if (p_imcmdline)\n\tim_set_active(TRUE);\n#endif\n\n    setmouse();\n#ifdef CURSOR_SHAPE\n    ui_cursor_shape();\t\t// may show different cursor shape\n#endif\n\n    // When inside an autocommand for writing \"exiting\" may be set and\n    // terminal mode set to cooked.  Need to set raw mode here then.\n    settmode(TMODE_RAW);\n\n    // Trigger CmdlineEnter autocommands.\n    cmdline_type = firstc == NUL ? '-' : firstc;\n    trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINEENTER);\n#ifdef FEAT_EVAL\n    if (!debug_mode)\n\tmay_trigger_modechanged();\n#endif\n\n    init_history();\n    hiscnt = get_hislen();\t// set hiscnt to impossible history value\n    histype = hist_char2type(firstc);\n\n#ifdef FEAT_DIGRAPHS\n    do_digraph(-1);\t\t// init digraph typeahead\n#endif\n\n    // If something above caused an error, reset the flags, we do want to type\n    // and execute commands. Display may be messed up a bit.\n    if (did_emsg)\n\tredrawcmd();\n\n#ifdef FEAT_STL_OPT\n    // Redraw the statusline in case it uses the current mode using the mode()\n    // function.\n    if (!cmd_silent && msg_scrolled == 0)\n    {\n\tint\tfound_one = FALSE;\n\twin_T\t*wp;\n\n\tFOR_ALL_WINDOWS(wp)\n\t    if (*p_stl != NUL || *wp->w_p_stl != NUL)\n\t    {\n\t\twp->w_redr_status = TRUE;\n\t\tfound_one = TRUE;\n\t    }\n\n\tif (*p_tal != NUL)\n\t{\n\t    redraw_tabline = TRUE;\n\t    found_one = TRUE;\n\t}\n\n\tif (found_one)\n\t    redraw_statuslines();\n    }\n#endif\n\n    did_emsg = FALSE;\n    got_int = FALSE;\n\n    /*\n     * Collect the command string, handling editing keys.\n     */\n    for (;;)\n    {\n\tint trigger_cmdlinechanged = TRUE;\n\tint end_wildmenu;\n\n\tredir_off = TRUE;\t// Don't redirect the typed command.\n\t\t\t\t// Repeated, because a \":redir\" inside\n\t\t\t\t// completion may switch it on.\n#ifdef USE_ON_FLY_SCROLL\n\tdont_scroll = FALSE;\t// allow scrolling here\n#endif\n\tquit_more = FALSE;\t// reset after CTRL-D which had a more-prompt\n\n\tdid_emsg = FALSE;\t// There can't really be a reason why an error\n\t\t\t\t// that occurs while typing a command should\n\t\t\t\t// cause the command not to be executed.\n\n\t// Trigger SafeState if nothing is pending.\n\tmay_trigger_safestate(xpc.xp_numfiles <= 0);\n\n\t// Get a character.  Ignore K_IGNORE and K_NOP, they should not do\n\t// anything, such as stop completion.\n\tdo\n\t{\n\t    cursorcmd();\t\t// set the cursor on the right spot\n\t    c = safe_vgetc();\n\t} while (c == K_IGNORE || c == K_NOP);\n\n\tif (c == K_COMMAND || c == K_SCRIPT_COMMAND)\n\t{\n\t    int\t    clen = ccline.cmdlen;\n\n\t    if (do_cmdkey_command(c, DOCMD_NOWAIT) == OK)\n\t    {\n\t\tif (clen == ccline.cmdlen)\n\t\t    trigger_cmdlinechanged = FALSE;\n\t\tgoto cmdline_changed;\n\t    }\n\t}\n\n\tif (KeyTyped)\n\t{\n\t    some_key_typed = TRUE;\n#ifdef FEAT_RIGHTLEFT\n\t    if (cmd_hkmap)\n\t\tc = hkmap(c);\n\t    if (cmdmsg_rl && !KeyStuffed)\n\t    {\n\t\t// Invert horizontal movements and operations.  Only when\n\t\t// typed by the user directly, not when the result of a\n\t\t// mapping.\n\t\tswitch (c)\n\t\t{\n\t\t    case K_RIGHT:   c = K_LEFT; break;\n\t\t    case K_S_RIGHT: c = K_S_LEFT; break;\n\t\t    case K_C_RIGHT: c = K_C_LEFT; break;\n\t\t    case K_LEFT:    c = K_RIGHT; break;\n\t\t    case K_S_LEFT:  c = K_S_RIGHT; break;\n\t\t    case K_C_LEFT:  c = K_C_RIGHT; break;\n\t\t}\n\t    }\n#endif\n\t}\n\n\t/*\n\t * Ignore got_int when CTRL-C was typed here.\n\t * Don't ignore it in :global, we really need to break then, e.g., for\n\t * \":g/pat/normal /pat\" (without the ).\n\t * Don't ignore it for the input() function.\n\t */\n\tif ((c == Ctrl_C\n#ifdef UNIX\n\t\t|| c == intr_char\n#endif\n\t\t\t\t)\n#if defined(FEAT_EVAL) || defined(FEAT_CRYPT)\n\t\t&& firstc != '@'\n#endif\n#ifdef FEAT_EVAL\n\t\t// do clear got_int in Ex mode to avoid infinite Ctrl-C loop\n\t\t&& (!break_ctrl_c || exmode_active)\n#endif\n\t\t&& !global_busy)\n\t    got_int = FALSE;\n\n\t// free old command line when finished moving around in the history\n\t// list\n\tif (lookfor != NULL\n\t\t&& c != K_S_DOWN && c != K_S_UP\n\t\t&& c != K_DOWN && c != K_UP\n\t\t&& c != K_PAGEDOWN && c != K_PAGEUP\n\t\t&& c != K_KPAGEDOWN && c != K_KPAGEUP\n\t\t&& c != K_LEFT && c != K_RIGHT\n\t\t&& (xpc.xp_numfiles > 0 || (c != Ctrl_P && c != Ctrl_N)))\n\t    VIM_CLEAR(lookfor);\n\n\t/*\n\t * When there are matching completions to select  works like\n\t * CTRL-P (unless 'wc' is ).\n\t */\n\tif (c != p_wc && c == K_S_TAB && xpc.xp_numfiles > 0)\n\t    c = Ctrl_P;\n\n\tif (p_wmnu)\n\t    c = wildmenu_translate_key(&ccline, c, &xpc, did_wild_list);\n\n\tif (cmdline_pum_active())\n\t{\n\t    // Ctrl-Y: Accept the current selection and close the popup menu.\n\t    // Ctrl-E: cancel the cmdline popup menu and return the original\n\t    // text.\n\t    if (c == Ctrl_E || c == Ctrl_Y)\n\t    {\n\t\twild_type = (c == Ctrl_E) ? WILD_CANCEL : WILD_APPLY;\n\t\tif (nextwild(&xpc, wild_type, WILD_NO_BEEP,\n\t\t\t\t\t\t\tfirstc != '@') == FAIL)\n\t\t    break;\n\t\tc = Ctrl_E;\n\t    }\n\t}\n\n\t// The wildmenu is cleared if the pressed key is not used for\n\t// navigating the wild menu (i.e. the key is not 'wildchar' or\n\t// 'wildcharm' or Ctrl-N or Ctrl-P or Ctrl-A or Ctrl-L).\n\t// If the popup menu is displayed, then PageDown and PageUp keys are\n\t// also used to navigate the menu.\n\tend_wildmenu = (!(c == p_wc && KeyTyped) && c != p_wcm\n\t\t&& c != Ctrl_N && c != Ctrl_P && c != Ctrl_A && c != Ctrl_L);\n\tend_wildmenu = end_wildmenu && (!cmdline_pum_active() ||\n\t\t\t    (c != K_PAGEDOWN && c != K_PAGEUP\n\t\t\t     && c != K_KPAGEDOWN && c != K_KPAGEUP));\n\n\t// free expanded names when finished walking through matches\n\tif (end_wildmenu)\n\t{\n\t    if (cmdline_pum_active())\n\t\tcmdline_pum_remove();\n\t    if (xpc.xp_numfiles != -1)\n\t\t(void)ExpandOne(&xpc, NULL, NULL, 0, WILD_FREE);\n\t    did_wild_list = FALSE;\n\t    if (!p_wmnu || (c != K_UP && c != K_DOWN))\n\t\txpc.xp_context = EXPAND_NOTHING;\n\t    wim_index = 0;\n\t    wildmenu_cleanup(&ccline);\n\t}\n\n\tif (p_wmnu)\n\t    c = wildmenu_process_key(&ccline, c, &xpc);\n\n\t// CTRL-\\ CTRL-N goes to Normal mode, CTRL-\\ CTRL-G goes to Insert\n\t// mode when 'insertmode' is set, CTRL-\\ e prompts for an expression.\n\tif (c == Ctrl_BSL)\n\t{\n\t    res = cmdline_handle_backslash_key(c, &gotesc);\n\t    if (res == CMDLINE_CHANGED)\n\t\tgoto cmdline_changed;\n\t    else if (res == CMDLINE_NOT_CHANGED)\n\t\tgoto cmdline_not_changed;\n\t    else if (res == GOTO_NORMAL_MODE)\n\t\tgoto returncmd;\t\t// back to cmd mode\n\t    c = Ctrl_BSL;\t\t// backslash key not processed by\n\t\t\t\t\t// cmdline_handle_backslash_key()\n\t}\n\n#ifdef FEAT_CMDWIN\n\tif (c == cedit_key || c == K_CMDWIN)\n\t{\n\t    // TODO: why is ex_normal_busy checked here?\n\t    if ((c == K_CMDWIN || ex_normal_busy == 0) && got_int == FALSE)\n\t    {\n\t\t/*\n\t\t * Open a window to edit the command line (and history).\n\t\t */\n\t\tc = open_cmdwin();\n\t\tsome_key_typed = TRUE;\n\t    }\n\t}\n# ifdef FEAT_DIGRAPHS\n\telse\n# endif\n#endif\n#ifdef FEAT_DIGRAPHS\n\t    c = do_digraph(c);\n#endif\n\n\tif (c == '\\n' || c == '\\r' || c == K_KENTER || (c == ESC\n\t\t\t&& (!KeyTyped || vim_strchr(p_cpo, CPO_ESC) != NULL)))\n\t{\n\t    // In Ex mode a backslash escapes a newline.\n\t    if (exmode_active\n\t\t    && c != ESC\n\t\t    && ccline.cmdpos == ccline.cmdlen\n\t\t    && ccline.cmdpos > 0\n\t\t    && ccline.cmdbuff[ccline.cmdpos - 1] == '\\\\')\n\t    {\n\t\tif (c == K_KENTER)\n\t\t    c = '\\n';\n\t    }\n\t    else\n\t    {\n\t\tgotesc = FALSE;\t// Might have typed ESC previously, don't\n\t\t\t\t// truncate the cmdline now.\n\t\tif (ccheck_abbr(c + ABBR_OFF))\n\t\t    goto cmdline_changed;\n\t\tif (!cmd_silent)\n\t\t{\n\t\t    windgoto(msg_row, 0);\n\t\t    out_flush();\n\t\t}\n\t\tbreak;\n\t    }\n\t}\n\n\t// Completion for 'wildchar' or 'wildcharm' key.\n\tif ((c == p_wc && !gotesc && KeyTyped) || c == p_wcm)\n\t{\n\t    res = cmdline_wildchar_complete(c, firstc != '@', &did_wild_list,\n\t\t    &wim_index, &xpc, &gotesc);\n\t    if (res == CMDLINE_CHANGED)\n\t\tgoto cmdline_changed;\n\t}\n\n\tgotesc = FALSE;\n\n\t//  goes to last match, in a clumsy way\n\tif (c == K_S_TAB && KeyTyped)\n\t{\n\t    if (nextwild(&xpc, WILD_EXPAND_KEEP, 0, firstc != '@') == OK)\n\t    {\n\t\tif (xpc.xp_numfiles > 1\n\t\t    && ((!did_wild_list && (wim_flags[wim_index] & WIM_LIST))\n\t\t\t    || p_wmnu))\n\t\t{\n\t\t    // Trigger the popup menu when wildoptions=pum\n\t\t    showmatches(&xpc, p_wmnu\n\t\t\t    && ((wim_flags[wim_index] & WIM_LIST) == 0));\n\t\t}\n\t\tif (nextwild(&xpc, WILD_PREV, 0, firstc != '@') == OK\n\t\t\t&& nextwild(&xpc, WILD_PREV, 0, firstc != '@') == OK)\n\t\t    goto cmdline_changed;\n\t    }\n\t}\n\n\tif (c == NUL || c == K_ZERO)\t    // NUL is stored as NL\n\t    c = NL;\n\n\tdo_abbr = TRUE;\t\t// default: check for abbreviation\n\n\t/*\n\t * Big switch for a typed command line character.\n\t */\n\tswitch (c)\n\t{\n\tcase K_BS:\n\tcase Ctrl_H:\n\tcase K_DEL:\n\tcase K_KDEL:\n\tcase Ctrl_W:\n\t    res = cmdline_erase_chars(c, indent\n#ifdef FEAT_SEARCH_EXTRA\n\t\t    , &is_state\n#endif\n\t\t    );\n\t    if (res == CMDLINE_NOT_CHANGED)\n\t\tgoto cmdline_not_changed;\n\t    else if (res == GOTO_NORMAL_MODE)\n\t\tgoto returncmd;\t\t// back to cmd mode\n\t    goto cmdline_changed;\n\n\tcase K_INS:\n\tcase K_KINS:\n\t\tccline.overstrike = !ccline.overstrike;\n#ifdef CURSOR_SHAPE\n\t\tui_cursor_shape();\t// may show different cursor shape\n#endif\n\t\tgoto cmdline_not_changed;\n\n\tcase Ctrl_HAT:\n\t\tcmdline_toggle_langmap(b_im_ptr);\n\t\tgoto cmdline_not_changed;\n\n//\tcase '@':   only in very old vi\n\tcase Ctrl_U:\n\t\t// delete all characters left of the cursor\n\t\tj = ccline.cmdpos;\n\t\tccline.cmdlen -= j;\n\t\ti = ccline.cmdpos = 0;\n\t\twhile (i < ccline.cmdlen)\n\t\t    ccline.cmdbuff[i++] = ccline.cmdbuff[j++];\n\t\t// Truncate at the end, required for multi-byte chars.\n\t\tccline.cmdbuff[ccline.cmdlen] = NUL;\n#ifdef FEAT_SEARCH_EXTRA\n\t\tif (ccline.cmdlen == 0)\n\t\t    is_state.search_start = is_state.save_cursor;\n#endif\n\t\tredrawcmd();\n\t\tgoto cmdline_changed;\n\n#ifdef FEAT_CLIPBOARD\n\tcase Ctrl_Y:\n\t\t// Copy the modeless selection, if there is one.\n\t\tif (clip_star.state != SELECT_CLEARED)\n\t\t{\n\t\t    if (clip_star.state == SELECT_DONE)\n\t\t\tclip_copy_modeless_selection(TRUE);\n\t\t    goto cmdline_not_changed;\n\t\t}\n\t\tbreak;\n#endif\n\n\tcase ESC:\t// get here if p_wc != ESC or when ESC typed twice\n\tcase Ctrl_C:\n\t\t// In exmode it doesn't make sense to return.  Except when\n\t\t// \":normal\" runs out of characters.\n\t\tif (exmode_active\n\t\t\t       && (ex_normal_busy == 0 || typebuf.tb_len > 0))\n\t\t    goto cmdline_not_changed;\n\n\t\tgotesc = TRUE;\t\t// will free ccline.cmdbuff after\n\t\t\t\t\t// putting it in history\n\t\tgoto returncmd;\t\t// back to cmd mode\n\n\tcase Ctrl_R:\t\t\t// insert register\n\t\tres = cmdline_insert_reg(&gotesc);\n\t\tif (res == CMDLINE_NOT_CHANGED)\n\t\t    goto cmdline_not_changed;\n\t\telse if (res == GOTO_NORMAL_MODE)\n\t\t    goto returncmd;\n\t\tgoto cmdline_changed;\n\n\tcase Ctrl_D:\n\t\tif (showmatches(&xpc, FALSE) == EXPAND_NOTHING)\n\t\t    break;\t// Use ^D as normal char instead\n\n\t\tredrawcmd();\n\t\tcontinue;\t// don't do incremental search now\n\n\tcase K_RIGHT:\n\tcase K_S_RIGHT:\n\tcase K_C_RIGHT:\n\t\tdo\n\t\t{\n\t\t    if (ccline.cmdpos >= ccline.cmdlen)\n\t\t\tbreak;\n\t\t    i = cmdline_charsize(ccline.cmdpos);\n\t\t    if (KeyTyped && ccline.cmdspos + i >= Columns * Rows)\n\t\t\tbreak;\n\t\t    ccline.cmdspos += i;\n\t\t    if (has_mbyte)\n\t\t\tccline.cmdpos += (*mb_ptr2len)(ccline.cmdbuff\n\t\t\t\t\t\t\t     + ccline.cmdpos);\n\t\t    else\n\t\t\t++ccline.cmdpos;\n\t\t}\n\t\twhile ((c == K_S_RIGHT || c == K_C_RIGHT\n\t\t\t       || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))\n\t\t\t&& ccline.cmdbuff[ccline.cmdpos] != ' ');\n\t\tif (has_mbyte)\n\t\t    set_cmdspos_cursor();\n\t\tgoto cmdline_not_changed;\n\n\tcase K_LEFT:\n\tcase K_S_LEFT:\n\tcase K_C_LEFT:\n\t\tif (ccline.cmdpos == 0)\n\t\t    goto cmdline_not_changed;\n\t\tdo\n\t\t{\n\t\t    --ccline.cmdpos;\n\t\t    if (has_mbyte)\t// move to first byte of char\n\t\t\tccline.cmdpos -= (*mb_head_off)(ccline.cmdbuff,\n\t\t\t\t\t      ccline.cmdbuff + ccline.cmdpos);\n\t\t    ccline.cmdspos -= cmdline_charsize(ccline.cmdpos);\n\t\t}\n\t\twhile (ccline.cmdpos > 0\n\t\t\t&& (c == K_S_LEFT || c == K_C_LEFT\n\t\t\t       || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))\n\t\t\t&& ccline.cmdbuff[ccline.cmdpos - 1] != ' ');\n\t\tif (has_mbyte)\n\t\t    set_cmdspos_cursor();\n\t\tgoto cmdline_not_changed;\n\n\tcase K_IGNORE:\n\t\t// Ignore mouse event or open_cmdwin() result.\n\t\tgoto cmdline_not_changed;\n\n#ifdef FEAT_GUI_MSWIN\n\t    // On MS-Windows ignore , we get it when closing the window\n\t    // was cancelled.\n\tcase K_F4:\n\t    if (mod_mask == MOD_MASK_ALT)\n\t    {\n\t\tredrawcmd();\t    // somehow the cmdline is cleared\n\t\tgoto cmdline_not_changed;\n\t    }\n\t    break;\n#endif\n\n\tcase K_MIDDLEDRAG:\n\tcase K_MIDDLERELEASE:\n\t\tgoto cmdline_not_changed;\t// Ignore mouse\n\n\tcase K_MIDDLEMOUSE:\n# ifdef FEAT_GUI\n\t\t// When GUI is active, also paste when 'mouse' is empty\n\t\tif (!gui.in_use)\n# endif\n\t\t    if (!mouse_has(MOUSE_COMMAND))\n\t\t\tgoto cmdline_not_changed;   // Ignore mouse\n# ifdef FEAT_CLIPBOARD\n\t\tif (clip_star.available)\n\t\t    cmdline_paste('*', TRUE, TRUE);\n\t\telse\n# endif\n\t\t    cmdline_paste(0, TRUE, TRUE);\n\t\tredrawcmd();\n\t\tgoto cmdline_changed;\n\n# ifdef FEAT_DND\n\tcase K_DROP:\n\t\tcmdline_paste('~', TRUE, FALSE);\n\t\tredrawcmd();\n\t\tgoto cmdline_changed;\n# endif\n\n\tcase K_LEFTDRAG:\n\tcase K_LEFTRELEASE:\n\tcase K_RIGHTDRAG:\n\tcase K_RIGHTRELEASE:\n\t\t// Ignore drag and release events when the button-down wasn't\n\t\t// seen before.\n\t\tif (ignore_drag_release)\n\t\t    goto cmdline_not_changed;\n\t\t// FALLTHROUGH\n\tcase K_LEFTMOUSE:\n\tcase K_RIGHTMOUSE:\n\t\tcmdline_left_right_mouse(c, &ignore_drag_release);\n\t\tgoto cmdline_not_changed;\n\n\t// Mouse scroll wheel: ignored here\n\tcase K_MOUSEDOWN:\n\tcase K_MOUSEUP:\n\tcase K_MOUSELEFT:\n\tcase K_MOUSERIGHT:\n\t// Alternate buttons ignored here\n\tcase K_X1MOUSE:\n\tcase K_X1DRAG:\n\tcase K_X1RELEASE:\n\tcase K_X2MOUSE:\n\tcase K_X2DRAG:\n\tcase K_X2RELEASE:\n\tcase K_MOUSEMOVE:\n\t\tgoto cmdline_not_changed;\n\n#ifdef FEAT_GUI\n\tcase K_LEFTMOUSE_NM:\t// mousefocus click, ignored\n\tcase K_LEFTRELEASE_NM:\n\t\tgoto cmdline_not_changed;\n\n\tcase K_VER_SCROLLBAR:\n\t\tif (msg_scrolled == 0)\n\t\t{\n\t\t    gui_do_scroll();\n\t\t    redrawcmd();\n\t\t}\n\t\tgoto cmdline_not_changed;\n\n\tcase K_HOR_SCROLLBAR:\n\t\tif (msg_scrolled == 0)\n\t\t{\n\t\t    gui_do_horiz_scroll(scrollbar_value, FALSE);\n\t\t    redrawcmd();\n\t\t}\n\t\tgoto cmdline_not_changed;\n#endif\n#ifdef FEAT_GUI_TABLINE\n\tcase K_TABLINE:\n\tcase K_TABMENU:\n\t\t// Don't want to change any tabs here.  Make sure the same tab\n\t\t// is still selected.\n\t\tif (gui_use_tabline())\n\t\t    gui_mch_set_curtab(tabpage_index(curtab));\n\t\tgoto cmdline_not_changed;\n#endif\n\n\tcase K_SELECT:\t    // end of Select mode mapping - ignore\n\t\tgoto cmdline_not_changed;\n\n\tcase Ctrl_B:\t    // begin of command line\n\tcase K_HOME:\n\tcase K_KHOME:\n\tcase K_S_HOME:\n\tcase K_C_HOME:\n\t\tccline.cmdpos = 0;\n\t\tset_cmdspos();\n\t\tgoto cmdline_not_changed;\n\n\tcase Ctrl_E:\t    // end of command line\n\tcase K_END:\n\tcase K_KEND:\n\tcase K_S_END:\n\tcase K_C_END:\n\t\tccline.cmdpos = ccline.cmdlen;\n\t\tset_cmdspos_cursor();\n\t\tgoto cmdline_not_changed;\n\n\tcase Ctrl_A:\t    // all matches\n\t\tif (cmdline_pum_active())\n\t\t    // As Ctrl-A completes all the matches, close the popup\n\t\t    // menu (if present)\n\t\t    cmdline_pum_cleanup(&ccline);\n\n\t\tif (nextwild(&xpc, WILD_ALL, 0, firstc != '@') == FAIL)\n\t\t    break;\n\t\txpc.xp_context = EXPAND_NOTHING;\n\t\tdid_wild_list = FALSE;\n\t\tgoto cmdline_changed;\n\n\tcase Ctrl_L:\n#ifdef FEAT_SEARCH_EXTRA\n\t\tif (may_add_char_to_search(firstc, &c, &is_state) == OK)\n\t\t    goto cmdline_not_changed;\n#endif\n\n\t\t// completion: longest common part\n\t\tif (nextwild(&xpc, WILD_LONGEST, 0, firstc != '@') == FAIL)\n\t\t    break;\n\t\tgoto cmdline_changed;\n\n\tcase Ctrl_N:\t    // next match\n\tcase Ctrl_P:\t    // previous match\n\t\tif (xpc.xp_numfiles > 0)\n\t\t{\n\t\t    wild_type = (c == Ctrl_P) ? WILD_PREV : WILD_NEXT;\n\t\t    if (nextwild(&xpc, wild_type, 0, firstc != '@') == FAIL)\n\t\t\tbreak;\n\t\t    goto cmdline_not_changed;\n\t\t}\n\t\t// FALLTHROUGH\n\tcase K_UP:\n\tcase K_DOWN:\n\tcase K_S_UP:\n\tcase K_S_DOWN:\n\tcase K_PAGEUP:\n\tcase K_KPAGEUP:\n\tcase K_PAGEDOWN:\n\tcase K_KPAGEDOWN:\n\t\tif (cmdline_pum_active()\n\t\t\t&& (c == K_PAGEUP || c == K_PAGEDOWN ||\n\t\t\t    c == K_KPAGEUP || c == K_KPAGEDOWN))\n\t\t{\n\t\t    // If the popup menu is displayed, then PageUp and PageDown\n\t\t    // are used to scroll the menu.\n\t\t    wild_type = WILD_PAGEUP;\n\t\t    if (c == K_PAGEDOWN || c == K_KPAGEDOWN)\n\t\t\twild_type = WILD_PAGEDOWN;\n\t\t    if (nextwild(&xpc, wild_type, 0, firstc != '@') == FAIL)\n\t\t\tbreak;\n\t\t    goto cmdline_not_changed;\n\t\t}\n\t\telse\n\t\t{\n\t\t    res = cmdline_browse_history(c, firstc, &lookfor, histype,\n\t\t\t    &hiscnt, &xpc);\n\t\t    if (res == CMDLINE_CHANGED)\n\t\t\tgoto cmdline_changed;\n\t\t    else if (res == GOTO_NORMAL_MODE)\n\t\t\tgoto returncmd;\n\t\t}\n\t\tgoto cmdline_not_changed;\n\n#ifdef FEAT_SEARCH_EXTRA\n\tcase Ctrl_G:\t    // next match\n\tcase Ctrl_T:\t    // previous match\n\t\tif (may_adjust_incsearch_highlighting(\n\t\t\t\t\t  firstc, count, &is_state, c) == FAIL)\n\t\t    goto cmdline_not_changed;\n\t\tbreak;\n#endif\n\n\tcase Ctrl_V:\n\tcase Ctrl_Q:\n\t\t{\n\t\t    ignore_drag_release = TRUE;\n\t\t    putcmdline('^', TRUE);\n\n\t\t    // Get next (two) character(s).  Do not change any\n\t\t    // modifyOtherKeys ESC sequence to a normal key for\n\t\t    // CTRL-SHIFT-V.\n\t\t    c = get_literal(mod_mask & MOD_MASK_SHIFT);\n\n\t\t    do_abbr = FALSE;\t    // don't do abbreviation now\n\t\t    extra_char = NUL;\n\t\t    // may need to remove ^ when composing char was typed\n\t\t    if (enc_utf8 && utf_iscomposing(c) && !cmd_silent)\n\t\t    {\n\t\t\tdraw_cmdline(ccline.cmdpos,\n\t\t\t\t\t\tccline.cmdlen - ccline.cmdpos);\n\t\t\tmsg_putchar(' ');\n\t\t\tcursorcmd();\n\t\t    }\n\t\t}\n\n\t\tbreak;\n\n#ifdef FEAT_DIGRAPHS\n\tcase Ctrl_K:\n\t\tignore_drag_release = TRUE;\n\t\tputcmdline('?', TRUE);\n# ifdef USE_ON_FLY_SCROLL\n\t\tdont_scroll = TRUE;\t    // disallow scrolling here\n# endif\n\t\tc = get_digraph(TRUE);\n\t\textra_char = NUL;\n\t\tif (c != NUL)\n\t\t    break;\n\n\t\tredrawcmd();\n\t\tgoto cmdline_not_changed;\n#endif // FEAT_DIGRAPHS\n\n#ifdef FEAT_RIGHTLEFT\n\tcase Ctrl__:\t    // CTRL-_: switch language mode\n\t\tif (!p_ari)\n\t\t    break;\n\t\tcmd_hkmap = !cmd_hkmap;\n\t\tgoto cmdline_not_changed;\n#endif\n\n\tcase K_PS:\n\t\tbracketed_paste(PASTE_CMDLINE, FALSE, NULL);\n\t\tgoto cmdline_changed;\n\n\tdefault:\n#ifdef UNIX\n\t\tif (c == intr_char)\n\t\t{\n\t\t    gotesc = TRUE;\t// will free ccline.cmdbuff after\n\t\t\t\t\t// putting it in history\n\t\t    goto returncmd;\t// back to Normal mode\n\t\t}\n#endif\n\t\t/*\n\t\t * Normal character with no special meaning.  Just set mod_mask\n\t\t * to 0x0 so that typing Shift-Space in the GUI doesn't enter\n\t\t * the string .  This should only happen after ^V.\n\t\t */\n\t\tif (!IS_SPECIAL(c))\n\t\t    mod_mask = 0x0;\n\t\tbreak;\n\t}\n\t/*\n\t * End of switch on command line character.\n\t * We come here if we have a normal character.\n\t */\n\n\tif (do_abbr && (IS_SPECIAL(c) || !vim_iswordc(c))\n\t\t&& (ccheck_abbr(\n\t\t\t// Add ABBR_OFF for characters above 0x100, this is\n\t\t\t// what check_abbr() expects.\n\t\t\t\t(has_mbyte && c >= 0x100) ? (c + ABBR_OFF) : c)\n\t\t    || c == Ctrl_RSB))\n\t    goto cmdline_changed;\n\n\t/*\n\t * put the character in the command line\n\t */\n\tif (IS_SPECIAL(c) || mod_mask != 0)\n\t    put_on_cmdline(get_special_key_name(c, mod_mask), -1, TRUE);\n\telse\n\t{\n\t    if (has_mbyte)\n\t    {\n\t\tj = (*mb_char2bytes)(c, IObuff);\n\t\tIObuff[j] = NUL;\t// exclude composing chars\n\t\tput_on_cmdline(IObuff, j, TRUE);\n\t    }\n\t    else\n\t    {\n\t\tIObuff[0] = c;\n\t\tput_on_cmdline(IObuff, 1, TRUE);\n\t    }\n\t}\n\tgoto cmdline_changed;\n\n/*\n * This part implements incremental searches for \"/\" and \"?\"\n * Jump to cmdline_not_changed when a character has been read but the command\n * line did not change. Then we only search and redraw if something changed in\n * the past.\n * Jump to cmdline_changed when the command line did change.\n * (Sorry for the goto's, I know it is ugly).\n */\ncmdline_not_changed:\n#ifdef FEAT_SEARCH_EXTRA\n\tif (!is_state.incsearch_postponed)\n\t    continue;\n#endif\n\ncmdline_changed:\n#ifdef FEAT_SEARCH_EXTRA\n\t// If the window changed incremental search state is not valid.\n\tif (is_state.winid != curwin->w_id)\n\t    init_incsearch_state(&is_state);\n#endif\n\tif (trigger_cmdlinechanged)\n\t    // Trigger CmdlineChanged autocommands.\n\t    trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINECHANGED);\n\n#ifdef FEAT_SEARCH_EXTRA\n\tif (xpc.xp_context == EXPAND_NOTHING && (KeyTyped || vpeekc() == NUL))\n\t    may_do_incsearch_highlighting(firstc, count, &is_state);\n#endif\n\n#ifdef FEAT_RIGHTLEFT\n\tif (cmdmsg_rl\n# ifdef FEAT_ARABIC\n\t\t|| (p_arshape && !p_tbidi\n\t\t\t\t       && cmdline_has_arabic(0, ccline.cmdlen))\n# endif\n\t\t)\n\t    // Always redraw the whole command line to fix shaping and\n\t    // right-left typing.  Not efficient, but it works.\n\t    // Do it only when there are no characters left to read\n\t    // to avoid useless intermediate redraws.\n\t    if (vpeekc() == NUL)\n\t\tredrawcmd();\n#endif\n    }\n\nreturncmd:\n\n#ifdef FEAT_RIGHTLEFT\n    cmdmsg_rl = FALSE;\n#endif\n\n    ExpandCleanup(&xpc);\n    ccline.xpc = NULL;\n\n#ifdef FEAT_SEARCH_EXTRA\n    finish_incsearch_highlighting(gotesc, &is_state, FALSE);\n#endif\n\n    if (ccline.cmdbuff != NULL)\n    {\n\t/*\n\t * Put line in history buffer (\":\" and \"=\" only when it was typed).\n\t */\n\tif (ccline.cmdlen && firstc != NUL\n\t\t&& (some_key_typed || histype == HIST_SEARCH))\n\t{\n\t    add_to_history(histype, ccline.cmdbuff, TRUE,\n\t\t\t\t       histype == HIST_SEARCH ? firstc : NUL);\n\t    if (firstc == ':')\n\t    {\n\t\tvim_free(new_last_cmdline);\n\t\tnew_last_cmdline = vim_strsave(ccline.cmdbuff);\n\t    }\n\t}\n\n\tif (gotesc)\n\t    abandon_cmdline();\n    }\n\n    /*\n     * If the screen was shifted up, redraw the whole screen (later).\n     * If the line is too long, clear it, so ruler and shown command do\n     * not get printed in the middle of it.\n     */\n    msg_check();\n    msg_scroll = save_msg_scroll;\n    redir_off = FALSE;\n\n    // When the command line was typed, no need for a wait-return prompt.\n    if (some_key_typed)\n\tneed_wait_return = FALSE;\n\n    // Trigger CmdlineLeave autocommands.\n    trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINELEAVE);\n\n    State = save_State;\n\n#ifdef FEAT_EVAL\n    if (!debug_mode)\n\tmay_trigger_modechanged();\n#endif\n\n#ifdef HAVE_INPUT_METHOD\n    if (b_im_ptr != NULL && *b_im_ptr != B_IMODE_LMAP)\n\tim_save_status(b_im_ptr);\n    im_set_active(FALSE);\n#endif\n    setmouse();\n#ifdef CURSOR_SHAPE\n    ui_cursor_shape();\t\t// may show different cursor shape\n#endif\n    sb_text_end_cmdline();\n\ntheend:\n    {\n\tchar_u *p = ccline.cmdbuff;\n\n\t--depth;\n\tif (did_save_ccline)\n\t    restore_cmdline(&save_ccline);\n\telse\n\t    ccline.cmdbuff = NULL;\n\treturn p;\n    }\n}", "func_hash": 318420655328659351378249069297989245289, "file_name": "ex_getln.c", "file_hash": 35630205531070235041879855338965504689, "cwe": ["CWE-416"], "cve": "CVE-2022-3235", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 9.0.0490.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3235"}
{"idx": 416366, "project": "vim", "commit_id": "1c3dd8ddcba63c1af5112e567215b3cec2de11d0", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/1c3dd8ddcba63c1af5112e567215b3cec2de11d0", "commit_message": "patch 9.0.0490: using freed memory with cmdwin and BufEnter autocmd\n\nProblem:    Using freed memory with cmdwin and BufEnter autocmd.\nSolution:   Make sure pointer to b_p_iminsert is still valid.", "target": 0, "func": "getcmdline_int(\n    int\t\tfirstc,\n    long\tcount UNUSED,\t// only used for incremental search\n    int\t\tindent,\t\t// indent for inside conditionals\n    int\t\tclear_ccline)\t// clear ccline first\n{\n    static int\tdepth = 0;\t    // call depth\n    int\t\tc;\n    int\t\ti;\n    int\t\tj;\n    int\t\tgotesc = FALSE;\t\t// TRUE when  just typed\n    int\t\tdo_abbr;\t\t// when TRUE check for abbr.\n    char_u\t*lookfor = NULL;\t// string to match\n    int\t\thiscnt;\t\t\t// current history line in use\n    int\t\thistype;\t\t// history type to be used\n#ifdef FEAT_SEARCH_EXTRA\n    incsearch_state_T\tis_state;\n#endif\n    int\t\tdid_wild_list = FALSE;\t// did wild_list() recently\n    int\t\twim_index = 0;\t\t// index in wim_flags[]\n    int\t\tres;\n    int\t\tsave_msg_scroll = msg_scroll;\n    int\t\tsave_State = State;\t// remember State when called\n    int\t\tsome_key_typed = FALSE;\t// one of the keys was typed\n    // mouse drag and release events are ignored, unless they are\n    // preceded with a mouse down event\n    int\t\tignore_drag_release = TRUE;\n#ifdef FEAT_EVAL\n    int\t\tbreak_ctrl_c = FALSE;\n#endif\n    expand_T\txpc;\n    long\t*b_im_ptr = NULL;\n    buf_T\t*b_im_ptr_buf = NULL;\t// buffer where b_im_ptr is valid\n    cmdline_info_T save_ccline;\n    int\t\tdid_save_ccline = FALSE;\n    int\t\tcmdline_type;\n    int\t\twild_type;\n\n    // one recursion level deeper\n    ++depth;\n\n    if (ccline.cmdbuff != NULL)\n    {\n\t// Being called recursively.  Since ccline is global, we need to save\n\t// the current buffer and restore it when returning.\n\tsave_cmdline(&save_ccline);\n\tdid_save_ccline = TRUE;\n    }\n    if (clear_ccline)\n\tCLEAR_FIELD(ccline);\n\n#ifdef FEAT_EVAL\n    if (firstc == -1)\n    {\n\tfirstc = NUL;\n\tbreak_ctrl_c = TRUE;\n    }\n#endif\n#ifdef FEAT_RIGHTLEFT\n    // start without Hebrew mapping for a command line\n    if (firstc == ':' || firstc == '=' || firstc == '>')\n\tcmd_hkmap = 0;\n#endif\n\n#ifdef FEAT_SEARCH_EXTRA\n    init_incsearch_state(&is_state);\n#endif\n\n    if (init_ccline(firstc, indent) != OK)\n\tgoto theend;\t// out of memory\n\n    if (depth == 50)\n    {\n\t// Somehow got into a loop recursively calling getcmdline(), bail out.\n\temsg(_(e_command_too_recursive));\n\tgoto theend;\n    }\n\n    ExpandInit(&xpc);\n    ccline.xpc = &xpc;\n\n#ifdef FEAT_RIGHTLEFT\n    if (curwin->w_p_rl && *curwin->w_p_rlc == 's'\n\t\t\t\t\t  && (firstc == '/' || firstc == '?'))\n\tcmdmsg_rl = TRUE;\n    else\n\tcmdmsg_rl = FALSE;\n#endif\n\n    redir_off = TRUE;\t\t// don't redirect the typed command\n    if (!cmd_silent)\n    {\n\ti = msg_scrolled;\n\tmsg_scrolled = 0;\t\t// avoid wait_return() message\n\tgotocmdline(TRUE);\n\tmsg_scrolled += i;\n\tredrawcmdprompt();\t\t// draw prompt or indent\n\tset_cmdspos();\n    }\n    xpc.xp_context = EXPAND_NOTHING;\n    xpc.xp_backslash = XP_BS_NONE;\n#ifndef BACKSLASH_IN_FILENAME\n    xpc.xp_shell = FALSE;\n#endif\n\n#if defined(FEAT_EVAL)\n    if (ccline.input_fn)\n    {\n\txpc.xp_context = ccline.xp_context;\n\txpc.xp_pattern = ccline.cmdbuff;\n\txpc.xp_arg = ccline.xp_arg;\n    }\n#endif\n\n    /*\n     * Avoid scrolling when called by a recursive do_cmdline(), e.g. when\n     * doing \":@0\" when register 0 doesn't contain a CR.\n     */\n    msg_scroll = FALSE;\n\n    State = MODE_CMDLINE;\n\n    if (firstc == '/' || firstc == '?' || firstc == '@')\n    {\n\t// Use \":lmap\" mappings for search pattern and input().\n\tif (curbuf->b_p_imsearch == B_IMODE_USE_INSERT)\n\t    b_im_ptr = &curbuf->b_p_iminsert;\n\telse\n\t    b_im_ptr = &curbuf->b_p_imsearch;\n\tb_im_ptr_buf = curbuf;\n\tif (*b_im_ptr == B_IMODE_LMAP)\n\t    State |= MODE_LANGMAP;\n#ifdef HAVE_INPUT_METHOD\n\tim_set_active(*b_im_ptr == B_IMODE_IM);\n#endif\n    }\n#ifdef HAVE_INPUT_METHOD\n    else if (p_imcmdline)\n\tim_set_active(TRUE);\n#endif\n\n    setmouse();\n#ifdef CURSOR_SHAPE\n    ui_cursor_shape();\t\t// may show different cursor shape\n#endif\n\n    // When inside an autocommand for writing \"exiting\" may be set and\n    // terminal mode set to cooked.  Need to set raw mode here then.\n    settmode(TMODE_RAW);\n\n    // Trigger CmdlineEnter autocommands.\n    cmdline_type = firstc == NUL ? '-' : firstc;\n    trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINEENTER);\n#ifdef FEAT_EVAL\n    if (!debug_mode)\n\tmay_trigger_modechanged();\n#endif\n\n    init_history();\n    hiscnt = get_hislen();\t// set hiscnt to impossible history value\n    histype = hist_char2type(firstc);\n\n#ifdef FEAT_DIGRAPHS\n    do_digraph(-1);\t\t// init digraph typeahead\n#endif\n\n    // If something above caused an error, reset the flags, we do want to type\n    // and execute commands. Display may be messed up a bit.\n    if (did_emsg)\n\tredrawcmd();\n\n#ifdef FEAT_STL_OPT\n    // Redraw the statusline in case it uses the current mode using the mode()\n    // function.\n    if (!cmd_silent && msg_scrolled == 0)\n    {\n\tint\tfound_one = FALSE;\n\twin_T\t*wp;\n\n\tFOR_ALL_WINDOWS(wp)\n\t    if (*p_stl != NUL || *wp->w_p_stl != NUL)\n\t    {\n\t\twp->w_redr_status = TRUE;\n\t\tfound_one = TRUE;\n\t    }\n\n\tif (*p_tal != NUL)\n\t{\n\t    redraw_tabline = TRUE;\n\t    found_one = TRUE;\n\t}\n\n\tif (found_one)\n\t    redraw_statuslines();\n    }\n#endif\n\n    did_emsg = FALSE;\n    got_int = FALSE;\n\n    /*\n     * Collect the command string, handling editing keys.\n     */\n    for (;;)\n    {\n\tint trigger_cmdlinechanged = TRUE;\n\tint end_wildmenu;\n\n\tredir_off = TRUE;\t// Don't redirect the typed command.\n\t\t\t\t// Repeated, because a \":redir\" inside\n\t\t\t\t// completion may switch it on.\n#ifdef USE_ON_FLY_SCROLL\n\tdont_scroll = FALSE;\t// allow scrolling here\n#endif\n\tquit_more = FALSE;\t// reset after CTRL-D which had a more-prompt\n\n\tdid_emsg = FALSE;\t// There can't really be a reason why an error\n\t\t\t\t// that occurs while typing a command should\n\t\t\t\t// cause the command not to be executed.\n\n\t// Trigger SafeState if nothing is pending.\n\tmay_trigger_safestate(xpc.xp_numfiles <= 0);\n\n\t// Get a character.  Ignore K_IGNORE and K_NOP, they should not do\n\t// anything, such as stop completion.\n\tdo\n\t{\n\t    cursorcmd();\t\t// set the cursor on the right spot\n\t    c = safe_vgetc();\n\t} while (c == K_IGNORE || c == K_NOP);\n\n\tif (c == K_COMMAND || c == K_SCRIPT_COMMAND)\n\t{\n\t    int\t    clen = ccline.cmdlen;\n\n\t    if (do_cmdkey_command(c, DOCMD_NOWAIT) == OK)\n\t    {\n\t\tif (clen == ccline.cmdlen)\n\t\t    trigger_cmdlinechanged = FALSE;\n\t\tgoto cmdline_changed;\n\t    }\n\t}\n\n\tif (KeyTyped)\n\t{\n\t    some_key_typed = TRUE;\n#ifdef FEAT_RIGHTLEFT\n\t    if (cmd_hkmap)\n\t\tc = hkmap(c);\n\t    if (cmdmsg_rl && !KeyStuffed)\n\t    {\n\t\t// Invert horizontal movements and operations.  Only when\n\t\t// typed by the user directly, not when the result of a\n\t\t// mapping.\n\t\tswitch (c)\n\t\t{\n\t\t    case K_RIGHT:   c = K_LEFT; break;\n\t\t    case K_S_RIGHT: c = K_S_LEFT; break;\n\t\t    case K_C_RIGHT: c = K_C_LEFT; break;\n\t\t    case K_LEFT:    c = K_RIGHT; break;\n\t\t    case K_S_LEFT:  c = K_S_RIGHT; break;\n\t\t    case K_C_LEFT:  c = K_C_RIGHT; break;\n\t\t}\n\t    }\n#endif\n\t}\n\n\t/*\n\t * Ignore got_int when CTRL-C was typed here.\n\t * Don't ignore it in :global, we really need to break then, e.g., for\n\t * \":g/pat/normal /pat\" (without the ).\n\t * Don't ignore it for the input() function.\n\t */\n\tif ((c == Ctrl_C\n#ifdef UNIX\n\t\t|| c == intr_char\n#endif\n\t\t\t\t)\n#if defined(FEAT_EVAL) || defined(FEAT_CRYPT)\n\t\t&& firstc != '@'\n#endif\n#ifdef FEAT_EVAL\n\t\t// do clear got_int in Ex mode to avoid infinite Ctrl-C loop\n\t\t&& (!break_ctrl_c || exmode_active)\n#endif\n\t\t&& !global_busy)\n\t    got_int = FALSE;\n\n\t// free old command line when finished moving around in the history\n\t// list\n\tif (lookfor != NULL\n\t\t&& c != K_S_DOWN && c != K_S_UP\n\t\t&& c != K_DOWN && c != K_UP\n\t\t&& c != K_PAGEDOWN && c != K_PAGEUP\n\t\t&& c != K_KPAGEDOWN && c != K_KPAGEUP\n\t\t&& c != K_LEFT && c != K_RIGHT\n\t\t&& (xpc.xp_numfiles > 0 || (c != Ctrl_P && c != Ctrl_N)))\n\t    VIM_CLEAR(lookfor);\n\n\t/*\n\t * When there are matching completions to select  works like\n\t * CTRL-P (unless 'wc' is ).\n\t */\n\tif (c != p_wc && c == K_S_TAB && xpc.xp_numfiles > 0)\n\t    c = Ctrl_P;\n\n\tif (p_wmnu)\n\t    c = wildmenu_translate_key(&ccline, c, &xpc, did_wild_list);\n\n\tif (cmdline_pum_active())\n\t{\n\t    // Ctrl-Y: Accept the current selection and close the popup menu.\n\t    // Ctrl-E: cancel the cmdline popup menu and return the original\n\t    // text.\n\t    if (c == Ctrl_E || c == Ctrl_Y)\n\t    {\n\t\twild_type = (c == Ctrl_E) ? WILD_CANCEL : WILD_APPLY;\n\t\tif (nextwild(&xpc, wild_type, WILD_NO_BEEP,\n\t\t\t\t\t\t\tfirstc != '@') == FAIL)\n\t\t    break;\n\t\tc = Ctrl_E;\n\t    }\n\t}\n\n\t// The wildmenu is cleared if the pressed key is not used for\n\t// navigating the wild menu (i.e. the key is not 'wildchar' or\n\t// 'wildcharm' or Ctrl-N or Ctrl-P or Ctrl-A or Ctrl-L).\n\t// If the popup menu is displayed, then PageDown and PageUp keys are\n\t// also used to navigate the menu.\n\tend_wildmenu = (!(c == p_wc && KeyTyped) && c != p_wcm\n\t\t&& c != Ctrl_N && c != Ctrl_P && c != Ctrl_A && c != Ctrl_L);\n\tend_wildmenu = end_wildmenu && (!cmdline_pum_active() ||\n\t\t\t    (c != K_PAGEDOWN && c != K_PAGEUP\n\t\t\t     && c != K_KPAGEDOWN && c != K_KPAGEUP));\n\n\t// free expanded names when finished walking through matches\n\tif (end_wildmenu)\n\t{\n\t    if (cmdline_pum_active())\n\t\tcmdline_pum_remove();\n\t    if (xpc.xp_numfiles != -1)\n\t\t(void)ExpandOne(&xpc, NULL, NULL, 0, WILD_FREE);\n\t    did_wild_list = FALSE;\n\t    if (!p_wmnu || (c != K_UP && c != K_DOWN))\n\t\txpc.xp_context = EXPAND_NOTHING;\n\t    wim_index = 0;\n\t    wildmenu_cleanup(&ccline);\n\t}\n\n\tif (p_wmnu)\n\t    c = wildmenu_process_key(&ccline, c, &xpc);\n\n\t// CTRL-\\ CTRL-N goes to Normal mode, CTRL-\\ CTRL-G goes to Insert\n\t// mode when 'insertmode' is set, CTRL-\\ e prompts for an expression.\n\tif (c == Ctrl_BSL)\n\t{\n\t    res = cmdline_handle_backslash_key(c, &gotesc);\n\t    if (res == CMDLINE_CHANGED)\n\t\tgoto cmdline_changed;\n\t    else if (res == CMDLINE_NOT_CHANGED)\n\t\tgoto cmdline_not_changed;\n\t    else if (res == GOTO_NORMAL_MODE)\n\t\tgoto returncmd;\t\t// back to cmd mode\n\t    c = Ctrl_BSL;\t\t// backslash key not processed by\n\t\t\t\t\t// cmdline_handle_backslash_key()\n\t}\n\n#ifdef FEAT_CMDWIN\n\tif (c == cedit_key || c == K_CMDWIN)\n\t{\n\t    // TODO: why is ex_normal_busy checked here?\n\t    if ((c == K_CMDWIN || ex_normal_busy == 0) && got_int == FALSE)\n\t    {\n\t\t/*\n\t\t * Open a window to edit the command line (and history).\n\t\t */\n\t\tc = open_cmdwin();\n\t\tsome_key_typed = TRUE;\n\t    }\n\t}\n# ifdef FEAT_DIGRAPHS\n\telse\n# endif\n#endif\n#ifdef FEAT_DIGRAPHS\n\t    c = do_digraph(c);\n#endif\n\n\tif (c == '\\n' || c == '\\r' || c == K_KENTER || (c == ESC\n\t\t\t&& (!KeyTyped || vim_strchr(p_cpo, CPO_ESC) != NULL)))\n\t{\n\t    // In Ex mode a backslash escapes a newline.\n\t    if (exmode_active\n\t\t    && c != ESC\n\t\t    && ccline.cmdpos == ccline.cmdlen\n\t\t    && ccline.cmdpos > 0\n\t\t    && ccline.cmdbuff[ccline.cmdpos - 1] == '\\\\')\n\t    {\n\t\tif (c == K_KENTER)\n\t\t    c = '\\n';\n\t    }\n\t    else\n\t    {\n\t\tgotesc = FALSE;\t// Might have typed ESC previously, don't\n\t\t\t\t// truncate the cmdline now.\n\t\tif (ccheck_abbr(c + ABBR_OFF))\n\t\t    goto cmdline_changed;\n\t\tif (!cmd_silent)\n\t\t{\n\t\t    windgoto(msg_row, 0);\n\t\t    out_flush();\n\t\t}\n\t\tbreak;\n\t    }\n\t}\n\n\t// Completion for 'wildchar' or 'wildcharm' key.\n\tif ((c == p_wc && !gotesc && KeyTyped) || c == p_wcm)\n\t{\n\t    res = cmdline_wildchar_complete(c, firstc != '@', &did_wild_list,\n\t\t    &wim_index, &xpc, &gotesc);\n\t    if (res == CMDLINE_CHANGED)\n\t\tgoto cmdline_changed;\n\t}\n\n\tgotesc = FALSE;\n\n\t//  goes to last match, in a clumsy way\n\tif (c == K_S_TAB && KeyTyped)\n\t{\n\t    if (nextwild(&xpc, WILD_EXPAND_KEEP, 0, firstc != '@') == OK)\n\t    {\n\t\tif (xpc.xp_numfiles > 1\n\t\t    && ((!did_wild_list && (wim_flags[wim_index] & WIM_LIST))\n\t\t\t    || p_wmnu))\n\t\t{\n\t\t    // Trigger the popup menu when wildoptions=pum\n\t\t    showmatches(&xpc, p_wmnu\n\t\t\t    && ((wim_flags[wim_index] & WIM_LIST) == 0));\n\t\t}\n\t\tif (nextwild(&xpc, WILD_PREV, 0, firstc != '@') == OK\n\t\t\t&& nextwild(&xpc, WILD_PREV, 0, firstc != '@') == OK)\n\t\t    goto cmdline_changed;\n\t    }\n\t}\n\n\tif (c == NUL || c == K_ZERO)\t    // NUL is stored as NL\n\t    c = NL;\n\n\tdo_abbr = TRUE;\t\t// default: check for abbreviation\n\n\t/*\n\t * Big switch for a typed command line character.\n\t */\n\tswitch (c)\n\t{\n\tcase K_BS:\n\tcase Ctrl_H:\n\tcase K_DEL:\n\tcase K_KDEL:\n\tcase Ctrl_W:\n\t    res = cmdline_erase_chars(c, indent\n#ifdef FEAT_SEARCH_EXTRA\n\t\t    , &is_state\n#endif\n\t\t    );\n\t    if (res == CMDLINE_NOT_CHANGED)\n\t\tgoto cmdline_not_changed;\n\t    else if (res == GOTO_NORMAL_MODE)\n\t\tgoto returncmd;\t\t// back to cmd mode\n\t    goto cmdline_changed;\n\n\tcase K_INS:\n\tcase K_KINS:\n\t\tccline.overstrike = !ccline.overstrike;\n#ifdef CURSOR_SHAPE\n\t\tui_cursor_shape();\t// may show different cursor shape\n#endif\n\t\tgoto cmdline_not_changed;\n\n\tcase Ctrl_HAT:\n\t\tcmdline_toggle_langmap(\n\t\t\t\t    buf_valid(b_im_ptr_buf) ? b_im_ptr : NULL);\n\t\tgoto cmdline_not_changed;\n\n//\tcase '@':   only in very old vi\n\tcase Ctrl_U:\n\t\t// delete all characters left of the cursor\n\t\tj = ccline.cmdpos;\n\t\tccline.cmdlen -= j;\n\t\ti = ccline.cmdpos = 0;\n\t\twhile (i < ccline.cmdlen)\n\t\t    ccline.cmdbuff[i++] = ccline.cmdbuff[j++];\n\t\t// Truncate at the end, required for multi-byte chars.\n\t\tccline.cmdbuff[ccline.cmdlen] = NUL;\n#ifdef FEAT_SEARCH_EXTRA\n\t\tif (ccline.cmdlen == 0)\n\t\t    is_state.search_start = is_state.save_cursor;\n#endif\n\t\tredrawcmd();\n\t\tgoto cmdline_changed;\n\n#ifdef FEAT_CLIPBOARD\n\tcase Ctrl_Y:\n\t\t// Copy the modeless selection, if there is one.\n\t\tif (clip_star.state != SELECT_CLEARED)\n\t\t{\n\t\t    if (clip_star.state == SELECT_DONE)\n\t\t\tclip_copy_modeless_selection(TRUE);\n\t\t    goto cmdline_not_changed;\n\t\t}\n\t\tbreak;\n#endif\n\n\tcase ESC:\t// get here if p_wc != ESC or when ESC typed twice\n\tcase Ctrl_C:\n\t\t// In exmode it doesn't make sense to return.  Except when\n\t\t// \":normal\" runs out of characters.\n\t\tif (exmode_active\n\t\t\t       && (ex_normal_busy == 0 || typebuf.tb_len > 0))\n\t\t    goto cmdline_not_changed;\n\n\t\tgotesc = TRUE;\t\t// will free ccline.cmdbuff after\n\t\t\t\t\t// putting it in history\n\t\tgoto returncmd;\t\t// back to cmd mode\n\n\tcase Ctrl_R:\t\t\t// insert register\n\t\tres = cmdline_insert_reg(&gotesc);\n\t\tif (res == CMDLINE_NOT_CHANGED)\n\t\t    goto cmdline_not_changed;\n\t\telse if (res == GOTO_NORMAL_MODE)\n\t\t    goto returncmd;\n\t\tgoto cmdline_changed;\n\n\tcase Ctrl_D:\n\t\tif (showmatches(&xpc, FALSE) == EXPAND_NOTHING)\n\t\t    break;\t// Use ^D as normal char instead\n\n\t\tredrawcmd();\n\t\tcontinue;\t// don't do incremental search now\n\n\tcase K_RIGHT:\n\tcase K_S_RIGHT:\n\tcase K_C_RIGHT:\n\t\tdo\n\t\t{\n\t\t    if (ccline.cmdpos >= ccline.cmdlen)\n\t\t\tbreak;\n\t\t    i = cmdline_charsize(ccline.cmdpos);\n\t\t    if (KeyTyped && ccline.cmdspos + i >= Columns * Rows)\n\t\t\tbreak;\n\t\t    ccline.cmdspos += i;\n\t\t    if (has_mbyte)\n\t\t\tccline.cmdpos += (*mb_ptr2len)(ccline.cmdbuff\n\t\t\t\t\t\t\t     + ccline.cmdpos);\n\t\t    else\n\t\t\t++ccline.cmdpos;\n\t\t}\n\t\twhile ((c == K_S_RIGHT || c == K_C_RIGHT\n\t\t\t       || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))\n\t\t\t&& ccline.cmdbuff[ccline.cmdpos] != ' ');\n\t\tif (has_mbyte)\n\t\t    set_cmdspos_cursor();\n\t\tgoto cmdline_not_changed;\n\n\tcase K_LEFT:\n\tcase K_S_LEFT:\n\tcase K_C_LEFT:\n\t\tif (ccline.cmdpos == 0)\n\t\t    goto cmdline_not_changed;\n\t\tdo\n\t\t{\n\t\t    --ccline.cmdpos;\n\t\t    if (has_mbyte)\t// move to first byte of char\n\t\t\tccline.cmdpos -= (*mb_head_off)(ccline.cmdbuff,\n\t\t\t\t\t      ccline.cmdbuff + ccline.cmdpos);\n\t\t    ccline.cmdspos -= cmdline_charsize(ccline.cmdpos);\n\t\t}\n\t\twhile (ccline.cmdpos > 0\n\t\t\t&& (c == K_S_LEFT || c == K_C_LEFT\n\t\t\t       || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))\n\t\t\t&& ccline.cmdbuff[ccline.cmdpos - 1] != ' ');\n\t\tif (has_mbyte)\n\t\t    set_cmdspos_cursor();\n\t\tgoto cmdline_not_changed;\n\n\tcase K_IGNORE:\n\t\t// Ignore mouse event or open_cmdwin() result.\n\t\tgoto cmdline_not_changed;\n\n#ifdef FEAT_GUI_MSWIN\n\t    // On MS-Windows ignore , we get it when closing the window\n\t    // was cancelled.\n\tcase K_F4:\n\t    if (mod_mask == MOD_MASK_ALT)\n\t    {\n\t\tredrawcmd();\t    // somehow the cmdline is cleared\n\t\tgoto cmdline_not_changed;\n\t    }\n\t    break;\n#endif\n\n\tcase K_MIDDLEDRAG:\n\tcase K_MIDDLERELEASE:\n\t\tgoto cmdline_not_changed;\t// Ignore mouse\n\n\tcase K_MIDDLEMOUSE:\n# ifdef FEAT_GUI\n\t\t// When GUI is active, also paste when 'mouse' is empty\n\t\tif (!gui.in_use)\n# endif\n\t\t    if (!mouse_has(MOUSE_COMMAND))\n\t\t\tgoto cmdline_not_changed;   // Ignore mouse\n# ifdef FEAT_CLIPBOARD\n\t\tif (clip_star.available)\n\t\t    cmdline_paste('*', TRUE, TRUE);\n\t\telse\n# endif\n\t\t    cmdline_paste(0, TRUE, TRUE);\n\t\tredrawcmd();\n\t\tgoto cmdline_changed;\n\n# ifdef FEAT_DND\n\tcase K_DROP:\n\t\tcmdline_paste('~', TRUE, FALSE);\n\t\tredrawcmd();\n\t\tgoto cmdline_changed;\n# endif\n\n\tcase K_LEFTDRAG:\n\tcase K_LEFTRELEASE:\n\tcase K_RIGHTDRAG:\n\tcase K_RIGHTRELEASE:\n\t\t// Ignore drag and release events when the button-down wasn't\n\t\t// seen before.\n\t\tif (ignore_drag_release)\n\t\t    goto cmdline_not_changed;\n\t\t// FALLTHROUGH\n\tcase K_LEFTMOUSE:\n\tcase K_RIGHTMOUSE:\n\t\tcmdline_left_right_mouse(c, &ignore_drag_release);\n\t\tgoto cmdline_not_changed;\n\n\t// Mouse scroll wheel: ignored here\n\tcase K_MOUSEDOWN:\n\tcase K_MOUSEUP:\n\tcase K_MOUSELEFT:\n\tcase K_MOUSERIGHT:\n\t// Alternate buttons ignored here\n\tcase K_X1MOUSE:\n\tcase K_X1DRAG:\n\tcase K_X1RELEASE:\n\tcase K_X2MOUSE:\n\tcase K_X2DRAG:\n\tcase K_X2RELEASE:\n\tcase K_MOUSEMOVE:\n\t\tgoto cmdline_not_changed;\n\n#ifdef FEAT_GUI\n\tcase K_LEFTMOUSE_NM:\t// mousefocus click, ignored\n\tcase K_LEFTRELEASE_NM:\n\t\tgoto cmdline_not_changed;\n\n\tcase K_VER_SCROLLBAR:\n\t\tif (msg_scrolled == 0)\n\t\t{\n\t\t    gui_do_scroll();\n\t\t    redrawcmd();\n\t\t}\n\t\tgoto cmdline_not_changed;\n\n\tcase K_HOR_SCROLLBAR:\n\t\tif (msg_scrolled == 0)\n\t\t{\n\t\t    gui_do_horiz_scroll(scrollbar_value, FALSE);\n\t\t    redrawcmd();\n\t\t}\n\t\tgoto cmdline_not_changed;\n#endif\n#ifdef FEAT_GUI_TABLINE\n\tcase K_TABLINE:\n\tcase K_TABMENU:\n\t\t// Don't want to change any tabs here.  Make sure the same tab\n\t\t// is still selected.\n\t\tif (gui_use_tabline())\n\t\t    gui_mch_set_curtab(tabpage_index(curtab));\n\t\tgoto cmdline_not_changed;\n#endif\n\n\tcase K_SELECT:\t    // end of Select mode mapping - ignore\n\t\tgoto cmdline_not_changed;\n\n\tcase Ctrl_B:\t    // begin of command line\n\tcase K_HOME:\n\tcase K_KHOME:\n\tcase K_S_HOME:\n\tcase K_C_HOME:\n\t\tccline.cmdpos = 0;\n\t\tset_cmdspos();\n\t\tgoto cmdline_not_changed;\n\n\tcase Ctrl_E:\t    // end of command line\n\tcase K_END:\n\tcase K_KEND:\n\tcase K_S_END:\n\tcase K_C_END:\n\t\tccline.cmdpos = ccline.cmdlen;\n\t\tset_cmdspos_cursor();\n\t\tgoto cmdline_not_changed;\n\n\tcase Ctrl_A:\t    // all matches\n\t\tif (cmdline_pum_active())\n\t\t    // As Ctrl-A completes all the matches, close the popup\n\t\t    // menu (if present)\n\t\t    cmdline_pum_cleanup(&ccline);\n\n\t\tif (nextwild(&xpc, WILD_ALL, 0, firstc != '@') == FAIL)\n\t\t    break;\n\t\txpc.xp_context = EXPAND_NOTHING;\n\t\tdid_wild_list = FALSE;\n\t\tgoto cmdline_changed;\n\n\tcase Ctrl_L:\n#ifdef FEAT_SEARCH_EXTRA\n\t\tif (may_add_char_to_search(firstc, &c, &is_state) == OK)\n\t\t    goto cmdline_not_changed;\n#endif\n\n\t\t// completion: longest common part\n\t\tif (nextwild(&xpc, WILD_LONGEST, 0, firstc != '@') == FAIL)\n\t\t    break;\n\t\tgoto cmdline_changed;\n\n\tcase Ctrl_N:\t    // next match\n\tcase Ctrl_P:\t    // previous match\n\t\tif (xpc.xp_numfiles > 0)\n\t\t{\n\t\t    wild_type = (c == Ctrl_P) ? WILD_PREV : WILD_NEXT;\n\t\t    if (nextwild(&xpc, wild_type, 0, firstc != '@') == FAIL)\n\t\t\tbreak;\n\t\t    goto cmdline_not_changed;\n\t\t}\n\t\t// FALLTHROUGH\n\tcase K_UP:\n\tcase K_DOWN:\n\tcase K_S_UP:\n\tcase K_S_DOWN:\n\tcase K_PAGEUP:\n\tcase K_KPAGEUP:\n\tcase K_PAGEDOWN:\n\tcase K_KPAGEDOWN:\n\t\tif (cmdline_pum_active()\n\t\t\t&& (c == K_PAGEUP || c == K_PAGEDOWN ||\n\t\t\t    c == K_KPAGEUP || c == K_KPAGEDOWN))\n\t\t{\n\t\t    // If the popup menu is displayed, then PageUp and PageDown\n\t\t    // are used to scroll the menu.\n\t\t    wild_type = WILD_PAGEUP;\n\t\t    if (c == K_PAGEDOWN || c == K_KPAGEDOWN)\n\t\t\twild_type = WILD_PAGEDOWN;\n\t\t    if (nextwild(&xpc, wild_type, 0, firstc != '@') == FAIL)\n\t\t\tbreak;\n\t\t    goto cmdline_not_changed;\n\t\t}\n\t\telse\n\t\t{\n\t\t    res = cmdline_browse_history(c, firstc, &lookfor, histype,\n\t\t\t    &hiscnt, &xpc);\n\t\t    if (res == CMDLINE_CHANGED)\n\t\t\tgoto cmdline_changed;\n\t\t    else if (res == GOTO_NORMAL_MODE)\n\t\t\tgoto returncmd;\n\t\t}\n\t\tgoto cmdline_not_changed;\n\n#ifdef FEAT_SEARCH_EXTRA\n\tcase Ctrl_G:\t    // next match\n\tcase Ctrl_T:\t    // previous match\n\t\tif (may_adjust_incsearch_highlighting(\n\t\t\t\t\t  firstc, count, &is_state, c) == FAIL)\n\t\t    goto cmdline_not_changed;\n\t\tbreak;\n#endif\n\n\tcase Ctrl_V:\n\tcase Ctrl_Q:\n\t\t{\n\t\t    ignore_drag_release = TRUE;\n\t\t    putcmdline('^', TRUE);\n\n\t\t    // Get next (two) character(s).  Do not change any\n\t\t    // modifyOtherKeys ESC sequence to a normal key for\n\t\t    // CTRL-SHIFT-V.\n\t\t    c = get_literal(mod_mask & MOD_MASK_SHIFT);\n\n\t\t    do_abbr = FALSE;\t    // don't do abbreviation now\n\t\t    extra_char = NUL;\n\t\t    // may need to remove ^ when composing char was typed\n\t\t    if (enc_utf8 && utf_iscomposing(c) && !cmd_silent)\n\t\t    {\n\t\t\tdraw_cmdline(ccline.cmdpos,\n\t\t\t\t\t\tccline.cmdlen - ccline.cmdpos);\n\t\t\tmsg_putchar(' ');\n\t\t\tcursorcmd();\n\t\t    }\n\t\t}\n\n\t\tbreak;\n\n#ifdef FEAT_DIGRAPHS\n\tcase Ctrl_K:\n\t\tignore_drag_release = TRUE;\n\t\tputcmdline('?', TRUE);\n# ifdef USE_ON_FLY_SCROLL\n\t\tdont_scroll = TRUE;\t    // disallow scrolling here\n# endif\n\t\tc = get_digraph(TRUE);\n\t\textra_char = NUL;\n\t\tif (c != NUL)\n\t\t    break;\n\n\t\tredrawcmd();\n\t\tgoto cmdline_not_changed;\n#endif // FEAT_DIGRAPHS\n\n#ifdef FEAT_RIGHTLEFT\n\tcase Ctrl__:\t    // CTRL-_: switch language mode\n\t\tif (!p_ari)\n\t\t    break;\n\t\tcmd_hkmap = !cmd_hkmap;\n\t\tgoto cmdline_not_changed;\n#endif\n\n\tcase K_PS:\n\t\tbracketed_paste(PASTE_CMDLINE, FALSE, NULL);\n\t\tgoto cmdline_changed;\n\n\tdefault:\n#ifdef UNIX\n\t\tif (c == intr_char)\n\t\t{\n\t\t    gotesc = TRUE;\t// will free ccline.cmdbuff after\n\t\t\t\t\t// putting it in history\n\t\t    goto returncmd;\t// back to Normal mode\n\t\t}\n#endif\n\t\t/*\n\t\t * Normal character with no special meaning.  Just set mod_mask\n\t\t * to 0x0 so that typing Shift-Space in the GUI doesn't enter\n\t\t * the string .  This should only happen after ^V.\n\t\t */\n\t\tif (!IS_SPECIAL(c))\n\t\t    mod_mask = 0x0;\n\t\tbreak;\n\t}\n\t/*\n\t * End of switch on command line character.\n\t * We come here if we have a normal character.\n\t */\n\n\tif (do_abbr && (IS_SPECIAL(c) || !vim_iswordc(c))\n\t\t&& (ccheck_abbr(\n\t\t\t// Add ABBR_OFF for characters above 0x100, this is\n\t\t\t// what check_abbr() expects.\n\t\t\t\t(has_mbyte && c >= 0x100) ? (c + ABBR_OFF) : c)\n\t\t    || c == Ctrl_RSB))\n\t    goto cmdline_changed;\n\n\t/*\n\t * put the character in the command line\n\t */\n\tif (IS_SPECIAL(c) || mod_mask != 0)\n\t    put_on_cmdline(get_special_key_name(c, mod_mask), -1, TRUE);\n\telse\n\t{\n\t    if (has_mbyte)\n\t    {\n\t\tj = (*mb_char2bytes)(c, IObuff);\n\t\tIObuff[j] = NUL;\t// exclude composing chars\n\t\tput_on_cmdline(IObuff, j, TRUE);\n\t    }\n\t    else\n\t    {\n\t\tIObuff[0] = c;\n\t\tput_on_cmdline(IObuff, 1, TRUE);\n\t    }\n\t}\n\tgoto cmdline_changed;\n\n/*\n * This part implements incremental searches for \"/\" and \"?\"\n * Jump to cmdline_not_changed when a character has been read but the command\n * line did not change. Then we only search and redraw if something changed in\n * the past.\n * Jump to cmdline_changed when the command line did change.\n * (Sorry for the goto's, I know it is ugly).\n */\ncmdline_not_changed:\n#ifdef FEAT_SEARCH_EXTRA\n\tif (!is_state.incsearch_postponed)\n\t    continue;\n#endif\n\ncmdline_changed:\n#ifdef FEAT_SEARCH_EXTRA\n\t// If the window changed incremental search state is not valid.\n\tif (is_state.winid != curwin->w_id)\n\t    init_incsearch_state(&is_state);\n#endif\n\tif (trigger_cmdlinechanged)\n\t    // Trigger CmdlineChanged autocommands.\n\t    trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINECHANGED);\n\n#ifdef FEAT_SEARCH_EXTRA\n\tif (xpc.xp_context == EXPAND_NOTHING && (KeyTyped || vpeekc() == NUL))\n\t    may_do_incsearch_highlighting(firstc, count, &is_state);\n#endif\n\n#ifdef FEAT_RIGHTLEFT\n\tif (cmdmsg_rl\n# ifdef FEAT_ARABIC\n\t\t|| (p_arshape && !p_tbidi\n\t\t\t\t       && cmdline_has_arabic(0, ccline.cmdlen))\n# endif\n\t\t)\n\t    // Always redraw the whole command line to fix shaping and\n\t    // right-left typing.  Not efficient, but it works.\n\t    // Do it only when there are no characters left to read\n\t    // to avoid useless intermediate redraws.\n\t    if (vpeekc() == NUL)\n\t\tredrawcmd();\n#endif\n    }\n\nreturncmd:\n\n#ifdef FEAT_RIGHTLEFT\n    cmdmsg_rl = FALSE;\n#endif\n\n    ExpandCleanup(&xpc);\n    ccline.xpc = NULL;\n\n#ifdef FEAT_SEARCH_EXTRA\n    finish_incsearch_highlighting(gotesc, &is_state, FALSE);\n#endif\n\n    if (ccline.cmdbuff != NULL)\n    {\n\t/*\n\t * Put line in history buffer (\":\" and \"=\" only when it was typed).\n\t */\n\tif (ccline.cmdlen && firstc != NUL\n\t\t&& (some_key_typed || histype == HIST_SEARCH))\n\t{\n\t    add_to_history(histype, ccline.cmdbuff, TRUE,\n\t\t\t\t       histype == HIST_SEARCH ? firstc : NUL);\n\t    if (firstc == ':')\n\t    {\n\t\tvim_free(new_last_cmdline);\n\t\tnew_last_cmdline = vim_strsave(ccline.cmdbuff);\n\t    }\n\t}\n\n\tif (gotesc)\n\t    abandon_cmdline();\n    }\n\n    /*\n     * If the screen was shifted up, redraw the whole screen (later).\n     * If the line is too long, clear it, so ruler and shown command do\n     * not get printed in the middle of it.\n     */\n    msg_check();\n    msg_scroll = save_msg_scroll;\n    redir_off = FALSE;\n\n    // When the command line was typed, no need for a wait-return prompt.\n    if (some_key_typed)\n\tneed_wait_return = FALSE;\n\n    // Trigger CmdlineLeave autocommands.\n    trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINELEAVE);\n\n    State = save_State;\n\n#ifdef FEAT_EVAL\n    if (!debug_mode)\n\tmay_trigger_modechanged();\n#endif\n\n#ifdef HAVE_INPUT_METHOD\n    if (b_im_ptr != NULL && buf_valid(b_im_ptr_buf)\n\t\t\t\t\t\t  && *b_im_ptr != B_IMODE_LMAP)\n\tim_save_status(b_im_ptr);\n    im_set_active(FALSE);\n#endif\n    setmouse();\n#ifdef CURSOR_SHAPE\n    ui_cursor_shape();\t\t// may show different cursor shape\n#endif\n    sb_text_end_cmdline();\n\ntheend:\n    {\n\tchar_u *p = ccline.cmdbuff;\n\n\t--depth;\n\tif (did_save_ccline)\n\t    restore_cmdline(&save_ccline);\n\telse\n\t    ccline.cmdbuff = NULL;\n\treturn p;\n    }\n}", "func_hash": 287277157755538522084742430465983420799, "file_name": "ex_getln.c", "file_hash": 200105240926561396065075027208565202210, "cwe": ["CWE-416"], "cve": "CVE-2022-3235", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 9.0.0490.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3235"}
{"idx": 208987, "project": "MilkyTracker", "commit_id": "7afd55c42ad80d01a339197a2d8b5461d214edaf", "project_url": "https://github.com/milkytracker/MilkyTracker", "commit_url": "https://github.com/milkytracker/MilkyTracker/commit/7afd55c42ad80d01a339197a2d8b5461d214edaf", "commit_message": "Fix use-after-free in PlayerGeneric destructor", "target": 1, "func": "PlayerGeneric::~PlayerGeneric()\n{\n\tif (mixer)\n\t\tdelete mixer;\n\n\tif (player)\n\t{\n\t\tif (mixer->isActive() && !mixer->isDeviceRemoved(player))\n\t\t\tmixer->removeDevice(player);\n\t\tdelete player;\n\t}\n\n\tdelete[] audioDriverName;\n\t\n\tdelete listener;\n}", "func_hash": 259737108889128783455987997759442352236, "file_name": "PlayerGeneric.cpp", "file_hash": 257439638235883999405270646373445692221, "cwe": ["CWE-416"], "cve": "CVE-2020-15569", "cve_desc": "PlayerGeneric.cpp in MilkyTracker through 1.02.00 has a use-after-free in the PlayerGeneric destructor.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15569"}
{"idx": 417093, "project": "MilkyTracker", "commit_id": "7afd55c42ad80d01a339197a2d8b5461d214edaf", "project_url": "https://github.com/milkytracker/MilkyTracker", "commit_url": "https://github.com/milkytracker/MilkyTracker/commit/7afd55c42ad80d01a339197a2d8b5461d214edaf", "commit_message": "Fix use-after-free in PlayerGeneric destructor", "target": 0, "func": "PlayerGeneric::~PlayerGeneric()\n{\n\n\tif (player)\n\t{\n\t\tif (mixer && mixer->isActive() && !mixer->isDeviceRemoved(player))\n\t\t\tmixer->removeDevice(player);\n\t\tdelete player;\n\t}\n\t\n\tif (mixer)\n\t\tdelete mixer;\n\n\tdelete[] audioDriverName;\n\t\n\tdelete listener;\n}", "func_hash": 322349041921925160891638302386197132402, "file_name": "PlayerGeneric.cpp", "file_hash": 114108410020377773864246355219706856245, "cwe": ["CWE-416"], "cve": "CVE-2020-15569", "cve_desc": "PlayerGeneric.cpp in MilkyTracker through 1.02.00 has a use-after-free in the PlayerGeneric destructor.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-15569"}
{"idx": 209026, "project": "libvirt", "commit_id": "4c4d0e2da07b5a035b26a0ff13ec27070f7c7b1a", "project_url": "https://github.com/libvirt/libvirt", "commit_url": "https://gitlab.com/libvirt/libvirt/-/commit/4c4d0e2da07b5a035b26a0ff13ec27070f7c7b1a", "commit_message": "conf: Fix segfault when parsing mdev types\n\nCommit f1b0890 introduced a potential crash due to incorrect operator\nprecedence when accessing an element from a pointer to an array.\n\nBacktrace below:\n\n  #0  virNodeDeviceGetMdevTypesCaps (sysfspath=0x7fff801661e0 \"/sys/devices/pci0000:00/0000:00:02.0\", mdev_types=0x7fff801c9b40, nmdev_types=0x7fff801c9b48) at ../src/conf/node_device_conf.c:2676\n  #1  0x00007ffff7caf53d in virNodeDeviceGetPCIDynamicCaps (sysfsPath=0x7fff801661e0 \"/sys/devices/pci0000:00/0000:00:02.0\", pci_dev=0x7fff801c9ac8) at ../src/conf/node_device_conf.c:2705\n  #2  0x00007ffff7cae38f in virNodeDeviceUpdateCaps (def=0x7fff80168a10) at ../src/conf/node_device_conf.c:2342\n  #3  0x00007ffff7cb11c0 in virNodeDeviceObjMatch (obj=0x7fff84002e50, flags=0) at ../src/conf/virnodedeviceobj.c:850\n  #4  0x00007ffff7cb153d in virNodeDeviceObjListExportCallback (payload=0x7fff84002e50, name=0x7fff801cbc20 \"pci_0000_00_02_0\", opaque=0x7fffe2ffc6a0) at ../src/conf/virnodedeviceobj.c:909\n  #5  0x00007ffff7b69146 in virHashForEach (table=0x7fff9814b700 = {...}, iter=0x7ffff7cb149e , opaque=0x7fffe2ffc6a0) at ../src/util/virhash.c:394\n  #6  0x00007ffff7cb1694 in virNodeDeviceObjListExport (conn=0x7fff98013170, devs=0x7fff98154430, devices=0x7fffe2ffc798, filter=0x7ffff7cf47a1 , flags=0)\n          at ../src/conf/virnodedeviceobj.c:943\n  #7  0x00007fffe00694b2 in nodeConnectListAllNodeDevices (conn=0x7fff98013170, devices=0x7fffe2ffc798, flags=0) at ../src/node_device/node_device_driver.c:228\n  #8  0x00007ffff7e703aa in virConnectListAllNodeDevices (conn=0x7fff98013170, devices=0x7fffe2ffc798, flags=0) at ../src/libvirt-nodedev.c:130\n  #9  0x000055555557f796 in remoteDispatchConnectListAllNodeDevices (server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000, rerr=0x7fffe2ffc8a0, args=0x7fffd4008470, ret=0x7fffd40084e0)\n          at src/remote/remote_daemon_dispatch_stubs.h:1613\n  #10 0x000055555557f6f9 in remoteDispatchConnectListAllNodeDevicesHelper (server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000, rerr=0x7fffe2ffc8a0, args=0x7fffd4008470, ret=0x7fffd40084e0)\n          at src/remote/remote_daemon_dispatch_stubs.h:1591\n  #11 0x00007ffff7ce9542 in virNetServerProgramDispatchCall (prog=0x555555690c10, server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000) at ../src/rpc/virnetserverprogram.c:428\n  #12 0x00007ffff7ce90bd in virNetServerProgramDispatch (prog=0x555555690c10, server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000) at ../src/rpc/virnetserverprogram.c:302\n  #13 0x00007ffff7cf042b in virNetServerProcessMsg (srv=0x555555627080, client=0x5555556bf050, prog=0x555555690c10, msg=0x5555556c0000) at ../src/rpc/virnetserver.c:137\n  #14 0x00007ffff7cf04eb in virNetServerHandleJob (jobOpaque=0x5555556b66b0, opaque=0x555555627080) at ../src/rpc/virnetserver.c:154\n  #15 0x00007ffff7bd912f in virThreadPoolWorker (opaque=0x55555562bc70) at ../src/util/virthreadpool.c:163\n  #16 0x00007ffff7bd8645 in virThreadHelper (data=0x55555562bc90) at ../src/util/virthread.c:233\n  #17 0x00007ffff6d90432 in start_thread () at /lib64/libpthread.so.0\n  #18 0x00007ffff75c5913 in clone () at /lib64/libc.so.6\n\nSigned-off-by: Jonathon Jongsma \nReviewed-by: J\u00e1n Tomko \nSigned-off-by: J\u00e1n Tomko ", "target": 1, "func": "virNodeDeviceGetMdevTypesCaps(const char *sysfspath,\n                              virMediatedDeviceTypePtr **mdev_types,\n                              size_t *nmdev_types)\n{\n    virMediatedDeviceTypePtr *types = NULL;\n    size_t ntypes = 0;\n    size_t i;\n\n    /* this could be a refresh, so clear out the old data */\n    for (i = 0; i < *nmdev_types; i++)\n       virMediatedDeviceTypeFree(*mdev_types[i]);\n    VIR_FREE(*mdev_types);\n    *nmdev_types = 0;\n\n    if (virMediatedDeviceGetMdevTypes(sysfspath, &types, &ntypes) < 0)\n        return -1;\n\n    *mdev_types = g_steal_pointer(&types);\n    *nmdev_types = ntypes;\n\n    return 0;\n}", "func_hash": 87286221830836043224209896676991521270, "file_name": "node_device_conf.c", "file_hash": 38019949320953450079385512587806047567, "cwe": ["CWE-119"], "cve": "CVE-2021-3559", "cve_desc": "A flaw was found in libvirt in the virConnectListAllNodeDevices API in versions before 7.0.0. It only affects hosts with a PCI device and driver that supports mediated devices (e.g., GRID driver). This flaw could be used by an unprivileged client with a read-only connection to crash the libvirt daemon by executing the 'nodedev-list' virsh command. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3559"}
{"idx": 417472, "project": "libvirt", "commit_id": "4c4d0e2da07b5a035b26a0ff13ec27070f7c7b1a", "project_url": "https://github.com/libvirt/libvirt", "commit_url": "https://gitlab.com/libvirt/libvirt/-/commit/4c4d0e2da07b5a035b26a0ff13ec27070f7c7b1a", "commit_message": "conf: Fix segfault when parsing mdev types\n\nCommit f1b0890 introduced a potential crash due to incorrect operator\nprecedence when accessing an element from a pointer to an array.\n\nBacktrace below:\n\n  #0  virNodeDeviceGetMdevTypesCaps (sysfspath=0x7fff801661e0 \"/sys/devices/pci0000:00/0000:00:02.0\", mdev_types=0x7fff801c9b40, nmdev_types=0x7fff801c9b48) at ../src/conf/node_device_conf.c:2676\n  #1  0x00007ffff7caf53d in virNodeDeviceGetPCIDynamicCaps (sysfsPath=0x7fff801661e0 \"/sys/devices/pci0000:00/0000:00:02.0\", pci_dev=0x7fff801c9ac8) at ../src/conf/node_device_conf.c:2705\n  #2  0x00007ffff7cae38f in virNodeDeviceUpdateCaps (def=0x7fff80168a10) at ../src/conf/node_device_conf.c:2342\n  #3  0x00007ffff7cb11c0 in virNodeDeviceObjMatch (obj=0x7fff84002e50, flags=0) at ../src/conf/virnodedeviceobj.c:850\n  #4  0x00007ffff7cb153d in virNodeDeviceObjListExportCallback (payload=0x7fff84002e50, name=0x7fff801cbc20 \"pci_0000_00_02_0\", opaque=0x7fffe2ffc6a0) at ../src/conf/virnodedeviceobj.c:909\n  #5  0x00007ffff7b69146 in virHashForEach (table=0x7fff9814b700 = {...}, iter=0x7ffff7cb149e , opaque=0x7fffe2ffc6a0) at ../src/util/virhash.c:394\n  #6  0x00007ffff7cb1694 in virNodeDeviceObjListExport (conn=0x7fff98013170, devs=0x7fff98154430, devices=0x7fffe2ffc798, filter=0x7ffff7cf47a1 , flags=0)\n          at ../src/conf/virnodedeviceobj.c:943\n  #7  0x00007fffe00694b2 in nodeConnectListAllNodeDevices (conn=0x7fff98013170, devices=0x7fffe2ffc798, flags=0) at ../src/node_device/node_device_driver.c:228\n  #8  0x00007ffff7e703aa in virConnectListAllNodeDevices (conn=0x7fff98013170, devices=0x7fffe2ffc798, flags=0) at ../src/libvirt-nodedev.c:130\n  #9  0x000055555557f796 in remoteDispatchConnectListAllNodeDevices (server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000, rerr=0x7fffe2ffc8a0, args=0x7fffd4008470, ret=0x7fffd40084e0)\n          at src/remote/remote_daemon_dispatch_stubs.h:1613\n  #10 0x000055555557f6f9 in remoteDispatchConnectListAllNodeDevicesHelper (server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000, rerr=0x7fffe2ffc8a0, args=0x7fffd4008470, ret=0x7fffd40084e0)\n          at src/remote/remote_daemon_dispatch_stubs.h:1591\n  #11 0x00007ffff7ce9542 in virNetServerProgramDispatchCall (prog=0x555555690c10, server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000) at ../src/rpc/virnetserverprogram.c:428\n  #12 0x00007ffff7ce90bd in virNetServerProgramDispatch (prog=0x555555690c10, server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000) at ../src/rpc/virnetserverprogram.c:302\n  #13 0x00007ffff7cf042b in virNetServerProcessMsg (srv=0x555555627080, client=0x5555556bf050, prog=0x555555690c10, msg=0x5555556c0000) at ../src/rpc/virnetserver.c:137\n  #14 0x00007ffff7cf04eb in virNetServerHandleJob (jobOpaque=0x5555556b66b0, opaque=0x555555627080) at ../src/rpc/virnetserver.c:154\n  #15 0x00007ffff7bd912f in virThreadPoolWorker (opaque=0x55555562bc70) at ../src/util/virthreadpool.c:163\n  #16 0x00007ffff7bd8645 in virThreadHelper (data=0x55555562bc90) at ../src/util/virthread.c:233\n  #17 0x00007ffff6d90432 in start_thread () at /lib64/libpthread.so.0\n  #18 0x00007ffff75c5913 in clone () at /lib64/libc.so.6\n\nSigned-off-by: Jonathon Jongsma \nReviewed-by: J\u00e1n Tomko \nSigned-off-by: J\u00e1n Tomko ", "target": 0, "func": "virNodeDeviceGetMdevTypesCaps(const char *sysfspath,\n                              virMediatedDeviceTypePtr **mdev_types,\n                              size_t *nmdev_types)\n{\n    virMediatedDeviceTypePtr *types = NULL;\n    size_t ntypes = 0;\n    size_t i;\n\n    /* this could be a refresh, so clear out the old data */\n    for (i = 0; i < *nmdev_types; i++)\n       virMediatedDeviceTypeFree((*mdev_types)[i]);\n    VIR_FREE(*mdev_types);\n    *nmdev_types = 0;\n\n    if (virMediatedDeviceGetMdevTypes(sysfspath, &types, &ntypes) < 0)\n        return -1;\n\n    *mdev_types = g_steal_pointer(&types);\n    *nmdev_types = ntypes;\n\n    return 0;\n}", "func_hash": 41677585075086071603512617130977145017, "file_name": "node_device_conf.c", "file_hash": 190835973650812059595485281579904597762, "cwe": ["CWE-119"], "cve": "CVE-2021-3559", "cve_desc": "A flaw was found in libvirt in the virConnectListAllNodeDevices API in versions before 7.0.0. It only affects hosts with a PCI device and driver that supports mediated devices (e.g., GRID driver). This flaw could be used by an unprivileged client with a read-only connection to crash the libvirt daemon by executing the 'nodedev-list' virsh command. The highest threat from this vulnerability is to system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3559"}
{"idx": 209102, "project": "vim", "commit_id": "80525751c5ce9ed82c41d83faf9ef38667bf61b1", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1", "commit_message": "patch 9.0.0259: crash with mouse click when not initialized\n\nProblem:    Crash with mouse click when not initialized.\nSolution:   Check TabPageIdxs[] is not NULL.", "target": 1, "func": "do_mouse(\n    oparg_T\t*oap,\t\t// operator argument, can be NULL\n    int\t\tc,\t\t// K_LEFTMOUSE, etc\n    int\t\tdir,\t\t// Direction to 'put' if necessary\n    long\tcount,\n    int\t\tfixindent)\t// PUT_FIXINDENT if fixing indent necessary\n{\n    static int\tdo_always = FALSE;\t// ignore 'mouse' setting next time\n    static int\tgot_click = FALSE;\t// got a click some time back\n\n    int\t\twhich_button;\t// MOUSE_LEFT, _MIDDLE or _RIGHT\n    int\t\tis_click = FALSE; // If FALSE it's a drag or release event\n    int\t\tis_drag = FALSE;  // If TRUE it's a drag event\n    int\t\tjump_flags = 0;\t// flags for jump_to_mouse()\n    pos_T\tstart_visual;\n    int\t\tmoved;\t\t// Has cursor moved?\n    int\t\tin_status_line;\t// mouse in status line\n    static int\tin_tab_line = FALSE; // mouse clicked in tab line\n    int\t\tin_sep_line;\t// mouse in vertical separator line\n    int\t\tc1, c2;\n#if defined(FEAT_FOLDING)\n    pos_T\tsave_cursor;\n#endif\n    win_T\t*old_curwin = curwin;\n    static pos_T orig_cursor;\n    colnr_T\tleftcol, rightcol;\n    pos_T\tend_visual;\n    int\t\tdiff;\n    int\t\told_active = VIsual_active;\n    int\t\told_mode = VIsual_mode;\n    int\t\tregname;\n\n#if defined(FEAT_FOLDING)\n    save_cursor = curwin->w_cursor;\n#endif\n\n    // When GUI is active, always recognize mouse events, otherwise:\n    // - Ignore mouse event in normal mode if 'mouse' doesn't include 'n'.\n    // - Ignore mouse event in visual mode if 'mouse' doesn't include 'v'.\n    // - For command line and insert mode 'mouse' is checked before calling\n    //\t do_mouse().\n    if (do_always)\n\tdo_always = FALSE;\n    else\n#ifdef FEAT_GUI\n\tif (!gui.in_use)\n#endif\n\t{\n\t    if (VIsual_active)\n\t    {\n\t\tif (!mouse_has(MOUSE_VISUAL))\n\t\t    return FALSE;\n\t    }\n\t    else if (State == MODE_NORMAL && !mouse_has(MOUSE_NORMAL))\n\t\treturn FALSE;\n\t}\n\n    for (;;)\n    {\n\twhich_button = get_mouse_button(KEY2TERMCAP1(c), &is_click, &is_drag);\n\tif (is_drag)\n\t{\n\t    // If the next character is the same mouse event then use that\n\t    // one. Speeds up dragging the status line.\n\t    // Note: Since characters added to the stuff buffer in the code\n\t    // below need to come before the next character, do not do this\n\t    // when the current character was stuffed.\n\t    if (!KeyStuffed && vpeekc() != NUL)\n\t    {\n\t\tint nc;\n\t\tint save_mouse_row = mouse_row;\n\t\tint save_mouse_col = mouse_col;\n\n\t\t// Need to get the character, peeking doesn't get the actual\n\t\t// one.\n\t\tnc = safe_vgetc();\n\t\tif (c == nc)\n\t\t    continue;\n\t\tvungetc(nc);\n\t\tmouse_row = save_mouse_row;\n\t\tmouse_col = save_mouse_col;\n\t    }\n\t}\n\tbreak;\n    }\n\n    if (c == K_MOUSEMOVE)\n    {\n\t// Mouse moved without a button pressed.\n#ifdef FEAT_BEVAL_TERM\n\tui_may_remove_balloon();\n\tif (p_bevalterm)\n\t{\n\t    profile_setlimit(p_bdlay, &bevalexpr_due);\n\t    bevalexpr_due_set = TRUE;\n\t}\n#endif\n#ifdef FEAT_PROP_POPUP\n\tpopup_handle_mouse_moved();\n#endif\n\treturn FALSE;\n    }\n\n#ifdef FEAT_MOUSESHAPE\n    // May have stopped dragging the status or separator line.  The pointer is\n    // most likely still on the status or separator line.\n    if (!is_drag && drag_status_line)\n    {\n\tdrag_status_line = FALSE;\n\tupdate_mouseshape(SHAPE_IDX_STATUS);\n    }\n    if (!is_drag && drag_sep_line)\n    {\n\tdrag_sep_line = FALSE;\n\tupdate_mouseshape(SHAPE_IDX_VSEP);\n    }\n#endif\n\n    // Ignore drag and release events if we didn't get a click.\n    if (is_click)\n\tgot_click = TRUE;\n    else\n    {\n\tif (!got_click)\t\t\t// didn't get click, ignore\n\t    return FALSE;\n\tif (!is_drag)\t\t\t// release, reset got_click\n\t{\n\t    got_click = FALSE;\n\t    if (in_tab_line)\n\t    {\n\t\tin_tab_line = FALSE;\n\t\treturn FALSE;\n\t    }\n\t}\n    }\n\n    // CTRL right mouse button does CTRL-T\n    if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_RIGHT)\n    {\n\tif (State & MODE_INSERT)\n\t    stuffcharReadbuff(Ctrl_O);\n\tif (count > 1)\n\t    stuffnumReadbuff(count);\n\tstuffcharReadbuff(Ctrl_T);\n\tgot_click = FALSE;\t\t// ignore drag&release now\n\treturn FALSE;\n    }\n\n    // CTRL only works with left mouse button\n    if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT)\n\treturn FALSE;\n\n    // When a modifier is down, ignore drag and release events, as well as\n    // multiple clicks and the middle mouse button.\n    // Accept shift-leftmouse drags when 'mousemodel' is \"popup.*\".\n    if ((mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT\n\t\t\t\t\t\t\t     | MOD_MASK_META))\n\t    && (!is_click\n\t\t|| (mod_mask & MOD_MASK_MULTI_CLICK)\n\t\t|| which_button == MOUSE_MIDDLE)\n\t    && !((mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT))\n\t\t&& mouse_model_popup()\n\t\t&& which_button == MOUSE_LEFT)\n\t    && !((mod_mask & MOD_MASK_ALT)\n\t\t&& !mouse_model_popup()\n\t\t&& which_button == MOUSE_RIGHT)\n\t    )\n\treturn FALSE;\n\n    // If the button press was used as the movement command for an operator\n    // (eg \"d\"), or it is the middle button that is held down, ignore\n    // drag/release events.\n    if (!is_click && which_button == MOUSE_MIDDLE)\n\treturn FALSE;\n\n    if (oap != NULL)\n\tregname = oap->regname;\n    else\n\tregname = 0;\n\n    // Middle mouse button does a 'put' of the selected text\n    if (which_button == MOUSE_MIDDLE)\n    {\n\tif (State == MODE_NORMAL)\n\t{\n\t    // If an operator was pending, we don't know what the user wanted\n\t    // to do. Go back to normal mode: Clear the operator and beep().\n\t    if (oap != NULL && oap->op_type != OP_NOP)\n\t    {\n\t\tclearopbeep(oap);\n\t\treturn FALSE;\n\t    }\n\n\t    // If visual was active, yank the highlighted text and put it\n\t    // before the mouse pointer position.\n\t    // In Select mode replace the highlighted text with the clipboard.\n\t    if (VIsual_active)\n\t    {\n\t\tif (VIsual_select)\n\t\t{\n\t\t    stuffcharReadbuff(Ctrl_G);\n\t\t    stuffReadbuff((char_u *)\"\\\"+p\");\n\t\t}\n\t\telse\n\t\t{\n\t\t    stuffcharReadbuff('y');\n\t\t    stuffcharReadbuff(K_MIDDLEMOUSE);\n\t\t}\n\t\tdo_always = TRUE;\t// ignore 'mouse' setting next time\n\t\treturn FALSE;\n\t    }\n\t    // The rest is below jump_to_mouse()\n\t}\n\n\telse if ((State & MODE_INSERT) == 0)\n\t    return FALSE;\n\n\t// Middle click in insert mode doesn't move the mouse, just insert the\n\t// contents of a register.  '.' register is special, can't insert that\n\t// with do_put().\n\t// Also paste at the cursor if the current mode isn't in 'mouse' (only\n\t// happens for the GUI).\n\tif ((State & MODE_INSERT) || !mouse_has(MOUSE_NORMAL))\n\t{\n\t    if (regname == '.')\n\t\tinsert_reg(regname, TRUE);\n\t    else\n\t    {\n#ifdef FEAT_CLIPBOARD\n\t\tif (clip_star.available && regname == 0)\n\t\t    regname = '*';\n#endif\n\t\tif ((State & REPLACE_FLAG) && !yank_register_mline(regname))\n\t\t    insert_reg(regname, TRUE);\n\t\telse\n\t\t{\n\t\t    do_put(regname, NULL, BACKWARD, 1L,\n\t\t\t\t\t\t      fixindent | PUT_CURSEND);\n\n\t\t    // Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r\n\t\t    AppendCharToRedobuff(Ctrl_R);\n\t\t    AppendCharToRedobuff(fixindent ? Ctrl_P : Ctrl_O);\n\t\t    AppendCharToRedobuff(regname == 0 ? '\"' : regname);\n\t\t}\n\t    }\n\t    return FALSE;\n\t}\n    }\n\n    // When dragging or button-up stay in the same window.\n    if (!is_click)\n\tjump_flags |= MOUSE_FOCUS | MOUSE_DID_MOVE;\n\n    start_visual.lnum = 0;\n\n    // Check for clicking in the tab page line.\n    if (mouse_row == 0 && firstwin->w_winrow > 0)\n    {\n\tif (is_drag)\n\t{\n\t    if (in_tab_line)\n\t    {\n\t\tc1 = TabPageIdxs[mouse_col];\n\t\ttabpage_move(c1 <= 0 ? 9999 : c1 < tabpage_index(curtab)\n\t\t\t\t\t\t\t\t? c1 - 1 : c1);\n\t    }\n\t    return FALSE;\n\t}\n\n\t// click in a tab selects that tab page\n\tif (is_click\n# ifdef FEAT_CMDWIN\n\t\t&& cmdwin_type == 0\n# endif\n\t\t&& mouse_col < Columns)\n\t{\n\t    in_tab_line = TRUE;\n\t    c1 = TabPageIdxs[mouse_col];\n\t    if (c1 >= 0)\n\t    {\n\t\tif ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t\t{\n\t\t    // double click opens new page\n\t\t    end_visual_mode_keep_button();\n\t\t    tabpage_new();\n\t\t    tabpage_move(c1 == 0 ? 9999 : c1 - 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t    // Go to specified tab page, or next one if not clicking\n\t\t    // on a label.\n\t\t    goto_tabpage(c1);\n\n\t\t    // It's like clicking on the status line of a window.\n\t\t    if (curwin != old_curwin)\n\t\t\tend_visual_mode_keep_button();\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\ttabpage_T\t*tp;\n\n\t\t// Close the current or specified tab page.\n\t\tif (c1 == -999)\n\t\t    tp = curtab;\n\t\telse\n\t\t    tp = find_tabpage(-c1);\n\t\tif (tp == curtab)\n\t\t{\n\t\t    if (first_tabpage->tp_next != NULL)\n\t\t\ttabpage_close(FALSE);\n\t\t}\n\t\telse if (tp != NULL)\n\t\t    tabpage_close_other(tp, FALSE);\n\t    }\n\t}\n\treturn TRUE;\n    }\n    else if (is_drag && in_tab_line)\n    {\n\tc1 = TabPageIdxs[mouse_col];\n\ttabpage_move(c1 <= 0 ? 9999 : c1 - 1);\n\treturn FALSE;\n    }\n\n    // When 'mousemodel' is \"popup\" or \"popup_setpos\", translate mouse events:\n    // right button up   -> pop-up menu\n    // shift-left button -> right button\n    // alt-left button   -> alt-right button\n    if (mouse_model_popup())\n    {\n\tif (which_button == MOUSE_RIGHT\n\t\t\t    && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))\n\t{\n#ifdef USE_POPUP_SETPOS\n# ifdef FEAT_GUI\n\t    if (gui.in_use)\n\t    {\n#  if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \\\n\t\t\t  || defined(FEAT_GUI_PHOTON)\n\t\tif (!is_click)\n\t\t    // Ignore right button release events, only shows the popup\n\t\t    // menu on the button down event.\n\t\t    return FALSE;\n#  endif\n#  if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_HAIKU)\n\t\tif (is_click || is_drag)\n\t\t    // Ignore right button down and drag mouse events.  Windows\n\t\t    // only shows the popup menu on the button up event.\n\t\t    return FALSE;\n#  endif\n\t    }\n# endif\n# if defined(FEAT_GUI) && defined(FEAT_TERM_POPUP_MENU)\n\t    else\n# endif\n# if defined(FEAT_TERM_POPUP_MENU)\n\t    if (!is_click)\n\t\t// Ignore right button release events, only shows the popup\n\t\t// menu on the button down event.\n\t\treturn FALSE;\n#endif\n\n\t    jump_flags = 0;\n\t    if (STRCMP(p_mousem, \"popup_setpos\") == 0)\n\t    {\n\t\t// First set the cursor position before showing the popup\n\t\t// menu.\n\t\tif (VIsual_active)\n\t\t{\n\t\t    pos_T    m_pos;\n\n\t\t    // set MOUSE_MAY_STOP_VIS if we are outside the\n\t\t    // selection or the current window (might have false\n\t\t    // negative here)\n\t\t    if (mouse_row < curwin->w_winrow\n\t\t\t || mouse_row\n\t\t\t\t  > (curwin->w_winrow + curwin->w_height))\n\t\t\tjump_flags = MOUSE_MAY_STOP_VIS;\n\t\t    else if (get_fpos_of_mouse(&m_pos) != IN_BUFFER)\n\t\t\tjump_flags = MOUSE_MAY_STOP_VIS;\n\t\t    else\n\t\t    {\n\t\t\tif ((LT_POS(curwin->w_cursor, VIsual)\n\t\t\t\t    && (LT_POS(m_pos, curwin->w_cursor)\n\t\t\t\t\t|| LT_POS(VIsual, m_pos)))\n\t\t\t\t|| (LT_POS(VIsual, curwin->w_cursor)\n\t\t\t\t    && (LT_POS(m_pos, VIsual)\n\t\t\t\t      || LT_POS(curwin->w_cursor, m_pos))))\n\t\t\t{\n\t\t\t    jump_flags = MOUSE_MAY_STOP_VIS;\n\t\t\t}\n\t\t\telse if (VIsual_mode == Ctrl_V)\n\t\t\t{\n\t\t\t    getvcols(curwin, &curwin->w_cursor, &VIsual,\n\t\t\t\t\t\t     &leftcol, &rightcol);\n\t\t\t    getvcol(curwin, &m_pos, NULL, &m_pos.col, NULL);\n\t\t\t    if (m_pos.col < leftcol || m_pos.col > rightcol)\n\t\t\t\tjump_flags = MOUSE_MAY_STOP_VIS;\n\t\t\t}\n\t\t    }\n\t\t}\n\t\telse\n\t\t    jump_flags = MOUSE_MAY_STOP_VIS;\n\t    }\n\t    if (jump_flags)\n\t    {\n\t\tjump_flags = jump_to_mouse(jump_flags, NULL, which_button);\n\t\tupdate_curbuf(VIsual_active ? UPD_INVERTED : UPD_VALID);\n\t\tsetcursor();\n\t\tout_flush();    // Update before showing popup menu\n\t    }\n# ifdef FEAT_MENU\n\t    show_popupmenu();\n\t    got_click = FALSE;\t// ignore release events\n# endif\n\t    return (jump_flags & CURSOR_MOVED) != 0;\n#else\n\t    return FALSE;\n#endif\n\t}\n\tif (which_button == MOUSE_LEFT\n\t\t\t\t&& (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT)))\n\t{\n\t    which_button = MOUSE_RIGHT;\n\t    mod_mask &= ~MOD_MASK_SHIFT;\n\t}\n    }\n\n    if ((State & (MODE_NORMAL | MODE_INSERT))\n\t\t\t    && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))\n    {\n\tif (which_button == MOUSE_LEFT)\n\t{\n\t    if (is_click)\n\t    {\n\t\t// stop Visual mode for a left click in a window, but not when\n\t\t// on a status line\n\t\tif (VIsual_active)\n\t\t    jump_flags |= MOUSE_MAY_STOP_VIS;\n\t    }\n\t    else if (mouse_has(MOUSE_VISUAL))\n\t\tjump_flags |= MOUSE_MAY_VIS;\n\t}\n\telse if (which_button == MOUSE_RIGHT)\n\t{\n\t    if (is_click && VIsual_active)\n\t    {\n\t\t// Remember the start and end of visual before moving the\n\t\t// cursor.\n\t\tif (LT_POS(curwin->w_cursor, VIsual))\n\t\t{\n\t\t    start_visual = curwin->w_cursor;\n\t\t    end_visual = VIsual;\n\t\t}\n\t\telse\n\t\t{\n\t\t    start_visual = VIsual;\n\t\t    end_visual = curwin->w_cursor;\n\t\t}\n\t    }\n\t    jump_flags |= MOUSE_FOCUS;\n\t    if (mouse_has(MOUSE_VISUAL))\n\t\tjump_flags |= MOUSE_MAY_VIS;\n\t}\n    }\n\n    // If an operator is pending, ignore all drags and releases until the\n    // next mouse click.\n    if (!is_drag && oap != NULL && oap->op_type != OP_NOP)\n    {\n\tgot_click = FALSE;\n\toap->motion_type = MCHAR;\n    }\n\n    // When releasing the button let jump_to_mouse() know.\n    if (!is_click && !is_drag)\n\tjump_flags |= MOUSE_RELEASED;\n\n    // JUMP!\n    jump_flags = jump_to_mouse(jump_flags,\n\t\t\toap == NULL ? NULL : &(oap->inclusive), which_button);\n\n#ifdef FEAT_MENU\n    // A click in the window toolbar has no side effects.\n    if (jump_flags & MOUSE_WINBAR)\n\treturn FALSE;\n#endif\n    moved = (jump_flags & CURSOR_MOVED);\n    in_status_line = (jump_flags & IN_STATUS_LINE);\n    in_sep_line = (jump_flags & IN_SEP_LINE);\n\n#ifdef FEAT_NETBEANS_INTG\n    if (isNetbeansBuffer(curbuf)\n\t\t\t    && !(jump_flags & (IN_STATUS_LINE | IN_SEP_LINE)))\n    {\n\tint key = KEY2TERMCAP1(c);\n\n\tif (key == (int)KE_LEFTRELEASE || key == (int)KE_MIDDLERELEASE\n\t\t\t\t\t       || key == (int)KE_RIGHTRELEASE)\n\t    netbeans_button_release(which_button);\n    }\n#endif\n\n    // When jumping to another window, clear a pending operator.  That's a bit\n    // friendlier than beeping and not jumping to that window.\n    if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP)\n\tclearop(oap);\n\n#ifdef FEAT_FOLDING\n    if (mod_mask == 0\n\t    && !is_drag\n\t    && (jump_flags & (MOUSE_FOLD_CLOSE | MOUSE_FOLD_OPEN))\n\t    && which_button == MOUSE_LEFT)\n    {\n\t// open or close a fold at this line\n\tif (jump_flags & MOUSE_FOLD_OPEN)\n\t    openFold(curwin->w_cursor.lnum, 1L);\n\telse\n\t    closeFold(curwin->w_cursor.lnum, 1L);\n\t// don't move the cursor if still in the same window\n\tif (curwin == old_curwin)\n\t    curwin->w_cursor = save_cursor;\n    }\n#endif\n\n#if defined(FEAT_CLIPBOARD) && defined(FEAT_CMDWIN)\n    if ((jump_flags & IN_OTHER_WIN) && !VIsual_active && clip_star.available)\n    {\n\tclip_modeless(which_button, is_click, is_drag);\n\treturn FALSE;\n    }\n#endif\n\n    // Set global flag that we are extending the Visual area with mouse\n    // dragging; temporarily minimize 'scrolloff'.\n    if (VIsual_active && is_drag && get_scrolloff_value())\n    {\n\t// In the very first line, allow scrolling one line\n\tif (mouse_row == 0)\n\t    mouse_dragging = 2;\n\telse\n\t    mouse_dragging = 1;\n    }\n\n    // When dragging the mouse above the window, scroll down.\n    if (is_drag && mouse_row < 0 && !in_status_line)\n    {\n\tscroll_redraw(FALSE, 1L);\n\tmouse_row = 0;\n    }\n\n    if (start_visual.lnum)\t\t// right click in visual mode\n    {\n       // When ALT is pressed make Visual mode blockwise.\n       if (mod_mask & MOD_MASK_ALT)\n\t   VIsual_mode = Ctrl_V;\n\n\t// In Visual-block mode, divide the area in four, pick up the corner\n\t// that is in the quarter that the cursor is in.\n\tif (VIsual_mode == Ctrl_V)\n\t{\n\t    getvcols(curwin, &start_visual, &end_visual, &leftcol, &rightcol);\n\t    if (curwin->w_curswant > (leftcol + rightcol) / 2)\n\t\tend_visual.col = leftcol;\n\t    else\n\t\tend_visual.col = rightcol;\n\t    if (curwin->w_cursor.lnum >=\n\t\t\t\t    (start_visual.lnum + end_visual.lnum) / 2)\n\t\tend_visual.lnum = start_visual.lnum;\n\n\t    // move VIsual to the right column\n\t    start_visual = curwin->w_cursor;\t    // save the cursor pos\n\t    curwin->w_cursor = end_visual;\n\t    coladvance(end_visual.col);\n\t    VIsual = curwin->w_cursor;\n\t    curwin->w_cursor = start_visual;\t    // restore the cursor\n\t}\n\telse\n\t{\n\t    // If the click is before the start of visual, change the start.\n\t    // If the click is after the end of visual, change the end.  If\n\t    // the click is inside the visual, change the closest side.\n\t    if (LT_POS(curwin->w_cursor, start_visual))\n\t\tVIsual = end_visual;\n\t    else if (LT_POS(end_visual, curwin->w_cursor))\n\t\tVIsual = start_visual;\n\t    else\n\t    {\n\t\t// In the same line, compare column number\n\t\tif (end_visual.lnum == start_visual.lnum)\n\t\t{\n\t\t    if (curwin->w_cursor.col - start_visual.col >\n\t\t\t\t    end_visual.col - curwin->w_cursor.col)\n\t\t\tVIsual = start_visual;\n\t\t    else\n\t\t\tVIsual = end_visual;\n\t\t}\n\n\t\t// In different lines, compare line number\n\t\telse\n\t\t{\n\t\t    diff = (curwin->w_cursor.lnum - start_visual.lnum) -\n\t\t\t\t(end_visual.lnum - curwin->w_cursor.lnum);\n\n\t\t    if (diff > 0)\t\t// closest to end\n\t\t\tVIsual = start_visual;\n\t\t    else if (diff < 0)\t// closest to start\n\t\t\tVIsual = end_visual;\n\t\t    else\t\t\t// in the middle line\n\t\t    {\n\t\t\tif (curwin->w_cursor.col <\n\t\t\t\t\t(start_visual.col + end_visual.col) / 2)\n\t\t\t    VIsual = end_visual;\n\t\t\telse\n\t\t\t    VIsual = start_visual;\n\t\t    }\n\t\t}\n\t    }\n\t}\n    }\n    // If Visual mode started in insert mode, execute \"CTRL-O\"\n    else if ((State & MODE_INSERT) && VIsual_active)\n\tstuffcharReadbuff(Ctrl_O);\n\n    // Middle mouse click: Put text before cursor.\n    if (which_button == MOUSE_MIDDLE)\n    {\n#ifdef FEAT_CLIPBOARD\n\tif (clip_star.available && regname == 0)\n\t    regname = '*';\n#endif\n\tif (yank_register_mline(regname))\n\t{\n\t    if (mouse_past_bottom)\n\t\tdir = FORWARD;\n\t}\n\telse if (mouse_past_eol)\n\t    dir = FORWARD;\n\n\tif (fixindent)\n\t{\n\t    c1 = (dir == BACKWARD) ? '[' : ']';\n\t    c2 = 'p';\n\t}\n\telse\n\t{\n\t    c1 = (dir == FORWARD) ? 'p' : 'P';\n\t    c2 = NUL;\n\t}\n\tprep_redo(regname, count, NUL, c1, NUL, c2, NUL);\n\n\t// Remember where the paste started, so in edit() Insstart can be set\n\t// to this position\n\tif (restart_edit != 0)\n\t    where_paste_started = curwin->w_cursor;\n\tdo_put(regname, NULL, dir, count, fixindent | PUT_CURSEND);\n    }\n\n#if defined(FEAT_QUICKFIX)\n    // Ctrl-Mouse click or double click in a quickfix window jumps to the\n    // error under the mouse pointer.\n    else if (((mod_mask & MOD_MASK_CTRL)\n\t\t|| (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t    && bt_quickfix(curbuf))\n    {\n\tif (curwin->w_llist_ref == NULL)\t// quickfix window\n\t    do_cmdline_cmd((char_u *)\".cc\");\n\telse\t\t\t\t\t// location list window\n\t    do_cmdline_cmd((char_u *)\".ll\");\n\tgot_click = FALSE;\t\t// ignore drag&release now\n    }\n#endif\n\n    // Ctrl-Mouse click (or double click in a help window) jumps to the tag\n    // under the mouse pointer.\n    else if ((mod_mask & MOD_MASK_CTRL) || (curbuf->b_help\n\t\t     && (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK))\n    {\n\tif (State & MODE_INSERT)\n\t    stuffcharReadbuff(Ctrl_O);\n\tstuffcharReadbuff(Ctrl_RSB);\n\tgot_click = FALSE;\t\t// ignore drag&release now\n    }\n\n    // Shift-Mouse click searches for the next occurrence of the word under\n    // the mouse pointer\n    else if ((mod_mask & MOD_MASK_SHIFT))\n    {\n\tif ((State & MODE_INSERT) || (VIsual_active && VIsual_select))\n\t    stuffcharReadbuff(Ctrl_O);\n\tif (which_button == MOUSE_LEFT)\n\t    stuffcharReadbuff('*');\n\telse\t// MOUSE_RIGHT\n\t    stuffcharReadbuff('#');\n    }\n\n    // Handle double clicks, unless on status line\n    else if (in_status_line)\n    {\n#ifdef FEAT_MOUSESHAPE\n\tif ((is_drag || is_click) && !drag_status_line)\n\t{\n\t    drag_status_line = TRUE;\n\t    update_mouseshape(-1);\n\t}\n#endif\n    }\n    else if (in_sep_line)\n    {\n#ifdef FEAT_MOUSESHAPE\n\tif ((is_drag || is_click) && !drag_sep_line)\n\t{\n\t    drag_sep_line = TRUE;\n\t    update_mouseshape(-1);\n\t}\n#endif\n    }\n    else if ((mod_mask & MOD_MASK_MULTI_CLICK)\n\t\t\t\t       && (State & (MODE_NORMAL | MODE_INSERT))\n\t     && mouse_has(MOUSE_VISUAL))\n    {\n\tif (is_click || !VIsual_active)\n\t{\n\t    if (VIsual_active)\n\t\torig_cursor = VIsual;\n\t    else\n\t    {\n\t\tcheck_visual_highlight();\n\t\tVIsual = curwin->w_cursor;\n\t\torig_cursor = VIsual;\n\t\tVIsual_active = TRUE;\n\t\tVIsual_reselect = TRUE;\n\t\t// start Select mode if 'selectmode' contains \"mouse\"\n\t\tmay_start_select('o');\n\t\tsetmouse();\n\t    }\n\t    if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t    {\n\t\t// Double click with ALT pressed makes it blockwise.\n\t\tif (mod_mask & MOD_MASK_ALT)\n\t\t    VIsual_mode = Ctrl_V;\n\t\telse\n\t\t    VIsual_mode = 'v';\n\t    }\n\t    else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK)\n\t\tVIsual_mode = 'V';\n\t    else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK)\n\t\tVIsual_mode = Ctrl_V;\n#ifdef FEAT_CLIPBOARD\n\t    // Make sure the clipboard gets updated.  Needed because start and\n\t    // end may still be the same, and the selection needs to be owned\n\t    clip_star.vmode = NUL;\n#endif\n\t}\n\t// A double click selects a word or a block.\n\tif ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t{\n\t    pos_T\t*pos = NULL;\n\t    int\t\tgc;\n\n\t    if (is_click)\n\t    {\n\t\t// If the character under the cursor (skipping white space) is\n\t\t// not a word character, try finding a match and select a (),\n\t\t// {}, [], #if/#endif, etc. block.\n\t\tend_visual = curwin->w_cursor;\n\t\twhile (gc = gchar_pos(&end_visual), VIM_ISWHITE(gc))\n\t\t    inc(&end_visual);\n\t\tif (oap != NULL)\n\t\t    oap->motion_type = MCHAR;\n\t\tif (oap != NULL\n\t\t\t&& VIsual_mode == 'v'\n\t\t\t&& !vim_iswordc(gchar_pos(&end_visual))\n\t\t\t&& EQUAL_POS(curwin->w_cursor, VIsual)\n\t\t\t&& (pos = findmatch(oap, NUL)) != NULL)\n\t\t{\n\t\t    curwin->w_cursor = *pos;\n\t\t    if (oap->motion_type == MLINE)\n\t\t\tVIsual_mode = 'V';\n\t\t    else if (*p_sel == 'e')\n\t\t    {\n\t\t\tif (LT_POS(curwin->w_cursor, VIsual))\n\t\t\t    ++VIsual.col;\n\t\t\telse\n\t\t\t    ++curwin->w_cursor.col;\n\t\t    }\n\t\t}\n\t    }\n\n\t    if (pos == NULL && (is_click || is_drag))\n\t    {\n\t\t// When not found a match or when dragging: extend to include\n\t\t// a word.\n\t\tif (LT_POS(curwin->w_cursor, orig_cursor))\n\t\t{\n\t\t    find_start_of_word(&curwin->w_cursor);\n\t\t    find_end_of_word(&VIsual);\n\t\t}\n\t\telse\n\t\t{\n\t\t    find_start_of_word(&VIsual);\n\t\t    if (*p_sel == 'e' && *ml_get_cursor() != NUL)\n\t\t\tcurwin->w_cursor.col +=\n\t\t\t\t\t (*mb_ptr2len)(ml_get_cursor());\n\t\t    find_end_of_word(&curwin->w_cursor);\n\t\t}\n\t    }\n\t    curwin->w_set_curswant = TRUE;\n\t}\n\tif (is_click)\n\t    redraw_curbuf_later(UPD_INVERTED);\t// update the inversion\n    }\n    else if (VIsual_active && !old_active)\n    {\n\tif (mod_mask & MOD_MASK_ALT)\n\t    VIsual_mode = Ctrl_V;\n\telse\n\t    VIsual_mode = 'v';\n    }\n\n    // If Visual mode changed show it later.\n    if ((!VIsual_active && old_active && mode_displayed)\n\t    || (VIsual_active && p_smd && msg_silent == 0\n\t\t\t\t && (!old_active || VIsual_mode != old_mode)))\n\tredraw_cmdline = TRUE;\n\n    return moved;\n}", "func_hash": 230981879452824566126490545559038336652, "file_name": "mouse.c", "file_hash": 48030859742909908779392834945640503907, "cwe": ["CWE-703"], "cve": "CVE-2022-2980", "cve_desc": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2980"}
{"idx": 418795, "project": "vim", "commit_id": "80525751c5ce9ed82c41d83faf9ef38667bf61b1", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1", "commit_message": "patch 9.0.0259: crash with mouse click when not initialized\n\nProblem:    Crash with mouse click when not initialized.\nSolution:   Check TabPageIdxs[] is not NULL.", "target": 0, "func": "do_mouse(\n    oparg_T\t*oap,\t\t// operator argument, can be NULL\n    int\t\tc,\t\t// K_LEFTMOUSE, etc\n    int\t\tdir,\t\t// Direction to 'put' if necessary\n    long\tcount,\n    int\t\tfixindent)\t// PUT_FIXINDENT if fixing indent necessary\n{\n    static int\tdo_always = FALSE;\t// ignore 'mouse' setting next time\n    static int\tgot_click = FALSE;\t// got a click some time back\n\n    int\t\twhich_button;\t// MOUSE_LEFT, _MIDDLE or _RIGHT\n    int\t\tis_click = FALSE; // If FALSE it's a drag or release event\n    int\t\tis_drag = FALSE;  // If TRUE it's a drag event\n    int\t\tjump_flags = 0;\t// flags for jump_to_mouse()\n    pos_T\tstart_visual;\n    int\t\tmoved;\t\t// Has cursor moved?\n    int\t\tin_status_line;\t// mouse in status line\n    static int\tin_tab_line = FALSE; // mouse clicked in tab line\n    int\t\tin_sep_line;\t// mouse in vertical separator line\n    int\t\tc1, c2;\n#if defined(FEAT_FOLDING)\n    pos_T\tsave_cursor;\n#endif\n    win_T\t*old_curwin = curwin;\n    static pos_T orig_cursor;\n    colnr_T\tleftcol, rightcol;\n    pos_T\tend_visual;\n    int\t\tdiff;\n    int\t\told_active = VIsual_active;\n    int\t\told_mode = VIsual_mode;\n    int\t\tregname;\n\n#if defined(FEAT_FOLDING)\n    save_cursor = curwin->w_cursor;\n#endif\n\n    // When GUI is active, always recognize mouse events, otherwise:\n    // - Ignore mouse event in normal mode if 'mouse' doesn't include 'n'.\n    // - Ignore mouse event in visual mode if 'mouse' doesn't include 'v'.\n    // - For command line and insert mode 'mouse' is checked before calling\n    //\t do_mouse().\n    if (do_always)\n\tdo_always = FALSE;\n    else\n#ifdef FEAT_GUI\n\tif (!gui.in_use)\n#endif\n\t{\n\t    if (VIsual_active)\n\t    {\n\t\tif (!mouse_has(MOUSE_VISUAL))\n\t\t    return FALSE;\n\t    }\n\t    else if (State == MODE_NORMAL && !mouse_has(MOUSE_NORMAL))\n\t\treturn FALSE;\n\t}\n\n    for (;;)\n    {\n\twhich_button = get_mouse_button(KEY2TERMCAP1(c), &is_click, &is_drag);\n\tif (is_drag)\n\t{\n\t    // If the next character is the same mouse event then use that\n\t    // one. Speeds up dragging the status line.\n\t    // Note: Since characters added to the stuff buffer in the code\n\t    // below need to come before the next character, do not do this\n\t    // when the current character was stuffed.\n\t    if (!KeyStuffed && vpeekc() != NUL)\n\t    {\n\t\tint nc;\n\t\tint save_mouse_row = mouse_row;\n\t\tint save_mouse_col = mouse_col;\n\n\t\t// Need to get the character, peeking doesn't get the actual\n\t\t// one.\n\t\tnc = safe_vgetc();\n\t\tif (c == nc)\n\t\t    continue;\n\t\tvungetc(nc);\n\t\tmouse_row = save_mouse_row;\n\t\tmouse_col = save_mouse_col;\n\t    }\n\t}\n\tbreak;\n    }\n\n    if (c == K_MOUSEMOVE)\n    {\n\t// Mouse moved without a button pressed.\n#ifdef FEAT_BEVAL_TERM\n\tui_may_remove_balloon();\n\tif (p_bevalterm)\n\t{\n\t    profile_setlimit(p_bdlay, &bevalexpr_due);\n\t    bevalexpr_due_set = TRUE;\n\t}\n#endif\n#ifdef FEAT_PROP_POPUP\n\tpopup_handle_mouse_moved();\n#endif\n\treturn FALSE;\n    }\n\n#ifdef FEAT_MOUSESHAPE\n    // May have stopped dragging the status or separator line.  The pointer is\n    // most likely still on the status or separator line.\n    if (!is_drag && drag_status_line)\n    {\n\tdrag_status_line = FALSE;\n\tupdate_mouseshape(SHAPE_IDX_STATUS);\n    }\n    if (!is_drag && drag_sep_line)\n    {\n\tdrag_sep_line = FALSE;\n\tupdate_mouseshape(SHAPE_IDX_VSEP);\n    }\n#endif\n\n    // Ignore drag and release events if we didn't get a click.\n    if (is_click)\n\tgot_click = TRUE;\n    else\n    {\n\tif (!got_click)\t\t\t// didn't get click, ignore\n\t    return FALSE;\n\tif (!is_drag)\t\t\t// release, reset got_click\n\t{\n\t    got_click = FALSE;\n\t    if (in_tab_line)\n\t    {\n\t\tin_tab_line = FALSE;\n\t\treturn FALSE;\n\t    }\n\t}\n    }\n\n    // CTRL right mouse button does CTRL-T\n    if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_RIGHT)\n    {\n\tif (State & MODE_INSERT)\n\t    stuffcharReadbuff(Ctrl_O);\n\tif (count > 1)\n\t    stuffnumReadbuff(count);\n\tstuffcharReadbuff(Ctrl_T);\n\tgot_click = FALSE;\t\t// ignore drag&release now\n\treturn FALSE;\n    }\n\n    // CTRL only works with left mouse button\n    if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT)\n\treturn FALSE;\n\n    // When a modifier is down, ignore drag and release events, as well as\n    // multiple clicks and the middle mouse button.\n    // Accept shift-leftmouse drags when 'mousemodel' is \"popup.*\".\n    if ((mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT\n\t\t\t\t\t\t\t     | MOD_MASK_META))\n\t    && (!is_click\n\t\t|| (mod_mask & MOD_MASK_MULTI_CLICK)\n\t\t|| which_button == MOUSE_MIDDLE)\n\t    && !((mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT))\n\t\t&& mouse_model_popup()\n\t\t&& which_button == MOUSE_LEFT)\n\t    && !((mod_mask & MOD_MASK_ALT)\n\t\t&& !mouse_model_popup()\n\t\t&& which_button == MOUSE_RIGHT)\n\t    )\n\treturn FALSE;\n\n    // If the button press was used as the movement command for an operator\n    // (eg \"d\"), or it is the middle button that is held down, ignore\n    // drag/release events.\n    if (!is_click && which_button == MOUSE_MIDDLE)\n\treturn FALSE;\n\n    if (oap != NULL)\n\tregname = oap->regname;\n    else\n\tregname = 0;\n\n    // Middle mouse button does a 'put' of the selected text\n    if (which_button == MOUSE_MIDDLE)\n    {\n\tif (State == MODE_NORMAL)\n\t{\n\t    // If an operator was pending, we don't know what the user wanted\n\t    // to do. Go back to normal mode: Clear the operator and beep().\n\t    if (oap != NULL && oap->op_type != OP_NOP)\n\t    {\n\t\tclearopbeep(oap);\n\t\treturn FALSE;\n\t    }\n\n\t    // If visual was active, yank the highlighted text and put it\n\t    // before the mouse pointer position.\n\t    // In Select mode replace the highlighted text with the clipboard.\n\t    if (VIsual_active)\n\t    {\n\t\tif (VIsual_select)\n\t\t{\n\t\t    stuffcharReadbuff(Ctrl_G);\n\t\t    stuffReadbuff((char_u *)\"\\\"+p\");\n\t\t}\n\t\telse\n\t\t{\n\t\t    stuffcharReadbuff('y');\n\t\t    stuffcharReadbuff(K_MIDDLEMOUSE);\n\t\t}\n\t\tdo_always = TRUE;\t// ignore 'mouse' setting next time\n\t\treturn FALSE;\n\t    }\n\t    // The rest is below jump_to_mouse()\n\t}\n\n\telse if ((State & MODE_INSERT) == 0)\n\t    return FALSE;\n\n\t// Middle click in insert mode doesn't move the mouse, just insert the\n\t// contents of a register.  '.' register is special, can't insert that\n\t// with do_put().\n\t// Also paste at the cursor if the current mode isn't in 'mouse' (only\n\t// happens for the GUI).\n\tif ((State & MODE_INSERT) || !mouse_has(MOUSE_NORMAL))\n\t{\n\t    if (regname == '.')\n\t\tinsert_reg(regname, TRUE);\n\t    else\n\t    {\n#ifdef FEAT_CLIPBOARD\n\t\tif (clip_star.available && regname == 0)\n\t\t    regname = '*';\n#endif\n\t\tif ((State & REPLACE_FLAG) && !yank_register_mline(regname))\n\t\t    insert_reg(regname, TRUE);\n\t\telse\n\t\t{\n\t\t    do_put(regname, NULL, BACKWARD, 1L,\n\t\t\t\t\t\t      fixindent | PUT_CURSEND);\n\n\t\t    // Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r\n\t\t    AppendCharToRedobuff(Ctrl_R);\n\t\t    AppendCharToRedobuff(fixindent ? Ctrl_P : Ctrl_O);\n\t\t    AppendCharToRedobuff(regname == 0 ? '\"' : regname);\n\t\t}\n\t    }\n\t    return FALSE;\n\t}\n    }\n\n    // When dragging or button-up stay in the same window.\n    if (!is_click)\n\tjump_flags |= MOUSE_FOCUS | MOUSE_DID_MOVE;\n\n    start_visual.lnum = 0;\n\n    if (TabPageIdxs != NULL)  // only when initialized\n    {\n\t// Check for clicking in the tab page line.\n\tif (mouse_row == 0 && firstwin->w_winrow > 0)\n\t{\n\t    if (is_drag)\n\t    {\n\t\tif (in_tab_line)\n\t\t{\n\t\t    c1 = TabPageIdxs[mouse_col];\n\t\t    tabpage_move(c1 <= 0 ? 9999 : c1 < tabpage_index(curtab)\n\t\t\t\t\t\t\t\t    ? c1 - 1 : c1);\n\t\t}\n\t\treturn FALSE;\n\t    }\n\n\t    // click in a tab selects that tab page\n\t    if (is_click\n# ifdef FEAT_CMDWIN\n\t\t    && cmdwin_type == 0\n# endif\n\t\t    && mouse_col < Columns)\n\t    {\n\t\tin_tab_line = TRUE;\n\t\tc1 = TabPageIdxs[mouse_col];\n\t\tif (c1 >= 0)\n\t\t{\n\t\t    if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t\t    {\n\t\t\t// double click opens new page\n\t\t\tend_visual_mode_keep_button();\n\t\t\ttabpage_new();\n\t\t\ttabpage_move(c1 == 0 ? 9999 : c1 - 1);\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\t// Go to specified tab page, or next one if not clicking\n\t\t\t// on a label.\n\t\t\tgoto_tabpage(c1);\n\n\t\t\t// It's like clicking on the status line of a window.\n\t\t\tif (curwin != old_curwin)\n\t\t\t    end_visual_mode_keep_button();\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    tabpage_T\t*tp;\n\n\t\t    // Close the current or specified tab page.\n\t\t    if (c1 == -999)\n\t\t\ttp = curtab;\n\t\t    else\n\t\t\ttp = find_tabpage(-c1);\n\t\t    if (tp == curtab)\n\t\t    {\n\t\t\tif (first_tabpage->tp_next != NULL)\n\t\t\t    tabpage_close(FALSE);\n\t\t    }\n\t\t    else if (tp != NULL)\n\t\t\ttabpage_close_other(tp, FALSE);\n\t\t}\n\t    }\n\t    return TRUE;\n\t}\n\telse if (is_drag && in_tab_line)\n\t{\n\t    c1 = TabPageIdxs[mouse_col];\n\t    tabpage_move(c1 <= 0 ? 9999 : c1 - 1);\n\t    return FALSE;\n\t}\n    }\n\n    // When 'mousemodel' is \"popup\" or \"popup_setpos\", translate mouse events:\n    // right button up   -> pop-up menu\n    // shift-left button -> right button\n    // alt-left button   -> alt-right button\n    if (mouse_model_popup())\n    {\n\tif (which_button == MOUSE_RIGHT\n\t\t\t    && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))\n\t{\n#ifdef USE_POPUP_SETPOS\n# ifdef FEAT_GUI\n\t    if (gui.in_use)\n\t    {\n#  if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \\\n\t\t\t  || defined(FEAT_GUI_PHOTON)\n\t\tif (!is_click)\n\t\t    // Ignore right button release events, only shows the popup\n\t\t    // menu on the button down event.\n\t\t    return FALSE;\n#  endif\n#  if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_HAIKU)\n\t\tif (is_click || is_drag)\n\t\t    // Ignore right button down and drag mouse events.  Windows\n\t\t    // only shows the popup menu on the button up event.\n\t\t    return FALSE;\n#  endif\n\t    }\n# endif\n# if defined(FEAT_GUI) && defined(FEAT_TERM_POPUP_MENU)\n\t    else\n# endif\n# if defined(FEAT_TERM_POPUP_MENU)\n\t    if (!is_click)\n\t\t// Ignore right button release events, only shows the popup\n\t\t// menu on the button down event.\n\t\treturn FALSE;\n#endif\n\n\t    jump_flags = 0;\n\t    if (STRCMP(p_mousem, \"popup_setpos\") == 0)\n\t    {\n\t\t// First set the cursor position before showing the popup\n\t\t// menu.\n\t\tif (VIsual_active)\n\t\t{\n\t\t    pos_T    m_pos;\n\n\t\t    // set MOUSE_MAY_STOP_VIS if we are outside the\n\t\t    // selection or the current window (might have false\n\t\t    // negative here)\n\t\t    if (mouse_row < curwin->w_winrow\n\t\t\t || mouse_row\n\t\t\t\t  > (curwin->w_winrow + curwin->w_height))\n\t\t\tjump_flags = MOUSE_MAY_STOP_VIS;\n\t\t    else if (get_fpos_of_mouse(&m_pos) != IN_BUFFER)\n\t\t\tjump_flags = MOUSE_MAY_STOP_VIS;\n\t\t    else\n\t\t    {\n\t\t\tif ((LT_POS(curwin->w_cursor, VIsual)\n\t\t\t\t    && (LT_POS(m_pos, curwin->w_cursor)\n\t\t\t\t\t|| LT_POS(VIsual, m_pos)))\n\t\t\t\t|| (LT_POS(VIsual, curwin->w_cursor)\n\t\t\t\t    && (LT_POS(m_pos, VIsual)\n\t\t\t\t      || LT_POS(curwin->w_cursor, m_pos))))\n\t\t\t{\n\t\t\t    jump_flags = MOUSE_MAY_STOP_VIS;\n\t\t\t}\n\t\t\telse if (VIsual_mode == Ctrl_V)\n\t\t\t{\n\t\t\t    getvcols(curwin, &curwin->w_cursor, &VIsual,\n\t\t\t\t\t\t     &leftcol, &rightcol);\n\t\t\t    getvcol(curwin, &m_pos, NULL, &m_pos.col, NULL);\n\t\t\t    if (m_pos.col < leftcol || m_pos.col > rightcol)\n\t\t\t\tjump_flags = MOUSE_MAY_STOP_VIS;\n\t\t\t}\n\t\t    }\n\t\t}\n\t\telse\n\t\t    jump_flags = MOUSE_MAY_STOP_VIS;\n\t    }\n\t    if (jump_flags)\n\t    {\n\t\tjump_flags = jump_to_mouse(jump_flags, NULL, which_button);\n\t\tupdate_curbuf(VIsual_active ? UPD_INVERTED : UPD_VALID);\n\t\tsetcursor();\n\t\tout_flush();    // Update before showing popup menu\n\t    }\n# ifdef FEAT_MENU\n\t    show_popupmenu();\n\t    got_click = FALSE;\t// ignore release events\n# endif\n\t    return (jump_flags & CURSOR_MOVED) != 0;\n#else\n\t    return FALSE;\n#endif\n\t}\n\tif (which_button == MOUSE_LEFT\n\t\t\t\t&& (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT)))\n\t{\n\t    which_button = MOUSE_RIGHT;\n\t    mod_mask &= ~MOD_MASK_SHIFT;\n\t}\n    }\n\n    if ((State & (MODE_NORMAL | MODE_INSERT))\n\t\t\t    && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))\n    {\n\tif (which_button == MOUSE_LEFT)\n\t{\n\t    if (is_click)\n\t    {\n\t\t// stop Visual mode for a left click in a window, but not when\n\t\t// on a status line\n\t\tif (VIsual_active)\n\t\t    jump_flags |= MOUSE_MAY_STOP_VIS;\n\t    }\n\t    else if (mouse_has(MOUSE_VISUAL))\n\t\tjump_flags |= MOUSE_MAY_VIS;\n\t}\n\telse if (which_button == MOUSE_RIGHT)\n\t{\n\t    if (is_click && VIsual_active)\n\t    {\n\t\t// Remember the start and end of visual before moving the\n\t\t// cursor.\n\t\tif (LT_POS(curwin->w_cursor, VIsual))\n\t\t{\n\t\t    start_visual = curwin->w_cursor;\n\t\t    end_visual = VIsual;\n\t\t}\n\t\telse\n\t\t{\n\t\t    start_visual = VIsual;\n\t\t    end_visual = curwin->w_cursor;\n\t\t}\n\t    }\n\t    jump_flags |= MOUSE_FOCUS;\n\t    if (mouse_has(MOUSE_VISUAL))\n\t\tjump_flags |= MOUSE_MAY_VIS;\n\t}\n    }\n\n    // If an operator is pending, ignore all drags and releases until the\n    // next mouse click.\n    if (!is_drag && oap != NULL && oap->op_type != OP_NOP)\n    {\n\tgot_click = FALSE;\n\toap->motion_type = MCHAR;\n    }\n\n    // When releasing the button let jump_to_mouse() know.\n    if (!is_click && !is_drag)\n\tjump_flags |= MOUSE_RELEASED;\n\n    // JUMP!\n    jump_flags = jump_to_mouse(jump_flags,\n\t\t\toap == NULL ? NULL : &(oap->inclusive), which_button);\n\n#ifdef FEAT_MENU\n    // A click in the window toolbar has no side effects.\n    if (jump_flags & MOUSE_WINBAR)\n\treturn FALSE;\n#endif\n    moved = (jump_flags & CURSOR_MOVED);\n    in_status_line = (jump_flags & IN_STATUS_LINE);\n    in_sep_line = (jump_flags & IN_SEP_LINE);\n\n#ifdef FEAT_NETBEANS_INTG\n    if (isNetbeansBuffer(curbuf)\n\t\t\t    && !(jump_flags & (IN_STATUS_LINE | IN_SEP_LINE)))\n    {\n\tint key = KEY2TERMCAP1(c);\n\n\tif (key == (int)KE_LEFTRELEASE || key == (int)KE_MIDDLERELEASE\n\t\t\t\t\t       || key == (int)KE_RIGHTRELEASE)\n\t    netbeans_button_release(which_button);\n    }\n#endif\n\n    // When jumping to another window, clear a pending operator.  That's a bit\n    // friendlier than beeping and not jumping to that window.\n    if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP)\n\tclearop(oap);\n\n#ifdef FEAT_FOLDING\n    if (mod_mask == 0\n\t    && !is_drag\n\t    && (jump_flags & (MOUSE_FOLD_CLOSE | MOUSE_FOLD_OPEN))\n\t    && which_button == MOUSE_LEFT)\n    {\n\t// open or close a fold at this line\n\tif (jump_flags & MOUSE_FOLD_OPEN)\n\t    openFold(curwin->w_cursor.lnum, 1L);\n\telse\n\t    closeFold(curwin->w_cursor.lnum, 1L);\n\t// don't move the cursor if still in the same window\n\tif (curwin == old_curwin)\n\t    curwin->w_cursor = save_cursor;\n    }\n#endif\n\n#if defined(FEAT_CLIPBOARD) && defined(FEAT_CMDWIN)\n    if ((jump_flags & IN_OTHER_WIN) && !VIsual_active && clip_star.available)\n    {\n\tclip_modeless(which_button, is_click, is_drag);\n\treturn FALSE;\n    }\n#endif\n\n    // Set global flag that we are extending the Visual area with mouse\n    // dragging; temporarily minimize 'scrolloff'.\n    if (VIsual_active && is_drag && get_scrolloff_value())\n    {\n\t// In the very first line, allow scrolling one line\n\tif (mouse_row == 0)\n\t    mouse_dragging = 2;\n\telse\n\t    mouse_dragging = 1;\n    }\n\n    // When dragging the mouse above the window, scroll down.\n    if (is_drag && mouse_row < 0 && !in_status_line)\n    {\n\tscroll_redraw(FALSE, 1L);\n\tmouse_row = 0;\n    }\n\n    if (start_visual.lnum)\t\t// right click in visual mode\n    {\n       // When ALT is pressed make Visual mode blockwise.\n       if (mod_mask & MOD_MASK_ALT)\n\t   VIsual_mode = Ctrl_V;\n\n\t// In Visual-block mode, divide the area in four, pick up the corner\n\t// that is in the quarter that the cursor is in.\n\tif (VIsual_mode == Ctrl_V)\n\t{\n\t    getvcols(curwin, &start_visual, &end_visual, &leftcol, &rightcol);\n\t    if (curwin->w_curswant > (leftcol + rightcol) / 2)\n\t\tend_visual.col = leftcol;\n\t    else\n\t\tend_visual.col = rightcol;\n\t    if (curwin->w_cursor.lnum >=\n\t\t\t\t    (start_visual.lnum + end_visual.lnum) / 2)\n\t\tend_visual.lnum = start_visual.lnum;\n\n\t    // move VIsual to the right column\n\t    start_visual = curwin->w_cursor;\t    // save the cursor pos\n\t    curwin->w_cursor = end_visual;\n\t    coladvance(end_visual.col);\n\t    VIsual = curwin->w_cursor;\n\t    curwin->w_cursor = start_visual;\t    // restore the cursor\n\t}\n\telse\n\t{\n\t    // If the click is before the start of visual, change the start.\n\t    // If the click is after the end of visual, change the end.  If\n\t    // the click is inside the visual, change the closest side.\n\t    if (LT_POS(curwin->w_cursor, start_visual))\n\t\tVIsual = end_visual;\n\t    else if (LT_POS(end_visual, curwin->w_cursor))\n\t\tVIsual = start_visual;\n\t    else\n\t    {\n\t\t// In the same line, compare column number\n\t\tif (end_visual.lnum == start_visual.lnum)\n\t\t{\n\t\t    if (curwin->w_cursor.col - start_visual.col >\n\t\t\t\t    end_visual.col - curwin->w_cursor.col)\n\t\t\tVIsual = start_visual;\n\t\t    else\n\t\t\tVIsual = end_visual;\n\t\t}\n\n\t\t// In different lines, compare line number\n\t\telse\n\t\t{\n\t\t    diff = (curwin->w_cursor.lnum - start_visual.lnum) -\n\t\t\t\t(end_visual.lnum - curwin->w_cursor.lnum);\n\n\t\t    if (diff > 0)\t\t// closest to end\n\t\t\tVIsual = start_visual;\n\t\t    else if (diff < 0)\t// closest to start\n\t\t\tVIsual = end_visual;\n\t\t    else\t\t\t// in the middle line\n\t\t    {\n\t\t\tif (curwin->w_cursor.col <\n\t\t\t\t\t(start_visual.col + end_visual.col) / 2)\n\t\t\t    VIsual = end_visual;\n\t\t\telse\n\t\t\t    VIsual = start_visual;\n\t\t    }\n\t\t}\n\t    }\n\t}\n    }\n    // If Visual mode started in insert mode, execute \"CTRL-O\"\n    else if ((State & MODE_INSERT) && VIsual_active)\n\tstuffcharReadbuff(Ctrl_O);\n\n    // Middle mouse click: Put text before cursor.\n    if (which_button == MOUSE_MIDDLE)\n    {\n#ifdef FEAT_CLIPBOARD\n\tif (clip_star.available && regname == 0)\n\t    regname = '*';\n#endif\n\tif (yank_register_mline(regname))\n\t{\n\t    if (mouse_past_bottom)\n\t\tdir = FORWARD;\n\t}\n\telse if (mouse_past_eol)\n\t    dir = FORWARD;\n\n\tif (fixindent)\n\t{\n\t    c1 = (dir == BACKWARD) ? '[' : ']';\n\t    c2 = 'p';\n\t}\n\telse\n\t{\n\t    c1 = (dir == FORWARD) ? 'p' : 'P';\n\t    c2 = NUL;\n\t}\n\tprep_redo(regname, count, NUL, c1, NUL, c2, NUL);\n\n\t// Remember where the paste started, so in edit() Insstart can be set\n\t// to this position\n\tif (restart_edit != 0)\n\t    where_paste_started = curwin->w_cursor;\n\tdo_put(regname, NULL, dir, count, fixindent | PUT_CURSEND);\n    }\n\n#if defined(FEAT_QUICKFIX)\n    // Ctrl-Mouse click or double click in a quickfix window jumps to the\n    // error under the mouse pointer.\n    else if (((mod_mask & MOD_MASK_CTRL)\n\t\t|| (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t    && bt_quickfix(curbuf))\n    {\n\tif (curwin->w_llist_ref == NULL)\t// quickfix window\n\t    do_cmdline_cmd((char_u *)\".cc\");\n\telse\t\t\t\t\t// location list window\n\t    do_cmdline_cmd((char_u *)\".ll\");\n\tgot_click = FALSE;\t\t// ignore drag&release now\n    }\n#endif\n\n    // Ctrl-Mouse click (or double click in a help window) jumps to the tag\n    // under the mouse pointer.\n    else if ((mod_mask & MOD_MASK_CTRL) || (curbuf->b_help\n\t\t     && (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK))\n    {\n\tif (State & MODE_INSERT)\n\t    stuffcharReadbuff(Ctrl_O);\n\tstuffcharReadbuff(Ctrl_RSB);\n\tgot_click = FALSE;\t\t// ignore drag&release now\n    }\n\n    // Shift-Mouse click searches for the next occurrence of the word under\n    // the mouse pointer\n    else if ((mod_mask & MOD_MASK_SHIFT))\n    {\n\tif ((State & MODE_INSERT) || (VIsual_active && VIsual_select))\n\t    stuffcharReadbuff(Ctrl_O);\n\tif (which_button == MOUSE_LEFT)\n\t    stuffcharReadbuff('*');\n\telse\t// MOUSE_RIGHT\n\t    stuffcharReadbuff('#');\n    }\n\n    // Handle double clicks, unless on status line\n    else if (in_status_line)\n    {\n#ifdef FEAT_MOUSESHAPE\n\tif ((is_drag || is_click) && !drag_status_line)\n\t{\n\t    drag_status_line = TRUE;\n\t    update_mouseshape(-1);\n\t}\n#endif\n    }\n    else if (in_sep_line)\n    {\n#ifdef FEAT_MOUSESHAPE\n\tif ((is_drag || is_click) && !drag_sep_line)\n\t{\n\t    drag_sep_line = TRUE;\n\t    update_mouseshape(-1);\n\t}\n#endif\n    }\n    else if ((mod_mask & MOD_MASK_MULTI_CLICK)\n\t\t\t\t       && (State & (MODE_NORMAL | MODE_INSERT))\n\t     && mouse_has(MOUSE_VISUAL))\n    {\n\tif (is_click || !VIsual_active)\n\t{\n\t    if (VIsual_active)\n\t\torig_cursor = VIsual;\n\t    else\n\t    {\n\t\tcheck_visual_highlight();\n\t\tVIsual = curwin->w_cursor;\n\t\torig_cursor = VIsual;\n\t\tVIsual_active = TRUE;\n\t\tVIsual_reselect = TRUE;\n\t\t// start Select mode if 'selectmode' contains \"mouse\"\n\t\tmay_start_select('o');\n\t\tsetmouse();\n\t    }\n\t    if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t    {\n\t\t// Double click with ALT pressed makes it blockwise.\n\t\tif (mod_mask & MOD_MASK_ALT)\n\t\t    VIsual_mode = Ctrl_V;\n\t\telse\n\t\t    VIsual_mode = 'v';\n\t    }\n\t    else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK)\n\t\tVIsual_mode = 'V';\n\t    else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK)\n\t\tVIsual_mode = Ctrl_V;\n#ifdef FEAT_CLIPBOARD\n\t    // Make sure the clipboard gets updated.  Needed because start and\n\t    // end may still be the same, and the selection needs to be owned\n\t    clip_star.vmode = NUL;\n#endif\n\t}\n\t// A double click selects a word or a block.\n\tif ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t{\n\t    pos_T\t*pos = NULL;\n\t    int\t\tgc;\n\n\t    if (is_click)\n\t    {\n\t\t// If the character under the cursor (skipping white space) is\n\t\t// not a word character, try finding a match and select a (),\n\t\t// {}, [], #if/#endif, etc. block.\n\t\tend_visual = curwin->w_cursor;\n\t\twhile (gc = gchar_pos(&end_visual), VIM_ISWHITE(gc))\n\t\t    inc(&end_visual);\n\t\tif (oap != NULL)\n\t\t    oap->motion_type = MCHAR;\n\t\tif (oap != NULL\n\t\t\t&& VIsual_mode == 'v'\n\t\t\t&& !vim_iswordc(gchar_pos(&end_visual))\n\t\t\t&& EQUAL_POS(curwin->w_cursor, VIsual)\n\t\t\t&& (pos = findmatch(oap, NUL)) != NULL)\n\t\t{\n\t\t    curwin->w_cursor = *pos;\n\t\t    if (oap->motion_type == MLINE)\n\t\t\tVIsual_mode = 'V';\n\t\t    else if (*p_sel == 'e')\n\t\t    {\n\t\t\tif (LT_POS(curwin->w_cursor, VIsual))\n\t\t\t    ++VIsual.col;\n\t\t\telse\n\t\t\t    ++curwin->w_cursor.col;\n\t\t    }\n\t\t}\n\t    }\n\n\t    if (pos == NULL && (is_click || is_drag))\n\t    {\n\t\t// When not found a match or when dragging: extend to include\n\t\t// a word.\n\t\tif (LT_POS(curwin->w_cursor, orig_cursor))\n\t\t{\n\t\t    find_start_of_word(&curwin->w_cursor);\n\t\t    find_end_of_word(&VIsual);\n\t\t}\n\t\telse\n\t\t{\n\t\t    find_start_of_word(&VIsual);\n\t\t    if (*p_sel == 'e' && *ml_get_cursor() != NUL)\n\t\t\tcurwin->w_cursor.col +=\n\t\t\t\t\t (*mb_ptr2len)(ml_get_cursor());\n\t\t    find_end_of_word(&curwin->w_cursor);\n\t\t}\n\t    }\n\t    curwin->w_set_curswant = TRUE;\n\t}\n\tif (is_click)\n\t    redraw_curbuf_later(UPD_INVERTED);\t// update the inversion\n    }\n    else if (VIsual_active && !old_active)\n    {\n\tif (mod_mask & MOD_MASK_ALT)\n\t    VIsual_mode = Ctrl_V;\n\telse\n\t    VIsual_mode = 'v';\n    }\n\n    // If Visual mode changed show it later.\n    if ((!VIsual_active && old_active && mode_displayed)\n\t    || (VIsual_active && p_smd && msg_silent == 0\n\t\t\t\t && (!old_active || VIsual_mode != old_mode)))\n\tredraw_cmdline = TRUE;\n\n    return moved;\n}", "func_hash": 340201685272816729984528939326600503133, "file_name": "mouse.c", "file_hash": 56805804002879785388836197750941387525, "cwe": ["CWE-703"], "cve": "CVE-2022-2980", "cve_desc": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2980"}
{"idx": 209801, "project": "mujs", "commit_id": "f5b3c703e18725e380b83427004632e744f85a6f", "project_url": "https://github.com/ccxvii/mujs", "commit_url": "https://github.com/ccxvii/mujs/commit/f5b3c703e18725e380b83427004632e744f85a6f", "commit_message": "Issue #161: Cope with empty programs in mujs-pp.", "target": 1, "func": "void jsP_dumpsyntax(js_State *J, js_Ast *prog, int dominify)\n{\n\tminify = dominify;\n\tif (prog->type == AST_LIST)\n\t\tpstmlist(-1, prog);\n\telse {\n\t\tpstm(0, prog);\n\t\tnl();\n\t}\n\tif (minify > 1)\n\t\tputchar('\\n');\n}", "func_hash": 236329653693817075818818411816465624514, "file_name": "jsdump.c", "file_hash": 195852189272926394340196020756121895406, "cwe": ["CWE-476"], "cve": "CVE-2022-30975", "cve_desc": "In Artifex MuJS through 1.2.0, jsP_dumpsyntax in jsdump.c has a NULL pointer dereference, as demonstrated by mujs-pp.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-30975"}
{"idx": 421378, "project": "mujs", "commit_id": "f5b3c703e18725e380b83427004632e744f85a6f", "project_url": "https://github.com/ccxvii/mujs", "commit_url": "https://github.com/ccxvii/mujs/commit/f5b3c703e18725e380b83427004632e744f85a6f", "commit_message": "Issue #161: Cope with empty programs in mujs-pp.", "target": 0, "func": "void jsP_dumpsyntax(js_State *J, js_Ast *prog, int dominify)\n{\n\tminify = dominify;\n\tif (prog) {\n\t\tif (prog->type == AST_LIST)\n\t\t\tpstmlist(-1, prog);\n\t\telse {\n\t\t\tpstm(0, prog);\n\t\t\tnl();\n\t\t}\n\t}\n\tif (minify > 1)\n\t\tputchar('\\n');\n}", "func_hash": 148093103302179844815401983905255483216, "file_name": "jsdump.c", "file_hash": 205390724250782891362749099686890673449, "cwe": ["CWE-476"], "cve": "CVE-2022-30975", "cve_desc": "In Artifex MuJS through 1.2.0, jsP_dumpsyntax in jsdump.c has a NULL pointer dereference, as demonstrated by mujs-pp.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-30975"}
{"idx": 209931, "project": "FreeRDP", "commit_id": "06c32f170093a6ecde93e3bc07fed6a706bfbeb3", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/06c32f170093a6ecde93e3bc07fed6a706bfbeb3", "commit_message": "Fixed int overflow in PresentationContext_new\n\nThanks to hac425 CVE-2020-11038", "target": 1, "func": "static PresentationContext* PresentationContext_new(VideoClientContext* video, BYTE PresentationId,\n                                                    UINT32 x, UINT32 y, UINT32 width, UINT32 height)\n{\n\tVideoClientContextPriv* priv = video->priv;\n\tPresentationContext* ret = calloc(1, sizeof(*ret));\n\tif (!ret)\n\t\treturn NULL;\n\n\tret->video = video;\n\tret->PresentationId = PresentationId;\n\n\tret->h264 = h264_context_new(FALSE);\n\tif (!ret->h264)\n\t{\n\t\tWLog_ERR(TAG, \"unable to create a h264 context\");\n\t\tgoto error_h264;\n\t}\n\th264_context_reset(ret->h264, width, height);\n\n\tret->currentSample = Stream_New(NULL, 4096);\n\tif (!ret->currentSample)\n\t{\n\t\tWLog_ERR(TAG, \"unable to create current packet stream\");\n\t\tgoto error_currentSample;\n\t}\n\n\tret->surfaceData = BufferPool_Take(priv->surfacePool, width * height * 4);\n\tif (!ret->surfaceData)\n\t{\n\t\tWLog_ERR(TAG, \"unable to allocate surfaceData\");\n\t\tgoto error_surfaceData;\n\t}\n\n\tret->surface = video->createSurface(video, ret->surfaceData, x, y, width, height);\n\tif (!ret->surface)\n\t{\n\t\tWLog_ERR(TAG, \"unable to create surface\");\n\t\tgoto error_surface;\n\t}\n\n\tret->yuv = yuv_context_new(FALSE);\n\tif (!ret->yuv)\n\t{\n\t\tWLog_ERR(TAG, \"unable to create YUV decoder\");\n\t\tgoto error_yuv;\n\t}\n\n\tyuv_context_reset(ret->yuv, width, height);\n\tret->refCounter = 1;\n\treturn ret;\n\nerror_yuv:\n\tvideo->deleteSurface(video, ret->surface);\nerror_surface:\n\tBufferPool_Return(priv->surfacePool, ret->surfaceData);\nerror_surfaceData:\n\tStream_Free(ret->currentSample, TRUE);\nerror_currentSample:\n\th264_context_free(ret->h264);\nerror_h264:\n\tfree(ret);\n\treturn NULL;\n}", "func_hash": 224995587751156021898591769013429196502, "file_name": "video_main.c", "file_hash": 35095058952192226011309281398214943960, "cwe": ["CWE-190"], "cve": "CVE-2020-11038", "cve_desc": "In FreeRDP less than or equal to 2.0.0, an Integer Overflow to Buffer Overflow exists. When using /video redirection, a manipulated server can instruct the client to allocate a buffer with a smaller size than requested due to an integer overflow in size calculation. With later messages, the server can manipulate the client to write data out of bound to the previously allocated buffer. This has been patched in 2.1.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11038"}
{"idx": 424522, "project": "FreeRDP", "commit_id": "06c32f170093a6ecde93e3bc07fed6a706bfbeb3", "project_url": "https://github.com/FreeRDP/FreeRDP", "commit_url": "https://github.com/FreeRDP/FreeRDP/commit/06c32f170093a6ecde93e3bc07fed6a706bfbeb3", "commit_message": "Fixed int overflow in PresentationContext_new\n\nThanks to hac425 CVE-2020-11038", "target": 0, "func": "static PresentationContext* PresentationContext_new(VideoClientContext* video, BYTE PresentationId,\n                                                    UINT32 x, UINT32 y, UINT32 width, UINT32 height)\n{\n\tsize_t s;\n\tVideoClientContextPriv* priv = video->priv;\n\tPresentationContext* ret;\n\ts = width * height * 4ULL;\n\tif (s > INT32_MAX)\n\t\treturn NULL;\n\n\tret = calloc(1, sizeof(*ret));\n\tif (!ret)\n\t\treturn NULL;\n\n\tret->video = video;\n\tret->PresentationId = PresentationId;\n\n\tret->h264 = h264_context_new(FALSE);\n\tif (!ret->h264)\n\t{\n\t\tWLog_ERR(TAG, \"unable to create a h264 context\");\n\t\tgoto error_h264;\n\t}\n\th264_context_reset(ret->h264, width, height);\n\n\tret->currentSample = Stream_New(NULL, 4096);\n\tif (!ret->currentSample)\n\t{\n\t\tWLog_ERR(TAG, \"unable to create current packet stream\");\n\t\tgoto error_currentSample;\n\t}\n\n\tret->surfaceData = BufferPool_Take(priv->surfacePool, s);\n\tif (!ret->surfaceData)\n\t{\n\t\tWLog_ERR(TAG, \"unable to allocate surfaceData\");\n\t\tgoto error_surfaceData;\n\t}\n\n\tret->surface = video->createSurface(video, ret->surfaceData, x, y, width, height);\n\tif (!ret->surface)\n\t{\n\t\tWLog_ERR(TAG, \"unable to create surface\");\n\t\tgoto error_surface;\n\t}\n\n\tret->yuv = yuv_context_new(FALSE);\n\tif (!ret->yuv)\n\t{\n\t\tWLog_ERR(TAG, \"unable to create YUV decoder\");\n\t\tgoto error_yuv;\n\t}\n\n\tyuv_context_reset(ret->yuv, width, height);\n\tret->refCounter = 1;\n\treturn ret;\n\nerror_yuv:\n\tvideo->deleteSurface(video, ret->surface);\nerror_surface:\n\tBufferPool_Return(priv->surfacePool, ret->surfaceData);\nerror_surfaceData:\n\tStream_Free(ret->currentSample, TRUE);\nerror_currentSample:\n\th264_context_free(ret->h264);\nerror_h264:\n\tfree(ret);\n\treturn NULL;\n}", "func_hash": 30972982164738968156907836977573699400, "file_name": "video_main.c", "file_hash": 287292368132527375714918493211433818803, "cwe": ["CWE-190"], "cve": "CVE-2020-11038", "cve_desc": "In FreeRDP less than or equal to 2.0.0, an Integer Overflow to Buffer Overflow exists. When using /video redirection, a manipulated server can instruct the client to allocate a buffer with a smaller size than requested due to an integer overflow in size calculation. With later messages, the server can manipulate the client to write data out of bound to the previously allocated buffer. This has been patched in 2.1.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11038"}
{"idx": 209955, "project": "linux", "commit_id": "8188a18ee2e48c9a7461139838048363bfce3fef", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=8188a18ee2e48c9a7461139838048363bfce3fef", "commit_message": "iwlwifi: pcie: fix rb_allocator workqueue allocation\n\nWe don't handle failures in the rb_allocator workqueue allocation\ncorrectly. To fix that, move the code earlier so the cleanup is\neasier and we don't have to undo all the interrupt allocations in\nthis case.\n\nSigned-off-by: Johannes Berg \nSigned-off-by: Luca Coelho ", "target": 1, "func": "struct iwl_trans *iwl_trans_pcie_alloc(struct pci_dev *pdev,\n\t\t\t       const struct pci_device_id *ent,\n\t\t\t       const struct iwl_cfg_trans_params *cfg_trans)\n{\n\tstruct iwl_trans_pcie *trans_pcie;\n\tstruct iwl_trans *trans;\n\tint ret, addr_size;\n\n\tret = pcim_enable_device(pdev);\n\tif (ret)\n\t\treturn ERR_PTR(ret);\n\n\tif (cfg_trans->gen2)\n\t\ttrans = iwl_trans_alloc(sizeof(struct iwl_trans_pcie),\n\t\t\t\t\t&pdev->dev, &trans_ops_pcie_gen2);\n\telse\n\t\ttrans = iwl_trans_alloc(sizeof(struct iwl_trans_pcie),\n\t\t\t\t\t&pdev->dev, &trans_ops_pcie);\n\n\tif (!trans)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\ttrans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);\n\n\ttrans_pcie->trans = trans;\n\ttrans_pcie->opmode_down = true;\n\tspin_lock_init(&trans_pcie->irq_lock);\n\tspin_lock_init(&trans_pcie->reg_lock);\n\tmutex_init(&trans_pcie->mutex);\n\tinit_waitqueue_head(&trans_pcie->ucode_write_waitq);\n\ttrans_pcie->tso_hdr_page = alloc_percpu(struct iwl_tso_hdr_page);\n\tif (!trans_pcie->tso_hdr_page) {\n\t\tret = -ENOMEM;\n\t\tgoto out_no_pci;\n\t}\n\ttrans_pcie->debug_rfkill = -1;\n\n\tif (!cfg_trans->base_params->pcie_l1_allowed) {\n\t\t/*\n\t\t * W/A - seems to solve weird behavior. We need to remove this\n\t\t * if we don't want to stay in L1 all the time. This wastes a\n\t\t * lot of power.\n\t\t */\n\t\tpci_disable_link_state(pdev, PCIE_LINK_STATE_L0S |\n\t\t\t\t       PCIE_LINK_STATE_L1 |\n\t\t\t\t       PCIE_LINK_STATE_CLKPM);\n\t}\n\n\ttrans_pcie->def_rx_queue = 0;\n\n\tif (cfg_trans->use_tfh) {\n\t\taddr_size = 64;\n\t\ttrans_pcie->max_tbs = IWL_TFH_NUM_TBS;\n\t\ttrans_pcie->tfd_size = sizeof(struct iwl_tfh_tfd);\n\t} else {\n\t\taddr_size = 36;\n\t\ttrans_pcie->max_tbs = IWL_NUM_OF_TBS;\n\t\ttrans_pcie->tfd_size = sizeof(struct iwl_tfd);\n\t}\n\ttrans->max_skb_frags = IWL_PCIE_MAX_FRAGS(trans_pcie);\n\n\tpci_set_master(pdev);\n\n\tret = pci_set_dma_mask(pdev, DMA_BIT_MASK(addr_size));\n\tif (!ret)\n\t\tret = pci_set_consistent_dma_mask(pdev,\n\t\t\t\t\t\t  DMA_BIT_MASK(addr_size));\n\tif (ret) {\n\t\tret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));\n\t\tif (!ret)\n\t\t\tret = pci_set_consistent_dma_mask(pdev,\n\t\t\t\t\t\t\t  DMA_BIT_MASK(32));\n\t\t/* both attempts failed: */\n\t\tif (ret) {\n\t\t\tdev_err(&pdev->dev, \"No suitable DMA available\\n\");\n\t\t\tgoto out_no_pci;\n\t\t}\n\t}\n\n\tret = pcim_iomap_regions_request_all(pdev, BIT(0), DRV_NAME);\n\tif (ret) {\n\t\tdev_err(&pdev->dev, \"pcim_iomap_regions_request_all failed\\n\");\n\t\tgoto out_no_pci;\n\t}\n\n\ttrans_pcie->hw_base = pcim_iomap_table(pdev)[0];\n\tif (!trans_pcie->hw_base) {\n\t\tdev_err(&pdev->dev, \"pcim_iomap_table failed\\n\");\n\t\tret = -ENODEV;\n\t\tgoto out_no_pci;\n\t}\n\n\t/* We disable the RETRY_TIMEOUT register (0x41) to keep\n\t * PCI Tx retries from interfering with C3 CPU state */\n\tpci_write_config_byte(pdev, PCI_CFG_RETRY_TIMEOUT, 0x00);\n\n\ttrans_pcie->pci_dev = pdev;\n\tiwl_disable_interrupts(trans);\n\n\ttrans->hw_rev = iwl_read32(trans, CSR_HW_REV);\n\tif (trans->hw_rev == 0xffffffff) {\n\t\tdev_err(&pdev->dev, \"HW_REV=0xFFFFFFFF, PCI issues?\\n\");\n\t\tret = -EIO;\n\t\tgoto out_no_pci;\n\t}\n\n\t/*\n\t * In the 8000 HW family the format of the 4 bytes of CSR_HW_REV have\n\t * changed, and now the revision step also includes bit 0-1 (no more\n\t * \"dash\" value). To keep hw_rev backwards compatible - we'll store it\n\t * in the old format.\n\t */\n\tif (cfg_trans->device_family >= IWL_DEVICE_FAMILY_8000) {\n\t\ttrans->hw_rev = (trans->hw_rev & 0xfff0) |\n\t\t\t\t(CSR_HW_REV_STEP(trans->hw_rev << 2) << 2);\n\n\t\tret = iwl_pcie_prepare_card_hw(trans);\n\t\tif (ret) {\n\t\t\tIWL_WARN(trans, \"Exit HW not ready\\n\");\n\t\t\tgoto out_no_pci;\n\t\t}\n\n\t\t/*\n\t\t * in-order to recognize C step driver should read chip version\n\t\t * id located at the AUX bus MISC address space.\n\t\t */\n\t\tret = iwl_finish_nic_init(trans, cfg_trans);\n\t\tif (ret)\n\t\t\tgoto out_no_pci;\n\n\t}\n\n\tIWL_DEBUG_INFO(trans, \"HW REV: 0x%0x\\n\", trans->hw_rev);\n\n\tiwl_pcie_set_interrupt_capa(pdev, trans, cfg_trans);\n\ttrans->hw_id = (pdev->device << 16) + pdev->subsystem_device;\n\tsnprintf(trans->hw_id_str, sizeof(trans->hw_id_str),\n\t\t \"PCI ID: 0x%04X:0x%04X\", pdev->device, pdev->subsystem_device);\n\n\t/* Initialize the wait queue for commands */\n\tinit_waitqueue_head(&trans_pcie->wait_command_queue);\n\n\tinit_waitqueue_head(&trans_pcie->sx_waitq);\n\n\tif (trans_pcie->msix_enabled) {\n\t\tret = iwl_pcie_init_msix_handler(pdev, trans_pcie);\n\t\tif (ret)\n\t\t\tgoto out_no_pci;\n\t } else {\n\t\tret = iwl_pcie_alloc_ict(trans);\n\t\tif (ret)\n\t\t\tgoto out_no_pci;\n\n\t\tret = devm_request_threaded_irq(&pdev->dev, pdev->irq,\n\t\t\t\t\t\tiwl_pcie_isr,\n\t\t\t\t\t\tiwl_pcie_irq_handler,\n\t\t\t\t\t\tIRQF_SHARED, DRV_NAME, trans);\n\t\tif (ret) {\n\t\t\tIWL_ERR(trans, \"Error allocating IRQ %d\\n\", pdev->irq);\n\t\t\tgoto out_free_ict;\n\t\t}\n\t\ttrans_pcie->inta_mask = CSR_INI_SET_MASK;\n\t }\n\n\ttrans_pcie->rba.alloc_wq = alloc_workqueue(\"rb_allocator\",\n\t\t\t\t\t\t   WQ_HIGHPRI | WQ_UNBOUND, 1);\n\tINIT_WORK(&trans_pcie->rba.rx_alloc, iwl_pcie_rx_allocator_work);\n\n#ifdef CONFIG_IWLWIFI_DEBUGFS\n\ttrans_pcie->fw_mon_data.state = IWL_FW_MON_DBGFS_STATE_CLOSED;\n\tmutex_init(&trans_pcie->fw_mon_data.mutex);\n#endif\n\n\treturn trans;\n\nout_free_ict:\n\tiwl_pcie_free_ict(trans);\nout_no_pci:\n\tfree_percpu(trans_pcie->tso_hdr_page);\n\tiwl_trans_free(trans);\n\treturn ERR_PTR(ret);\n}", "func_hash": 68049028566925957329669846026640837120, "file_name": "trans.c", "file_hash": 121825087774406788902524077810084378083, "cwe": ["CWE-476"], "cve": "CVE-2019-16234", "cve_desc": "drivers/net/wireless/intel/iwlwifi/pcie/trans.c in the Linux kernel 5.2.14 does not check the alloc_workqueue return value, leading to a NULL pointer dereference.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-16234"}
{"idx": 424969, "project": "linux", "commit_id": "8188a18ee2e48c9a7461139838048363bfce3fef", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=8188a18ee2e48c9a7461139838048363bfce3fef", "commit_message": "iwlwifi: pcie: fix rb_allocator workqueue allocation\n\nWe don't handle failures in the rb_allocator workqueue allocation\ncorrectly. To fix that, move the code earlier so the cleanup is\neasier and we don't have to undo all the interrupt allocations in\nthis case.\n\nSigned-off-by: Johannes Berg \nSigned-off-by: Luca Coelho ", "target": 0, "func": "struct iwl_trans *iwl_trans_pcie_alloc(struct pci_dev *pdev,\n\t\t\t       const struct pci_device_id *ent,\n\t\t\t       const struct iwl_cfg_trans_params *cfg_trans)\n{\n\tstruct iwl_trans_pcie *trans_pcie;\n\tstruct iwl_trans *trans;\n\tint ret, addr_size;\n\n\tret = pcim_enable_device(pdev);\n\tif (ret)\n\t\treturn ERR_PTR(ret);\n\n\tif (cfg_trans->gen2)\n\t\ttrans = iwl_trans_alloc(sizeof(struct iwl_trans_pcie),\n\t\t\t\t\t&pdev->dev, &trans_ops_pcie_gen2);\n\telse\n\t\ttrans = iwl_trans_alloc(sizeof(struct iwl_trans_pcie),\n\t\t\t\t\t&pdev->dev, &trans_ops_pcie);\n\n\tif (!trans)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\ttrans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);\n\n\ttrans_pcie->trans = trans;\n\ttrans_pcie->opmode_down = true;\n\tspin_lock_init(&trans_pcie->irq_lock);\n\tspin_lock_init(&trans_pcie->reg_lock);\n\tmutex_init(&trans_pcie->mutex);\n\tinit_waitqueue_head(&trans_pcie->ucode_write_waitq);\n\n\ttrans_pcie->rba.alloc_wq = alloc_workqueue(\"rb_allocator\",\n\t\t\t\t\t\t   WQ_HIGHPRI | WQ_UNBOUND, 1);\n\tif (!trans_pcie->rba.alloc_wq) {\n\t\tret = -ENOMEM;\n\t\tgoto out_free_trans;\n\t}\n\tINIT_WORK(&trans_pcie->rba.rx_alloc, iwl_pcie_rx_allocator_work);\n\n\ttrans_pcie->tso_hdr_page = alloc_percpu(struct iwl_tso_hdr_page);\n\tif (!trans_pcie->tso_hdr_page) {\n\t\tret = -ENOMEM;\n\t\tgoto out_no_pci;\n\t}\n\ttrans_pcie->debug_rfkill = -1;\n\n\tif (!cfg_trans->base_params->pcie_l1_allowed) {\n\t\t/*\n\t\t * W/A - seems to solve weird behavior. We need to remove this\n\t\t * if we don't want to stay in L1 all the time. This wastes a\n\t\t * lot of power.\n\t\t */\n\t\tpci_disable_link_state(pdev, PCIE_LINK_STATE_L0S |\n\t\t\t\t       PCIE_LINK_STATE_L1 |\n\t\t\t\t       PCIE_LINK_STATE_CLKPM);\n\t}\n\n\ttrans_pcie->def_rx_queue = 0;\n\n\tif (cfg_trans->use_tfh) {\n\t\taddr_size = 64;\n\t\ttrans_pcie->max_tbs = IWL_TFH_NUM_TBS;\n\t\ttrans_pcie->tfd_size = sizeof(struct iwl_tfh_tfd);\n\t} else {\n\t\taddr_size = 36;\n\t\ttrans_pcie->max_tbs = IWL_NUM_OF_TBS;\n\t\ttrans_pcie->tfd_size = sizeof(struct iwl_tfd);\n\t}\n\ttrans->max_skb_frags = IWL_PCIE_MAX_FRAGS(trans_pcie);\n\n\tpci_set_master(pdev);\n\n\tret = pci_set_dma_mask(pdev, DMA_BIT_MASK(addr_size));\n\tif (!ret)\n\t\tret = pci_set_consistent_dma_mask(pdev,\n\t\t\t\t\t\t  DMA_BIT_MASK(addr_size));\n\tif (ret) {\n\t\tret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));\n\t\tif (!ret)\n\t\t\tret = pci_set_consistent_dma_mask(pdev,\n\t\t\t\t\t\t\t  DMA_BIT_MASK(32));\n\t\t/* both attempts failed: */\n\t\tif (ret) {\n\t\t\tdev_err(&pdev->dev, \"No suitable DMA available\\n\");\n\t\t\tgoto out_no_pci;\n\t\t}\n\t}\n\n\tret = pcim_iomap_regions_request_all(pdev, BIT(0), DRV_NAME);\n\tif (ret) {\n\t\tdev_err(&pdev->dev, \"pcim_iomap_regions_request_all failed\\n\");\n\t\tgoto out_no_pci;\n\t}\n\n\ttrans_pcie->hw_base = pcim_iomap_table(pdev)[0];\n\tif (!trans_pcie->hw_base) {\n\t\tdev_err(&pdev->dev, \"pcim_iomap_table failed\\n\");\n\t\tret = -ENODEV;\n\t\tgoto out_no_pci;\n\t}\n\n\t/* We disable the RETRY_TIMEOUT register (0x41) to keep\n\t * PCI Tx retries from interfering with C3 CPU state */\n\tpci_write_config_byte(pdev, PCI_CFG_RETRY_TIMEOUT, 0x00);\n\n\ttrans_pcie->pci_dev = pdev;\n\tiwl_disable_interrupts(trans);\n\n\ttrans->hw_rev = iwl_read32(trans, CSR_HW_REV);\n\tif (trans->hw_rev == 0xffffffff) {\n\t\tdev_err(&pdev->dev, \"HW_REV=0xFFFFFFFF, PCI issues?\\n\");\n\t\tret = -EIO;\n\t\tgoto out_no_pci;\n\t}\n\n\t/*\n\t * In the 8000 HW family the format of the 4 bytes of CSR_HW_REV have\n\t * changed, and now the revision step also includes bit 0-1 (no more\n\t * \"dash\" value). To keep hw_rev backwards compatible - we'll store it\n\t * in the old format.\n\t */\n\tif (cfg_trans->device_family >= IWL_DEVICE_FAMILY_8000) {\n\t\ttrans->hw_rev = (trans->hw_rev & 0xfff0) |\n\t\t\t\t(CSR_HW_REV_STEP(trans->hw_rev << 2) << 2);\n\n\t\tret = iwl_pcie_prepare_card_hw(trans);\n\t\tif (ret) {\n\t\t\tIWL_WARN(trans, \"Exit HW not ready\\n\");\n\t\t\tgoto out_no_pci;\n\t\t}\n\n\t\t/*\n\t\t * in-order to recognize C step driver should read chip version\n\t\t * id located at the AUX bus MISC address space.\n\t\t */\n\t\tret = iwl_finish_nic_init(trans, cfg_trans);\n\t\tif (ret)\n\t\t\tgoto out_no_pci;\n\n\t}\n\n\tIWL_DEBUG_INFO(trans, \"HW REV: 0x%0x\\n\", trans->hw_rev);\n\n\tiwl_pcie_set_interrupt_capa(pdev, trans, cfg_trans);\n\ttrans->hw_id = (pdev->device << 16) + pdev->subsystem_device;\n\tsnprintf(trans->hw_id_str, sizeof(trans->hw_id_str),\n\t\t \"PCI ID: 0x%04X:0x%04X\", pdev->device, pdev->subsystem_device);\n\n\t/* Initialize the wait queue for commands */\n\tinit_waitqueue_head(&trans_pcie->wait_command_queue);\n\n\tinit_waitqueue_head(&trans_pcie->sx_waitq);\n\n\tif (trans_pcie->msix_enabled) {\n\t\tret = iwl_pcie_init_msix_handler(pdev, trans_pcie);\n\t\tif (ret)\n\t\t\tgoto out_no_pci;\n\t } else {\n\t\tret = iwl_pcie_alloc_ict(trans);\n\t\tif (ret)\n\t\t\tgoto out_no_pci;\n\n\t\tret = devm_request_threaded_irq(&pdev->dev, pdev->irq,\n\t\t\t\t\t\tiwl_pcie_isr,\n\t\t\t\t\t\tiwl_pcie_irq_handler,\n\t\t\t\t\t\tIRQF_SHARED, DRV_NAME, trans);\n\t\tif (ret) {\n\t\t\tIWL_ERR(trans, \"Error allocating IRQ %d\\n\", pdev->irq);\n\t\t\tgoto out_free_ict;\n\t\t}\n\t\ttrans_pcie->inta_mask = CSR_INI_SET_MASK;\n\t }\n\n#ifdef CONFIG_IWLWIFI_DEBUGFS\n\ttrans_pcie->fw_mon_data.state = IWL_FW_MON_DBGFS_STATE_CLOSED;\n\tmutex_init(&trans_pcie->fw_mon_data.mutex);\n#endif\n\n\treturn trans;\n\nout_free_ict:\n\tiwl_pcie_free_ict(trans);\nout_no_pci:\n\tfree_percpu(trans_pcie->tso_hdr_page);\n\tdestroy_workqueue(trans_pcie->rba.alloc_wq);\nout_free_trans:\n\tiwl_trans_free(trans);\n\treturn ERR_PTR(ret);\n}", "func_hash": 249581055441914689136534991194413858839, "file_name": "trans.c", "file_hash": 283396566562106139376150241807074258656, "cwe": ["CWE-476"], "cve": "CVE-2019-16234", "cve_desc": "drivers/net/wireless/intel/iwlwifi/pcie/trans.c in the Linux kernel 5.2.14 does not check the alloc_workqueue return value, leading to a NULL pointer dereference.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-16234"}
{"idx": 210050, "project": "lua", "commit_id": "1f3c6f4534c6411313361697d98d1145a1f030fa", "project_url": "https://github.com/lua/lua", "commit_url": "https://github.com/lua/lua/commit/1f3c6f4534c6411313361697d98d1145a1f030fa", "commit_message": "Bug: Lua can generate wrong code when _ENV is ", "target": 1, "func": "static void singlevar (LexState *ls, expdesc *var) {\n  TString *varname = str_checkname(ls);\n  FuncState *fs = ls->fs;\n  singlevaraux(fs, varname, var, 1);\n  if (var->k == VVOID) {  /* global name? */\n    expdesc key;\n    singlevaraux(fs, ls->envn, var, 1);  /* get environment variable */\n    lua_assert(var->k != VVOID);  /* this one must exist */\n    codestring(&key, varname);  /* key is variable name */\n    luaK_indexed(fs, var, &key);  /* env[varname] */\n  }\n}", "func_hash": 123763961511591581850775011069550713659, "file_name": "lparser.c", "file_hash": 295868068220261782570461856132388295005, "cwe": ["CWE-125"], "cve": "CVE-2022-28805", "cve_desc": "singlevar in lparser.c in Lua from (including) 5.4.0 up to (excluding) 5.4.4 lacks a certain luaK_exp2anyregup call, leading to a heap-based buffer over-read that might affect a system that compiles untrusted Lua code.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-28805"}
{"idx": 427153, "project": "lua", "commit_id": "1f3c6f4534c6411313361697d98d1145a1f030fa", "project_url": "https://github.com/lua/lua", "commit_url": "https://github.com/lua/lua/commit/1f3c6f4534c6411313361697d98d1145a1f030fa", "commit_message": "Bug: Lua can generate wrong code when _ENV is ", "target": 0, "func": "static void singlevar (LexState *ls, expdesc *var) {\n  TString *varname = str_checkname(ls);\n  FuncState *fs = ls->fs;\n  singlevaraux(fs, varname, var, 1);\n  if (var->k == VVOID) {  /* global name? */\n    expdesc key;\n    singlevaraux(fs, ls->envn, var, 1);  /* get environment variable */\n    lua_assert(var->k != VVOID);  /* this one must exist */\n    luaK_exp2anyregup(fs, var);  /* but could be a constant */\n    codestring(&key, varname);  /* key is variable name */\n    luaK_indexed(fs, var, &key);  /* env[varname] */\n  }\n}", "func_hash": 86104642186066137571814828089067244595, "file_name": "lparser.c", "file_hash": 131633022139792411216417604545990891123, "cwe": ["CWE-125"], "cve": "CVE-2022-28805", "cve_desc": "singlevar in lparser.c in Lua from (including) 5.4.0 up to (excluding) 5.4.4 lacks a certain luaK_exp2anyregup call, leading to a heap-based buffer over-read that might affect a system that compiles untrusted Lua code.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-28805"}
{"idx": 210090, "project": "file", "commit_id": "46a8443f76cec4b41ec736eca396984c74664f84", "project_url": "https://github.com/file/file", "commit_url": "https://github.com/file/file/commit/46a8443f76cec4b41ec736eca396984c74664f84", "commit_message": "Limit the number of elements in a vector (found by oss-fuzz)", "target": 1, "func": "cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,\n    uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)\n{\n\tconst cdf_section_header_t *shp;\n\tcdf_section_header_t sh;\n\tconst uint8_t *p, *q, *e;\n\tsize_t i, o4, nelements, j, slen, left;\n\tcdf_property_info_t *inp;\n\n\tif (offs > UINT32_MAX / 4) {\n\t\terrno = EFTYPE;\n\t\tgoto out;\n\t}\n\tshp = CAST(const cdf_section_header_t *,\n\t    cdf_offset(sst->sst_tab, offs));\n\tif (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)\n\t\tgoto out;\n\tsh.sh_len = CDF_TOLE4(shp->sh_len);\n\tif (sh.sh_len > CDF_SHLEN_LIMIT) {\n\t\terrno = EFTYPE;\n\t\tgoto out;\n\t}\n\n\tif (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1)\n\t\tgoto out;\n\n\tsh.sh_properties = CDF_TOLE4(shp->sh_properties);\n\tDPRINTF((\"section len: %u properties %u\\n\", sh.sh_len,\n\t    sh.sh_properties));\n\tif (sh.sh_properties > CDF_PROP_LIMIT)\n\t\tgoto out;\n\tinp = cdf_grow_info(info, maxcount, sh.sh_properties);\n\tif (inp == NULL)\n\t\tgoto out;\n\tinp += *count;\n\t*count += sh.sh_properties;\n\tp = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh)));\n\te = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len));\n\tif (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)\n\t\tgoto out;\n\n\tfor (i = 0; i < sh.sh_properties; i++) {\n\t\tif ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL)\n\t\t\tgoto out;\n\t\tinp[i].pi_id = CDF_GETUINT32(p, i << 1);\n\t\tleft = CAST(size_t, e - q);\n\t\tif (left < sizeof(uint32_t)) {\n\t\t\tDPRINTF((\"short info (no type)_\\n\"));\n\t\t\tgoto out;\n\t\t}\n\t\tinp[i].pi_type = CDF_GETUINT32(q, 0);\n\t\tDPRINTF((\"%\" SIZE_T_FORMAT \"u) id=%#x type=%#x offs=%#tx,%#x\\n\",\n\t\t    i, inp[i].pi_id, inp[i].pi_type, q - p, offs));\n\t\tif (inp[i].pi_type & CDF_VECTOR) {\n\t\t\tif (left < sizeof(uint32_t) * 2) {\n\t\t\t\tDPRINTF((\"missing CDF_VECTOR length\\n\"));\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tnelements = CDF_GETUINT32(q, 1);\n\t\t\tif (nelements == 0) {\n\t\t\t\tDPRINTF((\"CDF_VECTOR with nelements == 0\\n\"));\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tslen = 2;\n\t\t} else {\n\t\t\tnelements = 1;\n\t\t\tslen = 1;\n\t\t}\n\t\to4 = slen * sizeof(uint32_t);\n\t\tif (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))\n\t\t\tgoto unknown;\n\t\tswitch (inp[i].pi_type & CDF_TYPEMASK) {\n\t\tcase CDF_NULL:\n\t\tcase CDF_EMPTY:\n\t\t\tbreak;\n\t\tcase CDF_SIGNED16:\n\t\t\tif (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t)))\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tcase CDF_SIGNED32:\n\t\tcase CDF_BOOL:\n\t\tcase CDF_UNSIGNED32:\n\t\tcase CDF_FLOAT:\n\t\t\tif (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t)))\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tcase CDF_SIGNED64:\n\t\tcase CDF_UNSIGNED64:\n\t\tcase CDF_DOUBLE:\n\t\tcase CDF_FILETIME:\n\t\t\tif (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t)))\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tcase CDF_LENGTH32_STRING:\n\t\tcase CDF_LENGTH32_WSTRING:\n\t\t\tif (nelements > 1) {\n\t\t\t\tsize_t nelem = inp - *info;\n\t\t\t\tinp = cdf_grow_info(info, maxcount, nelements);\n\t\t\t\tif (inp == NULL)\n\t\t\t\t\tgoto out;\n\t\t\t\tinp += nelem;\n\t\t\t}\n\t\t\tDPRINTF((\"nelements = %\" SIZE_T_FORMAT \"u\\n\",\n\t\t\t    nelements));\n\t\t\tfor (j = 0; j < nelements && i < sh.sh_properties;\n\t\t\t    j++, i++)\n\t\t\t{\n\t\t\t\tuint32_t l;\n\n\t\t\t\tif (o4 + sizeof(uint32_t) > left)\n\t\t\t\t\tgoto out;\n\n\t\t\t\tl = CDF_GETUINT32(q, slen);\n\t\t\t\to4 += sizeof(uint32_t);\n\t\t\t\tif (o4 + l > left)\n\t\t\t\t\tgoto out;\n\n\t\t\t\tinp[i].pi_str.s_len = l;\n\t\t\t\tinp[i].pi_str.s_buf = CAST(const char *,\n\t\t\t\t    CAST(const void *, &q[o4]));\n\n\t\t\t\tDPRINTF((\"o=%\" SIZE_T_FORMAT \"u l=%d(%\"\n\t\t\t\t    SIZE_T_FORMAT \"u), t=%\" SIZE_T_FORMAT\n\t\t\t\t    \"u s=%s\\n\", o4, l, CDF_ROUND(l, sizeof(l)),\n\t\t\t\t    left, inp[i].pi_str.s_buf));\n\n\t\t\t\tif (l & 1)\n\t\t\t\t\tl++;\n\n\t\t\t\tslen += l >> 1;\n\t\t\t\to4 = slen * sizeof(uint32_t);\n\t\t\t}\n\t\t\ti--;\n\t\t\tbreak;\n\t\tcase CDF_CLIPBOARD:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tdefault:\n\t\tunknown:\n\t\t\tmemset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val));\n\t\t\tDPRINTF((\"Don't know how to deal with %#x\\n\",\n\t\t\t    inp[i].pi_type));\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn 0;\nout:\n\tfree(*info);\n\t*info = NULL;\n\t*count = 0;\n\t*maxcount = 0;\n\terrno = EFTYPE;\n\treturn -1;\n}", "func_hash": 73614762820995961147947254465500450851, "file_name": "cdf.c", "file_hash": 102975863888279484760686147789827176622, "cwe": ["CWE-787"], "cve": "CVE-2019-18218", "cve_desc": "cdf_read_property_info in cdf.c in file through 5.37 does not restrict the number of CDF_VECTOR elements, which allows a heap-based buffer overflow (4-byte out-of-bounds write).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-18218"}
{"idx": 427707, "project": "file", "commit_id": "46a8443f76cec4b41ec736eca396984c74664f84", "project_url": "https://github.com/file/file", "commit_url": "https://github.com/file/file/commit/46a8443f76cec4b41ec736eca396984c74664f84", "commit_message": "Limit the number of elements in a vector (found by oss-fuzz)", "target": 0, "func": "cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,\n    uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)\n{\n\tconst cdf_section_header_t *shp;\n\tcdf_section_header_t sh;\n\tconst uint8_t *p, *q, *e;\n\tsize_t i, o4, nelements, j, slen, left;\n\tcdf_property_info_t *inp;\n\n\tif (offs > UINT32_MAX / 4) {\n\t\terrno = EFTYPE;\n\t\tgoto out;\n\t}\n\tshp = CAST(const cdf_section_header_t *,\n\t    cdf_offset(sst->sst_tab, offs));\n\tif (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)\n\t\tgoto out;\n\tsh.sh_len = CDF_TOLE4(shp->sh_len);\n\tif (sh.sh_len > CDF_SHLEN_LIMIT) {\n\t\terrno = EFTYPE;\n\t\tgoto out;\n\t}\n\n\tif (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1)\n\t\tgoto out;\n\n\tsh.sh_properties = CDF_TOLE4(shp->sh_properties);\n\tDPRINTF((\"section len: %u properties %u\\n\", sh.sh_len,\n\t    sh.sh_properties));\n\tif (sh.sh_properties > CDF_PROP_LIMIT)\n\t\tgoto out;\n\tinp = cdf_grow_info(info, maxcount, sh.sh_properties);\n\tif (inp == NULL)\n\t\tgoto out;\n\tinp += *count;\n\t*count += sh.sh_properties;\n\tp = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh)));\n\te = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len));\n\tif (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)\n\t\tgoto out;\n\n\tfor (i = 0; i < sh.sh_properties; i++) {\n\t\tif ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL)\n\t\t\tgoto out;\n\t\tinp[i].pi_id = CDF_GETUINT32(p, i << 1);\n\t\tleft = CAST(size_t, e - q);\n\t\tif (left < sizeof(uint32_t)) {\n\t\t\tDPRINTF((\"short info (no type)_\\n\"));\n\t\t\tgoto out;\n\t\t}\n\t\tinp[i].pi_type = CDF_GETUINT32(q, 0);\n\t\tDPRINTF((\"%\" SIZE_T_FORMAT \"u) id=%#x type=%#x offs=%#tx,%#x\\n\",\n\t\t    i, inp[i].pi_id, inp[i].pi_type, q - p, offs));\n\t\tif (inp[i].pi_type & CDF_VECTOR) {\n\t\t\tif (left < sizeof(uint32_t) * 2) {\n\t\t\t\tDPRINTF((\"missing CDF_VECTOR length\\n\"));\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tnelements = CDF_GETUINT32(q, 1);\n\t\t\tif (nelements > CDF_ELEMENT_LIMIT || nelements == 0) {\n\t\t\t\tDPRINTF((\"CDF_VECTOR with nelements == %\"\n\t\t\t\t    SIZE_T_FORMAT \"u\\n\", nelements));\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tslen = 2;\n\t\t} else {\n\t\t\tnelements = 1;\n\t\t\tslen = 1;\n\t\t}\n\t\to4 = slen * sizeof(uint32_t);\n\t\tif (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))\n\t\t\tgoto unknown;\n\t\tswitch (inp[i].pi_type & CDF_TYPEMASK) {\n\t\tcase CDF_NULL:\n\t\tcase CDF_EMPTY:\n\t\t\tbreak;\n\t\tcase CDF_SIGNED16:\n\t\t\tif (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t)))\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tcase CDF_SIGNED32:\n\t\tcase CDF_BOOL:\n\t\tcase CDF_UNSIGNED32:\n\t\tcase CDF_FLOAT:\n\t\t\tif (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t)))\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tcase CDF_SIGNED64:\n\t\tcase CDF_UNSIGNED64:\n\t\tcase CDF_DOUBLE:\n\t\tcase CDF_FILETIME:\n\t\t\tif (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t)))\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tcase CDF_LENGTH32_STRING:\n\t\tcase CDF_LENGTH32_WSTRING:\n\t\t\tif (nelements > 1) {\n\t\t\t\tsize_t nelem = inp - *info;\n\t\t\t\tinp = cdf_grow_info(info, maxcount, nelements);\n\t\t\t\tif (inp == NULL)\n\t\t\t\t\tgoto out;\n\t\t\t\tinp += nelem;\n\t\t\t}\n\t\t\tfor (j = 0; j < nelements && i < sh.sh_properties;\n\t\t\t    j++, i++)\n\t\t\t{\n\t\t\t\tuint32_t l;\n\n\t\t\t\tif (o4 + sizeof(uint32_t) > left)\n\t\t\t\t\tgoto out;\n\n\t\t\t\tl = CDF_GETUINT32(q, slen);\n\t\t\t\to4 += sizeof(uint32_t);\n\t\t\t\tif (o4 + l > left)\n\t\t\t\t\tgoto out;\n\n\t\t\t\tinp[i].pi_str.s_len = l;\n\t\t\t\tinp[i].pi_str.s_buf = CAST(const char *,\n\t\t\t\t    CAST(const void *, &q[o4]));\n\n\t\t\t\tDPRINTF((\"o=%\" SIZE_T_FORMAT \"u l=%d(%\"\n\t\t\t\t    SIZE_T_FORMAT \"u), t=%\" SIZE_T_FORMAT\n\t\t\t\t    \"u s=%s\\n\", o4, l, CDF_ROUND(l, sizeof(l)),\n\t\t\t\t    left, inp[i].pi_str.s_buf));\n\n\t\t\t\tif (l & 1)\n\t\t\t\t\tl++;\n\n\t\t\t\tslen += l >> 1;\n\t\t\t\to4 = slen * sizeof(uint32_t);\n\t\t\t}\n\t\t\ti--;\n\t\t\tbreak;\n\t\tcase CDF_CLIPBOARD:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tdefault:\n\t\tunknown:\n\t\t\tmemset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val));\n\t\t\tDPRINTF((\"Don't know how to deal with %#x\\n\",\n\t\t\t    inp[i].pi_type));\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn 0;\nout:\n\tfree(*info);\n\t*info = NULL;\n\t*count = 0;\n\t*maxcount = 0;\n\terrno = EFTYPE;\n\treturn -1;\n}", "func_hash": 150937506413080071452042228145771315015, "file_name": "cdf.c", "file_hash": 54795377767819575688029736606662152773, "cwe": ["CWE-787"], "cve": "CVE-2019-18218", "cve_desc": "cdf_read_property_info in cdf.c in file through 5.37 does not restrict the number of CDF_VECTOR elements, which allows a heap-based buffer overflow (4-byte out-of-bounds write).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-18218"}
{"idx": 210203, "project": "linux", "commit_id": "8cae8cd89f05f6de223d63e6d15e31c8ba9cf53b", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/8cae8cd89f05f6de223d63e6d15e31c8ba9cf53b", "commit_message": "seq_file: disallow extremely large seq buffer allocations\n\nThere is no reasonable need for a buffer larger than this, and it avoids\nint overflow pitfalls.\n\nFixes: 058504edd026 (\"fs/seq_file: fallback to vmalloc allocation\")\nSuggested-by: Al Viro \nReported-by: Qualys Security Advisory \nSigned-off-by: Eric Sandeen \nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds ", "target": 1, "func": "static void *seq_buf_alloc(unsigned long size)\n{\n\treturn kvmalloc(size, GFP_KERNEL_ACCOUNT);\n}", "func_hash": 121083439970831812631280028038422882464, "file_name": "seq_file.c", "file_hash": 287921245214642386897154878925341860922, "cwe": ["CWE-787"], "cve": "CVE-2021-33909", "cve_desc": "fs/seq_file.c in the Linux kernel 3.16 through 5.13.x before 5.13.4 does not properly restrict seq buffer allocations, leading to an integer overflow, an Out-of-bounds Write, and escalation to root by an unprivileged user, aka CID-8cae8cd89f05.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-33909"}
{"idx": 430335, "project": "linux", "commit_id": "8cae8cd89f05f6de223d63e6d15e31c8ba9cf53b", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/8cae8cd89f05f6de223d63e6d15e31c8ba9cf53b", "commit_message": "seq_file: disallow extremely large seq buffer allocations\n\nThere is no reasonable need for a buffer larger than this, and it avoids\nint overflow pitfalls.\n\nFixes: 058504edd026 (\"fs/seq_file: fallback to vmalloc allocation\")\nSuggested-by: Al Viro \nReported-by: Qualys Security Advisory \nSigned-off-by: Eric Sandeen \nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds ", "target": 0, "func": "static void *seq_buf_alloc(unsigned long size)\n{\n\tif (unlikely(size > MAX_RW_COUNT))\n\t\treturn NULL;\n\n\treturn kvmalloc(size, GFP_KERNEL_ACCOUNT);\n}", "func_hash": 42519385330734652300654935585720178837, "file_name": "seq_file.c", "file_hash": 306638086039455779110548582120243774574, "cwe": ["CWE-787"], "cve": "CVE-2021-33909", "cve_desc": "fs/seq_file.c in the Linux kernel 3.16 through 5.13.x before 5.13.4 does not properly restrict seq buffer allocations, leading to an integer overflow, an Out-of-bounds Write, and escalation to root by an unprivileged user, aka CID-8cae8cd89f05.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-33909"}
{"idx": 210204, "project": "linux", "commit_id": "cefa91b2332d7009bc0be5d951d6cbbf349f90f8", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/cefa91b2332d7009bc0be5d951d6cbbf349f90f8", "commit_message": "openvswitch: fix OOB access in reserve_sfa_size()\n\nGiven a sufficiently large number of actions, while copying and\nreserving memory for a new action of a new flow, if next_offset is\ngreater than MAX_ACTIONS_BUFSIZE, the function reserve_sfa_size() does\nnot return -EMSGSIZE as expected, but it allocates MAX_ACTIONS_BUFSIZE\nbytes increasing actions_len by req_size. This can then lead to an OOB\nwrite access, especially when further actions need to be copied.\n\nFix it by rearranging the flow action size check.\n\nKASAN splat below:\n\n==================================================================\nBUG: KASAN: slab-out-of-bounds in reserve_sfa_size+0x1ba/0x380 [openvswitch]\nWrite of size 65360 at addr ffff888147e4001c by task handler15/836\n\nCPU: 1 PID: 836 Comm: handler15 Not tainted 5.18.0-rc1+ #27\n...\nCall Trace:\n \n dump_stack_lvl+0x45/0x5a\n print_report.cold+0x5e/0x5db\n ? __lock_text_start+0x8/0x8\n ? reserve_sfa_size+0x1ba/0x380 [openvswitch]\n kasan_report+0xb5/0x130\n ? reserve_sfa_size+0x1ba/0x380 [openvswitch]\n kasan_check_range+0xf5/0x1d0\n memcpy+0x39/0x60\n reserve_sfa_size+0x1ba/0x380 [openvswitch]\n __add_action+0x24/0x120 [openvswitch]\n ovs_nla_add_action+0xe/0x20 [openvswitch]\n ovs_ct_copy_action+0x29d/0x1130 [openvswitch]\n ? __kernel_text_address+0xe/0x30\n ? unwind_get_return_address+0x56/0xa0\n ? create_prof_cpu_mask+0x20/0x20\n ? ovs_ct_verify+0xf0/0xf0 [openvswitch]\n ? prep_compound_page+0x198/0x2a0\n ? __kasan_check_byte+0x10/0x40\n ? kasan_unpoison+0x40/0x70\n ? ksize+0x44/0x60\n ? reserve_sfa_size+0x75/0x380 [openvswitch]\n __ovs_nla_copy_actions+0xc26/0x2070 [openvswitch]\n ? __zone_watermark_ok+0x420/0x420\n ? validate_set.constprop.0+0xc90/0xc90 [openvswitch]\n ? __alloc_pages+0x1a9/0x3e0\n ? __alloc_pages_slowpath.constprop.0+0x1da0/0x1da0\n ? unwind_next_frame+0x991/0x1e40\n ? __mod_node_page_state+0x99/0x120\n ? __mod_lruvec_page_state+0x2e3/0x470\n ? __kasan_kmalloc_large+0x90/0xe0\n ovs_nla_copy_actions+0x1b4/0x2c0 [openvswitch]\n ovs_flow_cmd_new+0x3cd/0xb10 [openvswitch]\n ...\n\nCc: stable@vger.kernel.org\nFixes: f28cd2af22a0 (\"openvswitch: fix flow actions reallocation\")\nSigned-off-by: Paolo Valerio \nAcked-by: Eelco Chaudron \nSigned-off-by: David S. Miller ", "target": 1, "func": "static struct nlattr *reserve_sfa_size(struct sw_flow_actions **sfa,\n\t\t\t\t       int attr_len, bool log)\n{\n\n\tstruct sw_flow_actions *acts;\n\tint new_acts_size;\n\tsize_t req_size = NLA_ALIGN(attr_len);\n\tint next_offset = offsetof(struct sw_flow_actions, actions) +\n\t\t\t\t\t(*sfa)->actions_len;\n\n\tif (req_size <= (ksize(*sfa) - next_offset))\n\t\tgoto out;\n\n\tnew_acts_size = max(next_offset + req_size, ksize(*sfa) * 2);\n\n\tif (new_acts_size > MAX_ACTIONS_BUFSIZE) {\n\t\tif ((MAX_ACTIONS_BUFSIZE - next_offset) < req_size) {\n\t\t\tOVS_NLERR(log, \"Flow action size exceeds max %u\",\n\t\t\t\t  MAX_ACTIONS_BUFSIZE);\n\t\t\treturn ERR_PTR(-EMSGSIZE);\n\t\t}\n\t\tnew_acts_size = MAX_ACTIONS_BUFSIZE;\n\t}\n\n\tacts = nla_alloc_flow_actions(new_acts_size);\n\tif (IS_ERR(acts))\n\t\treturn (void *)acts;\n\n\tmemcpy(acts->actions, (*sfa)->actions, (*sfa)->actions_len);\n\tacts->actions_len = (*sfa)->actions_len;\n\tacts->orig_len = (*sfa)->orig_len;\n\tkfree(*sfa);\n\t*sfa = acts;\n\nout:\n\t(*sfa)->actions_len += req_size;\n\treturn  (struct nlattr *) ((unsigned char *)(*sfa) + next_offset);\n}", "func_hash": 66009891447134933026284929915758254537, "file_name": "flow_netlink.c", "file_hash": 47337588811900760055139247291202023489, "cwe": ["CWE-362"], "cve": "CVE-2022-2639", "cve_desc": "An integer coercion error was found in the openvswitch kernel module. Given a sufficiently large number of actions, while copying and reserving memory for a new action of a new flow, the reserve_sfa_size() function does not return -EMSGSIZE as expected, potentially leading to an out-of-bounds write access. This flaw allows a local user to crash or potentially escalate their privileges on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2639"}
{"idx": 430380, "project": "linux", "commit_id": "cefa91b2332d7009bc0be5d951d6cbbf349f90f8", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/cefa91b2332d7009bc0be5d951d6cbbf349f90f8", "commit_message": "openvswitch: fix OOB access in reserve_sfa_size()\n\nGiven a sufficiently large number of actions, while copying and\nreserving memory for a new action of a new flow, if next_offset is\ngreater than MAX_ACTIONS_BUFSIZE, the function reserve_sfa_size() does\nnot return -EMSGSIZE as expected, but it allocates MAX_ACTIONS_BUFSIZE\nbytes increasing actions_len by req_size. This can then lead to an OOB\nwrite access, especially when further actions need to be copied.\n\nFix it by rearranging the flow action size check.\n\nKASAN splat below:\n\n==================================================================\nBUG: KASAN: slab-out-of-bounds in reserve_sfa_size+0x1ba/0x380 [openvswitch]\nWrite of size 65360 at addr ffff888147e4001c by task handler15/836\n\nCPU: 1 PID: 836 Comm: handler15 Not tainted 5.18.0-rc1+ #27\n...\nCall Trace:\n \n dump_stack_lvl+0x45/0x5a\n print_report.cold+0x5e/0x5db\n ? __lock_text_start+0x8/0x8\n ? reserve_sfa_size+0x1ba/0x380 [openvswitch]\n kasan_report+0xb5/0x130\n ? reserve_sfa_size+0x1ba/0x380 [openvswitch]\n kasan_check_range+0xf5/0x1d0\n memcpy+0x39/0x60\n reserve_sfa_size+0x1ba/0x380 [openvswitch]\n __add_action+0x24/0x120 [openvswitch]\n ovs_nla_add_action+0xe/0x20 [openvswitch]\n ovs_ct_copy_action+0x29d/0x1130 [openvswitch]\n ? __kernel_text_address+0xe/0x30\n ? unwind_get_return_address+0x56/0xa0\n ? create_prof_cpu_mask+0x20/0x20\n ? ovs_ct_verify+0xf0/0xf0 [openvswitch]\n ? prep_compound_page+0x198/0x2a0\n ? __kasan_check_byte+0x10/0x40\n ? kasan_unpoison+0x40/0x70\n ? ksize+0x44/0x60\n ? reserve_sfa_size+0x75/0x380 [openvswitch]\n __ovs_nla_copy_actions+0xc26/0x2070 [openvswitch]\n ? __zone_watermark_ok+0x420/0x420\n ? validate_set.constprop.0+0xc90/0xc90 [openvswitch]\n ? __alloc_pages+0x1a9/0x3e0\n ? __alloc_pages_slowpath.constprop.0+0x1da0/0x1da0\n ? unwind_next_frame+0x991/0x1e40\n ? __mod_node_page_state+0x99/0x120\n ? __mod_lruvec_page_state+0x2e3/0x470\n ? __kasan_kmalloc_large+0x90/0xe0\n ovs_nla_copy_actions+0x1b4/0x2c0 [openvswitch]\n ovs_flow_cmd_new+0x3cd/0xb10 [openvswitch]\n ...\n\nCc: stable@vger.kernel.org\nFixes: f28cd2af22a0 (\"openvswitch: fix flow actions reallocation\")\nSigned-off-by: Paolo Valerio \nAcked-by: Eelco Chaudron \nSigned-off-by: David S. Miller ", "target": 0, "func": "static struct nlattr *reserve_sfa_size(struct sw_flow_actions **sfa,\n\t\t\t\t       int attr_len, bool log)\n{\n\n\tstruct sw_flow_actions *acts;\n\tint new_acts_size;\n\tsize_t req_size = NLA_ALIGN(attr_len);\n\tint next_offset = offsetof(struct sw_flow_actions, actions) +\n\t\t\t\t\t(*sfa)->actions_len;\n\n\tif (req_size <= (ksize(*sfa) - next_offset))\n\t\tgoto out;\n\n\tnew_acts_size = max(next_offset + req_size, ksize(*sfa) * 2);\n\n\tif (new_acts_size > MAX_ACTIONS_BUFSIZE) {\n\t\tif ((next_offset + req_size) > MAX_ACTIONS_BUFSIZE) {\n\t\t\tOVS_NLERR(log, \"Flow action size exceeds max %u\",\n\t\t\t\t  MAX_ACTIONS_BUFSIZE);\n\t\t\treturn ERR_PTR(-EMSGSIZE);\n\t\t}\n\t\tnew_acts_size = MAX_ACTIONS_BUFSIZE;\n\t}\n\n\tacts = nla_alloc_flow_actions(new_acts_size);\n\tif (IS_ERR(acts))\n\t\treturn (void *)acts;\n\n\tmemcpy(acts->actions, (*sfa)->actions, (*sfa)->actions_len);\n\tacts->actions_len = (*sfa)->actions_len;\n\tacts->orig_len = (*sfa)->orig_len;\n\tkfree(*sfa);\n\t*sfa = acts;\n\nout:\n\t(*sfa)->actions_len += req_size;\n\treturn  (struct nlattr *) ((unsigned char *)(*sfa) + next_offset);\n}", "func_hash": 241955732354437165048790183048012619919, "file_name": "flow_netlink.c", "file_hash": 169733194668607707184956779941409309704, "cwe": ["CWE-362"], "cve": "CVE-2022-2639", "cve_desc": "An integer coercion error was found in the openvswitch kernel module. Given a sufficiently large number of actions, while copying and reserving memory for a new action of a new flow, the reserve_sfa_size() function does not return -EMSGSIZE as expected, potentially leading to an out-of-bounds write access. This flaw allows a local user to crash or potentially escalate their privileges on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2639"}
{"idx": 210206, "project": "squid", "commit_id": "780c4ea1b4c9d2fb41f6962aa6ed73ae57f74b2b", "project_url": "https://github.com/squid-cache/squid", "commit_url": "https://github.com/squid-cache/squid/commit/780c4ea1b4c9d2fb41f6962aa6ed73ae57f74b2b", "commit_message": "Improve handling of Gopher responses (#1022)", "target": 1, "func": "gopherToHTML(GopherStateData * gopherState, char *inbuf, int len)\n{\n    char *pos = inbuf;\n    char *lpos = NULL;\n    char *tline = NULL;\n    LOCAL_ARRAY(char, line, TEMP_BUF_SIZE);\n    LOCAL_ARRAY(char, tmpbuf, TEMP_BUF_SIZE);\n    char *name = NULL;\n    char *selector = NULL;\n    char *host = NULL;\n    char *port = NULL;\n    char *escaped_selector = NULL;\n    const char *icon_url = NULL;\n    char gtype;\n    StoreEntry *entry = NULL;\n\n    memset(tmpbuf, '\\0', TEMP_BUF_SIZE);\n    memset(line, '\\0', TEMP_BUF_SIZE);\n\n    entry = gopherState->entry;\n\n    if (gopherState->conversion == GopherStateData::HTML_INDEX_PAGE) {\n        char *html_url = html_quote(entry->url());\n        gopherHTMLHeader(entry, \"Gopher Index %s\", html_url);\n        storeAppendPrintf(entry,\n                          \"

This is a searchable Gopher index. Use the search\\n\"\n \"function of your browser to enter search terms.\\n\"\n \"\\n\");\n gopherHTMLFooter(entry);\n /* now let start sending stuff to client */\n entry->flush();\n gopherState->HTML_header_added = 1;\n\n return;\n }\n\n if (gopherState->conversion == GopherStateData::HTML_CSO_PAGE) {\n char *html_url = html_quote(entry->url());\n gopherHTMLHeader(entry, \"CSO Search of %s\", html_url);\n storeAppendPrintf(entry,\n \"

A CSO database usually contains a phonebook or\\n\"\n \"directory. Use the search function of your browser to enter\\n\"\n \"search terms.

\\n\");\n gopherHTMLFooter(entry);\n /* now let start sending stuff to client */\n entry->flush();\n gopherState->HTML_header_added = 1;\n\n return;\n }\n\n String outbuf;\n\n if (!gopherState->HTML_header_added) {\n if (gopherState->conversion == GopherStateData::HTML_CSO_RESULT)\n gopherHTMLHeader(entry, \"CSO Search Result\", NULL);\n else\n gopherHTMLHeader(entry, \"Gopher Menu\", NULL);\n\n outbuf.append (\"
\");\n\n        gopherState->HTML_header_added = 1;\n\n        gopherState->HTML_pre = 1;\n    }\n\n    while (pos < inbuf + len) {\n        int llen;\n        int left = len - (pos - inbuf);\n        lpos = (char *)memchr(pos, '\\n', left);\n        if (lpos) {\n            ++lpos;             /* Next line is after \\n */\n            llen = lpos - pos;\n        } else {\n            llen = left;\n        }\n        if (gopherState->len + llen >= TEMP_BUF_SIZE) {\n            debugs(10, DBG_IMPORTANT, \"GopherHTML: Buffer overflow. Lost some data on URL: \" << entry->url()  );\n            llen = TEMP_BUF_SIZE - gopherState->len - 1;\n        }\n        if (!lpos) {\n            /* there is no complete line in inbuf */\n            /* copy it to temp buffer */\n            /* note: llen is adjusted above */\n            memcpy(gopherState->buf + gopherState->len, pos, llen);\n            gopherState->len += llen;\n            break;\n        }\n        if (gopherState->len != 0) {\n            /* there is something left from last tx. */\n            memcpy(line, gopherState->buf, gopherState->len);\n            memcpy(line + gopherState->len, pos, llen);\n            llen += gopherState->len;\n            gopherState->len = 0;\n        } else {\n            memcpy(line, pos, llen);\n        }\n        line[llen + 1] = '\\0';\n        /* move input to next line */\n        pos = lpos;\n\n        /* at this point. We should have one line in buffer to process */\n\n        if (*line == '.') {\n            /* skip it */\n            memset(line, '\\0', TEMP_BUF_SIZE);\n            continue;\n        }\n\n        switch (gopherState->conversion) {\n\n        case GopherStateData::HTML_INDEX_RESULT:\n\n        case GopherStateData::HTML_DIR: {\n            tline = line;\n            gtype = *tline;\n            ++tline;\n            name = tline;\n            selector = strchr(tline, TAB);\n\n            if (selector) {\n                *selector = '\\0';\n                ++selector;\n                host = strchr(selector, TAB);\n\n                if (host) {\n                    *host = '\\0';\n                    ++host;\n                    port = strchr(host, TAB);\n\n                    if (port) {\n                        char *junk;\n                        port[0] = ':';\n                        junk = strchr(host, TAB);\n\n                        if (junk)\n                            *junk++ = 0;    /* Chop port */\n                        else {\n                            junk = strchr(host, '\\r');\n\n                            if (junk)\n                                *junk++ = 0;    /* Chop port */\n                            else {\n                                junk = strchr(host, '\\n');\n\n                                if (junk)\n                                    *junk++ = 0;    /* Chop port */\n                            }\n                        }\n\n                        if ((port[1] == '0') && (!port[2]))\n                            port[0] = 0;    /* 0 means none */\n                    }\n\n                    /* escape a selector here */\n                    escaped_selector = xstrdup(rfc1738_escape_part(selector));\n\n                    switch (gtype) {\n\n                    case GOPHER_DIRECTORY:\n                        icon_url = mimeGetIconURL(\"internal-menu\");\n                        break;\n\n                    case GOPHER_HTML:\n\n                    case GOPHER_FILE:\n                        icon_url = mimeGetIconURL(\"internal-text\");\n                        break;\n\n                    case GOPHER_INDEX:\n\n                    case GOPHER_CSO:\n                        icon_url = mimeGetIconURL(\"internal-index\");\n                        break;\n\n                    case GOPHER_IMAGE:\n\n                    case GOPHER_GIF:\n\n                    case GOPHER_PLUS_IMAGE:\n                        icon_url = mimeGetIconURL(\"internal-image\");\n                        break;\n\n                    case GOPHER_SOUND:\n\n                    case GOPHER_PLUS_SOUND:\n                        icon_url = mimeGetIconURL(\"internal-sound\");\n                        break;\n\n                    case GOPHER_PLUS_MOVIE:\n                        icon_url = mimeGetIconURL(\"internal-movie\");\n                        break;\n\n                    case GOPHER_TELNET:\n\n                    case GOPHER_3270:\n                        icon_url = mimeGetIconURL(\"internal-telnet\");\n                        break;\n\n                    case GOPHER_BIN:\n\n                    case GOPHER_MACBINHEX:\n\n                    case GOPHER_DOSBIN:\n\n                    case GOPHER_UUENCODED:\n                        icon_url = mimeGetIconURL(\"internal-binary\");\n                        break;\n\n                    case GOPHER_INFO:\n                        icon_url = NULL;\n                        break;\n\n                    default:\n                        icon_url = mimeGetIconURL(\"internal-unknown\");\n                        break;\n                    }\n\n                    memset(tmpbuf, '\\0', TEMP_BUF_SIZE);\n\n                    if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) {\n                        if (strlen(escaped_selector) != 0)\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, escaped_selector, rfc1738_escape_part(host),\n                                     *port ? \":\" : \"\", port, html_quote(name));\n                        else\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, rfc1738_escape_part(host), *port ? \":\" : \"\",\n                                     port, html_quote(name));\n\n                    } else if (gtype == GOPHER_INFO) {\n                        snprintf(tmpbuf, TEMP_BUF_SIZE, \"\\t%s\\n\", html_quote(name));\n                    } else {\n                        if (strncmp(selector, \"GET /\", 5) == 0) {\n                            /* WWW link */\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name));\n                        } else {\n                            /* Standard link */\n                            snprintf(tmpbuf, TEMP_BUF_SIZE, \" %s\\n\",\n                                     icon_url, host, gtype, escaped_selector, html_quote(name));\n                        }\n                    }\n\n                    safe_free(escaped_selector);\n                    outbuf.append(tmpbuf);\n                } else {\n                    memset(line, '\\0', TEMP_BUF_SIZE);\n                    continue;\n                }\n            } else {\n                memset(line, '\\0', TEMP_BUF_SIZE);\n                continue;\n            }\n\n            break;\n            }           /* HTML_DIR, HTML_INDEX_RESULT */\n\n        case GopherStateData::HTML_CSO_RESULT: {\n            if (line[0] == '-') {\n                int code, recno;\n                char *s_code, *s_recno, *result;\n\n                s_code = strtok(line + 1, \":\\n\");\n                s_recno = strtok(NULL, \":\\n\");\n                result = strtok(NULL, \"\\n\");\n\n                if (!result)\n                    break;\n\n                code = atoi(s_code);\n\n                recno = atoi(s_recno);\n\n                if (code != 200)\n                    break;\n\n                if (gopherState->cso_recno != recno) {\n                    snprintf(tmpbuf, TEMP_BUF_SIZE, \"

Record# %d
%s

\\n
\", recno, html_quote(result));\n                    gopherState->cso_recno = recno;\n                } else {\n                    snprintf(tmpbuf, TEMP_BUF_SIZE, \"%s\\n\", html_quote(result));\n                }\n\n                outbuf.append(tmpbuf);\n                break;\n            } else {\n                int code;\n                char *s_code, *result;\n\n                s_code = strtok(line, \":\");\n                result = strtok(NULL, \"\\n\");\n\n                if (!result)\n                    break;\n\n                code = atoi(s_code);\n\n                switch (code) {\n\n                case 200: {\n                    /* OK */\n                    /* Do nothing here */\n                    break;\n                }\n\n                case 102:   /* Number of matches */\n\n                case 501:   /* No Match */\n\n                case 502: { /* Too Many Matches */\n                    /* Print the message the server returns */\n                    snprintf(tmpbuf, TEMP_BUF_SIZE, \"

%s

\\n
\", html_quote(result));\n                    outbuf.append(tmpbuf);\n                    break;\n                }\n\n                }\n            }\n\n            }           /* HTML_CSO_RESULT */\n\n        default:\n            break;      /* do nothing */\n\n        }           /* switch */\n\n    }               /* while loop */\n\n    if (outbuf.size() > 0) {\n        entry->append(outbuf.rawBuf(), outbuf.size());\n        /* now let start sending stuff to client */\n        entry->flush();\n    }\n\n    outbuf.clean();\n    return;\n}", "func_hash": 69907744519047196773632287126924030666, "file_name": "gopher.cc", "file_hash": 274206304991379198598012995880144954128, "cwe": ["CWE-400"], "cve": "CVE-2021-46784", "cve_desc": "In Squid 3.x through 3.5.28, 4.x through 4.17, and 5.x before 5.6, due to improper buffer management, a Denial of Service can occur when processing long Gopher server responses.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46784"}
{"idx": 430470, "project": "squid", "commit_id": "780c4ea1b4c9d2fb41f6962aa6ed73ae57f74b2b", "project_url": "https://github.com/squid-cache/squid", "commit_url": "https://github.com/squid-cache/squid/commit/780c4ea1b4c9d2fb41f6962aa6ed73ae57f74b2b", "commit_message": "Improve handling of Gopher responses (#1022)", "target": 0, "func": "gopherToHTML(GopherStateData * gopherState, char *inbuf, int len)\n{\n    char *pos = inbuf;\n    char *lpos = NULL;\n    char *tline = NULL;\n    LOCAL_ARRAY(char, line, TEMP_BUF_SIZE);\n    char *name = NULL;\n    char *selector = NULL;\n    char *host = NULL;\n    char *port = NULL;\n    char *escaped_selector = NULL;\n    const char *icon_url = NULL;\n    char gtype;\n    StoreEntry *entry = NULL;\n\n    memset(line, '\\0', TEMP_BUF_SIZE);\n\n    entry = gopherState->entry;\n\n    if (gopherState->conversion == GopherStateData::HTML_INDEX_PAGE) {\n        char *html_url = html_quote(entry->url());\n        gopherHTMLHeader(entry, \"Gopher Index %s\", html_url);\n        storeAppendPrintf(entry,\n                          \"

This is a searchable Gopher index. Use the search\\n\"\n \"function of your browser to enter search terms.\\n\"\n \"\\n\");\n gopherHTMLFooter(entry);\n /* now let start sending stuff to client */\n entry->flush();\n gopherState->HTML_header_added = 1;\n\n return;\n }\n\n if (gopherState->conversion == GopherStateData::HTML_CSO_PAGE) {\n char *html_url = html_quote(entry->url());\n gopherHTMLHeader(entry, \"CSO Search of %s\", html_url);\n storeAppendPrintf(entry,\n \"

A CSO database usually contains a phonebook or\\n\"\n \"directory. Use the search function of your browser to enter\\n\"\n \"search terms.

\\n\");\n gopherHTMLFooter(entry);\n /* now let start sending stuff to client */\n entry->flush();\n gopherState->HTML_header_added = 1;\n\n return;\n }\n\n SBuf outbuf;\n\n if (!gopherState->HTML_header_added) {\n if (gopherState->conversion == GopherStateData::HTML_CSO_RESULT)\n gopherHTMLHeader(entry, \"CSO Search Result\", NULL);\n else\n gopherHTMLHeader(entry, \"Gopher Menu\", NULL);\n\n outbuf.append (\"
\");\n\n        gopherState->HTML_header_added = 1;\n\n        gopherState->HTML_pre = 1;\n    }\n\n    while (pos < inbuf + len) {\n        int llen;\n        int left = len - (pos - inbuf);\n        lpos = (char *)memchr(pos, '\\n', left);\n        if (lpos) {\n            ++lpos;             /* Next line is after \\n */\n            llen = lpos - pos;\n        } else {\n            llen = left;\n        }\n        if (gopherState->len + llen >= TEMP_BUF_SIZE) {\n            debugs(10, DBG_IMPORTANT, \"GopherHTML: Buffer overflow. Lost some data on URL: \" << entry->url()  );\n            llen = TEMP_BUF_SIZE - gopherState->len - 1;\n        }\n        if (!lpos) {\n            /* there is no complete line in inbuf */\n            /* copy it to temp buffer */\n            /* note: llen is adjusted above */\n            memcpy(gopherState->buf + gopherState->len, pos, llen);\n            gopherState->len += llen;\n            break;\n        }\n        if (gopherState->len != 0) {\n            /* there is something left from last tx. */\n            memcpy(line, gopherState->buf, gopherState->len);\n            memcpy(line + gopherState->len, pos, llen);\n            llen += gopherState->len;\n            gopherState->len = 0;\n        } else {\n            memcpy(line, pos, llen);\n        }\n        line[llen + 1] = '\\0';\n        /* move input to next line */\n        pos = lpos;\n\n        /* at this point. We should have one line in buffer to process */\n\n        if (*line == '.') {\n            /* skip it */\n            memset(line, '\\0', TEMP_BUF_SIZE);\n            continue;\n        }\n\n        switch (gopherState->conversion) {\n\n        case GopherStateData::HTML_INDEX_RESULT:\n\n        case GopherStateData::HTML_DIR: {\n            tline = line;\n            gtype = *tline;\n            ++tline;\n            name = tline;\n            selector = strchr(tline, TAB);\n\n            if (selector) {\n                *selector = '\\0';\n                ++selector;\n                host = strchr(selector, TAB);\n\n                if (host) {\n                    *host = '\\0';\n                    ++host;\n                    port = strchr(host, TAB);\n\n                    if (port) {\n                        char *junk;\n                        port[0] = ':';\n                        junk = strchr(host, TAB);\n\n                        if (junk)\n                            *junk++ = 0;    /* Chop port */\n                        else {\n                            junk = strchr(host, '\\r');\n\n                            if (junk)\n                                *junk++ = 0;    /* Chop port */\n                            else {\n                                junk = strchr(host, '\\n');\n\n                                if (junk)\n                                    *junk++ = 0;    /* Chop port */\n                            }\n                        }\n\n                        if ((port[1] == '0') && (!port[2]))\n                            port[0] = 0;    /* 0 means none */\n                    }\n\n                    /* escape a selector here */\n                    escaped_selector = xstrdup(rfc1738_escape_part(selector));\n\n                    switch (gtype) {\n\n                    case GOPHER_DIRECTORY:\n                        icon_url = mimeGetIconURL(\"internal-menu\");\n                        break;\n\n                    case GOPHER_HTML:\n\n                    case GOPHER_FILE:\n                        icon_url = mimeGetIconURL(\"internal-text\");\n                        break;\n\n                    case GOPHER_INDEX:\n\n                    case GOPHER_CSO:\n                        icon_url = mimeGetIconURL(\"internal-index\");\n                        break;\n\n                    case GOPHER_IMAGE:\n\n                    case GOPHER_GIF:\n\n                    case GOPHER_PLUS_IMAGE:\n                        icon_url = mimeGetIconURL(\"internal-image\");\n                        break;\n\n                    case GOPHER_SOUND:\n\n                    case GOPHER_PLUS_SOUND:\n                        icon_url = mimeGetIconURL(\"internal-sound\");\n                        break;\n\n                    case GOPHER_PLUS_MOVIE:\n                        icon_url = mimeGetIconURL(\"internal-movie\");\n                        break;\n\n                    case GOPHER_TELNET:\n\n                    case GOPHER_3270:\n                        icon_url = mimeGetIconURL(\"internal-telnet\");\n                        break;\n\n                    case GOPHER_BIN:\n\n                    case GOPHER_MACBINHEX:\n\n                    case GOPHER_DOSBIN:\n\n                    case GOPHER_UUENCODED:\n                        icon_url = mimeGetIconURL(\"internal-binary\");\n                        break;\n\n                    case GOPHER_INFO:\n                        icon_url = NULL;\n                        break;\n\n                    default:\n                        icon_url = mimeGetIconURL(\"internal-unknown\");\n                        break;\n                    }\n\n                    if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) {\n                        if (strlen(escaped_selector) != 0)\n                            outbuf.appendf(\" %s\\n\",\n                                           icon_url, escaped_selector, rfc1738_escape_part(host),\n                                           *port ? \":\" : \"\", port, html_quote(name));\n                        else\n                            outbuf.appendf(\" %s\\n\",\n                                           icon_url, rfc1738_escape_part(host), *port ? \":\" : \"\",\n                                           port, html_quote(name));\n\n                    } else if (gtype == GOPHER_INFO) {\n                        outbuf.appendf(\"\\t%s\\n\", html_quote(name));\n                    } else {\n                        if (strncmp(selector, \"GET /\", 5) == 0) {\n                            /* WWW link */\n                            outbuf.appendf(\" %s\\n\",\n                                           icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name));\n                        } else if (gtype == GOPHER_WWW) {\n                            outbuf.appendf(\" %s\\n\",\n                                           icon_url, rfc1738_escape_unescaped(selector), html_quote(name));\n                        } else {\n                            /* Standard link */\n                            outbuf.appendf(\" %s\\n\",\n                                           icon_url, host, gtype, escaped_selector, html_quote(name));\n                        }\n                    }\n\n                    safe_free(escaped_selector);\n                } else {\n                    memset(line, '\\0', TEMP_BUF_SIZE);\n                    continue;\n                }\n            } else {\n                memset(line, '\\0', TEMP_BUF_SIZE);\n                continue;\n            }\n\n            break;\n            }           /* HTML_DIR, HTML_INDEX_RESULT */\n\n        case GopherStateData::HTML_CSO_RESULT: {\n            if (line[0] == '-') {\n                int code, recno;\n                char *s_code, *s_recno, *result;\n\n                s_code = strtok(line + 1, \":\\n\");\n                s_recno = strtok(NULL, \":\\n\");\n                result = strtok(NULL, \"\\n\");\n\n                if (!result)\n                    break;\n\n                code = atoi(s_code);\n\n                recno = atoi(s_recno);\n\n                if (code != 200)\n                    break;\n\n                if (gopherState->cso_recno != recno) {\n                    outbuf.appendf(\"

Record# %d
%s

\\n
\", recno, html_quote(result));\n                    gopherState->cso_recno = recno;\n                } else {\n                    outbuf.appendf(\"%s\\n\", html_quote(result));\n                }\n\n                break;\n            } else {\n                int code;\n                char *s_code, *result;\n\n                s_code = strtok(line, \":\");\n                result = strtok(NULL, \"\\n\");\n\n                if (!result)\n                    break;\n\n                code = atoi(s_code);\n\n                switch (code) {\n\n                case 200: {\n                    /* OK */\n                    /* Do nothing here */\n                    break;\n                }\n\n                case 102:   /* Number of matches */\n\n                case 501:   /* No Match */\n\n                case 502: { /* Too Many Matches */\n                    /* Print the message the server returns */\n                    outbuf.appendf(\"

%s

\\n
\", html_quote(result));\n                    break;\n                }\n\n                }\n            }\n\n            }           /* HTML_CSO_RESULT */\n\n        default:\n            break;      /* do nothing */\n\n        }           /* switch */\n\n    }               /* while loop */\n\n    if (outbuf.length() > 0) {\n        entry->append(outbuf.rawContent(), outbuf.length());\n        /* now let start sending stuff to client */\n        entry->flush();\n    }\n\n    return;\n}", "func_hash": 138686742216343389129906256835749429816, "file_name": "gopher.cc", "file_hash": 39955176817113992488945748005868573997, "cwe": ["CWE-400"], "cve": "CVE-2021-46784", "cve_desc": "In Squid 3.x through 3.5.28, 4.x through 4.17, and 5.x before 5.6, due to improper buffer management, a Denial of Service can occur when processing long Gopher server responses.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46784"}
{"idx": 210252, "project": "ImageMagick", "commit_id": "ca3654ebf7a439dc736f56f083c9aa98e4464b7f", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/ca3654ebf7a439dc736f56f083c9aa98e4464b7f", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/4988", "target": 1, "func": "static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define MonoColorType  1\n#define RGBColorType  3\n\n  char\n    property[MagickPathExtent];\n\n  CINInfo\n    cin;\n\n  Image\n    *image;\n\n  MagickBooleanType\n    status;\n\n  MagickOffsetType\n    offset;\n\n  QuantumInfo\n    *quantum_info;\n\n  QuantumType\n    quantum_type;\n\n  ssize_t\n    i;\n\n  Quantum\n    *q;\n\n  size_t\n    length;\n\n  ssize_t\n    count,\n    y;\n\n  unsigned char\n    magick[4],\n    *pixels;\n\n\n  /*\n    Open image file.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  image=AcquireImage(image_info,exception);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n    File information.\n  */\n  offset=0;\n  count=ReadBlob(image,4,magick);\n  offset+=count;\n  if ((count != 4) ||\n      ((LocaleNCompare((char *) magick,\"\\200\\052\\137\\327\",4) != 0)))\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  memset(&cin,0,sizeof(cin));\n  image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&\n    (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;\n  cin.file.image_offset=ReadBlobLong(image);\n  offset+=4;\n  cin.file.generic_length=ReadBlobLong(image);\n  offset+=4;\n  cin.file.industry_length=ReadBlobLong(image);\n  offset+=4;\n  cin.file.user_length=ReadBlobLong(image);\n  offset+=4;\n  cin.file.file_size=ReadBlobLong(image);\n  offset+=4;\n  offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)\n    cin.file.version);\n  (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));\n  (void) SetImageProperty(image,\"dpx:file.version\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)\n    cin.file.filename);\n  (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));\n  (void) SetImageProperty(image,\"dpx:file.filename\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)\n    cin.file.create_date);\n  (void) CopyMagickString(property,cin.file.create_date,\n    sizeof(cin.file.create_date));\n  (void) SetImageProperty(image,\"dpx:file.create_date\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)\n    cin.file.create_time);\n  (void) CopyMagickString(property,cin.file.create_time,\n    sizeof(cin.file.create_time));\n  (void) SetImageProperty(image,\"dpx:file.create_time\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)\n    cin.file.reserve);\n  /*\n    Image information.\n  */\n  cin.image.orientation=(unsigned char) ReadBlobByte(image);\n  offset++;\n  if (cin.image.orientation != (unsigned char) (~0))\n    (void) FormatImageProperty(image,\"dpx:image.orientation\",\"%d\",\n      cin.image.orientation);\n  switch (cin.image.orientation)\n  {\n    default:\n    case 0: image->orientation=TopLeftOrientation; break;\n    case 1: image->orientation=TopRightOrientation; break;\n    case 2: image->orientation=BottomLeftOrientation; break;\n    case 3: image->orientation=BottomRightOrientation; break;\n    case 4: image->orientation=LeftTopOrientation; break;\n    case 5: image->orientation=RightTopOrientation; break;\n    case 6: image->orientation=LeftBottomOrientation; break;\n    case 7: image->orientation=RightBottomOrientation; break;\n  }\n  cin.image.number_channels=(unsigned char) ReadBlobByte(image);\n  offset++;\n  offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)\n    cin.image.reserve1);\n  for (i=0; i < 8; i++)\n  {\n    cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].pixels_per_line=ReadBlobLong(image);\n    offset+=4;\n    cin.image.channel[i].lines_per_image=ReadBlobLong(image);\n    offset+=4;\n    cin.image.channel[i].min_data=ReadBlobFloat(image);\n    offset+=4;\n    cin.image.channel[i].min_quantity=ReadBlobFloat(image);\n    offset+=4;\n    cin.image.channel[i].max_data=ReadBlobFloat(image);\n    offset+=4;\n    cin.image.channel[i].max_quantity=ReadBlobFloat(image);\n    offset+=4;\n  }\n  cin.image.white_point[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)\n    image->chromaticity.white_point.x=cin.image.white_point[0];\n  cin.image.white_point[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)\n    image->chromaticity.white_point.y=cin.image.white_point[1];\n  cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)\n    image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];\n  cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)\n    image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];\n  cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)\n    image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];\n  cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)\n    image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];\n  cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)\n    image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];\n  cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)\n    image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];\n  offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)\n    cin.image.label);\n  (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));\n  (void) SetImageProperty(image,\"dpx:image.label\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)\n    cin.image.reserve);\n  /*\n    Image data format information.\n  */\n  cin.data_format.interleave=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.packing=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.sign=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.sense=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.line_pad=ReadBlobLong(image);\n  offset+=4;\n  cin.data_format.channel_pad=ReadBlobLong(image);\n  offset+=4;\n  offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)\n    cin.data_format.reserve);\n  /*\n    Image origination information.\n  */\n  cin.origination.x_offset=ReadBlobSignedLong(image);\n  offset+=4;\n  if ((size_t) cin.origination.x_offset != ~0UL)\n    (void) FormatImageProperty(image,\"dpx:origination.x_offset\",\"%.20g\",\n      (double) cin.origination.x_offset);\n  cin.origination.y_offset=(ssize_t) ReadBlobLong(image);\n  offset+=4;\n  if ((size_t) cin.origination.y_offset != ~0UL)\n    (void) FormatImageProperty(image,\"dpx:origination.y_offset\",\"%.20g\",\n      (double) cin.origination.y_offset);\n  offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)\n    cin.origination.filename);\n  (void) CopyMagickString(property,cin.origination.filename,\n    sizeof(cin.origination.filename));\n  (void) SetImageProperty(image,\"dpx:origination.filename\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)\n    cin.origination.create_date);\n  (void) CopyMagickString(property,cin.origination.create_date,\n    sizeof(cin.origination.create_date));\n  (void) SetImageProperty(image,\"dpx:origination.create_date\",property,\n    exception);\n  offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)\n    cin.origination.create_time);\n  (void) CopyMagickString(property,cin.origination.create_time,\n    sizeof(cin.origination.create_time));\n  (void) SetImageProperty(image,\"dpx:origination.create_time\",property,\n    exception);\n  offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)\n    cin.origination.device);\n  (void) CopyMagickString(property,cin.origination.device,\n    sizeof(cin.origination.device));\n  (void) SetImageProperty(image,\"dpx:origination.device\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)\n    cin.origination.model);\n  (void) CopyMagickString(property,cin.origination.model,\n    sizeof(cin.origination.model));\n  (void) SetImageProperty(image,\"dpx:origination.model\",property,exception);\n  (void) memset(cin.origination.serial,0, \n    sizeof(cin.origination.serial));\n  offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)\n    cin.origination.serial);\n  (void) CopyMagickString(property,cin.origination.serial,\n    sizeof(cin.origination.serial));\n  (void) SetImageProperty(image,\"dpx:origination.serial\",property,exception);\n  cin.origination.x_pitch=ReadBlobFloat(image);\n  offset+=4;\n  cin.origination.y_pitch=ReadBlobFloat(image);\n  offset+=4;\n  cin.origination.gamma=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.origination.gamma) != MagickFalse)\n    image->gamma=cin.origination.gamma;\n  offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)\n    cin.origination.reserve);\n  if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))\n    {\n      int\n        c;\n\n      /*\n        Image film information.\n      */\n      cin.film.id=ReadBlobByte(image);\n      offset++;\n      c=cin.film.id;\n      if (c != ~0)\n        (void) FormatImageProperty(image,\"dpx:film.id\",\"%d\",cin.film.id);\n      cin.film.type=ReadBlobByte(image);\n      offset++;\n      c=cin.film.type;\n      if (c != ~0)\n        (void) FormatImageProperty(image,\"dpx:film.type\",\"%d\",cin.film.type);\n      cin.film.offset=ReadBlobByte(image);\n      offset++;\n      c=cin.film.offset;\n      if (c != ~0)\n        (void) FormatImageProperty(image,\"dpx:film.offset\",\"%d\",\n          cin.film.offset);\n      cin.film.reserve1=ReadBlobByte(image);\n      offset++;\n      cin.film.prefix=ReadBlobLong(image);\n      offset+=4;\n      if (cin.film.prefix != ~0UL)\n        (void) FormatImageProperty(image,\"dpx:film.prefix\",\"%.20g\",(double)\n          cin.film.prefix);\n      cin.film.count=ReadBlobLong(image);\n      offset+=4;\n      offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)\n        cin.film.format);\n      (void) CopyMagickString(property,cin.film.format,sizeof(cin.film.format));\n      (void) SetImageProperty(image,\"dpx:film.format\",property,exception);\n      cin.film.frame_position=ReadBlobLong(image);\n      offset+=4;\n      if (cin.film.frame_position != ~0UL)\n        (void) FormatImageProperty(image,\"dpx:film.frame_position\",\"%.20g\",\n          (double) cin.film.frame_position);\n      cin.film.frame_rate=ReadBlobFloat(image);\n      offset+=4;\n      if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)\n        (void) FormatImageProperty(image,\"dpx:film.frame_rate\",\"%g\",\n          cin.film.frame_rate);\n      offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)\n        cin.film.frame_id);\n      (void) CopyMagickString(property,cin.film.frame_id,\n        sizeof(cin.film.frame_id));\n      (void) SetImageProperty(image,\"dpx:film.frame_id\",property,exception);\n      offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)\n        cin.film.slate_info);\n      (void) CopyMagickString(property,cin.film.slate_info,\n        sizeof(cin.film.slate_info));\n      (void) SetImageProperty(image,\"dpx:film.slate_info\",property,exception);\n      offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)\n        cin.film.reserve);\n    }\n  if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))\n    {\n      StringInfo\n        *profile;\n\n      /*\n        User defined data.\n      */\n      if (cin.file.user_length > GetBlobSize(image))\n        ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n      profile=BlobToStringInfo((const unsigned char *) NULL,\n        cin.file.user_length);\n      if (profile == (StringInfo *) NULL)\n        ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n      offset+=ReadBlob(image,GetStringInfoLength(profile),\n        GetStringInfoDatum(profile));\n      (void) SetImageProfile(image,\"dpx:user.data\",profile,exception);\n      profile=DestroyStringInfo(profile);\n    }\n  image->depth=cin.image.channel[0].bits_per_pixel;\n  image->columns=cin.image.channel[0].pixels_per_line;\n  image->rows=cin.image.channel[0].lines_per_image;\n  if (image_info->ping != MagickFalse)\n    {\n      (void) CloseBlob(image);\n      return(image);\n    }\n  if (((MagickSizeType) image->columns*image->rows/8) > GetBlobSize(image))\n    ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n  for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)\n  {\n    int\n      c;\n\n    c=ReadBlobByte(image);\n    if (c == EOF)\n      break;\n  }\n  if (offset < (MagickOffsetType) cin.file.image_offset)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  status=SetImageExtent(image,image->columns,image->rows,exception);\n  if (status == MagickFalse)\n    return(DestroyImageList(image));\n  (void) SetImageBackgroundColor(image,exception);\n  /*\n    Convert CIN raster image to pixel packets.\n  */\n  quantum_info=AcquireQuantumInfo(image_info,image);\n  if (quantum_info == (QuantumInfo *) NULL)\n    ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n  SetQuantumQuantum(quantum_info,32);\n  SetQuantumPack(quantum_info,MagickFalse);\n  quantum_type=RGBQuantum;\n  length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);\n  if (cin.image.number_channels == 1)\n    {\n      quantum_type=GrayQuantum;\n      length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);\n    }\n  status=SetQuantumPad(image,quantum_info,0);\n  pixels=GetQuantumPixels(quantum_info);\n  for (y=0; y < (ssize_t) image->rows; y++)\n  {\n    const void\n      *stream;\n\n    q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n    if (q == (Quantum *) NULL)\n      break;\n    stream=ReadBlobStream(image,length,pixels,&count);\n    if ((size_t) count != length)\n      break;\n    (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n      quantum_type,(unsigned char *) stream,exception);\n    if (SyncAuthenticPixels(image,exception) == MagickFalse)\n      break;\n    if (image->previous == (Image *) NULL)\n      {\n        status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n          image->rows);\n        if (status == MagickFalse)\n          break;\n      }\n  }\n  SetQuantumImageType(image,quantum_type);\n  quantum_info=DestroyQuantumInfo(quantum_info);\n  if (EOFBlob(image) != MagickFalse)\n    ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n      image->filename);\n  SetImageColorspace(image,LogColorspace,exception);\n  (void) CloseBlob(image);\n  return(GetFirstImageInList(image));\n}", "func_hash": 84114525283902179205757998475769488689, "file_name": "cin.c", "file_hash": 147300579133514318841291345997162565785, "cwe": ["CWE-787"], "cve": "CVE-2022-28463", "cve_desc": "ImageMagick 7.1.0-27 is vulnerable to Buffer Overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-28463"}
{"idx": 431633, "project": "ImageMagick", "commit_id": "ca3654ebf7a439dc736f56f083c9aa98e4464b7f", "project_url": "https://github.com/ImageMagick/ImageMagick", "commit_url": "https://github.com/ImageMagick/ImageMagick/commit/ca3654ebf7a439dc736f56f083c9aa98e4464b7f", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/4988", "target": 0, "func": "static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define MonoColorType  1\n#define RGBColorType  3\n\n  char\n    property[MagickPathExtent];\n\n  CINInfo\n    cin;\n\n  Image\n    *image;\n\n  MagickBooleanType\n    status;\n\n  MagickOffsetType\n    offset;\n\n  QuantumInfo\n    *quantum_info;\n\n  QuantumType\n    quantum_type;\n\n  ssize_t\n    i;\n\n  Quantum\n    *q;\n\n  size_t\n    length;\n\n  ssize_t\n    count,\n    y;\n\n  unsigned char\n    magick[4],\n    *pixels;\n\n\n  /*\n    Open image file.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  image=AcquireImage(image_info,exception);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n    File information.\n  */\n  offset=0;\n  count=ReadBlob(image,4,magick);\n  offset+=count;\n  if ((count != 4) ||\n      ((LocaleNCompare((char *) magick,\"\\200\\052\\137\\327\",4) != 0)))\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  memset(&cin,0,sizeof(cin));\n  image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&\n    (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;\n  cin.file.image_offset=ReadBlobLong(image);\n  if (cin.file.image_offset < 712)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  offset+=4;\n  cin.file.generic_length=ReadBlobLong(image);\n  offset+=4;\n  cin.file.industry_length=ReadBlobLong(image);\n  offset+=4;\n  cin.file.user_length=ReadBlobLong(image);\n  offset+=4;\n  cin.file.file_size=ReadBlobLong(image);\n  offset+=4;\n  offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)\n    cin.file.version);\n  (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));\n  (void) SetImageProperty(image,\"dpx:file.version\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)\n    cin.file.filename);\n  (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));\n  (void) SetImageProperty(image,\"dpx:file.filename\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)\n    cin.file.create_date);\n  (void) CopyMagickString(property,cin.file.create_date,\n    sizeof(cin.file.create_date));\n  (void) SetImageProperty(image,\"dpx:file.create_date\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)\n    cin.file.create_time);\n  (void) CopyMagickString(property,cin.file.create_time,\n    sizeof(cin.file.create_time));\n  (void) SetImageProperty(image,\"dpx:file.create_time\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)\n    cin.file.reserve);\n  /*\n    Image information.\n  */\n  cin.image.orientation=(unsigned char) ReadBlobByte(image);\n  offset++;\n  if (cin.image.orientation != (unsigned char) (~0))\n    (void) FormatImageProperty(image,\"dpx:image.orientation\",\"%d\",\n      cin.image.orientation);\n  switch (cin.image.orientation)\n  {\n    default:\n    case 0: image->orientation=TopLeftOrientation; break;\n    case 1: image->orientation=TopRightOrientation; break;\n    case 2: image->orientation=BottomLeftOrientation; break;\n    case 3: image->orientation=BottomRightOrientation; break;\n    case 4: image->orientation=LeftTopOrientation; break;\n    case 5: image->orientation=RightTopOrientation; break;\n    case 6: image->orientation=LeftBottomOrientation; break;\n    case 7: image->orientation=RightBottomOrientation; break;\n  }\n  cin.image.number_channels=(unsigned char) ReadBlobByte(image);\n  offset++;\n  offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)\n    cin.image.reserve1);\n  for (i=0; i < 8; i++)\n  {\n    cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);\n    offset++;\n    cin.image.channel[i].pixels_per_line=ReadBlobLong(image);\n    offset+=4;\n    cin.image.channel[i].lines_per_image=ReadBlobLong(image);\n    offset+=4;\n    cin.image.channel[i].min_data=ReadBlobFloat(image);\n    offset+=4;\n    cin.image.channel[i].min_quantity=ReadBlobFloat(image);\n    offset+=4;\n    cin.image.channel[i].max_data=ReadBlobFloat(image);\n    offset+=4;\n    cin.image.channel[i].max_quantity=ReadBlobFloat(image);\n    offset+=4;\n  }\n  cin.image.white_point[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)\n    image->chromaticity.white_point.x=cin.image.white_point[0];\n  cin.image.white_point[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)\n    image->chromaticity.white_point.y=cin.image.white_point[1];\n  cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)\n    image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];\n  cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)\n    image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];\n  cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)\n    image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];\n  cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)\n    image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];\n  cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)\n    image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];\n  cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)\n    image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];\n  offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)\n    cin.image.label);\n  (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));\n  (void) SetImageProperty(image,\"dpx:image.label\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)\n    cin.image.reserve);\n  /*\n    Image data format information.\n  */\n  cin.data_format.interleave=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.packing=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.sign=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.sense=(unsigned char) ReadBlobByte(image);\n  offset++;\n  cin.data_format.line_pad=ReadBlobLong(image);\n  offset+=4;\n  cin.data_format.channel_pad=ReadBlobLong(image);\n  offset+=4;\n  offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)\n    cin.data_format.reserve);\n  /*\n    Image origination information.\n  */\n  cin.origination.x_offset=ReadBlobSignedLong(image);\n  offset+=4;\n  if ((size_t) cin.origination.x_offset != ~0UL)\n    (void) FormatImageProperty(image,\"dpx:origination.x_offset\",\"%.20g\",\n      (double) cin.origination.x_offset);\n  cin.origination.y_offset=(ssize_t) ReadBlobLong(image);\n  offset+=4;\n  if ((size_t) cin.origination.y_offset != ~0UL)\n    (void) FormatImageProperty(image,\"dpx:origination.y_offset\",\"%.20g\",\n      (double) cin.origination.y_offset);\n  offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)\n    cin.origination.filename);\n  (void) CopyMagickString(property,cin.origination.filename,\n    sizeof(cin.origination.filename));\n  (void) SetImageProperty(image,\"dpx:origination.filename\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)\n    cin.origination.create_date);\n  (void) CopyMagickString(property,cin.origination.create_date,\n    sizeof(cin.origination.create_date));\n  (void) SetImageProperty(image,\"dpx:origination.create_date\",property,\n    exception);\n  offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)\n    cin.origination.create_time);\n  (void) CopyMagickString(property,cin.origination.create_time,\n    sizeof(cin.origination.create_time));\n  (void) SetImageProperty(image,\"dpx:origination.create_time\",property,\n    exception);\n  offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)\n    cin.origination.device);\n  (void) CopyMagickString(property,cin.origination.device,\n    sizeof(cin.origination.device));\n  (void) SetImageProperty(image,\"dpx:origination.device\",property,exception);\n  offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)\n    cin.origination.model);\n  (void) CopyMagickString(property,cin.origination.model,\n    sizeof(cin.origination.model));\n  (void) SetImageProperty(image,\"dpx:origination.model\",property,exception);\n  (void) memset(cin.origination.serial,0, \n    sizeof(cin.origination.serial));\n  offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)\n    cin.origination.serial);\n  (void) CopyMagickString(property,cin.origination.serial,\n    sizeof(cin.origination.serial));\n  (void) SetImageProperty(image,\"dpx:origination.serial\",property,exception);\n  cin.origination.x_pitch=ReadBlobFloat(image);\n  offset+=4;\n  cin.origination.y_pitch=ReadBlobFloat(image);\n  offset+=4;\n  cin.origination.gamma=ReadBlobFloat(image);\n  offset+=4;\n  if (IsFloatDefined(cin.origination.gamma) != MagickFalse)\n    image->gamma=cin.origination.gamma;\n  offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)\n    cin.origination.reserve);\n  if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))\n    {\n      int\n        c;\n\n      /*\n        Image film information.\n      */\n      cin.film.id=ReadBlobByte(image);\n      offset++;\n      c=cin.film.id;\n      if (c != ~0)\n        (void) FormatImageProperty(image,\"dpx:film.id\",\"%d\",cin.film.id);\n      cin.film.type=ReadBlobByte(image);\n      offset++;\n      c=cin.film.type;\n      if (c != ~0)\n        (void) FormatImageProperty(image,\"dpx:film.type\",\"%d\",cin.film.type);\n      cin.film.offset=ReadBlobByte(image);\n      offset++;\n      c=cin.film.offset;\n      if (c != ~0)\n        (void) FormatImageProperty(image,\"dpx:film.offset\",\"%d\",\n          cin.film.offset);\n      cin.film.reserve1=ReadBlobByte(image);\n      offset++;\n      cin.film.prefix=ReadBlobLong(image);\n      offset+=4;\n      if (cin.film.prefix != ~0UL)\n        (void) FormatImageProperty(image,\"dpx:film.prefix\",\"%.20g\",(double)\n          cin.film.prefix);\n      cin.film.count=ReadBlobLong(image);\n      offset+=4;\n      offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)\n        cin.film.format);\n      (void) CopyMagickString(property,cin.film.format,sizeof(cin.film.format));\n      (void) SetImageProperty(image,\"dpx:film.format\",property,exception);\n      cin.film.frame_position=ReadBlobLong(image);\n      offset+=4;\n      if (cin.film.frame_position != ~0UL)\n        (void) FormatImageProperty(image,\"dpx:film.frame_position\",\"%.20g\",\n          (double) cin.film.frame_position);\n      cin.film.frame_rate=ReadBlobFloat(image);\n      offset+=4;\n      if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)\n        (void) FormatImageProperty(image,\"dpx:film.frame_rate\",\"%g\",\n          cin.film.frame_rate);\n      offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)\n        cin.film.frame_id);\n      (void) CopyMagickString(property,cin.film.frame_id,\n        sizeof(cin.film.frame_id));\n      (void) SetImageProperty(image,\"dpx:film.frame_id\",property,exception);\n      offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)\n        cin.film.slate_info);\n      (void) CopyMagickString(property,cin.film.slate_info,\n        sizeof(cin.film.slate_info));\n      (void) SetImageProperty(image,\"dpx:film.slate_info\",property,exception);\n      offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)\n        cin.film.reserve);\n    }\n  if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))\n    {\n      StringInfo\n        *profile;\n\n      /*\n        User defined data.\n      */\n      if (cin.file.user_length > GetBlobSize(image))\n        ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n      profile=BlobToStringInfo((const unsigned char *) NULL,\n        cin.file.user_length);\n      if (profile == (StringInfo *) NULL)\n        ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n      offset+=ReadBlob(image,GetStringInfoLength(profile),\n        GetStringInfoDatum(profile));\n      (void) SetImageProfile(image,\"dpx:user.data\",profile,exception);\n      profile=DestroyStringInfo(profile);\n    }\n  image->depth=cin.image.channel[0].bits_per_pixel;\n  image->columns=cin.image.channel[0].pixels_per_line;\n  image->rows=cin.image.channel[0].lines_per_image;\n  if (image_info->ping != MagickFalse)\n    {\n      (void) CloseBlob(image);\n      return(image);\n    }\n  if (((MagickSizeType) image->columns*image->rows/8) > GetBlobSize(image))\n    ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n  for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)\n  {\n    int\n      c;\n\n    c=ReadBlobByte(image);\n    if (c == EOF)\n      break;\n  }\n  if (offset < (MagickOffsetType) cin.file.image_offset)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  status=SetImageExtent(image,image->columns,image->rows,exception);\n  if (status == MagickFalse)\n    return(DestroyImageList(image));\n  (void) SetImageBackgroundColor(image,exception);\n  /*\n    Convert CIN raster image to pixel packets.\n  */\n  quantum_info=AcquireQuantumInfo(image_info,image);\n  if (quantum_info == (QuantumInfo *) NULL)\n    ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n  SetQuantumQuantum(quantum_info,32);\n  SetQuantumPack(quantum_info,MagickFalse);\n  quantum_type=RGBQuantum;\n  length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);\n  if (cin.image.number_channels == 1)\n    {\n      quantum_type=GrayQuantum;\n      length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);\n    }\n  status=SetQuantumPad(image,quantum_info,0);\n  pixels=GetQuantumPixels(quantum_info);\n  for (y=0; y < (ssize_t) image->rows; y++)\n  {\n    const void\n      *stream;\n\n    q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n    if (q == (Quantum *) NULL)\n      break;\n    stream=ReadBlobStream(image,length,pixels,&count);\n    if ((size_t) count != length)\n      break;\n    (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n      quantum_type,(unsigned char *) stream,exception);\n    if (SyncAuthenticPixels(image,exception) == MagickFalse)\n      break;\n    if (image->previous == (Image *) NULL)\n      {\n        status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n          image->rows);\n        if (status == MagickFalse)\n          break;\n      }\n  }\n  SetQuantumImageType(image,quantum_type);\n  quantum_info=DestroyQuantumInfo(quantum_info);\n  if (EOFBlob(image) != MagickFalse)\n    ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n      image->filename);\n  SetImageColorspace(image,LogColorspace,exception);\n  (void) CloseBlob(image);\n  return(GetFirstImageInList(image));\n}", "func_hash": 125130615977204070333523361327116450874, "file_name": "cin.c", "file_hash": 296697563604173271604352885758570763809, "cwe": ["CWE-787"], "cve": "CVE-2022-28463", "cve_desc": "ImageMagick 7.1.0-27 is vulnerable to Buffer Overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-28463"}
{"idx": 210271, "project": "vim", "commit_id": "6669de1b235843968e88844ca6d3c8dec4b01a9e", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/6669de1b235843968e88844ca6d3c8dec4b01a9e", "commit_message": "patch 9.0.0240: crash when using \":mkspell\" with an empty .dic file\n\nProblem:    Crash when using \":mkspell\" with an empty .dic file.\nSolution:   Check for an empty word tree.", "target": 1, "func": "sug_filltree(spellinfo_T *spin, slang_T *slang)\n{\n    char_u\t*byts;\n    idx_T\t*idxs;\n    int\t\tdepth;\n    idx_T\tarridx[MAXWLEN];\n    int\t\tcuri[MAXWLEN];\n    char_u\ttword[MAXWLEN];\n    char_u\ttsalword[MAXWLEN];\n    int\t\tc;\n    idx_T\tn;\n    unsigned\twords_done = 0;\n    int\t\twordcount[MAXWLEN];\n\n    // We use si_foldroot for the soundfolded trie.\n    spin->si_foldroot = wordtree_alloc(spin);\n    if (spin->si_foldroot == NULL)\n\treturn FAIL;\n\n    // let tree_add_word() know we're adding to the soundfolded tree\n    spin->si_sugtree = TRUE;\n\n    /*\n     * Go through the whole case-folded tree, soundfold each word and put it\n     * in the trie.\n     */\n    byts = slang->sl_fbyts;\n    idxs = slang->sl_fidxs;\n\n    arridx[0] = 0;\n    curi[0] = 1;\n    wordcount[0] = 0;\n\n    depth = 0;\n    while (depth >= 0 && !got_int)\n    {\n\tif (curi[depth] > byts[arridx[depth]])\n\t{\n\t    // Done all bytes at this node, go up one level.\n\t    idxs[arridx[depth]] = wordcount[depth];\n\t    if (depth > 0)\n\t\twordcount[depth - 1] += wordcount[depth];\n\n\t    --depth;\n\t    line_breakcheck();\n\t}\n\telse\n\t{\n\n\t    // Do one more byte at this node.\n\t    n = arridx[depth] + curi[depth];\n\t    ++curi[depth];\n\n\t    c = byts[n];\n\t    if (c == 0)\n\t    {\n\t\t// Sound-fold the word.\n\t\ttword[depth] = NUL;\n\t\tspell_soundfold(slang, tword, TRUE, tsalword);\n\n\t\t// We use the \"flags\" field for the MSB of the wordnr,\n\t\t// \"region\" for the LSB of the wordnr.\n\t\tif (tree_add_word(spin, tsalword, spin->si_foldroot,\n\t\t\t\twords_done >> 16, words_done & 0xffff,\n\t\t\t\t\t\t\t   0) == FAIL)\n\t\t    return FAIL;\n\n\t\t++words_done;\n\t\t++wordcount[depth];\n\n\t\t// Reset the block count each time to avoid compression\n\t\t// kicking in.\n\t\tspin->si_blocks_cnt = 0;\n\n\t\t// Skip over any other NUL bytes (same word with different\n\t\t// flags).  But don't go over the end.\n\t\twhile (n + 1 < slang->sl_fbyts_len && byts[n + 1] == 0)\n\t\t{\n\t\t    ++n;\n\t\t    ++curi[depth];\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\t// Normal char, go one level deeper.\n\t\ttword[depth++] = c;\n\t\tarridx[depth] = idxs[n];\n\t\tcuri[depth] = 1;\n\t\twordcount[depth] = 0;\n\t    }\n\t}\n    }\n\n    smsg(_(\"Total number of words: %d\"), words_done);\n\n    return OK;\n}", "func_hash": 207388436213910008407743050781298909937, "file_name": "spellfile.c", "file_hash": 273224760850620955394187294241739462394, "cwe": ["CWE-787"], "cve": "CVE-2022-2923", "cve_desc": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0240.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2923"}
{"idx": 432093, "project": "vim", "commit_id": "6669de1b235843968e88844ca6d3c8dec4b01a9e", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/6669de1b235843968e88844ca6d3c8dec4b01a9e", "commit_message": "patch 9.0.0240: crash when using \":mkspell\" with an empty .dic file\n\nProblem:    Crash when using \":mkspell\" with an empty .dic file.\nSolution:   Check for an empty word tree.", "target": 0, "func": "sug_filltree(spellinfo_T *spin, slang_T *slang)\n{\n    char_u\t*byts;\n    idx_T\t*idxs;\n    int\t\tdepth;\n    idx_T\tarridx[MAXWLEN];\n    int\t\tcuri[MAXWLEN];\n    char_u\ttword[MAXWLEN];\n    char_u\ttsalword[MAXWLEN];\n    int\t\tc;\n    idx_T\tn;\n    unsigned\twords_done = 0;\n    int\t\twordcount[MAXWLEN];\n\n    // We use si_foldroot for the soundfolded trie.\n    spin->si_foldroot = wordtree_alloc(spin);\n    if (spin->si_foldroot == NULL)\n\treturn FAIL;\n\n    // let tree_add_word() know we're adding to the soundfolded tree\n    spin->si_sugtree = TRUE;\n\n    /*\n     * Go through the whole case-folded tree, soundfold each word and put it\n     * in the trie.  Bail out if the tree is empty.\n     */\n    byts = slang->sl_fbyts;\n    idxs = slang->sl_fidxs;\n    if (byts == NULL || idxs == NULL)\n\treturn FAIL;\n\n    arridx[0] = 0;\n    curi[0] = 1;\n    wordcount[0] = 0;\n\n    depth = 0;\n    while (depth >= 0 && !got_int)\n    {\n\tif (curi[depth] > byts[arridx[depth]])\n\t{\n\t    // Done all bytes at this node, go up one level.\n\t    idxs[arridx[depth]] = wordcount[depth];\n\t    if (depth > 0)\n\t\twordcount[depth - 1] += wordcount[depth];\n\n\t    --depth;\n\t    line_breakcheck();\n\t}\n\telse\n\t{\n\n\t    // Do one more byte at this node.\n\t    n = arridx[depth] + curi[depth];\n\t    ++curi[depth];\n\n\t    c = byts[n];\n\t    if (c == 0)\n\t    {\n\t\t// Sound-fold the word.\n\t\ttword[depth] = NUL;\n\t\tspell_soundfold(slang, tword, TRUE, tsalword);\n\n\t\t// We use the \"flags\" field for the MSB of the wordnr,\n\t\t// \"region\" for the LSB of the wordnr.\n\t\tif (tree_add_word(spin, tsalword, spin->si_foldroot,\n\t\t\t\twords_done >> 16, words_done & 0xffff,\n\t\t\t\t\t\t\t   0) == FAIL)\n\t\t    return FAIL;\n\n\t\t++words_done;\n\t\t++wordcount[depth];\n\n\t\t// Reset the block count each time to avoid compression\n\t\t// kicking in.\n\t\tspin->si_blocks_cnt = 0;\n\n\t\t// Skip over any other NUL bytes (same word with different\n\t\t// flags).  But don't go over the end.\n\t\twhile (n + 1 < slang->sl_fbyts_len && byts[n + 1] == 0)\n\t\t{\n\t\t    ++n;\n\t\t    ++curi[depth];\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\t// Normal char, go one level deeper.\n\t\ttword[depth++] = c;\n\t\tarridx[depth] = idxs[n];\n\t\tcuri[depth] = 1;\n\t\twordcount[depth] = 0;\n\t    }\n\t}\n    }\n\n    smsg(_(\"Total number of words: %d\"), words_done);\n\n    return OK;\n}", "func_hash": 208510972034693515698183125739179180871, "file_name": "spellfile.c", "file_hash": 159233725116993104212150761027929059833, "cwe": ["CWE-787"], "cve": "CVE-2022-2923", "cve_desc": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0240.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2923"}
{"idx": 210273, "project": "mongo", "commit_id": "f3604b901d688c194de5e430c7fbab060c9dc8e0", "project_url": "https://github.com/mongodb/mongo", "commit_url": "https://github.com/mongodb/mongo/commit/f3604b901d688c194de5e430c7fbab060c9dc8e0", "commit_message": "SERVER-59071 Treat '$sample' as unsharded when connecting directly to shards", "target": 1, "func": "createRandomCursorExecutor(const CollectionPtr& coll,\n                           const boost::intrusive_ptr& expCtx,\n                           long long sampleSize,\n                           long long numRecords,\n                           boost::optional bucketUnpacker) {\n    OperationContext* opCtx = expCtx->opCtx;\n\n    // Verify that we are already under a collection lock. We avoid taking locks ourselves in this\n    // function because double-locking forces any PlanExecutor we create to adopt a NO_YIELD policy.\n    invariant(opCtx->lockState()->isCollectionLockedForMode(coll->ns(), MODE_IS));\n\n    static const double kMaxSampleRatioForRandCursor = 0.05;\n    if (!expCtx->ns.isTimeseriesBucketsCollection()) {\n        if (sampleSize > numRecords * kMaxSampleRatioForRandCursor || numRecords <= 100) {\n            return std::pair{nullptr, false};\n        }\n    } else {\n        // Suppose that a time-series bucket collection is observed to contain 200 buckets, and the\n        // 'gTimeseriesBucketMaxCount' parameter is set to 1000. If all buckets are full, then the\n        // maximum possible measurment count would be 200 * 1000 = 200,000. While the\n        // 'SampleFromTimeseriesBucket' plan is more efficient when the sample size is small\n        // relative to the total number of measurements in the time-series collection, for larger\n        // sample sizes the top-k sort based sample is faster. Experiments have approximated that\n        // the tipping point is roughly when the requested sample size is greater than 1% of the\n        // maximum possible number of measurements in the collection (i.e. numBuckets *\n        // maxMeasurementsPerBucket).\n        static const double kCoefficient = 0.01;\n        if (sampleSize > kCoefficient * numRecords * gTimeseriesBucketMaxCount) {\n            return std::pair{nullptr, false};\n        }\n    }\n\n    // Attempt to get a random cursor from the RecordStore.\n    auto rsRandCursor = coll->getRecordStore()->getRandomCursor(opCtx);\n    if (!rsRandCursor) {\n        // The storage engine has no random cursor support.\n        return std::pair{nullptr, false};\n    }\n\n    // Build a MultiIteratorStage and pass it the random-sampling RecordCursor.\n    auto ws = std::make_unique();\n    std::unique_ptr root =\n        std::make_unique(expCtx.get(), ws.get(), coll);\n    static_cast(root.get())->addIterator(std::move(rsRandCursor));\n\n    // If the incoming operation is sharded, use the CSS to infer the filtering metadata for the\n    // collection, otherwise treat it as unsharded\n    auto collectionFilter =\n        CollectionShardingState::get(opCtx, coll->ns())\n            ->getOwnershipFilter(\n                opCtx, CollectionShardingState::OrphanCleanupPolicy::kDisallowOrphanCleanup);\n\n    TrialStage* trialStage = nullptr;\n\n    // Because 'numRecords' includes orphan documents, our initial decision to optimize the $sample\n    // cursor may have been mistaken. For sharded collections, build a TRIAL plan that will switch\n    // to a collection scan if the ratio of orphaned to owned documents encountered over the first\n    // 100 works() is such that we would have chosen not to optimize.\n    static const size_t kMaxPresampleSize = 100;\n    if (collectionFilter.isSharded() && !expCtx->ns.isTimeseriesBucketsCollection()) {\n        // The ratio of owned to orphaned documents must be at least equal to the ratio between the\n        // requested sampleSize and the maximum permitted sampleSize for the original constraints to\n        // be satisfied. For instance, if there are 200 documents and the sampleSize is 5, then at\n        // least (5 / (200*0.05)) = (5/10) = 50% of those documents must be owned. If less than 5%\n        // of the documents in the collection are owned, we default to the backup plan.\n        const auto minAdvancedToWorkRatio = std::max(\n            sampleSize / (numRecords * kMaxSampleRatioForRandCursor), kMaxSampleRatioForRandCursor);\n        // The trial plan is SHARDING_FILTER-MULTI_ITERATOR.\n        auto randomCursorPlan = std::make_unique(\n            expCtx.get(), collectionFilter, ws.get(), std::move(root));\n        // The backup plan is SHARDING_FILTER-COLLSCAN.\n        std::unique_ptr collScanPlan = std::make_unique(\n            expCtx.get(), coll, CollectionScanParams{}, ws.get(), nullptr);\n        collScanPlan = std::make_unique(\n            expCtx.get(), collectionFilter, ws.get(), std::move(collScanPlan));\n        // Place a TRIAL stage at the root of the plan tree, and pass it the trial and backup plans.\n        root = std::make_unique(expCtx.get(),\n                                            ws.get(),\n                                            std::move(randomCursorPlan),\n                                            std::move(collScanPlan),\n                                            kMaxPresampleSize,\n                                            minAdvancedToWorkRatio);\n        trialStage = static_cast(root.get());\n    } else if (expCtx->ns.isTimeseriesBucketsCollection()) {\n        // We can't take ARHASH optimization path for a direct $sample on the system.buckets\n        // collection because data is in compressed form. If we did have a direct $sample on the\n        // system.buckets collection, then the 'bucketUnpacker' would not be set up properly. We\n        // also should bail out early if a $sample is made against a time series collection that is\n        // empty. If we don't the 'minAdvancedToWorkRatio' can be nan/-nan depending on the\n        // architecture.\n        if (!(bucketUnpacker && numRecords)) {\n            return std::pair{nullptr, false};\n        }\n\n        // Use a 'TrialStage' to run a trial between 'SampleFromTimeseriesBucket' and\n        // 'UnpackTimeseriesBucket' with $sample left in the pipeline in-place. If the buckets are\n        // not sufficiently full, or the 'SampleFromTimeseriesBucket' plan draws too many\n        // duplicates, then we will fall back to the 'TrialStage' backup plan. This backup plan uses\n        // the top-k sort sampling approach.\n        //\n        // Suppose the 'gTimeseriesBucketMaxCount' is 1000, but each bucket only contains 500\n        // documents on average. The observed trial advanced/work ratio approximates the average\n        // bucket fullness, noted here as \"abf\". In this example, abf = 500 / 1000 = 0.5.\n        // Experiments have shown that the optimized 'SampleFromTimeseriesBucket' algorithm performs\n        // better than backup plan when\n        //\n        //     sampleSize < 0.02 * abf * numRecords * gTimeseriesBucketMaxCount\n        //\n        //  This inequality can be rewritten as\n        //\n        //     abf > sampleSize / (0.02 * numRecords * gTimeseriesBucketMaxCount)\n        //\n        // Therefore, if the advanced/work ratio exceeds this threshold, we will use the\n        // 'SampleFromTimeseriesBucket' plan. Note that as the sample size requested by the user\n        // becomes larger with respect to the number of buckets, we require a higher advanced/work\n        // ratio in order to justify using 'SampleFromTimeseriesBucket'.\n        //\n        // Additionally, we require the 'TrialStage' to approximate the abf as at least 0.25. When\n        // buckets are mostly empty, the 'SampleFromTimeseriesBucket' will be inefficient due to a\n        // lot of sampling \"misses\".\n        static const auto kCoefficient = 0.02;\n        static const auto kMinBucketFullness = 0.25;\n        const auto minAdvancedToWorkRatio = std::max(\n            std::min(sampleSize / (kCoefficient * numRecords * gTimeseriesBucketMaxCount), 1.0),\n            kMinBucketFullness);\n\n        auto arhashPlan = std::make_unique(\n            expCtx.get(),\n            ws.get(),\n            std::move(root),\n            *bucketUnpacker,\n            // By using a quantity slightly higher than 'kMaxPresampleSize', we ensure that the\n            // 'SampleFromTimeseriesBucket' stage won't fail due to too many consecutive sampling\n            // attempts during the 'TrialStage's trial period.\n            kMaxPresampleSize + 5,\n            sampleSize,\n            gTimeseriesBucketMaxCount);\n\n        std::unique_ptr collScanPlan = std::make_unique(\n            expCtx.get(), coll, CollectionScanParams{}, ws.get(), nullptr);\n\n        auto topkSortPlan = std::make_unique(\n            expCtx.get(), ws.get(), std::move(collScanPlan), *bucketUnpacker);\n\n        root = std::make_unique(expCtx.get(),\n                                            ws.get(),\n                                            std::move(arhashPlan),\n                                            std::move(topkSortPlan),\n                                            kMaxPresampleSize,\n                                            minAdvancedToWorkRatio);\n        trialStage = static_cast(root.get());\n    }\n\n    auto execStatus = plan_executor_factory::make(expCtx,\n                                                  std::move(ws),\n                                                  std::move(root),\n                                                  &coll,\n                                                  opCtx->inMultiDocumentTransaction()\n                                                      ? PlanYieldPolicy::YieldPolicy::INTERRUPT_ONLY\n                                                      : PlanYieldPolicy::YieldPolicy::YIELD_AUTO,\n                                                  QueryPlannerParams::RETURN_OWNED_DATA);\n    if (!execStatus.isOK()) {\n        return execStatus.getStatus();\n    }\n\n    // For sharded collections, the root of the plan tree is a TrialStage that may have chosen\n    // either a random-sampling cursor trial plan or a COLLSCAN backup plan. We can only optimize\n    // the $sample aggregation stage if the trial plan was chosen.\n    return std::pair{std::move(execStatus.getValue()),\n                     !trialStage || !trialStage->pickedBackupPlan()};\n}", "func_hash": 239583334467362355681176105432769486304, "file_name": "pipeline_d.cpp", "file_hash": 58061396446339864036845237439152201402, "cwe": ["CWE-617"], "cve": "CVE-2021-32037", "cve_desc": "An authorized user may trigger an invariant which may result in denial of service or server exit if a relevant aggregation request is sent to a shard. Usually, the requests are sent via mongos and special privileges are required in order to know the address of the shards and to log in to the shards of an auth enabled environment.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32037"}
{"idx": 432152, "project": "mongo", "commit_id": "f3604b901d688c194de5e430c7fbab060c9dc8e0", "project_url": "https://github.com/mongodb/mongo", "commit_url": "https://github.com/mongodb/mongo/commit/f3604b901d688c194de5e430c7fbab060c9dc8e0", "commit_message": "SERVER-59071 Treat '$sample' as unsharded when connecting directly to shards", "target": 0, "func": "createRandomCursorExecutor(const CollectionPtr& coll,\n                           const boost::intrusive_ptr& expCtx,\n                           long long sampleSize,\n                           long long numRecords,\n                           boost::optional bucketUnpacker) {\n    OperationContext* opCtx = expCtx->opCtx;\n\n    // Verify that we are already under a collection lock. We avoid taking locks ourselves in this\n    // function because double-locking forces any PlanExecutor we create to adopt a NO_YIELD policy.\n    invariant(opCtx->lockState()->isCollectionLockedForMode(coll->ns(), MODE_IS));\n\n    static const double kMaxSampleRatioForRandCursor = 0.05;\n    if (!expCtx->ns.isTimeseriesBucketsCollection()) {\n        if (sampleSize > numRecords * kMaxSampleRatioForRandCursor || numRecords <= 100) {\n            return std::pair{nullptr, false};\n        }\n    } else {\n        // Suppose that a time-series bucket collection is observed to contain 200 buckets, and the\n        // 'gTimeseriesBucketMaxCount' parameter is set to 1000. If all buckets are full, then the\n        // maximum possible measurment count would be 200 * 1000 = 200,000. While the\n        // 'SampleFromTimeseriesBucket' plan is more efficient when the sample size is small\n        // relative to the total number of measurements in the time-series collection, for larger\n        // sample sizes the top-k sort based sample is faster. Experiments have approximated that\n        // the tipping point is roughly when the requested sample size is greater than 1% of the\n        // maximum possible number of measurements in the collection (i.e. numBuckets *\n        // maxMeasurementsPerBucket).\n        static const double kCoefficient = 0.01;\n        if (sampleSize > kCoefficient * numRecords * gTimeseriesBucketMaxCount) {\n            return std::pair{nullptr, false};\n        }\n    }\n\n    // Attempt to get a random cursor from the RecordStore.\n    auto rsRandCursor = coll->getRecordStore()->getRandomCursor(opCtx);\n    if (!rsRandCursor) {\n        // The storage engine has no random cursor support.\n        return std::pair{nullptr, false};\n    }\n\n    // Build a MultiIteratorStage and pass it the random-sampling RecordCursor.\n    auto ws = std::make_unique();\n    std::unique_ptr root =\n        std::make_unique(expCtx.get(), ws.get(), coll);\n    static_cast(root.get())->addIterator(std::move(rsRandCursor));\n\n    TrialStage* trialStage = nullptr;\n\n    // Because 'numRecords' includes orphan documents, our initial decision to optimize the $sample\n    // cursor may have been mistaken. For sharded collections, build a TRIAL plan that will switch\n    // to a collection scan if the ratio of orphaned to owned documents encountered over the first\n    // 100 works() is such that we would have chosen not to optimize.\n    static const size_t kMaxPresampleSize = 100;\n    if (auto css = CollectionShardingState::get(opCtx, coll->ns());\n        css->getCollectionDescription(opCtx).isSharded() &&\n        !expCtx->ns.isTimeseriesBucketsCollection()) {\n        // The ratio of owned to orphaned documents must be at least equal to the ratio between the\n        // requested sampleSize and the maximum permitted sampleSize for the original constraints to\n        // be satisfied. For instance, if there are 200 documents and the sampleSize is 5, then at\n        // least (5 / (200*0.05)) = (5/10) = 50% of those documents must be owned. If less than 5%\n        // of the documents in the collection are owned, we default to the backup plan.\n        const auto minAdvancedToWorkRatio = std::max(\n            sampleSize / (numRecords * kMaxSampleRatioForRandCursor), kMaxSampleRatioForRandCursor);\n        // Since the incoming operation is sharded, use the CSS to infer the filtering metadata for\n        // the collection. We get the shard ownership filter after checking to see if the collection\n        // is sharded to avoid an invariant from being fired in this call.\n        auto collectionFilter = css->getOwnershipFilter(\n            opCtx, CollectionShardingState::OrphanCleanupPolicy::kDisallowOrphanCleanup);\n        // The trial plan is SHARDING_FILTER-MULTI_ITERATOR.\n        auto randomCursorPlan = std::make_unique(\n            expCtx.get(), collectionFilter, ws.get(), std::move(root));\n        // The backup plan is SHARDING_FILTER-COLLSCAN.\n        std::unique_ptr collScanPlan = std::make_unique(\n            expCtx.get(), coll, CollectionScanParams{}, ws.get(), nullptr);\n        collScanPlan = std::make_unique(\n            expCtx.get(), collectionFilter, ws.get(), std::move(collScanPlan));\n        // Place a TRIAL stage at the root of the plan tree, and pass it the trial and backup plans.\n        root = std::make_unique(expCtx.get(),\n                                            ws.get(),\n                                            std::move(randomCursorPlan),\n                                            std::move(collScanPlan),\n                                            kMaxPresampleSize,\n                                            minAdvancedToWorkRatio);\n        trialStage = static_cast(root.get());\n    } else if (expCtx->ns.isTimeseriesBucketsCollection()) {\n        // We can't take ARHASH optimization path for a direct $sample on the system.buckets\n        // collection because data is in compressed form. If we did have a direct $sample on the\n        // system.buckets collection, then the 'bucketUnpacker' would not be set up properly. We\n        // also should bail out early if a $sample is made against a time series collection that is\n        // empty. If we don't the 'minAdvancedToWorkRatio' can be nan/-nan depending on the\n        // architecture.\n        if (!(bucketUnpacker && numRecords)) {\n            return std::pair{nullptr, false};\n        }\n\n        // Use a 'TrialStage' to run a trial between 'SampleFromTimeseriesBucket' and\n        // 'UnpackTimeseriesBucket' with $sample left in the pipeline in-place. If the buckets are\n        // not sufficiently full, or the 'SampleFromTimeseriesBucket' plan draws too many\n        // duplicates, then we will fall back to the 'TrialStage' backup plan. This backup plan uses\n        // the top-k sort sampling approach.\n        //\n        // Suppose the 'gTimeseriesBucketMaxCount' is 1000, but each bucket only contains 500\n        // documents on average. The observed trial advanced/work ratio approximates the average\n        // bucket fullness, noted here as \"abf\". In this example, abf = 500 / 1000 = 0.5.\n        // Experiments have shown that the optimized 'SampleFromTimeseriesBucket' algorithm performs\n        // better than backup plan when\n        //\n        //     sampleSize < 0.02 * abf * numRecords * gTimeseriesBucketMaxCount\n        //\n        //  This inequality can be rewritten as\n        //\n        //     abf > sampleSize / (0.02 * numRecords * gTimeseriesBucketMaxCount)\n        //\n        // Therefore, if the advanced/work ratio exceeds this threshold, we will use the\n        // 'SampleFromTimeseriesBucket' plan. Note that as the sample size requested by the user\n        // becomes larger with respect to the number of buckets, we require a higher advanced/work\n        // ratio in order to justify using 'SampleFromTimeseriesBucket'.\n        //\n        // Additionally, we require the 'TrialStage' to approximate the abf as at least 0.25. When\n        // buckets are mostly empty, the 'SampleFromTimeseriesBucket' will be inefficient due to a\n        // lot of sampling \"misses\".\n        static const auto kCoefficient = 0.02;\n        static const auto kMinBucketFullness = 0.25;\n        const auto minAdvancedToWorkRatio = std::max(\n            std::min(sampleSize / (kCoefficient * numRecords * gTimeseriesBucketMaxCount), 1.0),\n            kMinBucketFullness);\n\n        auto arhashPlan = std::make_unique(\n            expCtx.get(),\n            ws.get(),\n            std::move(root),\n            *bucketUnpacker,\n            // By using a quantity slightly higher than 'kMaxPresampleSize', we ensure that the\n            // 'SampleFromTimeseriesBucket' stage won't fail due to too many consecutive sampling\n            // attempts during the 'TrialStage's trial period.\n            kMaxPresampleSize + 5,\n            sampleSize,\n            gTimeseriesBucketMaxCount);\n\n        std::unique_ptr collScanPlan = std::make_unique(\n            expCtx.get(), coll, CollectionScanParams{}, ws.get(), nullptr);\n\n        auto topkSortPlan = std::make_unique(\n            expCtx.get(), ws.get(), std::move(collScanPlan), *bucketUnpacker);\n\n        root = std::make_unique(expCtx.get(),\n                                            ws.get(),\n                                            std::move(arhashPlan),\n                                            std::move(topkSortPlan),\n                                            kMaxPresampleSize,\n                                            minAdvancedToWorkRatio);\n        trialStage = static_cast(root.get());\n    }\n\n    auto execStatus = plan_executor_factory::make(expCtx,\n                                                  std::move(ws),\n                                                  std::move(root),\n                                                  &coll,\n                                                  opCtx->inMultiDocumentTransaction()\n                                                      ? PlanYieldPolicy::YieldPolicy::INTERRUPT_ONLY\n                                                      : PlanYieldPolicy::YieldPolicy::YIELD_AUTO,\n                                                  QueryPlannerParams::RETURN_OWNED_DATA);\n    if (!execStatus.isOK()) {\n        return execStatus.getStatus();\n    }\n\n    // For sharded collections, the root of the plan tree is a TrialStage that may have chosen\n    // either a random-sampling cursor trial plan or a COLLSCAN backup plan. We can only optimize\n    // the $sample aggregation stage if the trial plan was chosen.\n    return std::pair{std::move(execStatus.getValue()),\n                     !trialStage || !trialStage->pickedBackupPlan()};\n}", "func_hash": 248936200771856096728172359306392383142, "file_name": "pipeline_d.cpp", "file_hash": 250256559163646850106921369320994189676, "cwe": ["CWE-617"], "cve": "CVE-2021-32037", "cve_desc": "An authorized user may trigger an invariant which may result in denial of service or server exit if a relevant aggregation request is sent to a shard. Usually, the requests are sent via mongos and special privileges are required in order to know the address of the shards and to log in to the shards of an auth enabled environment.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32037"}
{"idx": 210278, "project": "unicorn", "commit_id": "3d3deac5e6d38602b689c4fef5dac004f07a2e63", "project_url": "https://github.com/unicorn-engine/unicorn", "commit_url": "https://github.com/unicorn-engine/unicorn/commit/3d3deac5e6d38602b689c4fef5dac004f07a2e63", "commit_message": "Fix crash when mapping a big memory and calling uc_close", "target": 1, "func": "void qemu_ram_free(struct uc_struct *uc, RAMBlock *block)\n{\n    if (!block) {\n        return;\n    }\n\n    //if (block->host) {\n    //    ram_block_notify_remove(block->host, block->max_length);\n    //}\n\n    QLIST_REMOVE(block, next);\n    uc->ram_list.mru_block = NULL;\n    /* Write list before version */\n    //smp_wmb();\n    // call_rcu(block, reclaim_ramblock, rcu);\n    reclaim_ramblock(uc, block);\n}", "func_hash": 157575120486623399749960791680175069672, "file_name": "exec.c", "file_hash": 310161744044250278013604508128366354672, "cwe": ["CWE-476"], "cve": "CVE-2022-29694", "cve_desc": "Unicorn Engine v2.0.0-rc7 and below was discovered to contain a NULL pointer dereference via qemu_ram_free.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29694"}
{"idx": 432247, "project": "unicorn", "commit_id": "3d3deac5e6d38602b689c4fef5dac004f07a2e63", "project_url": "https://github.com/unicorn-engine/unicorn", "commit_url": "https://github.com/unicorn-engine/unicorn/commit/3d3deac5e6d38602b689c4fef5dac004f07a2e63", "commit_message": "Fix crash when mapping a big memory and calling uc_close", "target": 0, "func": "void qemu_ram_free(struct uc_struct *uc, RAMBlock *block)\n{\n    if (!block) {\n        return;\n    }\n\n    //if (block->host) {\n    //    ram_block_notify_remove(block->host, block->max_length);\n    //}\n\n    QLIST_REMOVE_RCU(block, next);\n    uc->ram_list.mru_block = NULL;\n    /* Write list before version */\n    //smp_wmb();\n    // call_rcu(block, reclaim_ramblock, rcu);\n    reclaim_ramblock(uc, block);\n}", "func_hash": 139151486807095402727767671215311097684, "file_name": "exec.c", "file_hash": 120586418967583212379316417474927455385, "cwe": ["CWE-476"], "cve": "CVE-2022-29694", "cve_desc": "Unicorn Engine v2.0.0-rc7 and below was discovered to contain a NULL pointer dereference via qemu_ram_free.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29694"}
{"idx": 210282, "project": "qemu", "commit_id": "b05b267840515730dbf6753495d5b7bd8b04ad1c", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://github.com/qemu/qemu/commit/b05b267840515730dbf6753495d5b7bd8b04ad1c", "commit_message": "i2c-ddc: fix oob read\n\nSuggested-by: Michael Hanselmann \nSigned-off-by: Gerd Hoffmann \nReviewed-by: Michael Hanselmann \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nMessage-id: 20190108102301.1957-1-kraxel@redhat.com", "target": 1, "func": "static int i2c_ddc_rx(I2CSlave *i2c)\n{\n    I2CDDCState *s = I2CDDC(i2c);\n\n    int value;\n    value = s->edid_blob[s->reg];\n    s->reg++;\n    return value;\n}", "func_hash": 231715994309117248387350691536475330701, "file_name": "i2c-ddc.c", "file_hash": 48804313309392962475337802621299781910, "cwe": ["CWE-125"], "cve": "CVE-2019-3812", "cve_desc": "QEMU, through version 2.10 and through version 3.1.0, is vulnerable to an out-of-bounds read of up to 128 bytes in the hw/i2c/i2c-ddc.c:i2c_ddc() function. A local attacker with permission to execute i2c commands could exploit this to read stack memory of the qemu process on the host.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-3812"}
{"idx": 432346, "project": "qemu", "commit_id": "b05b267840515730dbf6753495d5b7bd8b04ad1c", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://github.com/qemu/qemu/commit/b05b267840515730dbf6753495d5b7bd8b04ad1c", "commit_message": "i2c-ddc: fix oob read\n\nSuggested-by: Michael Hanselmann \nSigned-off-by: Gerd Hoffmann \nReviewed-by: Michael Hanselmann \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nMessage-id: 20190108102301.1957-1-kraxel@redhat.com", "target": 0, "func": "static int i2c_ddc_rx(I2CSlave *i2c)\n{\n    I2CDDCState *s = I2CDDC(i2c);\n\n    int value;\n    value = s->edid_blob[s->reg % sizeof(s->edid_blob)];\n    s->reg++;\n    return value;\n}", "func_hash": 197849623050732713088444316780408422340, "file_name": "i2c-ddc.c", "file_hash": 241703496436230749148573739318246335373, "cwe": ["CWE-125"], "cve": "CVE-2019-3812", "cve_desc": "QEMU, through version 2.10 and through version 3.1.0, is vulnerable to an out-of-bounds read of up to 128 bytes in the hw/i2c/i2c-ddc.c:i2c_ddc() function. A local attacker with permission to execute i2c commands could exploit this to read stack memory of the qemu process on the host.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-3812"}
{"idx": 210283, "project": "dpdk", "commit_id": "af74f7db384ed149fe42b21dbd7975f8a54ef227", "project_url": "https://github.com/DPDK/dpdk", "commit_url": "https://github.com/DPDK/dpdk/commit/af74f7db384ed149fe42b21dbd7975f8a54ef227", "commit_message": "vhost: fix FD leak with inflight messages\n\nEven if unlikely, a buggy vhost-user master might attach fds to inflight\nmessages. Add checks like for other types of vhost-user messages.\n\nFixes: d87f1a1cb7b6 (\"vhost: support inflight info sharing\")\nCc: stable@dpdk.org\n\nSigned-off-by: David Marchand \nReviewed-by: Maxime Coquelin ", "target": 1, "func": "vhost_user_set_inflight_fd(struct virtio_net **pdev,\n\t\t\t   struct vhu_msg_context *ctx,\n\t\t\t   int main_fd __rte_unused)\n{\n\tuint64_t mmap_size, mmap_offset;\n\tuint16_t num_queues, queue_size;\n\tstruct virtio_net *dev = *pdev;\n\tuint32_t pervq_inflight_size;\n\tstruct vhost_virtqueue *vq;\n\tvoid *addr;\n\tint fd, i;\n\tint numa_node = SOCKET_ID_ANY;\n\n\tfd = ctx->fds[0];\n\tif (ctx->msg.size != sizeof(ctx->msg.payload.inflight) || fd < 0) {\n\t\tVHOST_LOG_CONFIG(ERR, \"(%s) invalid set_inflight_fd message size is %d,fd is %d\\n\",\n\t\t\tdev->ifname, ctx->msg.size, fd);\n\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\t}\n\n\tmmap_size = ctx->msg.payload.inflight.mmap_size;\n\tmmap_offset = ctx->msg.payload.inflight.mmap_offset;\n\tnum_queues = ctx->msg.payload.inflight.num_queues;\n\tqueue_size = ctx->msg.payload.inflight.queue_size;\n\n\tif (vq_is_packed(dev))\n\t\tpervq_inflight_size = get_pervq_shm_size_packed(queue_size);\n\telse\n\t\tpervq_inflight_size = get_pervq_shm_size_split(queue_size);\n\n\tVHOST_LOG_CONFIG(INFO, \"(%s) set_inflight_fd mmap_size: %\"PRIu64\"\\n\",\n\t\t\tdev->ifname, mmap_size);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) set_inflight_fd mmap_offset: %\"PRIu64\"\\n\",\n\t\t\tdev->ifname, mmap_offset);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) set_inflight_fd num_queues: %u\\n\", dev->ifname, num_queues);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) set_inflight_fd queue_size: %u\\n\", dev->ifname, queue_size);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) set_inflight_fd fd: %d\\n\", dev->ifname, fd);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) set_inflight_fd pervq_inflight_size: %d\\n\",\n\t\t\tdev->ifname, pervq_inflight_size);\n\n\t/*\n\t * If VQ 0 has already been allocated, try to allocate on the same\n\t * NUMA node. It can be reallocated later in numa_realloc().\n\t */\n\tif (dev->nr_vring > 0)\n\t\tnuma_node = dev->virtqueue[0]->numa_node;\n\n\tif (!dev->inflight_info) {\n\t\tdev->inflight_info = rte_zmalloc_socket(\"inflight_info\",\n\t\t\t\tsizeof(struct inflight_mem_info), 0, numa_node);\n\t\tif (dev->inflight_info == NULL) {\n\t\t\tVHOST_LOG_CONFIG(ERR, \"(%s) failed to alloc dev inflight area\\n\",\n\t\t\t\t\tdev->ifname);\n\t\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\t\t}\n\t\tdev->inflight_info->fd = -1;\n\t}\n\n\tif (dev->inflight_info->addr) {\n\t\tmunmap(dev->inflight_info->addr, dev->inflight_info->size);\n\t\tdev->inflight_info->addr = NULL;\n\t}\n\n\taddr = mmap(0, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,\n\t\t    fd, mmap_offset);\n\tif (addr == MAP_FAILED) {\n\t\tVHOST_LOG_CONFIG(ERR, \"(%s) failed to mmap share memory.\\n\", dev->ifname);\n\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\t}\n\n\tif (dev->inflight_info->fd >= 0) {\n\t\tclose(dev->inflight_info->fd);\n\t\tdev->inflight_info->fd = -1;\n\t}\n\n\tdev->inflight_info->fd = fd;\n\tdev->inflight_info->addr = addr;\n\tdev->inflight_info->size = mmap_size;\n\n\tfor (i = 0; i < num_queues; i++) {\n\t\tvq = dev->virtqueue[i];\n\t\tif (!vq)\n\t\t\tcontinue;\n\n\t\tif (vq_is_packed(dev)) {\n\t\t\tvq->inflight_packed = addr;\n\t\t\tvq->inflight_packed->desc_num = queue_size;\n\t\t} else {\n\t\t\tvq->inflight_split = addr;\n\t\t\tvq->inflight_split->desc_num = queue_size;\n\t\t}\n\t\taddr = (void *)((char *)addr + pervq_inflight_size);\n\t}\n\n\treturn RTE_VHOST_MSG_RESULT_OK;\n}", "func_hash": 13095885723937845585670342074688916492, "file_name": "vhost_user.c", "file_hash": 63503821127437927181843920110423384686, "cwe": ["CWE-703"], "cve": "CVE-2022-0669", "cve_desc": "A flaw was found in dpdk. This flaw allows a malicious vhost-user master to attach an unexpected number of fds as ancillary data to VHOST_USER_GET_INFLIGHT_FD / VHOST_USER_SET_INFLIGHT_FD messages that are not closed by the vhost-user slave. By sending such messages continuously, the vhost-user master exhausts available fd in the vhost-user slave process, leading to a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0669"}
{"idx": 432351, "project": "dpdk", "commit_id": "af74f7db384ed149fe42b21dbd7975f8a54ef227", "project_url": "https://github.com/DPDK/dpdk", "commit_url": "https://github.com/DPDK/dpdk/commit/af74f7db384ed149fe42b21dbd7975f8a54ef227", "commit_message": "vhost: fix FD leak with inflight messages\n\nEven if unlikely, a buggy vhost-user master might attach fds to inflight\nmessages. Add checks like for other types of vhost-user messages.\n\nFixes: d87f1a1cb7b6 (\"vhost: support inflight info sharing\")\nCc: stable@dpdk.org\n\nSigned-off-by: David Marchand \nReviewed-by: Maxime Coquelin ", "target": 0, "func": "vhost_user_set_inflight_fd(struct virtio_net **pdev,\n\t\t\t   struct vhu_msg_context *ctx,\n\t\t\t   int main_fd __rte_unused)\n{\n\tuint64_t mmap_size, mmap_offset;\n\tuint16_t num_queues, queue_size;\n\tstruct virtio_net *dev = *pdev;\n\tuint32_t pervq_inflight_size;\n\tstruct vhost_virtqueue *vq;\n\tvoid *addr;\n\tint fd, i;\n\tint numa_node = SOCKET_ID_ANY;\n\n\tif (validate_msg_fds(dev, ctx, 1) != 0)\n\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\n\tfd = ctx->fds[0];\n\tif (ctx->msg.size != sizeof(ctx->msg.payload.inflight) || fd < 0) {\n\t\tVHOST_LOG_CONFIG(ERR, \"(%s) invalid set_inflight_fd message size is %d,fd is %d\\n\",\n\t\t\tdev->ifname, ctx->msg.size, fd);\n\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\t}\n\n\tmmap_size = ctx->msg.payload.inflight.mmap_size;\n\tmmap_offset = ctx->msg.payload.inflight.mmap_offset;\n\tnum_queues = ctx->msg.payload.inflight.num_queues;\n\tqueue_size = ctx->msg.payload.inflight.queue_size;\n\n\tif (vq_is_packed(dev))\n\t\tpervq_inflight_size = get_pervq_shm_size_packed(queue_size);\n\telse\n\t\tpervq_inflight_size = get_pervq_shm_size_split(queue_size);\n\n\tVHOST_LOG_CONFIG(INFO, \"(%s) set_inflight_fd mmap_size: %\"PRIu64\"\\n\",\n\t\t\tdev->ifname, mmap_size);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) set_inflight_fd mmap_offset: %\"PRIu64\"\\n\",\n\t\t\tdev->ifname, mmap_offset);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) set_inflight_fd num_queues: %u\\n\", dev->ifname, num_queues);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) set_inflight_fd queue_size: %u\\n\", dev->ifname, queue_size);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) set_inflight_fd fd: %d\\n\", dev->ifname, fd);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) set_inflight_fd pervq_inflight_size: %d\\n\",\n\t\t\tdev->ifname, pervq_inflight_size);\n\n\t/*\n\t * If VQ 0 has already been allocated, try to allocate on the same\n\t * NUMA node. It can be reallocated later in numa_realloc().\n\t */\n\tif (dev->nr_vring > 0)\n\t\tnuma_node = dev->virtqueue[0]->numa_node;\n\n\tif (!dev->inflight_info) {\n\t\tdev->inflight_info = rte_zmalloc_socket(\"inflight_info\",\n\t\t\t\tsizeof(struct inflight_mem_info), 0, numa_node);\n\t\tif (dev->inflight_info == NULL) {\n\t\t\tVHOST_LOG_CONFIG(ERR, \"(%s) failed to alloc dev inflight area\\n\",\n\t\t\t\t\tdev->ifname);\n\t\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\t\t}\n\t\tdev->inflight_info->fd = -1;\n\t}\n\n\tif (dev->inflight_info->addr) {\n\t\tmunmap(dev->inflight_info->addr, dev->inflight_info->size);\n\t\tdev->inflight_info->addr = NULL;\n\t}\n\n\taddr = mmap(0, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,\n\t\t    fd, mmap_offset);\n\tif (addr == MAP_FAILED) {\n\t\tVHOST_LOG_CONFIG(ERR, \"(%s) failed to mmap share memory.\\n\", dev->ifname);\n\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\t}\n\n\tif (dev->inflight_info->fd >= 0) {\n\t\tclose(dev->inflight_info->fd);\n\t\tdev->inflight_info->fd = -1;\n\t}\n\n\tdev->inflight_info->fd = fd;\n\tdev->inflight_info->addr = addr;\n\tdev->inflight_info->size = mmap_size;\n\n\tfor (i = 0; i < num_queues; i++) {\n\t\tvq = dev->virtqueue[i];\n\t\tif (!vq)\n\t\t\tcontinue;\n\n\t\tif (vq_is_packed(dev)) {\n\t\t\tvq->inflight_packed = addr;\n\t\t\tvq->inflight_packed->desc_num = queue_size;\n\t\t} else {\n\t\t\tvq->inflight_split = addr;\n\t\t\tvq->inflight_split->desc_num = queue_size;\n\t\t}\n\t\taddr = (void *)((char *)addr + pervq_inflight_size);\n\t}\n\n\treturn RTE_VHOST_MSG_RESULT_OK;\n}", "func_hash": 175493676655646817389391031814281109414, "file_name": "vhost_user.c", "file_hash": 99784894649346629896685974573557095486, "cwe": ["CWE-703"], "cve": "CVE-2022-0669", "cve_desc": "A flaw was found in dpdk. This flaw allows a malicious vhost-user master to attach an unexpected number of fds as ancillary data to VHOST_USER_GET_INFLIGHT_FD / VHOST_USER_SET_INFLIGHT_FD messages that are not closed by the vhost-user slave. By sending such messages continuously, the vhost-user master exhausts available fd in the vhost-user slave process, leading to a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0669"}
{"idx": 210284, "project": "dpdk", "commit_id": "af74f7db384ed149fe42b21dbd7975f8a54ef227", "project_url": "https://github.com/DPDK/dpdk", "commit_url": "https://github.com/DPDK/dpdk/commit/af74f7db384ed149fe42b21dbd7975f8a54ef227", "commit_message": "vhost: fix FD leak with inflight messages\n\nEven if unlikely, a buggy vhost-user master might attach fds to inflight\nmessages. Add checks like for other types of vhost-user messages.\n\nFixes: d87f1a1cb7b6 (\"vhost: support inflight info sharing\")\nCc: stable@dpdk.org\n\nSigned-off-by: David Marchand \nReviewed-by: Maxime Coquelin ", "target": 1, "func": "vhost_user_get_inflight_fd(struct virtio_net **pdev,\n\t\t\t   struct vhu_msg_context *ctx,\n\t\t\t   int main_fd __rte_unused)\n{\n\tstruct rte_vhost_inflight_info_packed *inflight_packed;\n\tuint64_t pervq_inflight_size, mmap_size;\n\tuint16_t num_queues, queue_size;\n\tstruct virtio_net *dev = *pdev;\n\tint fd, i, j;\n\tint numa_node = SOCKET_ID_ANY;\n\tvoid *addr;\n\n\tif (ctx->msg.size != sizeof(ctx->msg.payload.inflight)) {\n\t\tVHOST_LOG_CONFIG(ERR, \"(%s) invalid get_inflight_fd message size is %d\\n\",\n\t\t\tdev->ifname, ctx->msg.size);\n\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\t}\n\n\t/*\n\t * If VQ 0 has already been allocated, try to allocate on the same\n\t * NUMA node. It can be reallocated later in numa_realloc().\n\t */\n\tif (dev->nr_vring > 0)\n\t\tnuma_node = dev->virtqueue[0]->numa_node;\n\n\tif (dev->inflight_info == NULL) {\n\t\tdev->inflight_info = rte_zmalloc_socket(\"inflight_info\",\n\t\t\t\tsizeof(struct inflight_mem_info), 0, numa_node);\n\t\tif (!dev->inflight_info) {\n\t\t\tVHOST_LOG_CONFIG(ERR, \"(%s) failed to alloc dev inflight area\\n\",\n\t\t\t\t\tdev->ifname);\n\t\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\t\t}\n\t\tdev->inflight_info->fd = -1;\n\t}\n\n\tnum_queues = ctx->msg.payload.inflight.num_queues;\n\tqueue_size = ctx->msg.payload.inflight.queue_size;\n\n\tVHOST_LOG_CONFIG(INFO, \"(%s) get_inflight_fd num_queues: %u\\n\",\n\t\tdev->ifname, ctx->msg.payload.inflight.num_queues);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) get_inflight_fd queue_size: %u\\n\",\n\t\tdev->ifname, ctx->msg.payload.inflight.queue_size);\n\n\tif (vq_is_packed(dev))\n\t\tpervq_inflight_size = get_pervq_shm_size_packed(queue_size);\n\telse\n\t\tpervq_inflight_size = get_pervq_shm_size_split(queue_size);\n\n\tmmap_size = num_queues * pervq_inflight_size;\n\taddr = inflight_mem_alloc(dev, \"vhost-inflight\", mmap_size, &fd);\n\tif (!addr) {\n\t\tVHOST_LOG_CONFIG(ERR, \"(%s) failed to alloc vhost inflight area\\n\", dev->ifname);\n\t\t\tctx->msg.payload.inflight.mmap_size = 0;\n\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\t}\n\tmemset(addr, 0, mmap_size);\n\n\tif (dev->inflight_info->addr) {\n\t\tmunmap(dev->inflight_info->addr, dev->inflight_info->size);\n\t\tdev->inflight_info->addr = NULL;\n\t}\n\n\tif (dev->inflight_info->fd >= 0) {\n\t\tclose(dev->inflight_info->fd);\n\t\tdev->inflight_info->fd = -1;\n\t}\n\n\tdev->inflight_info->addr = addr;\n\tdev->inflight_info->size = ctx->msg.payload.inflight.mmap_size = mmap_size;\n\tdev->inflight_info->fd = ctx->fds[0] = fd;\n\tctx->msg.payload.inflight.mmap_offset = 0;\n\tctx->fd_num = 1;\n\n\tif (vq_is_packed(dev)) {\n\t\tfor (i = 0; i < num_queues; i++) {\n\t\t\tinflight_packed =\n\t\t\t\t(struct rte_vhost_inflight_info_packed *)addr;\n\t\t\tinflight_packed->used_wrap_counter = 1;\n\t\t\tinflight_packed->old_used_wrap_counter = 1;\n\t\t\tfor (j = 0; j < queue_size; j++)\n\t\t\t\tinflight_packed->desc[j].next = j + 1;\n\t\t\taddr = (void *)((char *)addr + pervq_inflight_size);\n\t\t}\n\t}\n\n\tVHOST_LOG_CONFIG(INFO, \"(%s) send inflight mmap_size: %\"PRIu64\"\\n\",\n\t\t\tdev->ifname, ctx->msg.payload.inflight.mmap_size);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) send inflight mmap_offset: %\"PRIu64\"\\n\",\n\t\t\tdev->ifname, ctx->msg.payload.inflight.mmap_offset);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) send inflight fd: %d\\n\", dev->ifname, ctx->fds[0]);\n\n\treturn RTE_VHOST_MSG_RESULT_REPLY;\n}", "func_hash": 188145158919819292025512968399906201688, "file_name": "vhost_user.c", "file_hash": 63503821127437927181843920110423384686, "cwe": ["CWE-703"], "cve": "CVE-2022-0669", "cve_desc": "A flaw was found in dpdk. This flaw allows a malicious vhost-user master to attach an unexpected number of fds as ancillary data to VHOST_USER_GET_INFLIGHT_FD / VHOST_USER_SET_INFLIGHT_FD messages that are not closed by the vhost-user slave. By sending such messages continuously, the vhost-user master exhausts available fd in the vhost-user slave process, leading to a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0669"}
{"idx": 432352, "project": "dpdk", "commit_id": "af74f7db384ed149fe42b21dbd7975f8a54ef227", "project_url": "https://github.com/DPDK/dpdk", "commit_url": "https://github.com/DPDK/dpdk/commit/af74f7db384ed149fe42b21dbd7975f8a54ef227", "commit_message": "vhost: fix FD leak with inflight messages\n\nEven if unlikely, a buggy vhost-user master might attach fds to inflight\nmessages. Add checks like for other types of vhost-user messages.\n\nFixes: d87f1a1cb7b6 (\"vhost: support inflight info sharing\")\nCc: stable@dpdk.org\n\nSigned-off-by: David Marchand \nReviewed-by: Maxime Coquelin ", "target": 0, "func": "vhost_user_get_inflight_fd(struct virtio_net **pdev,\n\t\t\t   struct vhu_msg_context *ctx,\n\t\t\t   int main_fd __rte_unused)\n{\n\tstruct rte_vhost_inflight_info_packed *inflight_packed;\n\tuint64_t pervq_inflight_size, mmap_size;\n\tuint16_t num_queues, queue_size;\n\tstruct virtio_net *dev = *pdev;\n\tint fd, i, j;\n\tint numa_node = SOCKET_ID_ANY;\n\tvoid *addr;\n\n\tif (validate_msg_fds(dev, ctx, 0) != 0)\n\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\n\tif (ctx->msg.size != sizeof(ctx->msg.payload.inflight)) {\n\t\tVHOST_LOG_CONFIG(ERR, \"(%s) invalid get_inflight_fd message size is %d\\n\",\n\t\t\tdev->ifname, ctx->msg.size);\n\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\t}\n\n\t/*\n\t * If VQ 0 has already been allocated, try to allocate on the same\n\t * NUMA node. It can be reallocated later in numa_realloc().\n\t */\n\tif (dev->nr_vring > 0)\n\t\tnuma_node = dev->virtqueue[0]->numa_node;\n\n\tif (dev->inflight_info == NULL) {\n\t\tdev->inflight_info = rte_zmalloc_socket(\"inflight_info\",\n\t\t\t\tsizeof(struct inflight_mem_info), 0, numa_node);\n\t\tif (!dev->inflight_info) {\n\t\t\tVHOST_LOG_CONFIG(ERR, \"(%s) failed to alloc dev inflight area\\n\",\n\t\t\t\t\tdev->ifname);\n\t\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\t\t}\n\t\tdev->inflight_info->fd = -1;\n\t}\n\n\tnum_queues = ctx->msg.payload.inflight.num_queues;\n\tqueue_size = ctx->msg.payload.inflight.queue_size;\n\n\tVHOST_LOG_CONFIG(INFO, \"(%s) get_inflight_fd num_queues: %u\\n\",\n\t\tdev->ifname, ctx->msg.payload.inflight.num_queues);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) get_inflight_fd queue_size: %u\\n\",\n\t\tdev->ifname, ctx->msg.payload.inflight.queue_size);\n\n\tif (vq_is_packed(dev))\n\t\tpervq_inflight_size = get_pervq_shm_size_packed(queue_size);\n\telse\n\t\tpervq_inflight_size = get_pervq_shm_size_split(queue_size);\n\n\tmmap_size = num_queues * pervq_inflight_size;\n\taddr = inflight_mem_alloc(dev, \"vhost-inflight\", mmap_size, &fd);\n\tif (!addr) {\n\t\tVHOST_LOG_CONFIG(ERR, \"(%s) failed to alloc vhost inflight area\\n\", dev->ifname);\n\t\t\tctx->msg.payload.inflight.mmap_size = 0;\n\t\treturn RTE_VHOST_MSG_RESULT_ERR;\n\t}\n\tmemset(addr, 0, mmap_size);\n\n\tif (dev->inflight_info->addr) {\n\t\tmunmap(dev->inflight_info->addr, dev->inflight_info->size);\n\t\tdev->inflight_info->addr = NULL;\n\t}\n\n\tif (dev->inflight_info->fd >= 0) {\n\t\tclose(dev->inflight_info->fd);\n\t\tdev->inflight_info->fd = -1;\n\t}\n\n\tdev->inflight_info->addr = addr;\n\tdev->inflight_info->size = ctx->msg.payload.inflight.mmap_size = mmap_size;\n\tdev->inflight_info->fd = ctx->fds[0] = fd;\n\tctx->msg.payload.inflight.mmap_offset = 0;\n\tctx->fd_num = 1;\n\n\tif (vq_is_packed(dev)) {\n\t\tfor (i = 0; i < num_queues; i++) {\n\t\t\tinflight_packed =\n\t\t\t\t(struct rte_vhost_inflight_info_packed *)addr;\n\t\t\tinflight_packed->used_wrap_counter = 1;\n\t\t\tinflight_packed->old_used_wrap_counter = 1;\n\t\t\tfor (j = 0; j < queue_size; j++)\n\t\t\t\tinflight_packed->desc[j].next = j + 1;\n\t\t\taddr = (void *)((char *)addr + pervq_inflight_size);\n\t\t}\n\t}\n\n\tVHOST_LOG_CONFIG(INFO, \"(%s) send inflight mmap_size: %\"PRIu64\"\\n\",\n\t\t\tdev->ifname, ctx->msg.payload.inflight.mmap_size);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) send inflight mmap_offset: %\"PRIu64\"\\n\",\n\t\t\tdev->ifname, ctx->msg.payload.inflight.mmap_offset);\n\tVHOST_LOG_CONFIG(INFO, \"(%s) send inflight fd: %d\\n\", dev->ifname, ctx->fds[0]);\n\n\treturn RTE_VHOST_MSG_RESULT_REPLY;\n}", "func_hash": 77090797647717556170769908563421841237, "file_name": "vhost_user.c", "file_hash": 99784894649346629896685974573557095486, "cwe": ["CWE-703"], "cve": "CVE-2022-0669", "cve_desc": "A flaw was found in dpdk. This flaw allows a malicious vhost-user master to attach an unexpected number of fds as ancillary data to VHOST_USER_GET_INFLIGHT_FD / VHOST_USER_SET_INFLIGHT_FD messages that are not closed by the vhost-user slave. By sending such messages continuously, the vhost-user master exhausts available fd in the vhost-user slave process, leading to a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0669"}
{"idx": 210393, "project": "vim", "commit_id": "6f98371532fcff911b462d51bc64f2ce8a6ae682", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/6f98371532fcff911b462d51bc64f2ce8a6ae682", "commit_message": "patch 8.2.3884: crash when clearing the argument list while using it\n\nProblem:    Crash when clearing the argument list while using it.\nSolution:   Lock the argument list for \":all\".", "target": 1, "func": "do_arg_all(\n    int\tcount,\n    int\tforceit,\t\t// hide buffers in current windows\n    int keep_tabs)\t\t// keep current tabs, for \":tab drop file\"\n{\n    int\t\ti;\n    win_T\t*wp, *wpnext;\n    char_u\t*opened;\t// Array of weight for which args are open:\n\t\t\t\t//  0: not opened\n\t\t\t\t//  1: opened in other tab\n\t\t\t\t//  2: opened in curtab\n\t\t\t\t//  3: opened in curtab and curwin\n\t\t\t\t//\n    int\t\topened_len;\t// length of opened[]\n    int\t\tuse_firstwin = FALSE;\t// use first window for arglist\n    int\t\ttab_drop_empty_window = FALSE;\n    int\t\tsplit_ret = OK;\n    int\t\tp_ea_save;\n    alist_T\t*alist;\t\t// argument list to be used\n    buf_T\t*buf;\n    tabpage_T\t*tpnext;\n    int\t\thad_tab = cmdmod.cmod_tab;\n    win_T\t*old_curwin, *last_curwin;\n    tabpage_T\t*old_curtab, *last_curtab;\n    win_T\t*new_curwin = NULL;\n    tabpage_T\t*new_curtab = NULL;\n\n#ifdef FEAT_CMDWIN\n    if (cmdwin_type != 0)\n    {\n\temsg(_(e_invalid_in_cmdline_window));\n\treturn;\n    }\n#endif\n    if (ARGCOUNT <= 0)\n    {\n\t// Don't give an error message.  We don't want it when the \":all\"\n\t// command is in the .vimrc.\n\treturn;\n    }\n    setpcmark();\n\n    opened_len = ARGCOUNT;\n    opened = alloc_clear(opened_len);\n    if (opened == NULL)\n\treturn;\n\n    // Autocommands may do anything to the argument list.  Make sure it's not\n    // freed while we are working here by \"locking\" it.  We still have to\n    // watch out for its size to be changed.\n    alist = curwin->w_alist;\n    ++alist->al_refcount;\n\n    old_curwin = curwin;\n    old_curtab = curtab;\n\n# ifdef FEAT_GUI\n    need_mouse_correct = TRUE;\n# endif\n\n    // Try closing all windows that are not in the argument list.\n    // Also close windows that are not full width;\n    // When 'hidden' or \"forceit\" set the buffer becomes hidden.\n    // Windows that have a changed buffer and can't be hidden won't be closed.\n    // When the \":tab\" modifier was used do this for all tab pages.\n    if (had_tab > 0)\n\tgoto_tabpage_tp(first_tabpage, TRUE, TRUE);\n    for (;;)\n    {\n\ttpnext = curtab->tp_next;\n\tfor (wp = firstwin; wp != NULL; wp = wpnext)\n\t{\n\t    wpnext = wp->w_next;\n\t    buf = wp->w_buffer;\n\t    if (buf->b_ffname == NULL\n\t\t    || (!keep_tabs && (buf->b_nwindows > 1\n\t\t\t    || wp->w_width != Columns)))\n\t\ti = opened_len;\n\t    else\n\t    {\n\t\t// check if the buffer in this window is in the arglist\n\t\tfor (i = 0; i < opened_len; ++i)\n\t\t{\n\t\t    if (i < alist->al_ga.ga_len\n\t\t\t    && (AARGLIST(alist)[i].ae_fnum == buf->b_fnum\n\t\t\t\t|| fullpathcmp(alist_name(&AARGLIST(alist)[i]),\n\t\t\t\t\tbuf->b_ffname, TRUE, TRUE) & FPC_SAME))\n\t\t    {\n\t\t\tint weight = 1;\n\n\t\t\tif (old_curtab == curtab)\n\t\t\t{\n\t\t\t    ++weight;\n\t\t\t    if (old_curwin == wp)\n\t\t\t\t++weight;\n\t\t\t}\n\n\t\t\tif (weight > (int)opened[i])\n\t\t\t{\n\t\t\t    opened[i] = (char_u)weight;\n\t\t\t    if (i == 0)\n\t\t\t    {\n\t\t\t\tif (new_curwin != NULL)\n\t\t\t\t    new_curwin->w_arg_idx = opened_len;\n\t\t\t\tnew_curwin = wp;\n\t\t\t\tnew_curtab = curtab;\n\t\t\t    }\n\t\t\t}\n\t\t\telse if (keep_tabs)\n\t\t\t    i = opened_len;\n\n\t\t\tif (wp->w_alist != alist)\n\t\t\t{\n\t\t\t    // Use the current argument list for all windows\n\t\t\t    // containing a file from it.\n\t\t\t    alist_unlink(wp->w_alist);\n\t\t\t    wp->w_alist = alist;\n\t\t\t    ++wp->w_alist->al_refcount;\n\t\t\t}\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t    }\n\t    wp->w_arg_idx = i;\n\n\t    if (i == opened_len && !keep_tabs)// close this window\n\t    {\n\t\tif (buf_hide(buf) || forceit || buf->b_nwindows > 1\n\t\t\t\t\t\t\t|| !bufIsChanged(buf))\n\t\t{\n\t\t    // If the buffer was changed, and we would like to hide it,\n\t\t    // try autowriting.\n\t\t    if (!buf_hide(buf) && buf->b_nwindows <= 1\n\t\t\t\t\t\t\t && bufIsChanged(buf))\n\t\t    {\n\t\t\tbufref_T    bufref;\n\n\t\t\tset_bufref(&bufref, buf);\n\n\t\t\t(void)autowrite(buf, FALSE);\n\n\t\t\t// check if autocommands removed the window\n\t\t\tif (!win_valid(wp) || !bufref_valid(&bufref))\n\t\t\t{\n\t\t\t    wpnext = firstwin;\t// start all over...\n\t\t\t    continue;\n\t\t\t}\n\t\t    }\n\t\t    // don't close last window\n\t\t    if (ONE_WINDOW\n\t\t\t    && (first_tabpage->tp_next == NULL || !had_tab))\n\t\t\tuse_firstwin = TRUE;\n\t\t    else\n\t\t    {\n\t\t\twin_close(wp, !buf_hide(buf) && !bufIsChanged(buf));\n\n\t\t\t// check if autocommands removed the next window\n\t\t\tif (!win_valid(wpnext))\n\t\t\t    wpnext = firstwin;\t// start all over...\n\t\t    }\n\t\t}\n\t    }\n\t}\n\n\t// Without the \":tab\" modifier only do the current tab page.\n\tif (had_tab == 0 || tpnext == NULL)\n\t    break;\n\n\t// check if autocommands removed the next tab page\n\tif (!valid_tabpage(tpnext))\n\t    tpnext = first_tabpage;\t// start all over...\n\n\tgoto_tabpage_tp(tpnext, TRUE, TRUE);\n    }\n\n    // Open a window for files in the argument list that don't have one.\n    // ARGCOUNT may change while doing this, because of autocommands.\n    if (count > opened_len || count <= 0)\n\tcount = opened_len;\n\n    // Don't execute Win/Buf Enter/Leave autocommands here.\n    ++autocmd_no_enter;\n    ++autocmd_no_leave;\n    last_curwin = curwin;\n    last_curtab = curtab;\n    win_enter(lastwin, FALSE);\n    // \":tab drop file\" should re-use an empty window to avoid \"--remote-tab\"\n    // leaving an empty tab page when executed locally.\n    if (keep_tabs && BUFEMPTY() && curbuf->b_nwindows == 1\n\t\t\t    && curbuf->b_ffname == NULL && !curbuf->b_changed)\n    {\n\tuse_firstwin = TRUE;\n\ttab_drop_empty_window = TRUE;\n    }\n\n    for (i = 0; i < count && !got_int; ++i)\n    {\n\tif (alist == &global_alist && i == global_alist.al_ga.ga_len - 1)\n\t    arg_had_last = TRUE;\n\tif (opened[i] > 0)\n\t{\n\t    // Move the already present window to below the current window\n\t    if (curwin->w_arg_idx != i)\n\t    {\n\t\tFOR_ALL_WINDOWS(wpnext)\n\t\t{\n\t\t    if (wpnext->w_arg_idx == i)\n\t\t    {\n\t\t\tif (keep_tabs)\n\t\t\t{\n\t\t\t    new_curwin = wpnext;\n\t\t\t    new_curtab = curtab;\n\t\t\t}\n\t\t\telse if (wpnext->w_frame->fr_parent\n\t\t\t\t\t\t != curwin->w_frame->fr_parent)\n\t\t\t{\n\t\t\t    emsg(_(\"E249: window layout changed unexpectedly\"));\n\t\t\t    i = count;\n\t\t\t    break;\n\t\t\t}\n\t\t\telse\n\t\t\t    win_move_after(wpnext, curwin);\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t    }\n\t}\n\telse if (split_ret == OK)\n\t{\n\t    // trigger events for tab drop\n\t    if (tab_drop_empty_window && i == count - 1)\n\t\t--autocmd_no_enter;\n\t    if (!use_firstwin)\t\t// split current window\n\t    {\n\t\tp_ea_save = p_ea;\n\t\tp_ea = TRUE;\t\t// use space from all windows\n\t\tsplit_ret = win_split(0, WSP_ROOM | WSP_BELOW);\n\t\tp_ea = p_ea_save;\n\t\tif (split_ret == FAIL)\n\t\t    continue;\n\t    }\n\t    else    // first window: do autocmd for leaving this buffer\n\t\t--autocmd_no_leave;\n\n\t    // edit file \"i\"\n\t    curwin->w_arg_idx = i;\n\t    if (i == 0)\n\t    {\n\t\tnew_curwin = curwin;\n\t\tnew_curtab = curtab;\n\t    }\n\t    (void)do_ecmd(0, alist_name(&AARGLIST(alist)[i]), NULL, NULL,\n\t\t      ECMD_ONE,\n\t\t      ((buf_hide(curwin->w_buffer)\n\t\t\t   || bufIsChanged(curwin->w_buffer)) ? ECMD_HIDE : 0)\n\t\t\t\t\t\t       + ECMD_OLDBUF, curwin);\n\t    if (tab_drop_empty_window && i == count - 1)\n\t\t++autocmd_no_enter;\n\t    if (use_firstwin)\n\t\t++autocmd_no_leave;\n\t    use_firstwin = FALSE;\n\t}\n\tui_breakcheck();\n\n\t// When \":tab\" was used open a new tab for a new window repeatedly.\n\tif (had_tab > 0 && tabpage_index(NULL) <= p_tpm)\n\t    cmdmod.cmod_tab = 9999;\n    }\n\n    // Remove the \"lock\" on the argument list.\n    alist_unlink(alist);\n\n    --autocmd_no_enter;\n\n    // restore last referenced tabpage's curwin\n    if (last_curtab != new_curtab)\n    {\n\tif (valid_tabpage(last_curtab))\n\t    goto_tabpage_tp(last_curtab, TRUE, TRUE);\n\tif (win_valid(last_curwin))\n\t    win_enter(last_curwin, FALSE);\n    }\n    // to window with first arg\n    if (valid_tabpage(new_curtab))\n\tgoto_tabpage_tp(new_curtab, TRUE, TRUE);\n    if (win_valid(new_curwin))\n\twin_enter(new_curwin, FALSE);\n\n    --autocmd_no_leave;\n    vim_free(opened);\n}", "func_hash": 231413303097445020226238674413950257364, "file_name": "arglist.c", "file_hash": 299441320904377920044719346235855663984, "cwe": ["CWE-416"], "cve": "CVE-2021-4166", "cve_desc": "vim is vulnerable to Out-of-bounds Read", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-4166"}
{"idx": 434093, "project": "vim", "commit_id": "6f98371532fcff911b462d51bc64f2ce8a6ae682", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/6f98371532fcff911b462d51bc64f2ce8a6ae682", "commit_message": "patch 8.2.3884: crash when clearing the argument list while using it\n\nProblem:    Crash when clearing the argument list while using it.\nSolution:   Lock the argument list for \":all\".", "target": 0, "func": "do_arg_all(\n    int\tcount,\n    int\tforceit,\t\t// hide buffers in current windows\n    int keep_tabs)\t\t// keep current tabs, for \":tab drop file\"\n{\n    int\t\ti;\n    win_T\t*wp, *wpnext;\n    char_u\t*opened;\t// Array of weight for which args are open:\n\t\t\t\t//  0: not opened\n\t\t\t\t//  1: opened in other tab\n\t\t\t\t//  2: opened in curtab\n\t\t\t\t//  3: opened in curtab and curwin\n\t\t\t\t//\n    int\t\topened_len;\t// length of opened[]\n    int\t\tuse_firstwin = FALSE;\t// use first window for arglist\n    int\t\ttab_drop_empty_window = FALSE;\n    int\t\tsplit_ret = OK;\n    int\t\tp_ea_save;\n    alist_T\t*alist;\t\t// argument list to be used\n    buf_T\t*buf;\n    tabpage_T\t*tpnext;\n    int\t\thad_tab = cmdmod.cmod_tab;\n    win_T\t*old_curwin, *last_curwin;\n    tabpage_T\t*old_curtab, *last_curtab;\n    win_T\t*new_curwin = NULL;\n    tabpage_T\t*new_curtab = NULL;\n    int\t\tprev_arglist_locked = arglist_locked;\n\n#ifdef FEAT_CMDWIN\n    if (cmdwin_type != 0)\n    {\n\temsg(_(e_invalid_in_cmdline_window));\n\treturn;\n    }\n#endif\n    if (ARGCOUNT <= 0)\n    {\n\t// Don't give an error message.  We don't want it when the \":all\"\n\t// command is in the .vimrc.\n\treturn;\n    }\n    setpcmark();\n\n    opened_len = ARGCOUNT;\n    opened = alloc_clear(opened_len);\n    if (opened == NULL)\n\treturn;\n\n    // Autocommands may do anything to the argument list.  Make sure it's not\n    // freed while we are working here by \"locking\" it.  We still have to\n    // watch out for its size to be changed.\n    alist = curwin->w_alist;\n    ++alist->al_refcount;\n    arglist_locked = TRUE;\n\n    old_curwin = curwin;\n    old_curtab = curtab;\n\n# ifdef FEAT_GUI\n    need_mouse_correct = TRUE;\n# endif\n\n    // Try closing all windows that are not in the argument list.\n    // Also close windows that are not full width;\n    // When 'hidden' or \"forceit\" set the buffer becomes hidden.\n    // Windows that have a changed buffer and can't be hidden won't be closed.\n    // When the \":tab\" modifier was used do this for all tab pages.\n    if (had_tab > 0)\n\tgoto_tabpage_tp(first_tabpage, TRUE, TRUE);\n    for (;;)\n    {\n\ttpnext = curtab->tp_next;\n\tfor (wp = firstwin; wp != NULL; wp = wpnext)\n\t{\n\t    wpnext = wp->w_next;\n\t    buf = wp->w_buffer;\n\t    if (buf->b_ffname == NULL\n\t\t    || (!keep_tabs && (buf->b_nwindows > 1\n\t\t\t    || wp->w_width != Columns)))\n\t\ti = opened_len;\n\t    else\n\t    {\n\t\t// check if the buffer in this window is in the arglist\n\t\tfor (i = 0; i < opened_len; ++i)\n\t\t{\n\t\t    if (i < alist->al_ga.ga_len\n\t\t\t    && (AARGLIST(alist)[i].ae_fnum == buf->b_fnum\n\t\t\t\t|| fullpathcmp(alist_name(&AARGLIST(alist)[i]),\n\t\t\t\t\tbuf->b_ffname, TRUE, TRUE) & FPC_SAME))\n\t\t    {\n\t\t\tint weight = 1;\n\n\t\t\tif (old_curtab == curtab)\n\t\t\t{\n\t\t\t    ++weight;\n\t\t\t    if (old_curwin == wp)\n\t\t\t\t++weight;\n\t\t\t}\n\n\t\t\tif (weight > (int)opened[i])\n\t\t\t{\n\t\t\t    opened[i] = (char_u)weight;\n\t\t\t    if (i == 0)\n\t\t\t    {\n\t\t\t\tif (new_curwin != NULL)\n\t\t\t\t    new_curwin->w_arg_idx = opened_len;\n\t\t\t\tnew_curwin = wp;\n\t\t\t\tnew_curtab = curtab;\n\t\t\t    }\n\t\t\t}\n\t\t\telse if (keep_tabs)\n\t\t\t    i = opened_len;\n\n\t\t\tif (wp->w_alist != alist)\n\t\t\t{\n\t\t\t    // Use the current argument list for all windows\n\t\t\t    // containing a file from it.\n\t\t\t    alist_unlink(wp->w_alist);\n\t\t\t    wp->w_alist = alist;\n\t\t\t    ++wp->w_alist->al_refcount;\n\t\t\t}\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t    }\n\t    wp->w_arg_idx = i;\n\n\t    if (i == opened_len && !keep_tabs)// close this window\n\t    {\n\t\tif (buf_hide(buf) || forceit || buf->b_nwindows > 1\n\t\t\t\t\t\t\t|| !bufIsChanged(buf))\n\t\t{\n\t\t    // If the buffer was changed, and we would like to hide it,\n\t\t    // try autowriting.\n\t\t    if (!buf_hide(buf) && buf->b_nwindows <= 1\n\t\t\t\t\t\t\t && bufIsChanged(buf))\n\t\t    {\n\t\t\tbufref_T    bufref;\n\n\t\t\tset_bufref(&bufref, buf);\n\n\t\t\t(void)autowrite(buf, FALSE);\n\n\t\t\t// check if autocommands removed the window\n\t\t\tif (!win_valid(wp) || !bufref_valid(&bufref))\n\t\t\t{\n\t\t\t    wpnext = firstwin;\t// start all over...\n\t\t\t    continue;\n\t\t\t}\n\t\t    }\n\t\t    // don't close last window\n\t\t    if (ONE_WINDOW\n\t\t\t    && (first_tabpage->tp_next == NULL || !had_tab))\n\t\t\tuse_firstwin = TRUE;\n\t\t    else\n\t\t    {\n\t\t\twin_close(wp, !buf_hide(buf) && !bufIsChanged(buf));\n\n\t\t\t// check if autocommands removed the next window\n\t\t\tif (!win_valid(wpnext))\n\t\t\t    wpnext = firstwin;\t// start all over...\n\t\t    }\n\t\t}\n\t    }\n\t}\n\n\t// Without the \":tab\" modifier only do the current tab page.\n\tif (had_tab == 0 || tpnext == NULL)\n\t    break;\n\n\t// check if autocommands removed the next tab page\n\tif (!valid_tabpage(tpnext))\n\t    tpnext = first_tabpage;\t// start all over...\n\n\tgoto_tabpage_tp(tpnext, TRUE, TRUE);\n    }\n\n    // Open a window for files in the argument list that don't have one.\n    // ARGCOUNT may change while doing this, because of autocommands.\n    if (count > opened_len || count <= 0)\n\tcount = opened_len;\n\n    // Don't execute Win/Buf Enter/Leave autocommands here.\n    ++autocmd_no_enter;\n    ++autocmd_no_leave;\n    last_curwin = curwin;\n    last_curtab = curtab;\n    win_enter(lastwin, FALSE);\n    // \":tab drop file\" should re-use an empty window to avoid \"--remote-tab\"\n    // leaving an empty tab page when executed locally.\n    if (keep_tabs && BUFEMPTY() && curbuf->b_nwindows == 1\n\t\t\t    && curbuf->b_ffname == NULL && !curbuf->b_changed)\n    {\n\tuse_firstwin = TRUE;\n\ttab_drop_empty_window = TRUE;\n    }\n\n    for (i = 0; i < count && !got_int; ++i)\n    {\n\tif (alist == &global_alist && i == global_alist.al_ga.ga_len - 1)\n\t    arg_had_last = TRUE;\n\tif (opened[i] > 0)\n\t{\n\t    // Move the already present window to below the current window\n\t    if (curwin->w_arg_idx != i)\n\t    {\n\t\tFOR_ALL_WINDOWS(wpnext)\n\t\t{\n\t\t    if (wpnext->w_arg_idx == i)\n\t\t    {\n\t\t\tif (keep_tabs)\n\t\t\t{\n\t\t\t    new_curwin = wpnext;\n\t\t\t    new_curtab = curtab;\n\t\t\t}\n\t\t\telse if (wpnext->w_frame->fr_parent\n\t\t\t\t\t\t != curwin->w_frame->fr_parent)\n\t\t\t{\n\t\t\t    emsg(_(\"E249: window layout changed unexpectedly\"));\n\t\t\t    i = count;\n\t\t\t    break;\n\t\t\t}\n\t\t\telse\n\t\t\t    win_move_after(wpnext, curwin);\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t    }\n\t}\n\telse if (split_ret == OK)\n\t{\n\t    // trigger events for tab drop\n\t    if (tab_drop_empty_window && i == count - 1)\n\t\t--autocmd_no_enter;\n\t    if (!use_firstwin)\t\t// split current window\n\t    {\n\t\tp_ea_save = p_ea;\n\t\tp_ea = TRUE;\t\t// use space from all windows\n\t\tsplit_ret = win_split(0, WSP_ROOM | WSP_BELOW);\n\t\tp_ea = p_ea_save;\n\t\tif (split_ret == FAIL)\n\t\t    continue;\n\t    }\n\t    else    // first window: do autocmd for leaving this buffer\n\t\t--autocmd_no_leave;\n\n\t    // edit file \"i\"\n\t    curwin->w_arg_idx = i;\n\t    if (i == 0)\n\t    {\n\t\tnew_curwin = curwin;\n\t\tnew_curtab = curtab;\n\t    }\n\t    (void)do_ecmd(0, alist_name(&AARGLIST(alist)[i]), NULL, NULL,\n\t\t      ECMD_ONE,\n\t\t      ((buf_hide(curwin->w_buffer)\n\t\t\t   || bufIsChanged(curwin->w_buffer)) ? ECMD_HIDE : 0)\n\t\t\t\t\t\t       + ECMD_OLDBUF, curwin);\n\t    if (tab_drop_empty_window && i == count - 1)\n\t\t++autocmd_no_enter;\n\t    if (use_firstwin)\n\t\t++autocmd_no_leave;\n\t    use_firstwin = FALSE;\n\t}\n\tui_breakcheck();\n\n\t// When \":tab\" was used open a new tab for a new window repeatedly.\n\tif (had_tab > 0 && tabpage_index(NULL) <= p_tpm)\n\t    cmdmod.cmod_tab = 9999;\n    }\n\n    // Remove the \"lock\" on the argument list.\n    alist_unlink(alist);\n    arglist_locked = prev_arglist_locked;\n\n    --autocmd_no_enter;\n\n    // restore last referenced tabpage's curwin\n    if (last_curtab != new_curtab)\n    {\n\tif (valid_tabpage(last_curtab))\n\t    goto_tabpage_tp(last_curtab, TRUE, TRUE);\n\tif (win_valid(last_curwin))\n\t    win_enter(last_curwin, FALSE);\n    }\n    // to window with first arg\n    if (valid_tabpage(new_curtab))\n\tgoto_tabpage_tp(new_curtab, TRUE, TRUE);\n    if (win_valid(new_curwin))\n\twin_enter(new_curwin, FALSE);\n\n    --autocmd_no_leave;\n    vim_free(opened);\n}", "func_hash": 267745419662130579869831756599776775733, "file_name": "arglist.c", "file_hash": 117785855197438392738154857809118603392, "cwe": ["CWE-416"], "cve": "CVE-2021-4166", "cve_desc": "vim is vulnerable to Out-of-bounds Read", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-4166"}
{"idx": 210420, "project": "ghostpdl", "commit_id": "362ec9daadb9992b0def3520cd1dc6fa52edd1c4", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=362ec9daadb9992b0def3520cd1dc6fa52edd1c4", "commit_message": "Fix bug 697459 Buffer overflow in fill_threshold_buffer\n\nThere was an overflow check for ht_buffer size, but none for the larger\nthreshold_buffer. Note that this file didn't fail on Windows because the\ncombination of the ht_buffer and the size of the (miscalculated due to\noverflow) threshold_buffer would have exceeded the 2Gb limit.", "target": 1, "func": "fill_threshhold_buffer(byte *dest_strip, byte *src_strip, int src_width,\n                       int left_offset, int left_width, int num_tiles,\n                       int right_width)\n{\n    byte *ptr_out_temp = dest_strip;\n    int ii;\n\n    /* Left part */\n    memcpy(dest_strip, src_strip + left_offset, left_width);\n    ptr_out_temp += left_width;\n    /* Now the full parts */\n    for (ii = 0; ii < num_tiles; ii++){\n        memcpy(ptr_out_temp, src_strip, src_width);\n        ptr_out_temp += src_width;\n    }\n    /* Now the remainder */\n    memcpy(ptr_out_temp, src_strip, right_width);\n#ifdef PACIFY_VALGRIND\n    ptr_out_temp += right_width;\n    ii = (dest_strip-ptr_out_temp) % (LAND_BITS-1);\n    if (ii > 0)\n        memset(ptr_out_temp, 0, ii);\n#endif\n}", "func_hash": 275119302871668131072600871324331925714, "file_name": "gxht_thresh.c", "file_hash": 55226233922377438981259129835747302773, "cwe": ["CWE-119"], "cve": "CVE-2016-10317", "cve_desc": "The fill_threshhold_buffer function in base/gxht_thresh.c in Artifex Software, Inc. Ghostscript 9.20 allows remote attackers to cause a denial of service (heap-based buffer overflow and application crash) or possibly have unspecified other impact via a crafted PostScript document.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-10317"}
{"idx": 434902, "project": "ghostpdl", "commit_id": "362ec9daadb9992b0def3520cd1dc6fa52edd1c4", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=362ec9daadb9992b0def3520cd1dc6fa52edd1c4", "commit_message": "Fix bug 697459 Buffer overflow in fill_threshold_buffer\n\nThere was an overflow check for ht_buffer size, but none for the larger\nthreshold_buffer. Note that this file didn't fail on Windows because the\ncombination of the ht_buffer and the size of the (miscalculated due to\noverflow) threshold_buffer would have exceeded the 2Gb limit.", "target": 0, "func": "fill_threshold_buffer(byte *dest_strip, byte *src_strip, int src_width,\n                       int left_offset, int left_width, int num_tiles,\n                       int right_width)\n{\n    byte *ptr_out_temp = dest_strip;\n    int ii;\n\n    /* Left part */\n    memcpy(dest_strip, src_strip + left_offset, left_width);\n    ptr_out_temp += left_width;\n    /* Now the full parts */\n    for (ii = 0; ii < num_tiles; ii++){\n        memcpy(ptr_out_temp, src_strip, src_width);\n        ptr_out_temp += src_width;\n    }\n    /* Now the remainder */\n    memcpy(ptr_out_temp, src_strip, right_width);\n#ifdef PACIFY_VALGRIND\n    ptr_out_temp += right_width;\n    ii = (dest_strip-ptr_out_temp) % (LAND_BITS-1);\n    if (ii > 0)\n        memset(ptr_out_temp, 0, ii);\n#endif\n}", "func_hash": 193585732429345138409504649279045778338, "file_name": "gxht_thresh.c", "file_hash": 56725769697123827323251738198105594342, "cwe": ["CWE-119"], "cve": "CVE-2016-10317", "cve_desc": "The fill_threshhold_buffer function in base/gxht_thresh.c in Artifex Software, Inc. Ghostscript 9.20 allows remote attackers to cause a denial of service (heap-based buffer overflow and application crash) or possibly have unspecified other impact via a crafted PostScript document.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-10317"}
{"idx": 210453, "project": "ghostpdl", "commit_id": "366ad48d076c1aa4c8f83c65011258a04e348207", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "https://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=366ad48d076c1aa4c8f83c65011258a04e348207", "commit_message": "Bug 701815: avoid uninitialised bytes being >7, which broke indexing.\n\nFixes:\n    ./sanbin/gs -dBATCH -dNOPAUSE -sOutputFile=tmp -sDEVICE=jetp3852 ../bug-701815.pdf", "target": 1, "func": "jetp3852_print_page(gx_device_printer *pdev, gp_file *prn_stream)\n{\n#define DATA_SIZE (LINE_SIZE * 8)\n\n    unsigned int cnt_2prn;\n    unsigned int count,tempcnt;\n    unsigned char vtp,cntc1,cntc2;\n    int line_size_color_plane;\n\n    byte data[DATA_SIZE];\n    byte plane_data[LINE_SIZE * 3];\n\n    /* Set initial condition for printer */\n    gp_fputs(\"\\033@\",prn_stream);\n\n    /* Send each scan line in turn */\n    {\n        int lnum;\n        int line_size = gdev_mem_bytes_per_scan_line((gx_device *)pdev);\n        int num_blank_lines = 0;\n\n        if (line_size > DATA_SIZE) {\n            emprintf2(pdev->memory, \"invalid resolution and/or width gives line_size = %d, max. is %d\\n\",\n                      line_size, DATA_SIZE);\n            return_error(gs_error_rangecheck);\n        }\n\n        for ( lnum = 0; lnum < pdev->height; lnum++ ) {\n            byte *end_data = data + line_size;\n            gdev_prn_copy_scan_lines(pdev, lnum,\n                                     (byte *)data, line_size);\n            /* Remove trailing 0s. */\n            while ( end_data > data && end_data[-1] == 0 )\n                end_data--;\n            if ( end_data == data ) {\n                /* Blank line */\n                num_blank_lines++;\n            } else {\n                int i;\n                byte *odp;\n                byte *row;\n\n                /* Pad with 0s to fill out the last */\n                /* block of 8 bytes. */\n                memset(end_data, 0, 7);\n\n                /* Transpose the data to get pixel planes. */\n                for ( i = 0, odp = plane_data; i < DATA_SIZE;\n                      i += 8, odp++\n                    ) { /* The following is for 16-bit machines */\n#define spread3(c)\\\n { 0, c, c*0x100, c*0x101, c*0x10000L, c*0x10001L, c*0x10100L, c*0x10101L }\n                    static ulong spr40[8] = spread3(0x40);\n                    static ulong spr8[8] = spread3(8);\n                    static ulong spr2[8] = spread3(2);\n                    register byte *dp = data + i;\n                    register ulong pword =\n                                     (spr40[dp[0]] << 1) +\n                                     (spr40[dp[1]]) +\n                                     (spr40[dp[2]] >> 1) +\n                                     (spr8[dp[3]] << 1) +\n                                     (spr8[dp[4]]) +\n                                     (spr8[dp[5]] >> 1) +\n                                     (spr2[dp[6]]) +\n                                     (spr2[dp[7]] >> 1);\n                    odp[0] = (byte)(pword >> 16);\n                    odp[LINE_SIZE] = (byte)(pword >> 8);\n                    odp[LINE_SIZE*2] = (byte)(pword);\n                }\n                /* Skip blank lines if any */\n                if ( num_blank_lines > 0 ) {\n                    /* Do \"dot skips\" */\n                    while(num_blank_lines > 255) {\n                        gp_fputs(\"\\033e\\377\",prn_stream);\n                        num_blank_lines -= 255;\n                    }\n                    vtp = num_blank_lines;\n                    gp_fprintf(prn_stream,\"\\033e%c\",vtp);\n                    num_blank_lines = 0;\n                }\n\n                /* Transfer raster graphics in the order R, G, B. */\n                /* Apparently it is stored in B, G, R */\n                /* Calculate the amount of data to send by what */\n                /* Ghostscript tells us the scan line_size in (bytes) */\n\n                count = line_size / 3;\n                line_size_color_plane = count / 3;\n                cnt_2prn = line_size_color_plane * 3 + 5;\n                tempcnt = cnt_2prn;\n                cntc1 = (tempcnt & 0xFF00) >> 8;\n                cntc2 = (tempcnt & 0x00FF);\n                gp_fprintf(prn_stream, \"\\033[O%c%c\\200\\037\",cntc2,cntc1);\n                gp_fputc('\\000',prn_stream);\n                gp_fputs(\"\\124\\124\",prn_stream);\n\n                for ( row = plane_data + LINE_SIZE * 2, i = 0;\n                      i < 3; row -= LINE_SIZE, i++ ) {\n                    int jj;\n                    byte ctemp;\n                    odp = row;\n                    /* Complement bytes */\n                    for (jj=0; jj< line_size_color_plane; jj++) {\n                        ctemp = *odp;\n                        *odp++ = ~ctemp;\n                    }\n                    gp_fwrite(row, sizeof(byte),\n                              line_size_color_plane, prn_stream);\n                }\n            }\n        }\n    }\n\n    /* eject page */\n    gp_fputs(\"\\014\", prn_stream);\n\n    return 0;\n}", "func_hash": 93148813029453334596229816591999204427, "file_name": "gdev3852.c", "file_hash": 229444063869235911698513683887059150132, "cwe": ["CWE-120"], "cve": "CVE-2020-16302", "cve_desc": "A buffer overflow vulnerability in jetp3852_print_page() in devices/gdev3852.c of Artifex Software GhostScript v9.50 allows a remote attacker to escalate privileges via a crafted PDF file. This is fixed in v9.51.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16302"}
{"idx": 435409, "project": "ghostpdl", "commit_id": "366ad48d076c1aa4c8f83c65011258a04e348207", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "https://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=366ad48d076c1aa4c8f83c65011258a04e348207", "commit_message": "Bug 701815: avoid uninitialised bytes being >7, which broke indexing.\n\nFixes:\n    ./sanbin/gs -dBATCH -dNOPAUSE -sOutputFile=tmp -sDEVICE=jetp3852 ../bug-701815.pdf", "target": 0, "func": "jetp3852_print_page(gx_device_printer *pdev, gp_file *prn_stream)\n{\n#define DATA_SIZE (LINE_SIZE * 8)\n\n    unsigned int cnt_2prn;\n    unsigned int count,tempcnt;\n    unsigned char vtp,cntc1,cntc2;\n    int line_size_color_plane;\n\n    byte data[DATA_SIZE];\n    byte plane_data[LINE_SIZE * 3];\n\n    /* Initialise data to zeros, otherwise later on, uninitialised bytes in\n    dp[] can be greater than 7, which breaks spr8[dp[]]. */\n    memset(data, 0x00, DATA_SIZE);\n\n    /* Set initial condition for printer */\n    gp_fputs(\"\\033@\",prn_stream);\n\n    /* Send each scan line in turn */\n    {\n        int lnum;\n        int line_size = gdev_mem_bytes_per_scan_line((gx_device *)pdev);\n        int num_blank_lines = 0;\n\n        if (line_size > DATA_SIZE) {\n            emprintf2(pdev->memory, \"invalid resolution and/or width gives line_size = %d, max. is %d\\n\",\n                      line_size, DATA_SIZE);\n            return_error(gs_error_rangecheck);\n        }\n\n        for ( lnum = 0; lnum < pdev->height; lnum++ ) {\n            byte *end_data = data + line_size;\n            gdev_prn_copy_scan_lines(pdev, lnum,\n                                     (byte *)data, line_size);\n            /* Remove trailing 0s. */\n            while ( end_data > data && end_data[-1] == 0 )\n                end_data--;\n            if ( end_data == data ) {\n                /* Blank line */\n                num_blank_lines++;\n            } else {\n                int i;\n                byte *odp;\n                byte *row;\n\n                /* Transpose the data to get pixel planes. */\n                for ( i = 0, odp = plane_data; i < DATA_SIZE;\n                      i += 8, odp++\n                    ) { /* The following is for 16-bit machines */\n#define spread3(c)\\\n { 0, c, c*0x100, c*0x101, c*0x10000L, c*0x10001L, c*0x10100L, c*0x10101L }\n                    static ulong spr40[8] = spread3(0x40);\n                    static ulong spr8[8] = spread3(8);\n                    static ulong spr2[8] = spread3(2);\n                    register byte *dp = data + i;\n                    register ulong pword =\n                                     (spr40[dp[0]] << 1) +\n                                     (spr40[dp[1]]) +\n                                     (spr40[dp[2]] >> 1) +\n                                     (spr8[dp[3]] << 1) +\n                                     (spr8[dp[4]]) +\n                                     (spr8[dp[5]] >> 1) +\n                                     (spr2[dp[6]]) +\n                                     (spr2[dp[7]] >> 1);\n                    odp[0] = (byte)(pword >> 16);\n                    odp[LINE_SIZE] = (byte)(pword >> 8);\n                    odp[LINE_SIZE*2] = (byte)(pword);\n                }\n                /* Skip blank lines if any */\n                if ( num_blank_lines > 0 ) {\n                    /* Do \"dot skips\" */\n                    while(num_blank_lines > 255) {\n                        gp_fputs(\"\\033e\\377\",prn_stream);\n                        num_blank_lines -= 255;\n                    }\n                    vtp = num_blank_lines;\n                    gp_fprintf(prn_stream,\"\\033e%c\",vtp);\n                    num_blank_lines = 0;\n                }\n\n                /* Transfer raster graphics in the order R, G, B. */\n                /* Apparently it is stored in B, G, R */\n                /* Calculate the amount of data to send by what */\n                /* Ghostscript tells us the scan line_size in (bytes) */\n\n                count = line_size / 3;\n                line_size_color_plane = count / 3;\n                cnt_2prn = line_size_color_plane * 3 + 5;\n                tempcnt = cnt_2prn;\n                cntc1 = (tempcnt & 0xFF00) >> 8;\n                cntc2 = (tempcnt & 0x00FF);\n                gp_fprintf(prn_stream, \"\\033[O%c%c\\200\\037\",cntc2,cntc1);\n                gp_fputc('\\000',prn_stream);\n                gp_fputs(\"\\124\\124\",prn_stream);\n\n                for ( row = plane_data + LINE_SIZE * 2, i = 0;\n                      i < 3; row -= LINE_SIZE, i++ ) {\n                    int jj;\n                    byte ctemp;\n                    odp = row;\n                    /* Complement bytes */\n                    for (jj=0; jj< line_size_color_plane; jj++) {\n                        ctemp = *odp;\n                        *odp++ = ~ctemp;\n                    }\n                    gp_fwrite(row, sizeof(byte),\n                              line_size_color_plane, prn_stream);\n                }\n            }\n        }\n    }\n\n    /* eject page */\n    gp_fputs(\"\\014\", prn_stream);\n\n    return 0;\n}", "func_hash": 85965008618432429994990471615914575554, "file_name": "gdev3852.c", "file_hash": 93770144039043531856386464739578824717, "cwe": ["CWE-120"], "cve": "CVE-2020-16302", "cve_desc": "A buffer overflow vulnerability in jetp3852_print_page() in devices/gdev3852.c of Artifex Software GhostScript v9.50 allows a remote attacker to escalate privileges via a crafted PDF file. This is fixed in v9.51.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-16302"}
{"idx": 210484, "project": "linux", "commit_id": "89c2b3b74918200e46699338d7bcc19b1ea12110", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=89c2b3b74918200e46699338d7bcc19b1ea12110", "commit_message": "io_uring: reexpand under-reexpanded iters\n\n[   74.211232] BUG: KASAN: stack-out-of-bounds in iov_iter_revert+0x809/0x900\n[   74.212778] Read of size 8 at addr ffff888025dc78b8 by task\nsyz-executor.0/828\n[   74.214756] CPU: 0 PID: 828 Comm: syz-executor.0 Not tainted\n5.14.0-rc3-next-20210730 #1\n[   74.216525] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996),\nBIOS rel-1.14.0-0-g155821a1990b-prebuilt.qemu.org 04/01/2014\n[   74.219033] Call Trace:\n[   74.219683]  dump_stack_lvl+0x8b/0xb3\n[   74.220706]  print_address_description.constprop.0+0x1f/0x140\n[   74.224226]  kasan_report.cold+0x7f/0x11b\n[   74.226085]  iov_iter_revert+0x809/0x900\n[   74.227960]  io_write+0x57d/0xe40\n[   74.232647]  io_issue_sqe+0x4da/0x6a80\n[   74.242578]  __io_queue_sqe+0x1ac/0xe60\n[   74.245358]  io_submit_sqes+0x3f6e/0x76a0\n[   74.248207]  __do_sys_io_uring_enter+0x90c/0x1a20\n[   74.257167]  do_syscall_64+0x3b/0x90\n[   74.257984]  entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nold_size = iov_iter_count();\n...\niov_iter_revert(old_size - iov_iter_count());\n\nIf iov_iter_revert() is done base on the initial size as above, and the\niter is truncated and not reexpanded in the middle, it miscalculates\nborders causing problems. This trace is due to no one reexpanding after\ngeneric_write_checks().\n\nNow iters store how many bytes has been truncated, so reexpand them to\nthe initial state right before reverting.\n\nCc: stable@vger.kernel.org\nReported-by: Palash Oswal \nReported-by: Sudip Mukherjee \nReported-and-tested-by: syzbot+9671693590ef5aad8953@syzkaller.appspotmail.com\nSigned-off-by: Pavel Begunkov \nSigned-off-by: Al Viro ", "target": 1, "func": "static int io_read(struct io_kiocb *req, unsigned int issue_flags)\n{\n\tstruct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;\n\tstruct kiocb *kiocb = &req->rw.kiocb;\n\tstruct iov_iter __iter, *iter = &__iter;\n\tstruct io_async_rw *rw = req->async_data;\n\tssize_t io_size, ret, ret2;\n\tbool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;\n\n\tif (rw) {\n\t\titer = &rw->iter;\n\t\tiovec = NULL;\n\t} else {\n\t\tret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t}\n\tio_size = iov_iter_count(iter);\n\treq->result = io_size;\n\n\t/* Ensure we clear previously set non-block flag */\n\tif (!force_nonblock)\n\t\tkiocb->ki_flags &= ~IOCB_NOWAIT;\n\telse\n\t\tkiocb->ki_flags |= IOCB_NOWAIT;\n\n\t/* If the file doesn't support async, just async punt */\n\tif (force_nonblock && !io_file_supports_async(req, READ)) {\n\t\tret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);\n\t\treturn ret ?: -EAGAIN;\n\t}\n\n\tret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);\n\tif (unlikely(ret)) {\n\t\tkfree(iovec);\n\t\treturn ret;\n\t}\n\n\tret = io_iter_do_read(req, iter);\n\n\tif (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {\n\t\treq->flags &= ~REQ_F_REISSUE;\n\t\t/* IOPOLL retry should happen for io-wq threads */\n\t\tif (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))\n\t\t\tgoto done;\n\t\t/* no retry on NONBLOCK nor RWF_NOWAIT */\n\t\tif (req->flags & REQ_F_NOWAIT)\n\t\t\tgoto done;\n\t\t/* some cases will consume bytes even on error returns */\n\t\tiov_iter_revert(iter, io_size - iov_iter_count(iter));\n\t\tret = 0;\n\t} else if (ret == -EIOCBQUEUED) {\n\t\tgoto out_free;\n\t} else if (ret <= 0 || ret == io_size || !force_nonblock ||\n\t\t   (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {\n\t\t/* read all, failed, already did sync or don't want to retry */\n\t\tgoto done;\n\t}\n\n\tret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);\n\tif (ret2)\n\t\treturn ret2;\n\n\tiovec = NULL;\n\trw = req->async_data;\n\t/* now use our persistent iterator, if we aren't already */\n\titer = &rw->iter;\n\n\tdo {\n\t\tio_size -= ret;\n\t\trw->bytes_done += ret;\n\t\t/* if we can retry, do so with the callbacks armed */\n\t\tif (!io_rw_should_retry(req)) {\n\t\t\tkiocb->ki_flags &= ~IOCB_WAITQ;\n\t\t\treturn -EAGAIN;\n\t\t}\n\n\t\t/*\n\t\t * Now retry read with the IOCB_WAITQ parts set in the iocb. If\n\t\t * we get -EIOCBQUEUED, then we'll get a notification when the\n\t\t * desired page gets unlocked. We can also get a partial read\n\t\t * here, and if we do, then just retry at the new offset.\n\t\t */\n\t\tret = io_iter_do_read(req, iter);\n\t\tif (ret == -EIOCBQUEUED)\n\t\t\treturn 0;\n\t\t/* we got some bytes, but not all. retry. */\n\t\tkiocb->ki_flags &= ~IOCB_WAITQ;\n\t} while (ret > 0 && ret < io_size);\ndone:\n\tkiocb_done(kiocb, ret, issue_flags);\nout_free:\n\t/* it's faster to check here then delegate to kfree */\n\tif (iovec)\n\t\tkfree(iovec);\n\treturn 0;\n}", "func_hash": 240635131512739563674871384281451113000, "file_name": "io_uring.c", "file_hash": 270228936608432888169467151756461550796, "cwe": ["CWE-125"], "cve": "CVE-2022-1508", "cve_desc": "An out-of-bounds read flaw was found in the Linux kernel\u2019s io_uring module in the way a user triggers the io_read() function with some special parameters. This flaw allows a local user to read some memory out of bounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1508"}
{"idx": 436066, "project": "linux", "commit_id": "89c2b3b74918200e46699338d7bcc19b1ea12110", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=89c2b3b74918200e46699338d7bcc19b1ea12110", "commit_message": "io_uring: reexpand under-reexpanded iters\n\n[   74.211232] BUG: KASAN: stack-out-of-bounds in iov_iter_revert+0x809/0x900\n[   74.212778] Read of size 8 at addr ffff888025dc78b8 by task\nsyz-executor.0/828\n[   74.214756] CPU: 0 PID: 828 Comm: syz-executor.0 Not tainted\n5.14.0-rc3-next-20210730 #1\n[   74.216525] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996),\nBIOS rel-1.14.0-0-g155821a1990b-prebuilt.qemu.org 04/01/2014\n[   74.219033] Call Trace:\n[   74.219683]  dump_stack_lvl+0x8b/0xb3\n[   74.220706]  print_address_description.constprop.0+0x1f/0x140\n[   74.224226]  kasan_report.cold+0x7f/0x11b\n[   74.226085]  iov_iter_revert+0x809/0x900\n[   74.227960]  io_write+0x57d/0xe40\n[   74.232647]  io_issue_sqe+0x4da/0x6a80\n[   74.242578]  __io_queue_sqe+0x1ac/0xe60\n[   74.245358]  io_submit_sqes+0x3f6e/0x76a0\n[   74.248207]  __do_sys_io_uring_enter+0x90c/0x1a20\n[   74.257167]  do_syscall_64+0x3b/0x90\n[   74.257984]  entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nold_size = iov_iter_count();\n...\niov_iter_revert(old_size - iov_iter_count());\n\nIf iov_iter_revert() is done base on the initial size as above, and the\niter is truncated and not reexpanded in the middle, it miscalculates\nborders causing problems. This trace is due to no one reexpanding after\ngeneric_write_checks().\n\nNow iters store how many bytes has been truncated, so reexpand them to\nthe initial state right before reverting.\n\nCc: stable@vger.kernel.org\nReported-by: Palash Oswal \nReported-by: Sudip Mukherjee \nReported-and-tested-by: syzbot+9671693590ef5aad8953@syzkaller.appspotmail.com\nSigned-off-by: Pavel Begunkov \nSigned-off-by: Al Viro ", "target": 0, "func": "static int io_read(struct io_kiocb *req, unsigned int issue_flags)\n{\n\tstruct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;\n\tstruct kiocb *kiocb = &req->rw.kiocb;\n\tstruct iov_iter __iter, *iter = &__iter;\n\tstruct io_async_rw *rw = req->async_data;\n\tssize_t io_size, ret, ret2;\n\tbool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;\n\n\tif (rw) {\n\t\titer = &rw->iter;\n\t\tiovec = NULL;\n\t} else {\n\t\tret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t}\n\tio_size = iov_iter_count(iter);\n\treq->result = io_size;\n\n\t/* Ensure we clear previously set non-block flag */\n\tif (!force_nonblock)\n\t\tkiocb->ki_flags &= ~IOCB_NOWAIT;\n\telse\n\t\tkiocb->ki_flags |= IOCB_NOWAIT;\n\n\t/* If the file doesn't support async, just async punt */\n\tif (force_nonblock && !io_file_supports_async(req, READ)) {\n\t\tret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);\n\t\treturn ret ?: -EAGAIN;\n\t}\n\n\tret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);\n\tif (unlikely(ret)) {\n\t\tkfree(iovec);\n\t\treturn ret;\n\t}\n\n\tret = io_iter_do_read(req, iter);\n\n\tif (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {\n\t\treq->flags &= ~REQ_F_REISSUE;\n\t\t/* IOPOLL retry should happen for io-wq threads */\n\t\tif (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))\n\t\t\tgoto done;\n\t\t/* no retry on NONBLOCK nor RWF_NOWAIT */\n\t\tif (req->flags & REQ_F_NOWAIT)\n\t\t\tgoto done;\n\t\t/* some cases will consume bytes even on error returns */\n\t\tiov_iter_reexpand(iter, iter->count + iter->truncated);\n\t\tiov_iter_revert(iter, io_size - iov_iter_count(iter));\n\t\tret = 0;\n\t} else if (ret == -EIOCBQUEUED) {\n\t\tgoto out_free;\n\t} else if (ret <= 0 || ret == io_size || !force_nonblock ||\n\t\t   (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {\n\t\t/* read all, failed, already did sync or don't want to retry */\n\t\tgoto done;\n\t}\n\n\tret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);\n\tif (ret2)\n\t\treturn ret2;\n\n\tiovec = NULL;\n\trw = req->async_data;\n\t/* now use our persistent iterator, if we aren't already */\n\titer = &rw->iter;\n\n\tdo {\n\t\tio_size -= ret;\n\t\trw->bytes_done += ret;\n\t\t/* if we can retry, do so with the callbacks armed */\n\t\tif (!io_rw_should_retry(req)) {\n\t\t\tkiocb->ki_flags &= ~IOCB_WAITQ;\n\t\t\treturn -EAGAIN;\n\t\t}\n\n\t\t/*\n\t\t * Now retry read with the IOCB_WAITQ parts set in the iocb. If\n\t\t * we get -EIOCBQUEUED, then we'll get a notification when the\n\t\t * desired page gets unlocked. We can also get a partial read\n\t\t * here, and if we do, then just retry at the new offset.\n\t\t */\n\t\tret = io_iter_do_read(req, iter);\n\t\tif (ret == -EIOCBQUEUED)\n\t\t\treturn 0;\n\t\t/* we got some bytes, but not all. retry. */\n\t\tkiocb->ki_flags &= ~IOCB_WAITQ;\n\t} while (ret > 0 && ret < io_size);\ndone:\n\tkiocb_done(kiocb, ret, issue_flags);\nout_free:\n\t/* it's faster to check here then delegate to kfree */\n\tif (iovec)\n\t\tkfree(iovec);\n\treturn 0;\n}", "func_hash": 272064897155914887448820335994410236838, "file_name": "io_uring.c", "file_hash": 29368837531971764003549686425861293292, "cwe": ["CWE-125"], "cve": "CVE-2022-1508", "cve_desc": "An out-of-bounds read flaw was found in the Linux kernel\u2019s io_uring module in the way a user triggers the io_read() function with some special parameters. This flaw allows a local user to read some memory out of bounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1508"}
{"idx": 210520, "project": "vim", "commit_id": "8eba2bd291b347e3008aa9e565652d51ad638cfa", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa", "commit_message": "patch 8.2.5151: reading beyond the end of the line with lisp indenting\n\nProblem:    Reading beyond the end of the line with lisp indenting.\nSolution:   Avoid going over the NUL at the end of the line.", "target": 1, "func": "get_lisp_indent(void)\n{\n    pos_T\t*pos, realpos, paren;\n    int\t\tamount;\n    char_u\t*that;\n    colnr_T\tcol;\n    colnr_T\tfirsttry;\n    int\t\tparencount, quotecount;\n    int\t\tvi_lisp;\n\n    // Set vi_lisp to use the vi-compatible method\n    vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);\n\n    realpos = curwin->w_cursor;\n    curwin->w_cursor.col = 0;\n\n    if ((pos = findmatch(NULL, '(')) == NULL)\n\tpos = findmatch(NULL, '[');\n    else\n    {\n\tparen = *pos;\n\tpos = findmatch(NULL, '[');\n\tif (pos == NULL || LT_POSP(pos, &paren))\n\t    pos = &paren;\n    }\n    if (pos != NULL)\n    {\n\t// Extra trick: Take the indent of the first previous non-white\n\t// line that is at the same () level.\n\tamount = -1;\n\tparencount = 0;\n\n\twhile (--curwin->w_cursor.lnum >= pos->lnum)\n\t{\n\t    if (linewhite(curwin->w_cursor.lnum))\n\t\tcontinue;\n\t    for (that = ml_get_curline(); *that != NUL; ++that)\n\t    {\n\t\tif (*that == ';')\n\t\t{\n\t\t    while (*(that + 1) != NUL)\n\t\t\t++that;\n\t\t    continue;\n\t\t}\n\t\tif (*that == '\\\\')\n\t\t{\n\t\t    if (*(that + 1) != NUL)\n\t\t\t++that;\n\t\t    continue;\n\t\t}\n\t\tif (*that == '\"' && *(that + 1) != NUL)\n\t\t{\n\t\t    while (*++that && *that != '\"')\n\t\t    {\n\t\t\t// skipping escaped characters in the string\n\t\t\tif (*that == '\\\\')\n\t\t\t{\n\t\t\t    if (*++that == NUL)\n\t\t\t\tbreak;\n\t\t\t    if (that[1] == NUL)\n\t\t\t    {\n\t\t\t\t++that;\n\t\t\t\tbreak;\n\t\t\t    }\n\t\t\t}\n\t\t    }\n\t\t    if (*that == NUL)\n\t\t\tbreak;\n\t\t}\n\t\tif (*that == '(' || *that == '[')\n\t\t    ++parencount;\n\t\telse if (*that == ')' || *that == ']')\n\t\t    --parencount;\n\t    }\n\t    if (parencount == 0)\n\t    {\n\t\tamount = get_indent();\n\t\tbreak;\n\t    }\n\t}\n\n\tif (amount == -1)\n\t{\n\t    curwin->w_cursor.lnum = pos->lnum;\n\t    curwin->w_cursor.col = pos->col;\n\t    col = pos->col;\n\n\t    that = ml_get_curline();\n\n\t    if (vi_lisp && get_indent() == 0)\n\t\tamount = 2;\n\t    else\n\t    {\n\t\tchar_u *line = that;\n\n\t\tamount = 0;\n\t\twhile (*that && col)\n\t\t{\n\t\t    amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount);\n\t\t    col--;\n\t\t}\n\n\t\t// Some keywords require \"body\" indenting rules (the\n\t\t// non-standard-lisp ones are Scheme special forms):\n\t\t//\n\t\t// (let ((a 1))    instead    (let ((a 1))\n\t\t//   (...))\t      of\t   (...))\n\n\t\tif (!vi_lisp && (*that == '(' || *that == '[')\n\t\t\t\t\t\t      && lisp_match(that + 1))\n\t\t    amount += 2;\n\t\telse\n\t\t{\n\t\t    that++;\n\t\t    amount++;\n\t\t    firsttry = amount;\n\n\t\t    while (VIM_ISWHITE(*that))\n\t\t    {\n\t\t\tamount += lbr_chartabsize(line, that, (colnr_T)amount);\n\t\t\t++that;\n\t\t    }\n\n\t\t    if (*that && *that != ';') // not a comment line\n\t\t    {\n\t\t\t// test *that != '(' to accommodate first let/do\n\t\t\t// argument if it is more than one line\n\t\t\tif (!vi_lisp && *that != '(' && *that != '[')\n\t\t\t    firsttry++;\n\n\t\t\tparencount = 0;\n\t\t\tquotecount = 0;\n\n\t\t\tif (vi_lisp\n\t\t\t\t|| (*that != '\"'\n\t\t\t\t    && *that != '\\''\n\t\t\t\t    && *that != '#'\n\t\t\t\t    && (*that < '0' || *that > '9')))\n\t\t\t{\n\t\t\t    while (*that\n\t\t\t\t    && (!VIM_ISWHITE(*that)\n\t\t\t\t\t|| quotecount\n\t\t\t\t\t|| parencount)\n\t\t\t\t    && (!((*that == '(' || *that == '[')\n\t\t\t\t\t    && !quotecount\n\t\t\t\t\t    && !parencount\n\t\t\t\t\t    && vi_lisp)))\n\t\t\t    {\n\t\t\t\tif (*that == '\"')\n\t\t\t\t    quotecount = !quotecount;\n\t\t\t\tif ((*that == '(' || *that == '[')\n\t\t\t\t\t\t\t       && !quotecount)\n\t\t\t\t    ++parencount;\n\t\t\t\tif ((*that == ')' || *that == ']')\n\t\t\t\t\t\t\t       && !quotecount)\n\t\t\t\t    --parencount;\n\t\t\t\tif (*that == '\\\\' && *(that+1) != NUL)\n\t\t\t\t    amount += lbr_chartabsize_adv(\n\t\t\t\t\t\tline, &that, (colnr_T)amount);\n\t\t\t\tamount += lbr_chartabsize_adv(\n\t\t\t\t\t\tline, &that, (colnr_T)amount);\n\t\t\t    }\n\t\t\t}\n\t\t\twhile (VIM_ISWHITE(*that))\n\t\t\t{\n\t\t\t    amount += lbr_chartabsize(\n\t\t\t\t\t\t line, that, (colnr_T)amount);\n\t\t\t    that++;\n\t\t\t}\n\t\t\tif (!*that || *that == ';')\n\t\t\t    amount = firsttry;\n\t\t    }\n\t\t}\n\t    }\n\t}\n    }\n    else\n\tamount = 0;\t// no matching '(' or '[' found, use zero indent\n\n    curwin->w_cursor = realpos;\n\n    return amount;\n}", "func_hash": 285577847836020601306828905018553438405, "file_name": "indent.c", "file_hash": 245226379140826048087051552287940041760, "cwe": ["CWE-125"], "cve": "CVE-2022-2183", "cve_desc": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2183"}
{"idx": 436990, "project": "vim", "commit_id": "8eba2bd291b347e3008aa9e565652d51ad638cfa", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa", "commit_message": "patch 8.2.5151: reading beyond the end of the line with lisp indenting\n\nProblem:    Reading beyond the end of the line with lisp indenting.\nSolution:   Avoid going over the NUL at the end of the line.", "target": 0, "func": "get_lisp_indent(void)\n{\n    pos_T\t*pos, realpos, paren;\n    int\t\tamount;\n    char_u\t*that;\n    colnr_T\tcol;\n    colnr_T\tfirsttry;\n    int\t\tparencount, quotecount;\n    int\t\tvi_lisp;\n\n    // Set vi_lisp to use the vi-compatible method\n    vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);\n\n    realpos = curwin->w_cursor;\n    curwin->w_cursor.col = 0;\n\n    if ((pos = findmatch(NULL, '(')) == NULL)\n\tpos = findmatch(NULL, '[');\n    else\n    {\n\tparen = *pos;\n\tpos = findmatch(NULL, '[');\n\tif (pos == NULL || LT_POSP(pos, &paren))\n\t    pos = &paren;\n    }\n    if (pos != NULL)\n    {\n\t// Extra trick: Take the indent of the first previous non-white\n\t// line that is at the same () level.\n\tamount = -1;\n\tparencount = 0;\n\n\twhile (--curwin->w_cursor.lnum >= pos->lnum)\n\t{\n\t    if (linewhite(curwin->w_cursor.lnum))\n\t\tcontinue;\n\t    for (that = ml_get_curline(); *that != NUL; ++that)\n\t    {\n\t\tif (*that == ';')\n\t\t{\n\t\t    while (*(that + 1) != NUL)\n\t\t\t++that;\n\t\t    continue;\n\t\t}\n\t\tif (*that == '\\\\')\n\t\t{\n\t\t    if (*(that + 1) != NUL)\n\t\t\t++that;\n\t\t    continue;\n\t\t}\n\t\tif (*that == '\"' && *(that + 1) != NUL)\n\t\t{\n\t\t    while (*++that && *that != '\"')\n\t\t    {\n\t\t\t// skipping escaped characters in the string\n\t\t\tif (*that == '\\\\')\n\t\t\t{\n\t\t\t    if (*++that == NUL)\n\t\t\t\tbreak;\n\t\t\t    if (that[1] == NUL)\n\t\t\t    {\n\t\t\t\t++that;\n\t\t\t\tbreak;\n\t\t\t    }\n\t\t\t}\n\t\t    }\n\t\t    if (*that == NUL)\n\t\t\tbreak;\n\t\t}\n\t\tif (*that == '(' || *that == '[')\n\t\t    ++parencount;\n\t\telse if (*that == ')' || *that == ']')\n\t\t    --parencount;\n\t    }\n\t    if (parencount == 0)\n\t    {\n\t\tamount = get_indent();\n\t\tbreak;\n\t    }\n\t}\n\n\tif (amount == -1)\n\t{\n\t    curwin->w_cursor.lnum = pos->lnum;\n\t    curwin->w_cursor.col = pos->col;\n\t    col = pos->col;\n\n\t    that = ml_get_curline();\n\n\t    if (vi_lisp && get_indent() == 0)\n\t\tamount = 2;\n\t    else\n\t    {\n\t\tchar_u *line = that;\n\n\t\tamount = 0;\n\t\twhile (*that && col)\n\t\t{\n\t\t    amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount);\n\t\t    col--;\n\t\t}\n\n\t\t// Some keywords require \"body\" indenting rules (the\n\t\t// non-standard-lisp ones are Scheme special forms):\n\t\t//\n\t\t// (let ((a 1))    instead    (let ((a 1))\n\t\t//   (...))\t      of\t   (...))\n\n\t\tif (!vi_lisp && (*that == '(' || *that == '[')\n\t\t\t\t\t\t      && lisp_match(that + 1))\n\t\t    amount += 2;\n\t\telse\n\t\t{\n\t\t    if (*that != NUL)\n\t\t    {\n\t\t\tthat++;\n\t\t\tamount++;\n\t\t    }\n\t\t    firsttry = amount;\n\n\t\t    while (VIM_ISWHITE(*that))\n\t\t    {\n\t\t\tamount += lbr_chartabsize(line, that, (colnr_T)amount);\n\t\t\t++that;\n\t\t    }\n\n\t\t    if (*that && *that != ';') // not a comment line\n\t\t    {\n\t\t\t// test *that != '(' to accommodate first let/do\n\t\t\t// argument if it is more than one line\n\t\t\tif (!vi_lisp && *that != '(' && *that != '[')\n\t\t\t    firsttry++;\n\n\t\t\tparencount = 0;\n\t\t\tquotecount = 0;\n\n\t\t\tif (vi_lisp\n\t\t\t\t|| (*that != '\"'\n\t\t\t\t    && *that != '\\''\n\t\t\t\t    && *that != '#'\n\t\t\t\t    && (*that < '0' || *that > '9')))\n\t\t\t{\n\t\t\t    while (*that\n\t\t\t\t    && (!VIM_ISWHITE(*that)\n\t\t\t\t\t|| quotecount\n\t\t\t\t\t|| parencount)\n\t\t\t\t    && (!((*that == '(' || *that == '[')\n\t\t\t\t\t    && !quotecount\n\t\t\t\t\t    && !parencount\n\t\t\t\t\t    && vi_lisp)))\n\t\t\t    {\n\t\t\t\tif (*that == '\"')\n\t\t\t\t    quotecount = !quotecount;\n\t\t\t\tif ((*that == '(' || *that == '[')\n\t\t\t\t\t\t\t       && !quotecount)\n\t\t\t\t    ++parencount;\n\t\t\t\tif ((*that == ')' || *that == ']')\n\t\t\t\t\t\t\t       && !quotecount)\n\t\t\t\t    --parencount;\n\t\t\t\tif (*that == '\\\\' && *(that+1) != NUL)\n\t\t\t\t    amount += lbr_chartabsize_adv(\n\t\t\t\t\t\tline, &that, (colnr_T)amount);\n\t\t\t\tamount += lbr_chartabsize_adv(\n\t\t\t\t\t\tline, &that, (colnr_T)amount);\n\t\t\t    }\n\t\t\t}\n\t\t\twhile (VIM_ISWHITE(*that))\n\t\t\t{\n\t\t\t    amount += lbr_chartabsize(\n\t\t\t\t\t\t line, that, (colnr_T)amount);\n\t\t\t    that++;\n\t\t\t}\n\t\t\tif (!*that || *that == ';')\n\t\t\t    amount = firsttry;\n\t\t    }\n\t\t}\n\t    }\n\t}\n    }\n    else\n\tamount = 0;\t// no matching '(' or '[' found, use zero indent\n\n    curwin->w_cursor = realpos;\n\n    return amount;\n}", "func_hash": 309369228494831536830069160339652260754, "file_name": "indent.c", "file_hash": 124492176625563887995731103684583862461, "cwe": ["CWE-125"], "cve": "CVE-2022-2183", "cve_desc": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2183"}
{"idx": 210527, "project": "linux", "commit_id": "04c9b00ba83594a29813d6b1fb8fdc93a3915174", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/04c9b00ba83594a29813d6b1fb8fdc93a3915174", "commit_message": "can: mcba_usb: mcba_usb_start_xmit(): fix double dev_kfree_skb in error path\n\nThere is no need to call dev_kfree_skb() when usb_submit_urb() fails\nbecause can_put_echo_skb() deletes original skb and\ncan_free_echo_skb() deletes the cloned skb.\n\nFixes: 51f3baad7de9 (\"can: mcba_usb: Add support for Microchip CAN BUS Analyzer\")\nLink: https://lore.kernel.org/all/20220311080208.45047-1-hbh25y@gmail.com\nSigned-off-by: Hangyu Hua \nSigned-off-by: Marc Kleine-Budde ", "target": 1, "func": "static netdev_tx_t mcba_usb_start_xmit(struct sk_buff *skb,\n\t\t\t\t       struct net_device *netdev)\n{\n\tstruct mcba_priv *priv = netdev_priv(netdev);\n\tstruct can_frame *cf = (struct can_frame *)skb->data;\n\tstruct mcba_usb_ctx *ctx = NULL;\n\tstruct net_device_stats *stats = &priv->netdev->stats;\n\tu16 sid;\n\tint err;\n\tstruct mcba_usb_msg_can usb_msg = {\n\t\t.cmd_id = MBCA_CMD_TRANSMIT_MESSAGE_EV\n\t};\n\n\tif (can_dropped_invalid_skb(netdev, skb))\n\t\treturn NETDEV_TX_OK;\n\n\tctx = mcba_usb_get_free_ctx(priv, cf);\n\tif (!ctx)\n\t\treturn NETDEV_TX_BUSY;\n\n\tif (cf->can_id & CAN_EFF_FLAG) {\n\t\t/* SIDH    | SIDL                 | EIDH   | EIDL\n\t\t * 28 - 21 | 20 19 18 x x x 17 16 | 15 - 8 | 7 - 0\n\t\t */\n\t\tsid = MCBA_SIDL_EXID_MASK;\n\t\t/* store 28-18 bits */\n\t\tsid |= (cf->can_id & 0x1ffc0000) >> 13;\n\t\t/* store 17-16 bits */\n\t\tsid |= (cf->can_id & 0x30000) >> 16;\n\t\tput_unaligned_be16(sid, &usb_msg.sid);\n\n\t\t/* store 15-0 bits */\n\t\tput_unaligned_be16(cf->can_id & 0xffff, &usb_msg.eid);\n\t} else {\n\t\t/* SIDH   | SIDL\n\t\t * 10 - 3 | 2 1 0 x x x x x\n\t\t */\n\t\tput_unaligned_be16((cf->can_id & CAN_SFF_MASK) << 5,\n\t\t\t\t   &usb_msg.sid);\n\t\tusb_msg.eid = 0;\n\t}\n\n\tusb_msg.dlc = cf->len;\n\n\tmemcpy(usb_msg.data, cf->data, usb_msg.dlc);\n\n\tif (cf->can_id & CAN_RTR_FLAG)\n\t\tusb_msg.dlc |= MCBA_DLC_RTR_MASK;\n\n\tcan_put_echo_skb(skb, priv->netdev, ctx->ndx, 0);\n\n\terr = mcba_usb_xmit(priv, (struct mcba_usb_msg *)&usb_msg, ctx);\n\tif (err)\n\t\tgoto xmit_failed;\n\n\treturn NETDEV_TX_OK;\n\nxmit_failed:\n\tcan_free_echo_skb(priv->netdev, ctx->ndx, NULL);\n\tmcba_usb_free_ctx(ctx);\n\tdev_kfree_skb(skb);\n\tstats->tx_dropped++;\n\n\treturn NETDEV_TX_OK;\n}", "func_hash": 172735624364172829210994016303529848569, "file_name": "mcba_usb.c", "file_hash": 40788166885165937548034053241977805267, "cwe": ["CWE-415"], "cve": "CVE-2022-28389", "cve_desc": "mcba_usb_start_xmit in drivers/net/can/usb/mcba_usb.c in the Linux kernel through 5.17.1 has a double free.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-28389"}
{"idx": 437003, "project": "linux", "commit_id": "04c9b00ba83594a29813d6b1fb8fdc93a3915174", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/04c9b00ba83594a29813d6b1fb8fdc93a3915174", "commit_message": "can: mcba_usb: mcba_usb_start_xmit(): fix double dev_kfree_skb in error path\n\nThere is no need to call dev_kfree_skb() when usb_submit_urb() fails\nbecause can_put_echo_skb() deletes original skb and\ncan_free_echo_skb() deletes the cloned skb.\n\nFixes: 51f3baad7de9 (\"can: mcba_usb: Add support for Microchip CAN BUS Analyzer\")\nLink: https://lore.kernel.org/all/20220311080208.45047-1-hbh25y@gmail.com\nSigned-off-by: Hangyu Hua \nSigned-off-by: Marc Kleine-Budde ", "target": 0, "func": "static netdev_tx_t mcba_usb_start_xmit(struct sk_buff *skb,\n\t\t\t\t       struct net_device *netdev)\n{\n\tstruct mcba_priv *priv = netdev_priv(netdev);\n\tstruct can_frame *cf = (struct can_frame *)skb->data;\n\tstruct mcba_usb_ctx *ctx = NULL;\n\tstruct net_device_stats *stats = &priv->netdev->stats;\n\tu16 sid;\n\tint err;\n\tstruct mcba_usb_msg_can usb_msg = {\n\t\t.cmd_id = MBCA_CMD_TRANSMIT_MESSAGE_EV\n\t};\n\n\tif (can_dropped_invalid_skb(netdev, skb))\n\t\treturn NETDEV_TX_OK;\n\n\tctx = mcba_usb_get_free_ctx(priv, cf);\n\tif (!ctx)\n\t\treturn NETDEV_TX_BUSY;\n\n\tif (cf->can_id & CAN_EFF_FLAG) {\n\t\t/* SIDH    | SIDL                 | EIDH   | EIDL\n\t\t * 28 - 21 | 20 19 18 x x x 17 16 | 15 - 8 | 7 - 0\n\t\t */\n\t\tsid = MCBA_SIDL_EXID_MASK;\n\t\t/* store 28-18 bits */\n\t\tsid |= (cf->can_id & 0x1ffc0000) >> 13;\n\t\t/* store 17-16 bits */\n\t\tsid |= (cf->can_id & 0x30000) >> 16;\n\t\tput_unaligned_be16(sid, &usb_msg.sid);\n\n\t\t/* store 15-0 bits */\n\t\tput_unaligned_be16(cf->can_id & 0xffff, &usb_msg.eid);\n\t} else {\n\t\t/* SIDH   | SIDL\n\t\t * 10 - 3 | 2 1 0 x x x x x\n\t\t */\n\t\tput_unaligned_be16((cf->can_id & CAN_SFF_MASK) << 5,\n\t\t\t\t   &usb_msg.sid);\n\t\tusb_msg.eid = 0;\n\t}\n\n\tusb_msg.dlc = cf->len;\n\n\tmemcpy(usb_msg.data, cf->data, usb_msg.dlc);\n\n\tif (cf->can_id & CAN_RTR_FLAG)\n\t\tusb_msg.dlc |= MCBA_DLC_RTR_MASK;\n\n\tcan_put_echo_skb(skb, priv->netdev, ctx->ndx, 0);\n\n\terr = mcba_usb_xmit(priv, (struct mcba_usb_msg *)&usb_msg, ctx);\n\tif (err)\n\t\tgoto xmit_failed;\n\n\treturn NETDEV_TX_OK;\n\nxmit_failed:\n\tcan_free_echo_skb(priv->netdev, ctx->ndx, NULL);\n\tmcba_usb_free_ctx(ctx);\n\tstats->tx_dropped++;\n\n\treturn NETDEV_TX_OK;\n}", "func_hash": 258268247542541544374716457033829849164, "file_name": "mcba_usb.c", "file_hash": 278357705682492618477693192859299956324, "cwe": ["CWE-415"], "cve": "CVE-2022-28389", "cve_desc": "mcba_usb_start_xmit in drivers/net/can/usb/mcba_usb.c in the Linux kernel through 5.17.1 has a double free.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-28389"}
{"idx": 210551, "project": "oniguruma", "commit_id": "4d461376bd85e7994835677b2ff453a43c49cd28", "project_url": "https://github.com/kkos/oniguruma", "commit_url": "https://github.com/kkos/oniguruma/commit/4d461376bd85e7994835677b2ff453a43c49cd28", "commit_message": "don't expand string case folds to alternatives if code length == 1 and byte length is same", "target": 1, "func": "expand_case_fold_string(Node* node, regex_t* reg)\n{\n#define THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION  8\n\n  int r, n, len, alt_num;\n  UChar *start, *end, *p;\n  Node *top_root, *root, *snode, *prev_node;\n  OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM];\n  StrNode* sn = STR_(node);\n\n  if (NODE_STRING_IS_AMBIG(node)) return 0;\n\n  start = sn->s;\n  end   = sn->end;\n  if (start >= end) return 0;\n\n  r = 0;\n  top_root = root = prev_node = snode = NULL_NODE;\n  alt_num = 1;\n  p = start;\n  while (p < end) {\n    n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(reg->enc, reg->case_fold_flag, p, end,\n                                           items);\n    if (n < 0) {\n      r = n;\n      goto err;\n    }\n\n    len = enclen(reg->enc, p);\n\n    if (n == 0) {\n      if (IS_NULL(snode)) {\n        if (IS_NULL(root) && IS_NOT_NULL(prev_node)) {\n          top_root = root = onig_node_list_add(NULL_NODE, prev_node);\n          if (IS_NULL(root)) {\n            onig_node_free(prev_node);\n            goto mem_err;\n          }\n        }\n\n        prev_node = snode = onig_node_new_str(NULL, NULL);\n        if (IS_NULL(snode)) goto mem_err;\n        if (IS_NOT_NULL(root)) {\n          if (IS_NULL(onig_node_list_add(root, snode))) {\n            onig_node_free(snode);\n            goto mem_err;\n          }\n        }\n      }\n\n      r = onig_node_str_cat(snode, p, p + len);\n      if (r != 0) goto err;\n    }\n    else {\n      alt_num *= (n + 1);\n      if (alt_num > THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION) break;\n\n      if (IS_NULL(root) && IS_NOT_NULL(prev_node)) {\n        top_root = root = onig_node_list_add(NULL_NODE, prev_node);\n        if (IS_NULL(root)) {\n          onig_node_free(prev_node);\n          goto mem_err;\n        }\n      }\n\n      r = expand_case_fold_string_alt(n, items, p, len, end, reg, &prev_node);\n      if (r < 0) goto mem_err;\n      if (r == 1) {\n        if (IS_NULL(root)) {\n          top_root = prev_node;\n        }\n        else {\n          if (IS_NULL(onig_node_list_add(root, prev_node))) {\n            onig_node_free(prev_node);\n            goto mem_err;\n          }\n        }\n\n        root = NODE_CAR(prev_node);\n      }\n      else { /* r == 0 */\n        if (IS_NOT_NULL(root)) {\n          if (IS_NULL(onig_node_list_add(root, prev_node))) {\n            onig_node_free(prev_node);\n            goto mem_err;\n          }\n        }\n      }\n\n      snode = NULL_NODE;\n    }\n\n    p += len;\n  }\n\n  if (p < end) {\n    Node *srem;\n\n    r = expand_case_fold_make_rem_string(&srem, p, end, reg);\n    if (r != 0) goto mem_err;\n\n    if (IS_NOT_NULL(prev_node) && IS_NULL(root)) {\n      top_root = root = onig_node_list_add(NULL_NODE, prev_node);\n      if (IS_NULL(root)) {\n        onig_node_free(srem);\n        onig_node_free(prev_node);\n        goto mem_err;\n      }\n    }\n\n    if (IS_NULL(root)) {\n      prev_node = srem;\n    }\n    else {\n      if (IS_NULL(onig_node_list_add(root, srem))) {\n        onig_node_free(srem);\n        goto mem_err;\n      }\n    }\n  }\n\n  /* ending */\n  top_root = (IS_NOT_NULL(top_root) ? top_root : prev_node);\n  swap_node(node, top_root);\n  onig_node_free(top_root);\n  return 0;\n\n mem_err:\n  r = ONIGERR_MEMORY;\n\n err:\n  onig_node_free(top_root);\n  return r;\n}", "func_hash": 183402285676240178400514858197717953400, "file_name": "regcomp.c", "file_hash": 30592731921158278474590718116243340454, "cwe": ["CWE-125"], "cve": "CVE-2019-19246", "cve_desc": "Oniguruma through 6.9.3, as used in PHP 7.3.x and other products, has a heap-based buffer over-read in str_lower_case_match in regexec.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19246"}
{"idx": 437291, "project": "oniguruma", "commit_id": "4d461376bd85e7994835677b2ff453a43c49cd28", "project_url": "https://github.com/kkos/oniguruma", "commit_url": "https://github.com/kkos/oniguruma/commit/4d461376bd85e7994835677b2ff453a43c49cd28", "commit_message": "don't expand string case folds to alternatives if code length == 1 and byte length is same", "target": 0, "func": "expand_case_fold_string(Node* node, regex_t* reg)\n{\n#define THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION  8\n\n  int r, n, len, alt_num;\n  int is_ambig, fold_len;\n  UChar *start, *end, *p;\n  UChar* foldp;\n  Node *top_root, *root, *snode, *prev_node;\n  OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM];\n  UChar buf[ONIGENC_MBC_CASE_FOLD_MAXLEN];\n  StrNode* sn = STR_(node);\n\n  if (NODE_STRING_IS_AMBIG(node)) return 0;\n\n  start = sn->s;\n  end   = sn->end;\n  if (start >= end) return 0;\n\n  r = 0;\n  top_root = root = prev_node = snode = NULL_NODE;\n  alt_num = 1;\n  p = start;\n  while (p < end) {\n    n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(reg->enc, reg->case_fold_flag,\n                                           p, end, items);\n    if (n < 0) {\n      r = n;\n      goto err;\n    }\n\n    len = enclen(reg->enc, p);\n\n    if (n == 0 || IS_NOT_NULL(snode) ||\n        is_good_case_fold_items_for_search(reg->enc, len, n, items)) {\n      if (IS_NULL(snode)) {\n        if (IS_NULL(root) && IS_NOT_NULL(prev_node)) {\n          top_root = root = onig_node_list_add(NULL_NODE, prev_node);\n          if (IS_NULL(root)) {\n            onig_node_free(prev_node);\n            goto mem_err;\n          }\n        }\n\n        prev_node = snode = onig_node_new_str(NULL, NULL);\n        if (IS_NULL(snode)) goto mem_err;\n        if (IS_NOT_NULL(root)) {\n          if (IS_NULL(onig_node_list_add(root, snode))) {\n            onig_node_free(snode);\n            goto mem_err;\n          }\n        }\n\n        is_ambig = -1; /* -1: new */\n      }\n      else {\n        is_ambig = NODE_STRING_IS_AMBIG(snode);\n      }\n\n      if (n != 0) {\n        foldp = p;\n        fold_len = ONIGENC_MBC_CASE_FOLD(reg->enc, reg->case_fold_flag,\n                                         &foldp, end, buf);\n        foldp = buf;\n      }\n      else {\n        foldp = p; fold_len = len;\n      }\n\n      if ((n != 0 && is_ambig == 0) || (n == 0 && is_ambig > 0)) {\n        if (IS_NULL(root) /* && IS_NOT_NULL(prev_node) */) {\n          top_root = root = onig_node_list_add(NULL_NODE, prev_node);\n          if (IS_NULL(root)) {\n            onig_node_free(prev_node);\n            goto mem_err;\n          }\n        }\n\n        prev_node = snode = onig_node_new_str(foldp, foldp + fold_len);\n        if (IS_NULL(snode)) goto mem_err;\n        if (IS_NULL(onig_node_list_add(root, snode))) {\n          onig_node_free(snode);\n          goto mem_err;\n        }\n      }\n      else {\n        r = onig_node_str_cat(snode, foldp, foldp + fold_len);\n        if (r != 0) goto err;\n      }\n\n      if (n != 0) NODE_STRING_SET_AMBIG(snode);\n    }\n    else {\n      alt_num *= (n + 1);\n      if (alt_num > THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION) break;\n\n      if (IS_NULL(root) && IS_NOT_NULL(prev_node)) {\n        top_root = root = onig_node_list_add(NULL_NODE, prev_node);\n        if (IS_NULL(root)) {\n          onig_node_free(prev_node);\n          goto mem_err;\n        }\n      }\n\n      r = expand_case_fold_string_alt(n, items, p, len, end, reg, &prev_node);\n      if (r < 0) goto mem_err;\n      if (r == 1) {\n        if (IS_NULL(root)) {\n          top_root = prev_node;\n        }\n        else {\n          if (IS_NULL(onig_node_list_add(root, prev_node))) {\n            onig_node_free(prev_node);\n            goto mem_err;\n          }\n        }\n\n        root = NODE_CAR(prev_node);\n      }\n      else { /* r == 0 */\n        if (IS_NOT_NULL(root)) {\n          if (IS_NULL(onig_node_list_add(root, prev_node))) {\n            onig_node_free(prev_node);\n            goto mem_err;\n          }\n        }\n      }\n\n      snode = NULL_NODE;\n    }\n\n    p += len;\n  }\n\n  if (p < end) {\n    Node *srem;\n\n    r = expand_case_fold_make_rem_string(&srem, p, end, reg);\n    if (r != 0) goto mem_err;\n\n    if (IS_NOT_NULL(prev_node) && IS_NULL(root)) {\n      top_root = root = onig_node_list_add(NULL_NODE, prev_node);\n      if (IS_NULL(root)) {\n        onig_node_free(srem);\n        onig_node_free(prev_node);\n        goto mem_err;\n      }\n    }\n\n    if (IS_NULL(root)) {\n      prev_node = srem;\n    }\n    else {\n      if (IS_NULL(onig_node_list_add(root, srem))) {\n        onig_node_free(srem);\n        goto mem_err;\n      }\n    }\n  }\n\n  /* ending */\n  top_root = (IS_NOT_NULL(top_root) ? top_root : prev_node);\n  swap_node(node, top_root);\n  onig_node_free(top_root);\n  return 0;\n\n mem_err:\n  r = ONIGERR_MEMORY;\n\n err:\n  onig_node_free(top_root);\n  return r;\n}", "func_hash": 98258741045227921109976574238500358148, "file_name": "regcomp.c", "file_hash": 65059023969392718812527129333061905098, "cwe": ["CWE-125"], "cve": "CVE-2019-19246", "cve_desc": "Oniguruma through 6.9.3, as used in PHP 7.3.x and other products, has a heap-based buffer over-read in str_lower_case_match in regexec.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19246"}
{"idx": 210570, "project": "radare2", "commit_id": "d4ce40b516ffd70cf2e9e36832d8de139117d522", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/d4ce40b516ffd70cf2e9e36832d8de139117d522", "commit_message": "Fix oobread in symbols header parsing ##bin", "target": 1, "func": "static RCoreSymCacheElement *parseDragons(RBinFile *bf, RBuffer *buf, int off, int bits, R_OWN char *file_name) {\n\tD eprintf (\"Dragons at 0x%x\\n\", off);\n\tut64 size = r_buf_size (buf);\n\tif (off >= size) {\n\t\treturn NULL;\n\t}\n\tsize -= off;\n\tif (!size) {\n\t\treturn NULL;\n\t}\n\tut8 *b = malloc (size);\n\tif (!b) {\n\t\treturn NULL;\n\t}\n\tint available = r_buf_read_at (buf, off, b, size);\n\tif (available != size) {\n\t\teprintf (\"Warning: r_buf_read_at failed\\n\");\n\t\treturn NULL;\n\t}\n#if 0\n\t// after the list of sections, there's a bunch of unknown\n\t// data, brobably dwords, and then the same section list again\n\t// this function aims to parse it.\n\t0x00000138 |1a2b b2a1 0300 0000 1a2b b2a1 e055 0000| .+.......+...U..\n                         n_segments ----.          .--- how many sections ?\n\t0x00000148 |0100 0000 ca55 0000 0400 0000 1800 0000| .....U..........\n\t             .---- how many symbols? 0xc7\n\t0x00000158 |c700 0000 0000 0000 0000 0000 0104 0000| ................\n\t0x00000168 |250b e803 0000 0100 0000 0000 bd55 0000| %............U..\n\t0x00000178 |91bb e903 e35a b42c 93a4 340a 8746 9489| .....Z.,..4..F..\n\t0x00000188 |0cea 4c40 0c00 0000 0900 0000 0000 0000| ..L@............\n\t0x00000198 |0000 0000 0000 0000 0000 0000 0000 0000| ................\n\t0x000001a8 |0080 0000 0000 0000 5f5f 5445 5854 0000| ........__TEXT..\n\t0x000001b8 |0000 0000 0000 0000 0080 0000 0000 0000| ................\n\t0x000001c8 |0040 0000 0000 0000 5f5f 4441 5441 0000| .@......__DATA..\n\t0x000001d8 |0000 0000 0000 0000 00c0 0000 0000 0000| ................\n\t0x000001e8 |0000 0100 0000 0000 5f5f 4c4c 564d 0000| ........__LLVM..\n\t0x000001f8 |0000 0000 0000 0000 00c0 0100 0000 0000| ................\n\t0x00000208 |00c0 0000 0000 0000 5f5f 4c49 4e4b 4544| ........__LINKED\n\t0x00000218 |4954 0000 0000 0000 0000 0000 d069 0000| IT...........i..\n#endif\n\t// eprintf (\"Dragon's magic:\\n\");\n\tint magicCombo = 0;\n\tif (!memcmp (\"\\x1a\\x2b\\xb2\\xa1\", b, 4)) { // 0x130  ?\n\t\tmagicCombo++;\n\t}\n\tif (!memcmp (\"\\x1a\\x2b\\xb2\\xa1\", b + 8, 4)) {\n\t\tmagicCombo++;\n\t}\n\tif (magicCombo != 2) {\n\t\t// hack for C22F7494\n\t\tavailable = r_buf_read_at (buf, off - 8, b, size);\n\t\tif (available != size) {\n\t\t\teprintf (\"Warning: r_buf_read_at failed\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t\tif (!memcmp (\"\\x1a\\x2b\\xb2\\xa1\", b, 4)) { // 0x130  ?\n\t\t\toff -= 8;\n\t\t} else {\n\t\t\teprintf (\"0x%08x  parsing error: invalid magic retry\\n\", off);\n\t\t}\n\t}\n\tD eprintf (\"0x%08x  magic  OK\\n\", off);\n\tD {\n\t\tconst int e0ss = r_read_le32 (b + 12);\n\t\teprintf (\"0x%08x  eoss   0x%x\\n\", off + 12, e0ss);\n\t}\n\tfree (b);\n\treturn r_coresym_cache_element_new (bf, buf, off + 16, bits, file_name);\n}", "func_hash": 12354681142783714645575373162879180963, "file_name": "bin_symbols.c", "file_hash": 5185444036263415559996433677051676690, "cwe": ["CWE-787"], "cve": "CVE-2022-1061", "cve_desc": "Heap Buffer Overflow in parseDragons in GitHub repository radareorg/radare2 prior to 5.6.8.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1061"}
{"idx": 437671, "project": "radare2", "commit_id": "d4ce40b516ffd70cf2e9e36832d8de139117d522", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/d4ce40b516ffd70cf2e9e36832d8de139117d522", "commit_message": "Fix oobread in symbols header parsing ##bin", "target": 0, "func": "static RCoreSymCacheElement *parseDragons(RBinFile *bf, RBuffer *buf, int off, int bits, R_OWN char *file_name) {\n\tD eprintf (\"Dragons at 0x%x\\n\", off);\n\tst64 size = r_buf_size (buf);\n\tif (off >= size) {\n\t\treturn NULL;\n\t}\n\tsize -= off;\n\tif (!size) {\n\t\treturn NULL;\n\t}\n\tif (size < 32) {\n\t\treturn NULL;\n\t}\n\tut8 *b = malloc (size);\n\tif (!b) {\n\t\treturn NULL;\n\t}\n\tint available = r_buf_read_at (buf, off, b, size);\n\tif (available != size) {\n\t\teprintf (\"Warning: r_buf_read_at failed\\n\");\n\t\treturn NULL;\n\t}\n#if 0\n\t// after the list of sections, there's a bunch of unknown\n\t// data, brobably dwords, and then the same section list again\n\t// this function aims to parse it.\n\t0x00000138 |1a2b b2a1 0300 0000 1a2b b2a1 e055 0000| .+.......+...U..\n                         n_segments ----.          .--- how many sections ?\n\t0x00000148 |0100 0000 ca55 0000 0400 0000 1800 0000| .....U..........\n\t             .---- how many symbols? 0xc7\n\t0x00000158 |c700 0000 0000 0000 0000 0000 0104 0000| ................\n\t0x00000168 |250b e803 0000 0100 0000 0000 bd55 0000| %............U..\n\t0x00000178 |91bb e903 e35a b42c 93a4 340a 8746 9489| .....Z.,..4..F..\n\t0x00000188 |0cea 4c40 0c00 0000 0900 0000 0000 0000| ..L@............\n\t0x00000198 |0000 0000 0000 0000 0000 0000 0000 0000| ................\n\t0x000001a8 |0080 0000 0000 0000 5f5f 5445 5854 0000| ........__TEXT..\n\t0x000001b8 |0000 0000 0000 0000 0080 0000 0000 0000| ................\n\t0x000001c8 |0040 0000 0000 0000 5f5f 4441 5441 0000| .@......__DATA..\n\t0x000001d8 |0000 0000 0000 0000 00c0 0000 0000 0000| ................\n\t0x000001e8 |0000 0100 0000 0000 5f5f 4c4c 564d 0000| ........__LLVM..\n\t0x000001f8 |0000 0000 0000 0000 00c0 0100 0000 0000| ................\n\t0x00000208 |00c0 0000 0000 0000 5f5f 4c49 4e4b 4544| ........__LINKED\n\t0x00000218 |4954 0000 0000 0000 0000 0000 d069 0000| IT...........i..\n#endif\n\t// eprintf (\"Dragon's magic:\\n\");\n\tint magicCombo = 0;\n\tif (!memcmp (\"\\x1a\\x2b\\xb2\\xa1\", b, 4)) { // 0x130  ?\n\t\tmagicCombo++;\n\t}\n\tif (!memcmp (\"\\x1a\\x2b\\xb2\\xa1\", b + 8, 4)) {\n\t\tmagicCombo++;\n\t}\n\tif (magicCombo != 2) {\n\t\t// hack for C22F7494\n\t\tavailable = r_buf_read_at (buf, off - 8, b, size);\n\t\tif (available != size) {\n\t\t\teprintf (\"Warning: r_buf_read_at failed\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t\tif (!memcmp (\"\\x1a\\x2b\\xb2\\xa1\", b, 4)) { // 0x130  ?\n\t\t\toff -= 8;\n\t\t} else {\n\t\t\teprintf (\"0x%08x  parsing error: invalid magic retry\\n\", off);\n\t\t}\n\t}\n\tD eprintf (\"0x%08x  magic  OK\\n\", off);\n\tD {\n\t\tconst int e0ss = r_read_le32 (b + 12);\n\t\teprintf (\"0x%08x  eoss   0x%x\\n\", off + 12, e0ss);\n\t}\n\tfree (b);\n\treturn r_coresym_cache_element_new (bf, buf, off + 16, bits, file_name);\n}", "func_hash": 161522561097046138638560232136347291203, "file_name": "bin_symbols.c", "file_hash": 78009235824912653993940702914741768463, "cwe": ["CWE-787"], "cve": "CVE-2022-1061", "cve_desc": "Heap Buffer Overflow in parseDragons in GitHub repository radareorg/radare2 prior to 5.6.8.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1061"}
{"idx": 210571, "project": "linux", "commit_id": "a7b2df76b42bdd026e3106cf2ba97db41345a177", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/a7b2df76b42bdd026e3106cf2ba97db41345a177", "commit_message": "media: rc: prevent memory leak in cx23888_ir_probe\n\nIn cx23888_ir_probe if kfifo_alloc fails the allocated memory for state\nshould be released.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Sean Young \nSigned-off-by: Mauro Carvalho Chehab ", "target": 1, "func": "int cx23888_ir_probe(struct cx23885_dev *dev)\n{\n\tstruct cx23888_ir_state *state;\n\tstruct v4l2_subdev *sd;\n\tstruct v4l2_subdev_ir_parameters default_params;\n\tint ret;\n\n\tstate = kzalloc(sizeof(struct cx23888_ir_state), GFP_KERNEL);\n\tif (state == NULL)\n\t\treturn -ENOMEM;\n\n\tspin_lock_init(&state->rx_kfifo_lock);\n\tif (kfifo_alloc(&state->rx_kfifo, CX23888_IR_RX_KFIFO_SIZE, GFP_KERNEL))\n\t\treturn -ENOMEM;\n\n\tstate->dev = dev;\n\tsd = &state->sd;\n\n\tv4l2_subdev_init(sd, &cx23888_ir_controller_ops);\n\tv4l2_set_subdevdata(sd, state);\n\t/* FIXME - fix the formatting of dev->v4l2_dev.name and use it */\n\tsnprintf(sd->name, sizeof(sd->name), \"%s/888-ir\", dev->name);\n\tsd->grp_id = CX23885_HW_888_IR;\n\n\tret = v4l2_device_register_subdev(&dev->v4l2_dev, sd);\n\tif (ret == 0) {\n\t\t/*\n\t\t * Ensure no interrupts arrive from '888 specific conditions,\n\t\t * since we ignore them in this driver to have commonality with\n\t\t * similar IR controller cores.\n\t\t */\n\t\tcx23888_ir_write4(dev, CX23888_IR_IRQEN_REG, 0);\n\n\t\tmutex_init(&state->rx_params_lock);\n\t\tdefault_params = default_rx_params;\n\t\tv4l2_subdev_call(sd, ir, rx_s_parameters, &default_params);\n\n\t\tmutex_init(&state->tx_params_lock);\n\t\tdefault_params = default_tx_params;\n\t\tv4l2_subdev_call(sd, ir, tx_s_parameters, &default_params);\n\t} else {\n\t\tkfifo_free(&state->rx_kfifo);\n\t}\n\treturn ret;\n}", "func_hash": 312936233884251143267490272609054572019, "file_name": "cx23888-ir.c", "file_hash": 272401351605402096339960832660708824692, "cwe": ["CWE-401"], "cve": "CVE-2019-19054", "cve_desc": "A memory leak in the cx23888_ir_probe() function in drivers/media/pci/cx23885/cx23888-ir.c in the Linux kernel through 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering kfifo_alloc() failures, aka CID-a7b2df76b42b.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19054"}
{"idx": 437708, "project": "linux", "commit_id": "a7b2df76b42bdd026e3106cf2ba97db41345a177", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/a7b2df76b42bdd026e3106cf2ba97db41345a177", "commit_message": "media: rc: prevent memory leak in cx23888_ir_probe\n\nIn cx23888_ir_probe if kfifo_alloc fails the allocated memory for state\nshould be released.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Sean Young \nSigned-off-by: Mauro Carvalho Chehab ", "target": 0, "func": "int cx23888_ir_probe(struct cx23885_dev *dev)\n{\n\tstruct cx23888_ir_state *state;\n\tstruct v4l2_subdev *sd;\n\tstruct v4l2_subdev_ir_parameters default_params;\n\tint ret;\n\n\tstate = kzalloc(sizeof(struct cx23888_ir_state), GFP_KERNEL);\n\tif (state == NULL)\n\t\treturn -ENOMEM;\n\n\tspin_lock_init(&state->rx_kfifo_lock);\n\tif (kfifo_alloc(&state->rx_kfifo, CX23888_IR_RX_KFIFO_SIZE,\n\t\t\tGFP_KERNEL)) {\n\t\tkfree(state);\n\t\treturn -ENOMEM;\n\t}\n\n\tstate->dev = dev;\n\tsd = &state->sd;\n\n\tv4l2_subdev_init(sd, &cx23888_ir_controller_ops);\n\tv4l2_set_subdevdata(sd, state);\n\t/* FIXME - fix the formatting of dev->v4l2_dev.name and use it */\n\tsnprintf(sd->name, sizeof(sd->name), \"%s/888-ir\", dev->name);\n\tsd->grp_id = CX23885_HW_888_IR;\n\n\tret = v4l2_device_register_subdev(&dev->v4l2_dev, sd);\n\tif (ret == 0) {\n\t\t/*\n\t\t * Ensure no interrupts arrive from '888 specific conditions,\n\t\t * since we ignore them in this driver to have commonality with\n\t\t * similar IR controller cores.\n\t\t */\n\t\tcx23888_ir_write4(dev, CX23888_IR_IRQEN_REG, 0);\n\n\t\tmutex_init(&state->rx_params_lock);\n\t\tdefault_params = default_rx_params;\n\t\tv4l2_subdev_call(sd, ir, rx_s_parameters, &default_params);\n\n\t\tmutex_init(&state->tx_params_lock);\n\t\tdefault_params = default_tx_params;\n\t\tv4l2_subdev_call(sd, ir, tx_s_parameters, &default_params);\n\t} else {\n\t\tkfifo_free(&state->rx_kfifo);\n\t}\n\treturn ret;\n}", "func_hash": 310888185962214479719327851650221547215, "file_name": "cx23888-ir.c", "file_hash": 50999505342653188692843142607524492176, "cwe": ["CWE-401"], "cve": "CVE-2019-19054", "cve_desc": "A memory leak in the cx23888_ir_probe() function in drivers/media/pci/cx23885/cx23888-ir.c in the Linux kernel through 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering kfifo_alloc() failures, aka CID-a7b2df76b42b.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19054"}
{"idx": 210620, "project": "linux", "commit_id": "1680939e9ecf7764fba8689cfb3429c2fe2bb23c", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/1680939e9ecf7764fba8689cfb3429c2fe2bb23c", "commit_message": "rpmsg: virtio: Fix possible double free in rpmsg_virtio_add_ctrl_dev()\n\nvch will be free in virtio_rpmsg_release_device() when\nrpmsg_ctrldev_register_device() fails. There is no need to call\nkfree() again.\n\nFixes: c486682ae1e2 (\"rpmsg: virtio: Register the rpmsg_char device\")\nSigned-off-by: Hangyu Hua \nTested-by: Arnaud Pouliquen \nLink: https://lore.kernel.org/r/20220426060536.15594-3-hbh25y@gmail.com\nSigned-off-by: Mathieu Poirier ", "target": 1, "func": "static struct rpmsg_device *rpmsg_virtio_add_ctrl_dev(struct virtio_device *vdev)\n{\n\tstruct virtproc_info *vrp = vdev->priv;\n\tstruct virtio_rpmsg_channel *vch;\n\tstruct rpmsg_device *rpdev_ctrl;\n\tint err = 0;\n\n\tvch = kzalloc(sizeof(*vch), GFP_KERNEL);\n\tif (!vch)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\t/* Link the channel to the vrp */\n\tvch->vrp = vrp;\n\n\t/* Assign public information to the rpmsg_device */\n\trpdev_ctrl = &vch->rpdev;\n\trpdev_ctrl->ops = &virtio_rpmsg_ops;\n\n\trpdev_ctrl->dev.parent = &vrp->vdev->dev;\n\trpdev_ctrl->dev.release = virtio_rpmsg_release_device;\n\trpdev_ctrl->little_endian = virtio_is_little_endian(vrp->vdev);\n\n\terr = rpmsg_ctrldev_register_device(rpdev_ctrl);\n\tif (err) {\n\t\tkfree(vch);\n\t\treturn ERR_PTR(err);\n\t}\n\n\treturn rpdev_ctrl;\n}", "func_hash": 150406368149549050043918111917098327944, "file_name": "virtio_rpmsg_bus.c", "file_hash": 336962103599370684764332520718550760249, "cwe": ["CWE-415"], "cve": "CVE-2022-34494", "cve_desc": "rpmsg_virtio_add_ctrl_dev in drivers/rpmsg/virtio_rpmsg_bus.c in the Linux kernel before 5.18.4 has a double free.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-34494"}
{"idx": 438686, "project": "linux", "commit_id": "1680939e9ecf7764fba8689cfb3429c2fe2bb23c", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/1680939e9ecf7764fba8689cfb3429c2fe2bb23c", "commit_message": "rpmsg: virtio: Fix possible double free in rpmsg_virtio_add_ctrl_dev()\n\nvch will be free in virtio_rpmsg_release_device() when\nrpmsg_ctrldev_register_device() fails. There is no need to call\nkfree() again.\n\nFixes: c486682ae1e2 (\"rpmsg: virtio: Register the rpmsg_char device\")\nSigned-off-by: Hangyu Hua \nTested-by: Arnaud Pouliquen \nLink: https://lore.kernel.org/r/20220426060536.15594-3-hbh25y@gmail.com\nSigned-off-by: Mathieu Poirier ", "target": 0, "func": "static struct rpmsg_device *rpmsg_virtio_add_ctrl_dev(struct virtio_device *vdev)\n{\n\tstruct virtproc_info *vrp = vdev->priv;\n\tstruct virtio_rpmsg_channel *vch;\n\tstruct rpmsg_device *rpdev_ctrl;\n\tint err = 0;\n\n\tvch = kzalloc(sizeof(*vch), GFP_KERNEL);\n\tif (!vch)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\t/* Link the channel to the vrp */\n\tvch->vrp = vrp;\n\n\t/* Assign public information to the rpmsg_device */\n\trpdev_ctrl = &vch->rpdev;\n\trpdev_ctrl->ops = &virtio_rpmsg_ops;\n\n\trpdev_ctrl->dev.parent = &vrp->vdev->dev;\n\trpdev_ctrl->dev.release = virtio_rpmsg_release_device;\n\trpdev_ctrl->little_endian = virtio_is_little_endian(vrp->vdev);\n\n\terr = rpmsg_ctrldev_register_device(rpdev_ctrl);\n\tif (err) {\n\t\t/* vch will be free in virtio_rpmsg_release_device() */\n\t\treturn ERR_PTR(err);\n\t}\n\n\treturn rpdev_ctrl;\n}", "func_hash": 314874178327010725718086387225453172923, "file_name": "virtio_rpmsg_bus.c", "file_hash": 58817315653971019678120939707169466841, "cwe": ["CWE-415"], "cve": "CVE-2022-34494", "cve_desc": "rpmsg_virtio_add_ctrl_dev in drivers/rpmsg/virtio_rpmsg_bus.c in the Linux kernel before 5.18.4 has a double free.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-34494"}
{"idx": 210636, "project": "linux", "commit_id": "b2f37aead1b82a770c48b5d583f35ec22aabb61e", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=b2f37aead1b82a770c48b5d583f35ec22aabb61e", "commit_message": "hamradio: improve the incomplete fix to avoid NPD\n\nThe previous commit 3e0588c291d6 (\"hamradio: defer ax25 kfree after\nunregister_netdev\") reorder the kfree operations and unregister_netdev\noperation to prevent UAF.\n\nThis commit improves the previous one by also deferring the nullify of\nthe ax->tty pointer. Otherwise, a NULL pointer dereference bug occurs.\nPartial of the stack trace is shown below.\n\nBUG: kernel NULL pointer dereference, address: 0000000000000538\nRIP: 0010:ax_xmit+0x1f9/0x400\n...\nCall Trace:\n dev_hard_start_xmit+0xec/0x320\n sch_direct_xmit+0xea/0x240\n __qdisc_run+0x166/0x5c0\n __dev_queue_xmit+0x2c7/0xaf0\n ax25_std_establish_data_link+0x59/0x60\n ax25_connect+0x3a0/0x500\n ? security_socket_connect+0x2b/0x40\n __sys_connect+0x96/0xc0\n ? __hrtimer_init+0xc0/0xc0\n ? common_nsleep+0x2e/0x50\n ? switch_fpu_return+0x139/0x1a0\n __x64_sys_connect+0x11/0x20\n do_syscall_64+0x33/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xa9\n\nThe crash point is shown as below\n\nstatic void ax_encaps(...) {\n  ...\n  set_bit(TTY_DO_WRITE_WAKEUP, &ax->tty->flags); // ax->tty = NULL!\n  ...\n}\n\nBy placing the nullify action after the unregister_netdev, the ax->tty\npointer won't be assigned as NULL net_device framework layer is well\nsynchronized.\n\nSigned-off-by: Lin Ma \nSigned-off-by: David S. Miller ", "target": 1, "func": "static void mkiss_close(struct tty_struct *tty)\n{\n\tstruct mkiss *ax;\n\n\twrite_lock_irq(&disc_data_lock);\n\tax = tty->disc_data;\n\ttty->disc_data = NULL;\n\twrite_unlock_irq(&disc_data_lock);\n\n\tif (!ax)\n\t\treturn;\n\n\t/*\n\t * We have now ensured that nobody can start using ap from now on, but\n\t * we have to wait for all existing users to finish.\n\t */\n\tif (!refcount_dec_and_test(&ax->refcnt))\n\t\twait_for_completion(&ax->dead);\n\t/*\n\t * Halt the transmit queue so that a new transmit cannot scribble\n\t * on our buffers\n\t */\n\tnetif_stop_queue(ax->dev);\n\n\tax->tty = NULL;\n\n\tunregister_netdev(ax->dev);\n\n\t/* Free all AX25 frame buffers after unreg. */\n\tkfree(ax->rbuff);\n\tkfree(ax->xbuff);\n\n\tfree_netdev(ax->dev);\n}", "func_hash": 140859804260946534434971467639833630245, "file_name": "mkiss.c", "file_hash": 323524717208884828374258926730832117051, "cwe": ["CWE-416"], "cve": "CVE-2022-1195", "cve_desc": "A use-after-free vulnerability was found in the Linux kernel in drivers/net/hamradio. This flaw allows a local attacker with a user privilege to cause a denial of service (DOS) when the mkiss or sixpack device is detached and reclaim resources early.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1195"}
{"idx": 438876, "project": "linux", "commit_id": "b2f37aead1b82a770c48b5d583f35ec22aabb61e", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=b2f37aead1b82a770c48b5d583f35ec22aabb61e", "commit_message": "hamradio: improve the incomplete fix to avoid NPD\n\nThe previous commit 3e0588c291d6 (\"hamradio: defer ax25 kfree after\nunregister_netdev\") reorder the kfree operations and unregister_netdev\noperation to prevent UAF.\n\nThis commit improves the previous one by also deferring the nullify of\nthe ax->tty pointer. Otherwise, a NULL pointer dereference bug occurs.\nPartial of the stack trace is shown below.\n\nBUG: kernel NULL pointer dereference, address: 0000000000000538\nRIP: 0010:ax_xmit+0x1f9/0x400\n...\nCall Trace:\n dev_hard_start_xmit+0xec/0x320\n sch_direct_xmit+0xea/0x240\n __qdisc_run+0x166/0x5c0\n __dev_queue_xmit+0x2c7/0xaf0\n ax25_std_establish_data_link+0x59/0x60\n ax25_connect+0x3a0/0x500\n ? security_socket_connect+0x2b/0x40\n __sys_connect+0x96/0xc0\n ? __hrtimer_init+0xc0/0xc0\n ? common_nsleep+0x2e/0x50\n ? switch_fpu_return+0x139/0x1a0\n __x64_sys_connect+0x11/0x20\n do_syscall_64+0x33/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xa9\n\nThe crash point is shown as below\n\nstatic void ax_encaps(...) {\n  ...\n  set_bit(TTY_DO_WRITE_WAKEUP, &ax->tty->flags); // ax->tty = NULL!\n  ...\n}\n\nBy placing the nullify action after the unregister_netdev, the ax->tty\npointer won't be assigned as NULL net_device framework layer is well\nsynchronized.\n\nSigned-off-by: Lin Ma \nSigned-off-by: David S. Miller ", "target": 0, "func": "static void mkiss_close(struct tty_struct *tty)\n{\n\tstruct mkiss *ax;\n\n\twrite_lock_irq(&disc_data_lock);\n\tax = tty->disc_data;\n\ttty->disc_data = NULL;\n\twrite_unlock_irq(&disc_data_lock);\n\n\tif (!ax)\n\t\treturn;\n\n\t/*\n\t * We have now ensured that nobody can start using ap from now on, but\n\t * we have to wait for all existing users to finish.\n\t */\n\tif (!refcount_dec_and_test(&ax->refcnt))\n\t\twait_for_completion(&ax->dead);\n\t/*\n\t * Halt the transmit queue so that a new transmit cannot scribble\n\t * on our buffers\n\t */\n\tnetif_stop_queue(ax->dev);\n\n\tunregister_netdev(ax->dev);\n\n\t/* Free all AX25 frame buffers after unreg. */\n\tkfree(ax->rbuff);\n\tkfree(ax->xbuff);\n\n\tax->tty = NULL;\n\n\tfree_netdev(ax->dev);\n}", "func_hash": 276776356182297757626406563490166856594, "file_name": "mkiss.c", "file_hash": 198075594258051390374765397886029907954, "cwe": ["CWE-416"], "cve": "CVE-2022-1195", "cve_desc": "A use-after-free vulnerability was found in the Linux kernel in drivers/net/hamradio. This flaw allows a local attacker with a user privilege to cause a denial of service (DOS) when the mkiss or sixpack device is detached and reclaim resources early.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1195"}
{"idx": 210669, "project": "ImageMagick6", "commit_id": "210474b2fac6a661bfa7ed563213920e93e76395", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/210474b2fac6a661bfa7ed563213920e93e76395", "commit_message": "Fix ultra rare but potential memory-leak", "target": 1, "func": "static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n  BMPInfo\n    bmp_info;\n\n  Image\n    *image;\n\n  IndexPacket\n    index;\n\n  MagickBooleanType\n    status;\n\n  MagickOffsetType\n    offset,\n    start_position;\n\n  MemoryInfo\n    *pixel_info;\n\n  register IndexPacket\n    *indexes;\n\n  register PixelPacket\n    *q;\n\n  register ssize_t\n    i,\n    x;\n\n  register unsigned char\n    *p;\n\n  size_t\n    bit,\n    bytes_per_line,\n    length;\n\n  ssize_t\n    count,\n    y;\n\n  unsigned char\n    magick[12],\n    *pixels;\n\n  unsigned int\n    blue,\n    green,\n    offset_bits,\n    red;\n\n  /*\n    Open image file.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  image=AcquireImage(image_info);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n    Determine if this a BMP file.\n  */\n  (void) memset(&bmp_info,0,sizeof(bmp_info));\n  bmp_info.ba_offset=0;\n  start_position=0;\n  offset_bits=0;\n  count=ReadBlob(image,2,magick);\n  if (count != 2)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  do\n  {\n    LongPixelPacket\n      shift;\n\n    PixelPacket\n      quantum_bits;\n\n    /*\n      Verify BMP identifier.\n    */\n    if (bmp_info.ba_offset == 0)\n      start_position=TellBlob(image)-2;\n    bmp_info.ba_offset=0;\n    while (LocaleNCompare((char *) magick,\"BA\",2) == 0)\n    {\n      bmp_info.file_size=ReadBlobLSBLong(image);\n      bmp_info.ba_offset=ReadBlobLSBLong(image);\n      bmp_info.offset_bits=ReadBlobLSBLong(image);\n      count=ReadBlob(image,2,magick);\n      if (count != 2)\n        break;\n    }\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  Magick: %c%c\",\n        magick[0],magick[1]);\n    if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) &&\n        (LocaleNCompare((char *) magick,\"CI\",2) != 0)))\n      ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n    bmp_info.file_size=ReadBlobLSBLong(image);\n    (void) ReadBlobLSBLong(image);\n\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n         \"  File_size in header:  %u bytes\",bmp_info.file_size);\n\n    bmp_info.offset_bits=ReadBlobLSBLong(image);\n    bmp_info.size=ReadBlobLSBLong(image);\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  BMP size: %u\",\n        bmp_info.size);\n    if (bmp_info.size == 12)\n      {\n        /*\n          OS/2 BMP image file.\n        */\n        (void) CopyMagickString(image->magick,\"BMP2\",MaxTextExtent);\n        bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));\n        bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));\n        bmp_info.planes=ReadBlobLSBShort(image);\n        bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n        bmp_info.x_pixels=0;\n        bmp_info.y_pixels=0;\n        bmp_info.number_colors=0;\n        bmp_info.compression=BI_RGB;\n        bmp_info.image_size=0;\n        bmp_info.alpha_mask=0;\n        if (image->debug != MagickFalse)\n          {\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Format: OS/2 Bitmap\");\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n              bmp_info.height);\n          }\n      }\n    else\n      {\n        /*\n          Microsoft Windows BMP image file.\n        */\n        if (bmp_info.size < 40)\n          ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\");\n        bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);\n        bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);\n        bmp_info.planes=ReadBlobLSBShort(image);\n        bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n        bmp_info.compression=ReadBlobLSBLong(image);\n        bmp_info.image_size=ReadBlobLSBLong(image);\n        bmp_info.x_pixels=ReadBlobLSBLong(image);\n        bmp_info.y_pixels=ReadBlobLSBLong(image);\n        bmp_info.number_colors=ReadBlobLSBLong(image);\n        bmp_info.colors_important=ReadBlobLSBLong(image);\n        if (image->debug != MagickFalse)\n          {\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Format: MS Windows bitmap\");\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n              bmp_info.height);\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel);\n            switch (bmp_info.compression)\n            {\n              case BI_RGB:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_RGB\");\n                break;\n              }\n              case BI_RLE4:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_RLE4\");\n                break;\n              }\n              case BI_RLE8:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_RLE8\");\n                break;\n              }\n              case BI_BITFIELDS:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_BITFIELDS\");\n                break;\n              }\n              case BI_PNG:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_PNG\");\n                break;\n              }\n              case BI_JPEG:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_JPEG\");\n                break;\n              }\n              default:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: UNKNOWN (%u)\",bmp_info.compression);\n              }\n            }\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Number of colors: %u\",bmp_info.number_colors);\n          }\n        bmp_info.red_mask=ReadBlobLSBLong(image);\n        bmp_info.green_mask=ReadBlobLSBLong(image);\n        bmp_info.blue_mask=ReadBlobLSBLong(image);\n        if (bmp_info.size > 40)\n          {\n            double\n              gamma;\n\n            /*\n              Read color management information.\n            */\n            bmp_info.alpha_mask=ReadBlobLSBLong(image);\n            bmp_info.colorspace=ReadBlobLSBSignedLong(image);\n            /*\n              Decode 2^30 fixed point formatted CIE primaries.\n            */\n#           define BMP_DENOM ((double) 0x40000000)\n            bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n\n            gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+\n              bmp_info.red_primary.z;\n            gamma=PerceptibleReciprocal(gamma);\n            bmp_info.red_primary.x*=gamma;\n            bmp_info.red_primary.y*=gamma;\n            image->chromaticity.red_primary.x=bmp_info.red_primary.x;\n            image->chromaticity.red_primary.y=bmp_info.red_primary.y;\n\n            gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+\n              bmp_info.green_primary.z;\n            gamma=PerceptibleReciprocal(gamma);\n            bmp_info.green_primary.x*=gamma;\n            bmp_info.green_primary.y*=gamma;\n            image->chromaticity.green_primary.x=bmp_info.green_primary.x;\n            image->chromaticity.green_primary.y=bmp_info.green_primary.y;\n\n            gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+\n              bmp_info.blue_primary.z;\n            gamma=PerceptibleReciprocal(gamma);\n            bmp_info.blue_primary.x*=gamma;\n            bmp_info.blue_primary.y*=gamma;\n            image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;\n            image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;\n\n            /*\n              Decode 16^16 fixed point formatted gamma_scales.\n            */\n            bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;\n            bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;\n            bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;\n            /*\n              Compute a single gamma from the BMP 3-channel gamma.\n            */\n            image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+\n              bmp_info.gamma_scale.z)/3.0;\n          }\n        else\n          (void) CopyMagickString(image->magick,\"BMP3\",MaxTextExtent);\n\n        if (bmp_info.size > 108)\n          {\n            size_t\n              intent;\n\n            /*\n              Read BMP Version 5 color management information.\n            */\n            intent=ReadBlobLSBLong(image);\n            switch ((int) intent)\n            {\n              case LCS_GM_BUSINESS:\n              {\n                image->rendering_intent=SaturationIntent;\n                break;\n              }\n              case LCS_GM_GRAPHICS:\n              {\n                image->rendering_intent=RelativeIntent;\n                break;\n              }\n              case LCS_GM_IMAGES:\n              {\n                image->rendering_intent=PerceptualIntent;\n                break;\n              }\n              case LCS_GM_ABS_COLORIMETRIC:\n              {\n                image->rendering_intent=AbsoluteIntent;\n                break;\n              }\n            }\n            (void) ReadBlobLSBLong(image);  /* Profile data */\n            (void) ReadBlobLSBLong(image);  /* Profile size */\n            (void) ReadBlobLSBLong(image);  /* Reserved byte */\n          }\n      }\n    if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))\n      (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n        \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename);\n    else\n      if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))\n        (void) ThrowMagickException(exception,GetMagickModule(),\n          CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\",\n          image->filename);\n    if (bmp_info.width <= 0)\n      ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n    if (bmp_info.height == 0)\n      ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n    if (bmp_info.planes != 1)\n      ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\");\n    if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&\n        (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&\n        (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    if (bmp_info.bits_per_pixel < 16 &&\n        bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedNumberOfColors\");\n    if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    switch (bmp_info.compression)\n    {\n      case BI_RGB:\n        image->compression=NoCompression;\n        break;\n      case BI_RLE8:\n      case BI_RLE4:\n        image->compression=RLECompression;\n        break;\n      case BI_BITFIELDS:\n        break;\n      case BI_JPEG:\n        ThrowReaderException(CoderError,\"JPEGCompressNotSupported\");\n      case BI_PNG:\n        ThrowReaderException(CoderError,\"PNGCompressNotSupported\");\n      default:\n        ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\");\n    }\n    image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);\n    image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);\n    image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;\n    image->matte=((bmp_info.alpha_mask != 0) &&\n      (bmp_info.compression == BI_BITFIELDS)) ? MagickTrue : MagickFalse;\n    if (bmp_info.bits_per_pixel < 16)\n      {\n        size_t\n          one;\n\n        image->storage_class=PseudoClass;\n        image->colors=bmp_info.number_colors;\n        one=1;\n        if (image->colors == 0)\n          image->colors=one << bmp_info.bits_per_pixel;\n      }\n    image->x_resolution=(double) bmp_info.x_pixels/100.0;\n    image->y_resolution=(double) bmp_info.y_pixels/100.0;\n    image->units=PixelsPerCentimeterResolution;\n    if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n      if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n        break;\n    status=SetImageExtent(image,image->columns,image->rows);\n    if (status == MagickFalse)\n      {\n        InheritException(exception,&image->exception);\n        return(DestroyImageList(image));\n      }\n    if (image->storage_class == PseudoClass)\n      {\n        unsigned char\n          *bmp_colormap;\n\n        size_t\n          packet_size;\n\n        /*\n          Read BMP raster colormap.\n        */\n        if (image->debug != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Reading colormap of %.20g colors\",(double) image->colors);\n        if (AcquireImageColormap(image,image->colors) == MagickFalse)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)\n          image->colors,4*sizeof(*bmp_colormap));\n        if (bmp_colormap == (unsigned char *) NULL)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        if ((bmp_info.size == 12) || (bmp_info.size == 64))\n          packet_size=3;\n        else\n          packet_size=4;\n        offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);\n        if (offset < 0)\n          {\n            bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n            ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n          }\n        count=ReadBlob(image,packet_size*image->colors,bmp_colormap);\n        if (count != (ssize_t) (packet_size*image->colors))\n          {\n            bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n            ThrowReaderException(CorruptImageError,\n              \"InsufficientImageDataInFile\");\n          }\n        p=bmp_colormap;\n        for (i=0; i < (ssize_t) image->colors; i++)\n        {\n          image->colormap[i].blue=ScaleCharToQuantum(*p++);\n          image->colormap[i].green=ScaleCharToQuantum(*p++);\n          image->colormap[i].red=ScaleCharToQuantum(*p++);\n          if (packet_size == 4)\n            p++;\n        }\n        bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n      }\n    /*\n      Read image data.\n    */\n    if (bmp_info.offset_bits == offset_bits)\n      ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n    offset_bits=bmp_info.offset_bits;\n    offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);\n    if (offset < 0)\n      ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n    if (bmp_info.compression == BI_RLE4)\n      bmp_info.bits_per_pixel<<=1;\n    bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);\n    length=(size_t) bytes_per_line*image->rows;\n    if (((MagickSizeType) length/8) > GetBlobSize(image))\n      ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n    if ((bmp_info.compression == BI_RGB) ||\n        (bmp_info.compression == BI_BITFIELDS))\n      {\n        pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n          image->columns+256UL)*sizeof(*pixels));\n        if (pixel_info == (MemoryInfo *) NULL)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n        if (image->debug != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Reading pixels (%.20g bytes)\",(double) length);\n        count=ReadBlob(image,length,pixels);\n        if (count != (ssize_t) length)\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"InsufficientImageDataInFile\");\n          }\n      }\n    else\n      {\n        /*\n          Convert run-length encoded raster pixels.\n        */\n        pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n          image->columns+256UL)*sizeof(*pixels));\n        if (pixel_info == (MemoryInfo *) NULL)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n        status=DecodeImage(image,bmp_info.compression,pixels,\n          image->columns*image->rows);\n        if (status == MagickFalse)\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"UnableToRunlengthDecodeImage\");\n          }\n      }\n    /*\n      Convert BMP raster image to pixel packets.\n    */\n    if (bmp_info.compression == BI_RGB)\n      {\n        /*\n          We should ignore the alpha value in BMP3 files but there have been\n          reports about 32 bit files with alpha. We do a quick check to see if\n          the alpha channel contains a value that is not zero (default value).\n          If we find a non zero value we asume the program that wrote the file\n          wants to use the alpha channel.\n        */\n        if ((image->matte == MagickFalse) && (bmp_info.size == 40) &&\n            (bmp_info.bits_per_pixel == 32))\n          {\n            bytes_per_line=4*(image->columns);\n            for (y=(ssize_t) image->rows-1; y >= 0; y--)\n            {\n              p=pixels+(image->rows-y-1)*bytes_per_line;\n              for (x=0; x < (ssize_t) image->columns; x++)\n              {\n                if (*(p+3) != 0)\n                  {\n                    image->matte=MagickTrue;\n                    y=-1;\n                    break;\n                  }\n                p+=4;\n              }\n            }\n          }\n        bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U;\n        bmp_info.red_mask=0x00ff0000U;\n        bmp_info.green_mask=0x0000ff00U;\n        bmp_info.blue_mask=0x000000ffU;\n        if (bmp_info.bits_per_pixel == 16)\n          {\n            /*\n              RGB555.\n            */\n            bmp_info.red_mask=0x00007c00U;\n            bmp_info.green_mask=0x000003e0U;\n            bmp_info.blue_mask=0x0000001fU;\n          }\n      }\n    (void) memset(&shift,0,sizeof(shift));\n    (void) memset(&quantum_bits,0,sizeof(quantum_bits));\n    if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))\n      {\n        register size_t\n          sample;\n\n        /*\n          Get shift and quantum bits info from bitfield masks.\n        */\n        if (bmp_info.red_mask != 0)\n          while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)\n          {\n            shift.red++;\n            if (shift.red > 32U)\n              break;\n          }\n        if (bmp_info.green_mask != 0)\n          while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)\n          {\n            shift.green++;\n            if (shift.green > 32U)\n              break;\n          }\n        if (bmp_info.blue_mask != 0)\n          while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)\n          {\n            shift.blue++;\n            if (shift.blue > 32U)\n              break;\n          }\n        if (bmp_info.alpha_mask != 0)\n          while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0)\n          {\n            shift.opacity++;\n            if (shift.opacity > 32U)\n              break;\n          }\n        sample=shift.red;\n        while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red);\n        sample=shift.green;\n        while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green);\n        sample=shift.blue;\n        while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue);\n        sample=shift.opacity;\n        while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.opacity=ClampToQuantum((MagickRealType) sample-\n          shift.opacity);\n      }\n    switch (bmp_info.bits_per_pixel)\n    {\n      case 1:\n      {\n        /*\n          Convert bitmap scanline.\n        */\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n          {\n            for (bit=0; bit < 8; bit++)\n            {\n              index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n              SetPixelIndex(indexes+x+bit,index);\n              q++;\n            }\n            p++;\n          }\n          if ((image->columns % 8) != 0)\n            {\n              for (bit=0; bit < (image->columns % 8); bit++)\n              {\n                index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n                SetPixelIndex(indexes+x+bit,index);\n              }\n              p++;\n            }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        (void) SyncImage(image);\n        break;\n      }\n      case 4:\n      {\n        /*\n          Convert PseudoColor scanline.\n        */\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n          {\n            (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0x0f),\n              &index,exception);\n            SetPixelIndex(indexes+x,index);\n            (void) IsValidColormapIndex(image,(ssize_t) (*p & 0x0f),&index,\n              exception);\n            SetPixelIndex(indexes+x+1,index);\n            p++;\n          }\n          if ((image->columns % 2) != 0)\n            {\n              (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0xf),\n                &index,exception);\n              SetPixelIndex(indexes+(x++),index);\n              p++;\n            }\n          if (x < (ssize_t) image->columns)\n            break;\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        (void) SyncImage(image);\n        break;\n      }\n      case 8:\n      {\n        /*\n          Convert PseudoColor scanline.\n        */\n        if ((bmp_info.compression == BI_RLE8) ||\n            (bmp_info.compression == BI_RLE4))\n          bytes_per_line=image->columns;\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          for (x=(ssize_t) image->columns; x != 0; --x)\n          {\n            (void) IsValidColormapIndex(image,(ssize_t) *p,&index,exception);\n            SetPixelIndex(indexes,index);\n            indexes++;\n            p++;\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        (void) SyncImage(image);\n        break;\n      }\n      case 16:\n      {\n        unsigned int\n          alpha,\n          pixel;\n\n        /*\n          Convert bitfield encoded 16-bit PseudoColor scanline.\n        */\n        if (bmp_info.compression != BI_RGB &&\n            bmp_info.compression != BI_BITFIELDS)\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"UnrecognizedImageCompression\");\n          }\n        bytes_per_line=2*(image->columns+image->columns % 2);\n        image->storage_class=DirectClass;\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            pixel=(unsigned int) (*p++);\n            pixel|=(*p++) << 8;\n            red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n            if (quantum_bits.red == 5)\n              red|=((red & 0xe000) >> 5);\n            if (quantum_bits.red <= 8)\n              red|=((red & 0xff00) >> 8);\n            green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n            if (quantum_bits.green == 5)\n              green|=((green & 0xe000) >> 5);\n            if (quantum_bits.green == 6)\n              green|=((green & 0xc000) >> 6);\n            if (quantum_bits.green <= 8)\n              green|=((green & 0xff00) >> 8);\n            blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n            if (quantum_bits.blue == 5)\n              blue|=((blue & 0xe000) >> 5);\n            if (quantum_bits.blue <= 8)\n              blue|=((blue & 0xff00) >> 8);\n            SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n            SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n            SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n            SetPixelOpacity(q,OpaqueOpacity);\n            if (image->matte != MagickFalse)\n              {\n                alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n                if (quantum_bits.opacity <= 8)\n                  alpha|=((alpha & 0xff00) >> 8);\n                SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n              }\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      case 24:\n      {\n        /*\n          Convert DirectColor scanline.\n        */\n        bytes_per_line=4*((image->columns*24+31)/32);\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            SetPixelBlue(q,ScaleCharToQuantum(*p++));\n            SetPixelGreen(q,ScaleCharToQuantum(*p++));\n            SetPixelRed(q,ScaleCharToQuantum(*p++));\n            SetPixelOpacity(q,OpaqueOpacity);\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      case 32:\n      {\n        /*\n          Convert bitfield encoded DirectColor scanline.\n        */\n        if ((bmp_info.compression != BI_RGB) &&\n            (bmp_info.compression != BI_BITFIELDS))\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"UnrecognizedImageCompression\");\n          }\n        bytes_per_line=4*(image->columns);\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          unsigned int\n            alpha,\n            pixel;\n\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            pixel=(unsigned int) (*p++);\n            pixel|=((unsigned int) *p++ << 8);\n            pixel|=((unsigned int) *p++ << 16);\n            pixel|=((unsigned int) *p++ << 24);\n            red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n            if (quantum_bits.red == 8)\n              red|=(red >> 8);\n            green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n            if (quantum_bits.green == 8)\n              green|=(green >> 8);\n            blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n            if (quantum_bits.blue == 8)\n              blue|=(blue >> 8);\n            SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n            SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n            SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n            SetPixelAlpha(q,OpaqueOpacity);\n            if (image->matte != MagickFalse)\n              {\n                alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n                if (quantum_bits.opacity == 8)\n                  alpha|=(alpha >> 8);\n                SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n              }\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      default:\n      {\n        pixel_info=RelinquishVirtualMemory(pixel_info);\n        ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n    }\n    pixel_info=RelinquishVirtualMemory(pixel_info);\n    if (y > 0)\n      break;\n    if (EOFBlob(image) != MagickFalse)\n      {\n        ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n          image->filename);\n        break;\n      }\n    if (bmp_info.height < 0)\n      {\n        Image\n          *flipped_image;\n\n        /*\n          Correct image orientation.\n        */\n        flipped_image=FlipImage(image,exception);\n        if (flipped_image != (Image *) NULL)\n          {\n            DuplicateBlob(flipped_image,image);\n            ReplaceImageInList(&image, flipped_image);\n            image=flipped_image;\n          }\n      }\n    /*\n      Proceed to next image.\n    */\n    if (image_info->number_scenes != 0)\n      if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n        break;\n    *magick='\\0';\n    if (bmp_info.ba_offset != 0)\n      {\n        offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);\n        if (offset < 0)\n          ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n    count=ReadBlob(image,2,magick);\n    if ((count == 2) && (IsBMP(magick,2) != MagickFalse))\n      {\n        /*\n          Acquire next image structure.\n        */\n        AcquireNextImage(image_info,image);\n        if (GetNextImageInList(image) == (Image *) NULL)\n          {\n            image=DestroyImageList(image);\n            return((Image *) NULL);\n          }\n        image=SyncNextImageInList(image);\n        status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n          GetBlobSize(image));\n        if (status == MagickFalse)\n          break;\n      }\n  } while (IsBMP(magick,2) != MagickFalse);\n  (void) CloseBlob(image);\n  return(GetFirstImageInList(image));\n}", "func_hash": 30229592861865697728644210229360552083, "file_name": "bmp.c", "file_hash": 87642086170701008397384161090320956088, "cwe": ["CWE-401"], "cve": "CVE-2019-13133", "cve_desc": "ImageMagick before 7.0.8-50 has a memory leak vulnerability in the function ReadBMPImage in coders/bmp.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-13133"}
{"idx": 439114, "project": "ImageMagick6", "commit_id": "210474b2fac6a661bfa7ed563213920e93e76395", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/210474b2fac6a661bfa7ed563213920e93e76395", "commit_message": "Fix ultra rare but potential memory-leak", "target": 0, "func": "static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n  BMPInfo\n    bmp_info;\n\n  Image\n    *image;\n\n  IndexPacket\n    index;\n\n  MagickBooleanType\n    status;\n\n  MagickOffsetType\n    offset,\n    start_position;\n\n  MemoryInfo\n    *pixel_info;\n\n  register IndexPacket\n    *indexes;\n\n  register PixelPacket\n    *q;\n\n  register ssize_t\n    i,\n    x;\n\n  register unsigned char\n    *p;\n\n  size_t\n    bit,\n    bytes_per_line,\n    length;\n\n  ssize_t\n    count,\n    y;\n\n  unsigned char\n    magick[12],\n    *pixels;\n\n  unsigned int\n    blue,\n    green,\n    offset_bits,\n    red;\n\n  /*\n    Open image file.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  image=AcquireImage(image_info);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n    Determine if this a BMP file.\n  */\n  (void) memset(&bmp_info,0,sizeof(bmp_info));\n  bmp_info.ba_offset=0;\n  start_position=0;\n  offset_bits=0;\n  count=ReadBlob(image,2,magick);\n  if (count != 2)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  do\n  {\n    LongPixelPacket\n      shift;\n\n    PixelPacket\n      quantum_bits;\n\n    /*\n      Verify BMP identifier.\n    */\n    if (bmp_info.ba_offset == 0)\n      start_position=TellBlob(image)-2;\n    bmp_info.ba_offset=0;\n    while (LocaleNCompare((char *) magick,\"BA\",2) == 0)\n    {\n      bmp_info.file_size=ReadBlobLSBLong(image);\n      bmp_info.ba_offset=ReadBlobLSBLong(image);\n      bmp_info.offset_bits=ReadBlobLSBLong(image);\n      count=ReadBlob(image,2,magick);\n      if (count != 2)\n        break;\n    }\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  Magick: %c%c\",\n        magick[0],magick[1]);\n    if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) &&\n        (LocaleNCompare((char *) magick,\"CI\",2) != 0)))\n      ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n    bmp_info.file_size=ReadBlobLSBLong(image);\n    (void) ReadBlobLSBLong(image);\n\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n         \"  File_size in header:  %u bytes\",bmp_info.file_size);\n\n    bmp_info.offset_bits=ReadBlobLSBLong(image);\n    bmp_info.size=ReadBlobLSBLong(image);\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  BMP size: %u\",\n        bmp_info.size);\n    if (bmp_info.size == 12)\n      {\n        /*\n          OS/2 BMP image file.\n        */\n        (void) CopyMagickString(image->magick,\"BMP2\",MaxTextExtent);\n        bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));\n        bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));\n        bmp_info.planes=ReadBlobLSBShort(image);\n        bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n        bmp_info.x_pixels=0;\n        bmp_info.y_pixels=0;\n        bmp_info.number_colors=0;\n        bmp_info.compression=BI_RGB;\n        bmp_info.image_size=0;\n        bmp_info.alpha_mask=0;\n        if (image->debug != MagickFalse)\n          {\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Format: OS/2 Bitmap\");\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n              bmp_info.height);\n          }\n      }\n    else\n      {\n        /*\n          Microsoft Windows BMP image file.\n        */\n        if (bmp_info.size < 40)\n          ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\");\n        bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);\n        bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);\n        bmp_info.planes=ReadBlobLSBShort(image);\n        bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n        bmp_info.compression=ReadBlobLSBLong(image);\n        bmp_info.image_size=ReadBlobLSBLong(image);\n        bmp_info.x_pixels=ReadBlobLSBLong(image);\n        bmp_info.y_pixels=ReadBlobLSBLong(image);\n        bmp_info.number_colors=ReadBlobLSBLong(image);\n        bmp_info.colors_important=ReadBlobLSBLong(image);\n        if (image->debug != MagickFalse)\n          {\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Format: MS Windows bitmap\");\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n              bmp_info.height);\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel);\n            switch (bmp_info.compression)\n            {\n              case BI_RGB:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_RGB\");\n                break;\n              }\n              case BI_RLE4:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_RLE4\");\n                break;\n              }\n              case BI_RLE8:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_RLE8\");\n                break;\n              }\n              case BI_BITFIELDS:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_BITFIELDS\");\n                break;\n              }\n              case BI_PNG:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_PNG\");\n                break;\n              }\n              case BI_JPEG:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_JPEG\");\n                break;\n              }\n              default:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: UNKNOWN (%u)\",bmp_info.compression);\n              }\n            }\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Number of colors: %u\",bmp_info.number_colors);\n          }\n        bmp_info.red_mask=ReadBlobLSBLong(image);\n        bmp_info.green_mask=ReadBlobLSBLong(image);\n        bmp_info.blue_mask=ReadBlobLSBLong(image);\n        if (bmp_info.size > 40)\n          {\n            double\n              gamma;\n\n            /*\n              Read color management information.\n            */\n            bmp_info.alpha_mask=ReadBlobLSBLong(image);\n            bmp_info.colorspace=ReadBlobLSBSignedLong(image);\n            /*\n              Decode 2^30 fixed point formatted CIE primaries.\n            */\n#           define BMP_DENOM ((double) 0x40000000)\n            bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n\n            gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+\n              bmp_info.red_primary.z;\n            gamma=PerceptibleReciprocal(gamma);\n            bmp_info.red_primary.x*=gamma;\n            bmp_info.red_primary.y*=gamma;\n            image->chromaticity.red_primary.x=bmp_info.red_primary.x;\n            image->chromaticity.red_primary.y=bmp_info.red_primary.y;\n\n            gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+\n              bmp_info.green_primary.z;\n            gamma=PerceptibleReciprocal(gamma);\n            bmp_info.green_primary.x*=gamma;\n            bmp_info.green_primary.y*=gamma;\n            image->chromaticity.green_primary.x=bmp_info.green_primary.x;\n            image->chromaticity.green_primary.y=bmp_info.green_primary.y;\n\n            gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+\n              bmp_info.blue_primary.z;\n            gamma=PerceptibleReciprocal(gamma);\n            bmp_info.blue_primary.x*=gamma;\n            bmp_info.blue_primary.y*=gamma;\n            image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;\n            image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;\n\n            /*\n              Decode 16^16 fixed point formatted gamma_scales.\n            */\n            bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;\n            bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;\n            bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;\n            /*\n              Compute a single gamma from the BMP 3-channel gamma.\n            */\n            image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+\n              bmp_info.gamma_scale.z)/3.0;\n          }\n        else\n          (void) CopyMagickString(image->magick,\"BMP3\",MaxTextExtent);\n\n        if (bmp_info.size > 108)\n          {\n            size_t\n              intent;\n\n            /*\n              Read BMP Version 5 color management information.\n            */\n            intent=ReadBlobLSBLong(image);\n            switch ((int) intent)\n            {\n              case LCS_GM_BUSINESS:\n              {\n                image->rendering_intent=SaturationIntent;\n                break;\n              }\n              case LCS_GM_GRAPHICS:\n              {\n                image->rendering_intent=RelativeIntent;\n                break;\n              }\n              case LCS_GM_IMAGES:\n              {\n                image->rendering_intent=PerceptualIntent;\n                break;\n              }\n              case LCS_GM_ABS_COLORIMETRIC:\n              {\n                image->rendering_intent=AbsoluteIntent;\n                break;\n              }\n            }\n            (void) ReadBlobLSBLong(image);  /* Profile data */\n            (void) ReadBlobLSBLong(image);  /* Profile size */\n            (void) ReadBlobLSBLong(image);  /* Reserved byte */\n          }\n      }\n    if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))\n      (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n        \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename);\n    else\n      if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))\n        (void) ThrowMagickException(exception,GetMagickModule(),\n          CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\",\n          image->filename);\n    if (bmp_info.width <= 0)\n      ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n    if (bmp_info.height == 0)\n      ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n    if (bmp_info.planes != 1)\n      ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\");\n    if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&\n        (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&\n        (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    if (bmp_info.bits_per_pixel < 16 &&\n        bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedNumberOfColors\");\n    if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    switch (bmp_info.compression)\n    {\n      case BI_RGB:\n        image->compression=NoCompression;\n        break;\n      case BI_RLE8:\n      case BI_RLE4:\n        image->compression=RLECompression;\n        break;\n      case BI_BITFIELDS:\n        break;\n      case BI_JPEG:\n        ThrowReaderException(CoderError,\"JPEGCompressNotSupported\");\n      case BI_PNG:\n        ThrowReaderException(CoderError,\"PNGCompressNotSupported\");\n      default:\n        ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\");\n    }\n    image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);\n    image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);\n    image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;\n    image->matte=((bmp_info.alpha_mask != 0) &&\n      (bmp_info.compression == BI_BITFIELDS)) ? MagickTrue : MagickFalse;\n    if (bmp_info.bits_per_pixel < 16)\n      {\n        size_t\n          one;\n\n        image->storage_class=PseudoClass;\n        image->colors=bmp_info.number_colors;\n        one=1;\n        if (image->colors == 0)\n          image->colors=one << bmp_info.bits_per_pixel;\n      }\n    image->x_resolution=(double) bmp_info.x_pixels/100.0;\n    image->y_resolution=(double) bmp_info.y_pixels/100.0;\n    image->units=PixelsPerCentimeterResolution;\n    if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n      if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n        break;\n    status=SetImageExtent(image,image->columns,image->rows);\n    if (status == MagickFalse)\n      {\n        InheritException(exception,&image->exception);\n        return(DestroyImageList(image));\n      }\n    if (image->storage_class == PseudoClass)\n      {\n        unsigned char\n          *bmp_colormap;\n\n        size_t\n          packet_size;\n\n        /*\n          Read BMP raster colormap.\n        */\n        if (image->debug != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Reading colormap of %.20g colors\",(double) image->colors);\n        if (AcquireImageColormap(image,image->colors) == MagickFalse)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)\n          image->colors,4*sizeof(*bmp_colormap));\n        if (bmp_colormap == (unsigned char *) NULL)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        if ((bmp_info.size == 12) || (bmp_info.size == 64))\n          packet_size=3;\n        else\n          packet_size=4;\n        offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);\n        if (offset < 0)\n          {\n            bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n            ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n          }\n        count=ReadBlob(image,packet_size*image->colors,bmp_colormap);\n        if (count != (ssize_t) (packet_size*image->colors))\n          {\n            bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n            ThrowReaderException(CorruptImageError,\n              \"InsufficientImageDataInFile\");\n          }\n        p=bmp_colormap;\n        for (i=0; i < (ssize_t) image->colors; i++)\n        {\n          image->colormap[i].blue=ScaleCharToQuantum(*p++);\n          image->colormap[i].green=ScaleCharToQuantum(*p++);\n          image->colormap[i].red=ScaleCharToQuantum(*p++);\n          if (packet_size == 4)\n            p++;\n        }\n        bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n      }\n    /*\n      Read image data.\n    */\n    if (bmp_info.offset_bits == offset_bits)\n      ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n    offset_bits=bmp_info.offset_bits;\n    offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);\n    if (offset < 0)\n      ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n    if (bmp_info.compression == BI_RLE4)\n      bmp_info.bits_per_pixel<<=1;\n    bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);\n    length=(size_t) bytes_per_line*image->rows;\n    if (((MagickSizeType) length/8) > GetBlobSize(image))\n      ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n    if ((bmp_info.compression == BI_RGB) ||\n        (bmp_info.compression == BI_BITFIELDS))\n      {\n        pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n          image->columns+256UL)*sizeof(*pixels));\n        if (pixel_info == (MemoryInfo *) NULL)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n        if (image->debug != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Reading pixels (%.20g bytes)\",(double) length);\n        count=ReadBlob(image,length,pixels);\n        if (count != (ssize_t) length)\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"InsufficientImageDataInFile\");\n          }\n      }\n    else\n      {\n        /*\n          Convert run-length encoded raster pixels.\n        */\n        pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n          image->columns+256UL)*sizeof(*pixels));\n        if (pixel_info == (MemoryInfo *) NULL)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n        status=DecodeImage(image,bmp_info.compression,pixels,\n          image->columns*image->rows);\n        if (status == MagickFalse)\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"UnableToRunlengthDecodeImage\");\n          }\n      }\n    /*\n      Convert BMP raster image to pixel packets.\n    */\n    if (bmp_info.compression == BI_RGB)\n      {\n        /*\n          We should ignore the alpha value in BMP3 files but there have been\n          reports about 32 bit files with alpha. We do a quick check to see if\n          the alpha channel contains a value that is not zero (default value).\n          If we find a non zero value we asume the program that wrote the file\n          wants to use the alpha channel.\n        */\n        if ((image->matte == MagickFalse) && (bmp_info.size == 40) &&\n            (bmp_info.bits_per_pixel == 32))\n          {\n            bytes_per_line=4*(image->columns);\n            for (y=(ssize_t) image->rows-1; y >= 0; y--)\n            {\n              p=pixels+(image->rows-y-1)*bytes_per_line;\n              for (x=0; x < (ssize_t) image->columns; x++)\n              {\n                if (*(p+3) != 0)\n                  {\n                    image->matte=MagickTrue;\n                    y=-1;\n                    break;\n                  }\n                p+=4;\n              }\n            }\n          }\n        bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U;\n        bmp_info.red_mask=0x00ff0000U;\n        bmp_info.green_mask=0x0000ff00U;\n        bmp_info.blue_mask=0x000000ffU;\n        if (bmp_info.bits_per_pixel == 16)\n          {\n            /*\n              RGB555.\n            */\n            bmp_info.red_mask=0x00007c00U;\n            bmp_info.green_mask=0x000003e0U;\n            bmp_info.blue_mask=0x0000001fU;\n          }\n      }\n    (void) memset(&shift,0,sizeof(shift));\n    (void) memset(&quantum_bits,0,sizeof(quantum_bits));\n    if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))\n      {\n        register size_t\n          sample;\n\n        /*\n          Get shift and quantum bits info from bitfield masks.\n        */\n        if (bmp_info.red_mask != 0)\n          while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)\n          {\n            shift.red++;\n            if (shift.red > 32U)\n              break;\n          }\n        if (bmp_info.green_mask != 0)\n          while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)\n          {\n            shift.green++;\n            if (shift.green > 32U)\n              break;\n          }\n        if (bmp_info.blue_mask != 0)\n          while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)\n          {\n            shift.blue++;\n            if (shift.blue > 32U)\n              break;\n          }\n        if (bmp_info.alpha_mask != 0)\n          while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0)\n          {\n            shift.opacity++;\n            if (shift.opacity > 32U)\n              break;\n          }\n        sample=shift.red;\n        while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red);\n        sample=shift.green;\n        while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green);\n        sample=shift.blue;\n        while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue);\n        sample=shift.opacity;\n        while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.opacity=ClampToQuantum((MagickRealType) sample-\n          shift.opacity);\n      }\n    switch (bmp_info.bits_per_pixel)\n    {\n      case 1:\n      {\n        /*\n          Convert bitmap scanline.\n        */\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n          {\n            for (bit=0; bit < 8; bit++)\n            {\n              index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n              SetPixelIndex(indexes+x+bit,index);\n              q++;\n            }\n            p++;\n          }\n          if ((image->columns % 8) != 0)\n            {\n              for (bit=0; bit < (image->columns % 8); bit++)\n              {\n                index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n                SetPixelIndex(indexes+x+bit,index);\n              }\n              p++;\n            }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        (void) SyncImage(image);\n        break;\n      }\n      case 4:\n      {\n        /*\n          Convert PseudoColor scanline.\n        */\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n          {\n            (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0x0f),\n              &index,exception);\n            SetPixelIndex(indexes+x,index);\n            (void) IsValidColormapIndex(image,(ssize_t) (*p & 0x0f),&index,\n              exception);\n            SetPixelIndex(indexes+x+1,index);\n            p++;\n          }\n          if ((image->columns % 2) != 0)\n            {\n              (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0xf),\n                &index,exception);\n              SetPixelIndex(indexes+(x++),index);\n              p++;\n            }\n          if (x < (ssize_t) image->columns)\n            break;\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        (void) SyncImage(image);\n        break;\n      }\n      case 8:\n      {\n        /*\n          Convert PseudoColor scanline.\n        */\n        if ((bmp_info.compression == BI_RLE8) ||\n            (bmp_info.compression == BI_RLE4))\n          bytes_per_line=image->columns;\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          for (x=(ssize_t) image->columns; x != 0; --x)\n          {\n            (void) IsValidColormapIndex(image,(ssize_t) *p,&index,exception);\n            SetPixelIndex(indexes,index);\n            indexes++;\n            p++;\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        (void) SyncImage(image);\n        break;\n      }\n      case 16:\n      {\n        unsigned int\n          alpha,\n          pixel;\n\n        /*\n          Convert bitfield encoded 16-bit PseudoColor scanline.\n        */\n        if (bmp_info.compression != BI_RGB &&\n            bmp_info.compression != BI_BITFIELDS)\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"UnrecognizedImageCompression\");\n          }\n        bytes_per_line=2*(image->columns+image->columns % 2);\n        image->storage_class=DirectClass;\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            pixel=(unsigned int) (*p++);\n            pixel|=(*p++) << 8;\n            red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n            if (quantum_bits.red == 5)\n              red|=((red & 0xe000) >> 5);\n            if (quantum_bits.red <= 8)\n              red|=((red & 0xff00) >> 8);\n            green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n            if (quantum_bits.green == 5)\n              green|=((green & 0xe000) >> 5);\n            if (quantum_bits.green == 6)\n              green|=((green & 0xc000) >> 6);\n            if (quantum_bits.green <= 8)\n              green|=((green & 0xff00) >> 8);\n            blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n            if (quantum_bits.blue == 5)\n              blue|=((blue & 0xe000) >> 5);\n            if (quantum_bits.blue <= 8)\n              blue|=((blue & 0xff00) >> 8);\n            SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n            SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n            SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n            SetPixelOpacity(q,OpaqueOpacity);\n            if (image->matte != MagickFalse)\n              {\n                alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n                if (quantum_bits.opacity <= 8)\n                  alpha|=((alpha & 0xff00) >> 8);\n                SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n              }\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      case 24:\n      {\n        /*\n          Convert DirectColor scanline.\n        */\n        bytes_per_line=4*((image->columns*24+31)/32);\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            SetPixelBlue(q,ScaleCharToQuantum(*p++));\n            SetPixelGreen(q,ScaleCharToQuantum(*p++));\n            SetPixelRed(q,ScaleCharToQuantum(*p++));\n            SetPixelOpacity(q,OpaqueOpacity);\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      case 32:\n      {\n        /*\n          Convert bitfield encoded DirectColor scanline.\n        */\n        if ((bmp_info.compression != BI_RGB) &&\n            (bmp_info.compression != BI_BITFIELDS))\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"UnrecognizedImageCompression\");\n          }\n        bytes_per_line=4*(image->columns);\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          unsigned int\n            alpha,\n            pixel;\n\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            pixel=(unsigned int) (*p++);\n            pixel|=((unsigned int) *p++ << 8);\n            pixel|=((unsigned int) *p++ << 16);\n            pixel|=((unsigned int) *p++ << 24);\n            red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n            if (quantum_bits.red == 8)\n              red|=(red >> 8);\n            green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n            if (quantum_bits.green == 8)\n              green|=(green >> 8);\n            blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n            if (quantum_bits.blue == 8)\n              blue|=(blue >> 8);\n            SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n            SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n            SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n            SetPixelAlpha(q,OpaqueOpacity);\n            if (image->matte != MagickFalse)\n              {\n                alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n                if (quantum_bits.opacity == 8)\n                  alpha|=(alpha >> 8);\n                SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n              }\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      default:\n      {\n        pixel_info=RelinquishVirtualMemory(pixel_info);\n        ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n    }\n    pixel_info=RelinquishVirtualMemory(pixel_info);\n    if (y > 0)\n      break;\n    if (EOFBlob(image) != MagickFalse)\n      {\n        ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n          image->filename);\n        break;\n      }\n    if (bmp_info.height < 0)\n      {\n        Image\n          *flipped_image;\n\n        /*\n          Correct image orientation.\n        */\n        flipped_image=FlipImage(image,exception);\n        if (flipped_image != (Image *) NULL)\n          {\n            DuplicateBlob(flipped_image,image);\n            ReplaceImageInList(&image, flipped_image);\n            image=flipped_image;\n          }\n      }\n    /*\n      Proceed to next image.\n    */\n    if (image_info->number_scenes != 0)\n      if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n        break;\n    *magick='\\0';\n    if (bmp_info.ba_offset != 0)\n      {\n        offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);\n        if (offset < 0)\n          ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n    count=ReadBlob(image,2,magick);\n    if ((count == 2) && (IsBMP(magick,2) != MagickFalse))\n      {\n        /*\n          Acquire next image structure.\n        */\n        AcquireNextImage(image_info,image);\n        if (GetNextImageInList(image) == (Image *) NULL)\n          {\n            status=MagickFalse;\n            break;\n          }\n        image=SyncNextImageInList(image);\n        status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n          GetBlobSize(image));\n        if (status == MagickFalse)\n          break;\n      }\n  } while (IsBMP(magick,2) != MagickFalse);\n  (void) CloseBlob(image);\n  if (status == MagickFalse)\n    return(DestroyImageList(image));\n  return(GetFirstImageInList(image));\n}", "func_hash": 31482023248196761538245576709415402386, "file_name": "bmp.c", "file_hash": 138018406162232274943459037643327051251, "cwe": ["CWE-401"], "cve": "CVE-2019-13133", "cve_desc": "ImageMagick before 7.0.8-50 has a memory leak vulnerability in the function ReadBMPImage in coders/bmp.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-13133"}
{"idx": 210692, "project": "ImageMagick6", "commit_id": "b268ce7a59440972f4476b9fd98104b6a836d971", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/b268ce7a59440972f4476b9fd98104b6a836d971", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1337", "target": 1, "func": "static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n  BMPInfo\n    bmp_info;\n\n  Image\n    *image;\n\n  IndexPacket\n    index;\n\n  MagickBooleanType\n    status;\n\n  MagickOffsetType\n    offset,\n    start_position;\n\n  MemoryInfo\n    *pixel_info;\n\n  register IndexPacket\n    *indexes;\n\n  register PixelPacket\n    *q;\n\n  register ssize_t\n    i,\n    x;\n\n  register unsigned char\n    *p;\n\n  size_t\n    bit,\n    bytes_per_line,\n    length;\n\n  ssize_t\n    count,\n    y;\n\n  unsigned char\n    magick[12],\n    *pixels;\n\n  unsigned int\n    blue,\n    green,\n    offset_bits,\n    red;\n\n  /*\n    Open image file.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  image=AcquireImage(image_info);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n    Determine if this a BMP file.\n  */\n  (void) memset(&bmp_info,0,sizeof(bmp_info));\n  bmp_info.ba_offset=0;\n  start_position=0;\n  offset_bits=0;\n  count=ReadBlob(image,2,magick);\n  if (count != 2)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  do\n  {\n    LongPixelPacket\n      shift;\n\n    PixelPacket\n      quantum_bits;\n\n    /*\n      Verify BMP identifier.\n    */\n    if (bmp_info.ba_offset == 0)\n      start_position=TellBlob(image)-2;\n    bmp_info.ba_offset=0;\n    while (LocaleNCompare((char *) magick,\"BA\",2) == 0)\n    {\n      bmp_info.file_size=ReadBlobLSBLong(image);\n      bmp_info.ba_offset=ReadBlobLSBLong(image);\n      bmp_info.offset_bits=ReadBlobLSBLong(image);\n      count=ReadBlob(image,2,magick);\n      if (count != 2)\n        break;\n    }\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  Magick: %c%c\",\n        magick[0],magick[1]);\n    if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) &&\n        (LocaleNCompare((char *) magick,\"CI\",2) != 0)))\n      ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n    bmp_info.file_size=ReadBlobLSBLong(image);\n    (void) ReadBlobLSBLong(image);\n\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n         \"  File_size in header:  %u bytes\",bmp_info.file_size);\n\n    bmp_info.offset_bits=ReadBlobLSBLong(image);\n    bmp_info.size=ReadBlobLSBLong(image);\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  BMP size: %u\",\n        bmp_info.size);\n    if (bmp_info.size == 12)\n      {\n        /*\n          OS/2 BMP image file.\n        */\n        (void) CopyMagickString(image->magick,\"BMP2\",MaxTextExtent);\n        bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));\n        bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));\n        bmp_info.planes=ReadBlobLSBShort(image);\n        bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n        bmp_info.x_pixels=0;\n        bmp_info.y_pixels=0;\n        bmp_info.number_colors=0;\n        bmp_info.compression=BI_RGB;\n        bmp_info.image_size=0;\n        bmp_info.alpha_mask=0;\n        if (image->debug != MagickFalse)\n          {\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Format: OS/2 Bitmap\");\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n              bmp_info.height);\n          }\n      }\n    else\n      {\n        /*\n          Microsoft Windows BMP image file.\n        */\n        if (bmp_info.size < 40)\n          ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\");\n        bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);\n        bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);\n        bmp_info.planes=ReadBlobLSBShort(image);\n        bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n        bmp_info.compression=ReadBlobLSBLong(image);\n        bmp_info.image_size=ReadBlobLSBLong(image);\n        bmp_info.x_pixels=ReadBlobLSBLong(image);\n        bmp_info.y_pixels=ReadBlobLSBLong(image);\n        bmp_info.number_colors=ReadBlobLSBLong(image);\n        if (bmp_info.number_colors > GetBlobSize(image))\n          ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n        bmp_info.colors_important=ReadBlobLSBLong(image);\n        if (image->debug != MagickFalse)\n          {\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Format: MS Windows bitmap\");\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n              bmp_info.height);\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel);\n            switch (bmp_info.compression)\n            {\n              case BI_RGB:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_RGB\");\n                break;\n              }\n              case BI_RLE4:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_RLE4\");\n                break;\n              }\n              case BI_RLE8:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_RLE8\");\n                break;\n              }\n              case BI_BITFIELDS:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_BITFIELDS\");\n                break;\n              }\n              case BI_PNG:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_PNG\");\n                break;\n              }\n              case BI_JPEG:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_JPEG\");\n                break;\n              }\n              default:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: UNKNOWN (%u)\",bmp_info.compression);\n              }\n            }\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Number of colors: %u\",bmp_info.number_colors);\n          }\n        bmp_info.red_mask=ReadBlobLSBLong(image);\n        bmp_info.green_mask=ReadBlobLSBLong(image);\n        bmp_info.blue_mask=ReadBlobLSBLong(image);\n        if (bmp_info.size > 40)\n          {\n            double\n              gamma;\n\n            /*\n              Read color management information.\n            */\n            bmp_info.alpha_mask=ReadBlobLSBLong(image);\n            bmp_info.colorspace=ReadBlobLSBSignedLong(image);\n            /*\n              Decode 2^30 fixed point formatted CIE primaries.\n            */\n#           define BMP_DENOM ((double) 0x40000000)\n            bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n\n            gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+\n              bmp_info.red_primary.z;\n            gamma=PerceptibleReciprocal(gamma);\n            bmp_info.red_primary.x*=gamma;\n            bmp_info.red_primary.y*=gamma;\n            image->chromaticity.red_primary.x=bmp_info.red_primary.x;\n            image->chromaticity.red_primary.y=bmp_info.red_primary.y;\n\n            gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+\n              bmp_info.green_primary.z;\n            gamma=PerceptibleReciprocal(gamma);\n            bmp_info.green_primary.x*=gamma;\n            bmp_info.green_primary.y*=gamma;\n            image->chromaticity.green_primary.x=bmp_info.green_primary.x;\n            image->chromaticity.green_primary.y=bmp_info.green_primary.y;\n\n            gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+\n              bmp_info.blue_primary.z;\n            gamma=PerceptibleReciprocal(gamma);\n            bmp_info.blue_primary.x*=gamma;\n            bmp_info.blue_primary.y*=gamma;\n            image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;\n            image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;\n\n            /*\n              Decode 16^16 fixed point formatted gamma_scales.\n            */\n            bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;\n            bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;\n            bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;\n            /*\n              Compute a single gamma from the BMP 3-channel gamma.\n            */\n            image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+\n              bmp_info.gamma_scale.z)/3.0;\n          }\n        else\n          (void) CopyMagickString(image->magick,\"BMP3\",MaxTextExtent);\n\n        if (bmp_info.size > 108)\n          {\n            size_t\n              intent;\n\n            /*\n              Read BMP Version 5 color management information.\n            */\n            intent=ReadBlobLSBLong(image);\n            switch ((int) intent)\n            {\n              case LCS_GM_BUSINESS:\n              {\n                image->rendering_intent=SaturationIntent;\n                break;\n              }\n              case LCS_GM_GRAPHICS:\n              {\n                image->rendering_intent=RelativeIntent;\n                break;\n              }\n              case LCS_GM_IMAGES:\n              {\n                image->rendering_intent=PerceptualIntent;\n                break;\n              }\n              case LCS_GM_ABS_COLORIMETRIC:\n              {\n                image->rendering_intent=AbsoluteIntent;\n                break;\n              }\n            }\n            (void) ReadBlobLSBLong(image);  /* Profile data */\n            (void) ReadBlobLSBLong(image);  /* Profile size */\n            (void) ReadBlobLSBLong(image);  /* Reserved byte */\n          }\n      }\n    if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))\n      (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n        \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename);\n    else\n      if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))\n        (void) ThrowMagickException(exception,GetMagickModule(),\n          CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\",\n          image->filename);\n    if (bmp_info.width <= 0)\n      ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n    if (bmp_info.height == 0)\n      ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n    if (bmp_info.planes != 1)\n      ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\");\n    if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&\n        (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&\n        (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    if (bmp_info.bits_per_pixel < 16 &&\n        bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedNumberOfColors\");\n    if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    switch (bmp_info.compression)\n    {\n      case BI_RGB:\n        image->compression=NoCompression;\n        break;\n      case BI_RLE8:\n      case BI_RLE4:\n        image->compression=RLECompression;\n        break;\n      case BI_BITFIELDS:\n        break;\n      case BI_JPEG:\n        ThrowReaderException(CoderError,\"JPEGCompressNotSupported\");\n      case BI_PNG:\n        ThrowReaderException(CoderError,\"PNGCompressNotSupported\");\n      default:\n        ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\");\n    }\n    image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);\n    image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);\n    image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;\n    image->matte=((bmp_info.alpha_mask != 0) &&\n      (bmp_info.compression == BI_BITFIELDS)) ? MagickTrue : MagickFalse;\n    if (bmp_info.bits_per_pixel < 16)\n      {\n        size_t\n          one;\n\n        image->storage_class=PseudoClass;\n        image->colors=bmp_info.number_colors;\n        one=1;\n        if (image->colors == 0)\n          image->colors=one << bmp_info.bits_per_pixel;\n      }\n    image->x_resolution=(double) bmp_info.x_pixels/100.0;\n    image->y_resolution=(double) bmp_info.y_pixels/100.0;\n    image->units=PixelsPerCentimeterResolution;\n    if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n      if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n        break;\n    status=SetImageExtent(image,image->columns,image->rows);\n    if (status == MagickFalse)\n      {\n        InheritException(exception,&image->exception);\n        return(DestroyImageList(image));\n      }\n    if (image->storage_class == PseudoClass)\n      {\n        unsigned char\n          *bmp_colormap;\n\n        size_t\n          packet_size;\n\n        /*\n          Read BMP raster colormap.\n        */\n        if (image->debug != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Reading colormap of %.20g colors\",(double) image->colors);\n        if (AcquireImageColormap(image,image->colors) == MagickFalse)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)\n          image->colors,4*sizeof(*bmp_colormap));\n        if (bmp_colormap == (unsigned char *) NULL)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        if ((bmp_info.size == 12) || (bmp_info.size == 64))\n          packet_size=3;\n        else\n          packet_size=4;\n        offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);\n        if (offset < 0)\n          {\n            bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n            ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n          }\n        count=ReadBlob(image,packet_size*image->colors,bmp_colormap);\n        if (count != (ssize_t) (packet_size*image->colors))\n          {\n            bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n            ThrowReaderException(CorruptImageError,\n              \"InsufficientImageDataInFile\");\n          }\n        p=bmp_colormap;\n        for (i=0; i < (ssize_t) image->colors; i++)\n        {\n          image->colormap[i].blue=ScaleCharToQuantum(*p++);\n          image->colormap[i].green=ScaleCharToQuantum(*p++);\n          image->colormap[i].red=ScaleCharToQuantum(*p++);\n          if (packet_size == 4)\n            p++;\n        }\n        bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n      }\n    /*\n      Read image data.\n    */\n    if (bmp_info.offset_bits == offset_bits)\n      ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n    offset_bits=bmp_info.offset_bits;\n    offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);\n    if (offset < 0)\n      ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n    if (bmp_info.compression == BI_RLE4)\n      bmp_info.bits_per_pixel<<=1;\n    bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);\n    length=(size_t) bytes_per_line*image->rows;\n    if (((MagickSizeType) length/8) > GetBlobSize(image))\n      ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n    if ((bmp_info.compression == BI_RGB) ||\n        (bmp_info.compression == BI_BITFIELDS))\n      {\n        pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n          image->columns+256UL)*sizeof(*pixels));\n        if (pixel_info == (MemoryInfo *) NULL)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n        if (image->debug != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Reading pixels (%.20g bytes)\",(double) length);\n        count=ReadBlob(image,length,pixels);\n        if (count != (ssize_t) length)\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"InsufficientImageDataInFile\");\n          }\n      }\n    else\n      {\n        /*\n          Convert run-length encoded raster pixels.\n        */\n        pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n          image->columns+256UL)*sizeof(*pixels));\n        if (pixel_info == (MemoryInfo *) NULL)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n        status=DecodeImage(image,bmp_info.compression,pixels,\n          image->columns*image->rows);\n        if (status == MagickFalse)\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"UnableToRunlengthDecodeImage\");\n          }\n      }\n    /*\n      Convert BMP raster image to pixel packets.\n    */\n    if (bmp_info.compression == BI_RGB)\n      {\n        /*\n          We should ignore the alpha value in BMP3 files but there have been\n          reports about 32 bit files with alpha. We do a quick check to see if\n          the alpha channel contains a value that is not zero (default value).\n          If we find a non zero value we asume the program that wrote the file\n          wants to use the alpha channel.\n        */\n        if ((image->matte == MagickFalse) && (bmp_info.size == 40) &&\n            (bmp_info.bits_per_pixel == 32))\n          {\n            bytes_per_line=4*(image->columns);\n            for (y=(ssize_t) image->rows-1; y >= 0; y--)\n            {\n              p=pixels+(image->rows-y-1)*bytes_per_line;\n              for (x=0; x < (ssize_t) image->columns; x++)\n              {\n                if (*(p+3) != 0)\n                  {\n                    image->matte=MagickTrue;\n                    y=-1;\n                    break;\n                  }\n                p+=4;\n              }\n            }\n          }\n        bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U;\n        bmp_info.red_mask=0x00ff0000U;\n        bmp_info.green_mask=0x0000ff00U;\n        bmp_info.blue_mask=0x000000ffU;\n        if (bmp_info.bits_per_pixel == 16)\n          {\n            /*\n              RGB555.\n            */\n            bmp_info.red_mask=0x00007c00U;\n            bmp_info.green_mask=0x000003e0U;\n            bmp_info.blue_mask=0x0000001fU;\n          }\n      }\n    (void) memset(&shift,0,sizeof(shift));\n    (void) memset(&quantum_bits,0,sizeof(quantum_bits));\n    if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))\n      {\n        register size_t\n          sample;\n\n        /*\n          Get shift and quantum bits info from bitfield masks.\n        */\n        if (bmp_info.red_mask != 0)\n          while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)\n          {\n            shift.red++;\n            if (shift.red > 32U)\n              break;\n          }\n        if (bmp_info.green_mask != 0)\n          while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)\n          {\n            shift.green++;\n            if (shift.green > 32U)\n              break;\n          }\n        if (bmp_info.blue_mask != 0)\n          while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)\n          {\n            shift.blue++;\n            if (shift.blue > 32U)\n              break;\n          }\n        if (bmp_info.alpha_mask != 0)\n          while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0)\n          {\n            shift.opacity++;\n            if (shift.opacity > 32U)\n              break;\n          }\n        sample=shift.red;\n        while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red);\n        sample=shift.green;\n        while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green);\n        sample=shift.blue;\n        while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue);\n        sample=shift.opacity;\n        while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.opacity=ClampToQuantum((MagickRealType) sample-\n          shift.opacity);\n      }\n    switch (bmp_info.bits_per_pixel)\n    {\n      case 1:\n      {\n        /*\n          Convert bitmap scanline.\n        */\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n          {\n            for (bit=0; bit < 8; bit++)\n            {\n              index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n              SetPixelIndex(indexes+x+bit,index);\n              q++;\n            }\n            p++;\n          }\n          if ((image->columns % 8) != 0)\n            {\n              for (bit=0; bit < (image->columns % 8); bit++)\n              {\n                index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n                SetPixelIndex(indexes+x+bit,index);\n              }\n              p++;\n            }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        (void) SyncImage(image);\n        break;\n      }\n      case 4:\n      {\n        /*\n          Convert PseudoColor scanline.\n        */\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n          {\n            (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0x0f),\n              &index,exception);\n            SetPixelIndex(indexes+x,index);\n            (void) IsValidColormapIndex(image,(ssize_t) (*p & 0x0f),&index,\n              exception);\n            SetPixelIndex(indexes+x+1,index);\n            p++;\n          }\n          if ((image->columns % 2) != 0)\n            {\n              (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0xf),\n                &index,exception);\n              SetPixelIndex(indexes+(x++),index);\n              p++;\n            }\n          if (x < (ssize_t) image->columns)\n            break;\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        (void) SyncImage(image);\n        break;\n      }\n      case 8:\n      {\n        /*\n          Convert PseudoColor scanline.\n        */\n        if ((bmp_info.compression == BI_RLE8) ||\n            (bmp_info.compression == BI_RLE4))\n          bytes_per_line=image->columns;\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          for (x=(ssize_t) image->columns; x != 0; --x)\n          {\n            (void) IsValidColormapIndex(image,(ssize_t) *p,&index,exception);\n            SetPixelIndex(indexes,index);\n            indexes++;\n            p++;\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        (void) SyncImage(image);\n        break;\n      }\n      case 16:\n      {\n        unsigned int\n          alpha,\n          pixel;\n\n        /*\n          Convert bitfield encoded 16-bit PseudoColor scanline.\n        */\n        if (bmp_info.compression != BI_RGB &&\n            bmp_info.compression != BI_BITFIELDS)\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"UnrecognizedImageCompression\");\n          }\n        bytes_per_line=2*(image->columns+image->columns % 2);\n        image->storage_class=DirectClass;\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            pixel=(unsigned int) (*p++);\n            pixel|=(*p++) << 8;\n            red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n            if (quantum_bits.red == 5)\n              red|=((red & 0xe000) >> 5);\n            if (quantum_bits.red <= 8)\n              red|=((red & 0xff00) >> 8);\n            green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n            if (quantum_bits.green == 5)\n              green|=((green & 0xe000) >> 5);\n            if (quantum_bits.green == 6)\n              green|=((green & 0xc000) >> 6);\n            if (quantum_bits.green <= 8)\n              green|=((green & 0xff00) >> 8);\n            blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n            if (quantum_bits.blue == 5)\n              blue|=((blue & 0xe000) >> 5);\n            if (quantum_bits.blue <= 8)\n              blue|=((blue & 0xff00) >> 8);\n            SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n            SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n            SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n            SetPixelOpacity(q,OpaqueOpacity);\n            if (image->matte != MagickFalse)\n              {\n                alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n                if (quantum_bits.opacity <= 8)\n                  alpha|=((alpha & 0xff00) >> 8);\n                SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n              }\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      case 24:\n      {\n        /*\n          Convert DirectColor scanline.\n        */\n        bytes_per_line=4*((image->columns*24+31)/32);\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            SetPixelBlue(q,ScaleCharToQuantum(*p++));\n            SetPixelGreen(q,ScaleCharToQuantum(*p++));\n            SetPixelRed(q,ScaleCharToQuantum(*p++));\n            SetPixelOpacity(q,OpaqueOpacity);\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      case 32:\n      {\n        /*\n          Convert bitfield encoded DirectColor scanline.\n        */\n        if ((bmp_info.compression != BI_RGB) &&\n            (bmp_info.compression != BI_BITFIELDS))\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"UnrecognizedImageCompression\");\n          }\n        bytes_per_line=4*(image->columns);\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          unsigned int\n            alpha,\n            pixel;\n\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            pixel=(unsigned int) (*p++);\n            pixel|=((unsigned int) *p++ << 8);\n            pixel|=((unsigned int) *p++ << 16);\n            pixel|=((unsigned int) *p++ << 24);\n            red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n            if (quantum_bits.red == 8)\n              red|=(red >> 8);\n            green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n            if (quantum_bits.green == 8)\n              green|=(green >> 8);\n            blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n            if (quantum_bits.blue == 8)\n              blue|=(blue >> 8);\n            SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n            SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n            SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n            SetPixelAlpha(q,OpaqueOpacity);\n            if (image->matte != MagickFalse)\n              {\n                alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n                if (quantum_bits.opacity == 8)\n                  alpha|=(alpha >> 8);\n                SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n              }\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      default:\n      {\n        pixel_info=RelinquishVirtualMemory(pixel_info);\n        ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n    }\n    pixel_info=RelinquishVirtualMemory(pixel_info);\n    if (y > 0)\n      break;\n    if (EOFBlob(image) != MagickFalse)\n      {\n        ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n          image->filename);\n        break;\n      }\n    if (bmp_info.height < 0)\n      {\n        Image\n          *flipped_image;\n\n        /*\n          Correct image orientation.\n        */\n        flipped_image=FlipImage(image,exception);\n        if (flipped_image != (Image *) NULL)\n          {\n            DuplicateBlob(flipped_image,image);\n            ReplaceImageInList(&image, flipped_image);\n            image=flipped_image;\n          }\n      }\n    /*\n      Proceed to next image.\n    */\n    if (image_info->number_scenes != 0)\n      if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n        break;\n    *magick='\\0';\n    if (bmp_info.ba_offset != 0)\n      {\n        offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);\n        if (offset < 0)\n          ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n    count=ReadBlob(image,2,magick);\n    if ((count == 2) && (IsBMP(magick,2) != MagickFalse))\n      {\n        /*\n          Acquire next image structure.\n        */\n        AcquireNextImage(image_info,image);\n        if (GetNextImageInList(image) == (Image *) NULL)\n          {\n            status=MagickFalse;\n            break;\n          }\n        image=SyncNextImageInList(image);\n        status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n          GetBlobSize(image));\n        if (status == MagickFalse)\n          break;\n      }\n  } while (IsBMP(magick,2) != MagickFalse);\n  (void) CloseBlob(image);\n  if (status == MagickFalse)\n    return(DestroyImageList(image));\n  return(GetFirstImageInList(image));\n}", "func_hash": 219736517469656591803182113097996134338, "file_name": "bmp.c", "file_hash": 111107907086942366665713567153559895973, "cwe": ["CWE-835"], "cve": "CVE-2018-18024", "cve_desc": "In ImageMagick 7.0.8-13 Q16, there is an infinite loop in the ReadBMPImage function of the coders/bmp.c file. Remote attackers could leverage this vulnerability to cause a denial of service via a crafted bmp file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-18024"}
{"idx": 439266, "project": "ImageMagick6", "commit_id": "b268ce7a59440972f4476b9fd98104b6a836d971", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/b268ce7a59440972f4476b9fd98104b6a836d971", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1337", "target": 0, "func": "static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n  BMPInfo\n    bmp_info;\n\n  Image\n    *image;\n\n  IndexPacket\n    index;\n\n  MagickBooleanType\n    status;\n\n  MagickOffsetType\n    offset,\n    start_position;\n\n  MemoryInfo\n    *pixel_info;\n\n  register IndexPacket\n    *indexes;\n\n  register PixelPacket\n    *q;\n\n  register ssize_t\n    i,\n    x;\n\n  register unsigned char\n    *p;\n\n  size_t\n    bit,\n    bytes_per_line,\n    length;\n\n  ssize_t\n    count,\n    y;\n\n  unsigned char\n    magick[12],\n    *pixels;\n\n  unsigned int\n    blue,\n    green,\n    offset_bits,\n    red;\n\n  /*\n    Open image file.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  if (image_info->debug != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  image=AcquireImage(image_info);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  /*\n    Determine if this a BMP file.\n  */\n  (void) memset(&bmp_info,0,sizeof(bmp_info));\n  bmp_info.ba_offset=0;\n  start_position=0;\n  offset_bits=0;\n  count=ReadBlob(image,2,magick);\n  if (count != 2)\n    ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n  do\n  {\n    LongPixelPacket\n      shift;\n\n    PixelPacket\n      quantum_bits;\n\n    /*\n      Verify BMP identifier.\n    */\n    start_position=TellBlob(image)-2;\n    bmp_info.ba_offset=0;\n    while (LocaleNCompare((char *) magick,\"BA\",2) == 0)\n    {\n      bmp_info.file_size=ReadBlobLSBLong(image);\n      bmp_info.ba_offset=ReadBlobLSBLong(image);\n      bmp_info.offset_bits=ReadBlobLSBLong(image);\n      count=ReadBlob(image,2,magick);\n      if (count != 2)\n        break;\n    }\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  Magick: %c%c\",\n        magick[0],magick[1]);\n    if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) &&\n        (LocaleNCompare((char *) magick,\"CI\",2) != 0)))\n      ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n    bmp_info.file_size=ReadBlobLSBLong(image);\n    (void) ReadBlobLSBLong(image);\n\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n         \"  File_size in header:  %u bytes\",bmp_info.file_size);\n\n    bmp_info.offset_bits=ReadBlobLSBLong(image);\n    bmp_info.size=ReadBlobLSBLong(image);\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"  BMP size: %u\",\n        bmp_info.size);\n    if (bmp_info.size == 12)\n      {\n        /*\n          OS/2 BMP image file.\n        */\n        (void) CopyMagickString(image->magick,\"BMP2\",MaxTextExtent);\n        bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));\n        bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));\n        bmp_info.planes=ReadBlobLSBShort(image);\n        bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n        bmp_info.x_pixels=0;\n        bmp_info.y_pixels=0;\n        bmp_info.number_colors=0;\n        bmp_info.compression=BI_RGB;\n        bmp_info.image_size=0;\n        bmp_info.alpha_mask=0;\n        if (image->debug != MagickFalse)\n          {\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Format: OS/2 Bitmap\");\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n              bmp_info.height);\n          }\n      }\n    else\n      {\n        /*\n          Microsoft Windows BMP image file.\n        */\n        if (bmp_info.size < 40)\n          ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\");\n        bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);\n        bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);\n        bmp_info.planes=ReadBlobLSBShort(image);\n        bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n        bmp_info.compression=ReadBlobLSBLong(image);\n        bmp_info.image_size=ReadBlobLSBLong(image);\n        bmp_info.x_pixels=ReadBlobLSBLong(image);\n        bmp_info.y_pixels=ReadBlobLSBLong(image);\n        bmp_info.number_colors=ReadBlobLSBLong(image);\n        if (bmp_info.number_colors > GetBlobSize(image))\n          ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n        bmp_info.colors_important=ReadBlobLSBLong(image);\n        if (image->debug != MagickFalse)\n          {\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Format: MS Windows bitmap\");\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n              bmp_info.height);\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel);\n            switch (bmp_info.compression)\n            {\n              case BI_RGB:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_RGB\");\n                break;\n              }\n              case BI_RLE4:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_RLE4\");\n                break;\n              }\n              case BI_RLE8:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_RLE8\");\n                break;\n              }\n              case BI_BITFIELDS:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_BITFIELDS\");\n                break;\n              }\n              case BI_PNG:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_PNG\");\n                break;\n              }\n              case BI_JPEG:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: BI_JPEG\");\n                break;\n              }\n              default:\n              {\n                (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                  \"  Compression: UNKNOWN (%u)\",bmp_info.compression);\n              }\n            }\n            (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n              \"  Number of colors: %u\",bmp_info.number_colors);\n          }\n        bmp_info.red_mask=ReadBlobLSBLong(image);\n        bmp_info.green_mask=ReadBlobLSBLong(image);\n        bmp_info.blue_mask=ReadBlobLSBLong(image);\n        if (bmp_info.size > 40)\n          {\n            double\n              gamma;\n\n            /*\n              Read color management information.\n            */\n            bmp_info.alpha_mask=ReadBlobLSBLong(image);\n            bmp_info.colorspace=ReadBlobLSBSignedLong(image);\n            /*\n              Decode 2^30 fixed point formatted CIE primaries.\n            */\n#           define BMP_DENOM ((double) 0x40000000)\n            bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n            bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n\n            gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+\n              bmp_info.red_primary.z;\n            gamma=PerceptibleReciprocal(gamma);\n            bmp_info.red_primary.x*=gamma;\n            bmp_info.red_primary.y*=gamma;\n            image->chromaticity.red_primary.x=bmp_info.red_primary.x;\n            image->chromaticity.red_primary.y=bmp_info.red_primary.y;\n\n            gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+\n              bmp_info.green_primary.z;\n            gamma=PerceptibleReciprocal(gamma);\n            bmp_info.green_primary.x*=gamma;\n            bmp_info.green_primary.y*=gamma;\n            image->chromaticity.green_primary.x=bmp_info.green_primary.x;\n            image->chromaticity.green_primary.y=bmp_info.green_primary.y;\n\n            gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+\n              bmp_info.blue_primary.z;\n            gamma=PerceptibleReciprocal(gamma);\n            bmp_info.blue_primary.x*=gamma;\n            bmp_info.blue_primary.y*=gamma;\n            image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;\n            image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;\n\n            /*\n              Decode 16^16 fixed point formatted gamma_scales.\n            */\n            bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;\n            bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;\n            bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;\n            /*\n              Compute a single gamma from the BMP 3-channel gamma.\n            */\n            image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+\n              bmp_info.gamma_scale.z)/3.0;\n          }\n        else\n          (void) CopyMagickString(image->magick,\"BMP3\",MaxTextExtent);\n\n        if (bmp_info.size > 108)\n          {\n            size_t\n              intent;\n\n            /*\n              Read BMP Version 5 color management information.\n            */\n            intent=ReadBlobLSBLong(image);\n            switch ((int) intent)\n            {\n              case LCS_GM_BUSINESS:\n              {\n                image->rendering_intent=SaturationIntent;\n                break;\n              }\n              case LCS_GM_GRAPHICS:\n              {\n                image->rendering_intent=RelativeIntent;\n                break;\n              }\n              case LCS_GM_IMAGES:\n              {\n                image->rendering_intent=PerceptualIntent;\n                break;\n              }\n              case LCS_GM_ABS_COLORIMETRIC:\n              {\n                image->rendering_intent=AbsoluteIntent;\n                break;\n              }\n            }\n            (void) ReadBlobLSBLong(image);  /* Profile data */\n            (void) ReadBlobLSBLong(image);  /* Profile size */\n            (void) ReadBlobLSBLong(image);  /* Reserved byte */\n          }\n      }\n    if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))\n      (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n        \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename);\n    else\n      if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))\n        (void) ThrowMagickException(exception,GetMagickModule(),\n          CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\",\n          image->filename);\n    if (bmp_info.width <= 0)\n      ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n    if (bmp_info.height == 0)\n      ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n    if (bmp_info.planes != 1)\n      ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\");\n    if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&\n        (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&\n        (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    if (bmp_info.bits_per_pixel < 16 &&\n        bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedNumberOfColors\");\n    if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))\n      ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n    switch (bmp_info.compression)\n    {\n      case BI_RGB:\n        image->compression=NoCompression;\n        break;\n      case BI_RLE8:\n      case BI_RLE4:\n        image->compression=RLECompression;\n        break;\n      case BI_BITFIELDS:\n        break;\n      case BI_JPEG:\n        ThrowReaderException(CoderError,\"JPEGCompressNotSupported\");\n      case BI_PNG:\n        ThrowReaderException(CoderError,\"PNGCompressNotSupported\");\n      default:\n        ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\");\n    }\n    image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);\n    image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);\n    image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;\n    image->matte=((bmp_info.alpha_mask != 0) &&\n      (bmp_info.compression == BI_BITFIELDS)) ? MagickTrue : MagickFalse;\n    if (bmp_info.bits_per_pixel < 16)\n      {\n        size_t\n          one;\n\n        image->storage_class=PseudoClass;\n        image->colors=bmp_info.number_colors;\n        one=1;\n        if (image->colors == 0)\n          image->colors=one << bmp_info.bits_per_pixel;\n      }\n    image->x_resolution=(double) bmp_info.x_pixels/100.0;\n    image->y_resolution=(double) bmp_info.y_pixels/100.0;\n    image->units=PixelsPerCentimeterResolution;\n    if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n      if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n        break;\n    status=SetImageExtent(image,image->columns,image->rows);\n    if (status == MagickFalse)\n      {\n        InheritException(exception,&image->exception);\n        return(DestroyImageList(image));\n      }\n    if (image->storage_class == PseudoClass)\n      {\n        unsigned char\n          *bmp_colormap;\n\n        size_t\n          packet_size;\n\n        /*\n          Read BMP raster colormap.\n        */\n        if (image->debug != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Reading colormap of %.20g colors\",(double) image->colors);\n        if (AcquireImageColormap(image,image->colors) == MagickFalse)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)\n          image->colors,4*sizeof(*bmp_colormap));\n        if (bmp_colormap == (unsigned char *) NULL)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        if ((bmp_info.size == 12) || (bmp_info.size == 64))\n          packet_size=3;\n        else\n          packet_size=4;\n        offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);\n        if (offset < 0)\n          {\n            bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n            ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n          }\n        count=ReadBlob(image,packet_size*image->colors,bmp_colormap);\n        if (count != (ssize_t) (packet_size*image->colors))\n          {\n            bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n            ThrowReaderException(CorruptImageError,\n              \"InsufficientImageDataInFile\");\n          }\n        p=bmp_colormap;\n        for (i=0; i < (ssize_t) image->colors; i++)\n        {\n          image->colormap[i].blue=ScaleCharToQuantum(*p++);\n          image->colormap[i].green=ScaleCharToQuantum(*p++);\n          image->colormap[i].red=ScaleCharToQuantum(*p++);\n          if (packet_size == 4)\n            p++;\n        }\n        bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n      }\n    /*\n      Read image data.\n    */\n    if (bmp_info.offset_bits == offset_bits)\n      ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n    offset_bits=bmp_info.offset_bits;\n    offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);\n    if (offset < 0)\n      ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n    if (bmp_info.compression == BI_RLE4)\n      bmp_info.bits_per_pixel<<=1;\n    bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);\n    length=(size_t) bytes_per_line*image->rows;\n    if (((MagickSizeType) length/8) > GetBlobSize(image))\n      ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n    if ((bmp_info.compression == BI_RGB) ||\n        (bmp_info.compression == BI_BITFIELDS))\n      {\n        pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n          image->columns+256UL)*sizeof(*pixels));\n        if (pixel_info == (MemoryInfo *) NULL)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n        if (image->debug != MagickFalse)\n          (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n            \"  Reading pixels (%.20g bytes)\",(double) length);\n        count=ReadBlob(image,length,pixels);\n        if (count != (ssize_t) length)\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"InsufficientImageDataInFile\");\n          }\n      }\n    else\n      {\n        /*\n          Convert run-length encoded raster pixels.\n        */\n        pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line,\n          image->columns+256UL)*sizeof(*pixels));\n        if (pixel_info == (MemoryInfo *) NULL)\n          ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n        pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n        status=DecodeImage(image,bmp_info.compression,pixels,\n          image->columns*image->rows);\n        if (status == MagickFalse)\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"UnableToRunlengthDecodeImage\");\n          }\n      }\n    /*\n      Convert BMP raster image to pixel packets.\n    */\n    if (bmp_info.compression == BI_RGB)\n      {\n        /*\n          We should ignore the alpha value in BMP3 files but there have been\n          reports about 32 bit files with alpha. We do a quick check to see if\n          the alpha channel contains a value that is not zero (default value).\n          If we find a non zero value we asume the program that wrote the file\n          wants to use the alpha channel.\n        */\n        if ((image->matte == MagickFalse) && (bmp_info.size == 40) &&\n            (bmp_info.bits_per_pixel == 32))\n          {\n            bytes_per_line=4*(image->columns);\n            for (y=(ssize_t) image->rows-1; y >= 0; y--)\n            {\n              p=pixels+(image->rows-y-1)*bytes_per_line;\n              for (x=0; x < (ssize_t) image->columns; x++)\n              {\n                if (*(p+3) != 0)\n                  {\n                    image->matte=MagickTrue;\n                    y=-1;\n                    break;\n                  }\n                p+=4;\n              }\n            }\n          }\n        bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U;\n        bmp_info.red_mask=0x00ff0000U;\n        bmp_info.green_mask=0x0000ff00U;\n        bmp_info.blue_mask=0x000000ffU;\n        if (bmp_info.bits_per_pixel == 16)\n          {\n            /*\n              RGB555.\n            */\n            bmp_info.red_mask=0x00007c00U;\n            bmp_info.green_mask=0x000003e0U;\n            bmp_info.blue_mask=0x0000001fU;\n          }\n      }\n    (void) memset(&shift,0,sizeof(shift));\n    (void) memset(&quantum_bits,0,sizeof(quantum_bits));\n    if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))\n      {\n        register size_t\n          sample;\n\n        /*\n          Get shift and quantum bits info from bitfield masks.\n        */\n        if (bmp_info.red_mask != 0)\n          while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)\n          {\n            shift.red++;\n            if (shift.red > 32U)\n              break;\n          }\n        if (bmp_info.green_mask != 0)\n          while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)\n          {\n            shift.green++;\n            if (shift.green > 32U)\n              break;\n          }\n        if (bmp_info.blue_mask != 0)\n          while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)\n          {\n            shift.blue++;\n            if (shift.blue > 32U)\n              break;\n          }\n        if (bmp_info.alpha_mask != 0)\n          while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0)\n          {\n            shift.opacity++;\n            if (shift.opacity > 32U)\n              break;\n          }\n        sample=shift.red;\n        while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red);\n        sample=shift.green;\n        while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green);\n        sample=shift.blue;\n        while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue);\n        sample=shift.opacity;\n        while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)\n        {\n          sample++;\n          if (sample > 32U)\n            break;\n        }\n        quantum_bits.opacity=ClampToQuantum((MagickRealType) sample-\n          shift.opacity);\n      }\n    switch (bmp_info.bits_per_pixel)\n    {\n      case 1:\n      {\n        /*\n          Convert bitmap scanline.\n        */\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n          {\n            for (bit=0; bit < 8; bit++)\n            {\n              index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n              SetPixelIndex(indexes+x+bit,index);\n              q++;\n            }\n            p++;\n          }\n          if ((image->columns % 8) != 0)\n            {\n              for (bit=0; bit < (image->columns % 8); bit++)\n              {\n                index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n                SetPixelIndex(indexes+x+bit,index);\n              }\n              p++;\n            }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        (void) SyncImage(image);\n        break;\n      }\n      case 4:\n      {\n        /*\n          Convert PseudoColor scanline.\n        */\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n          {\n            (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0x0f),\n              &index,exception);\n            SetPixelIndex(indexes+x,index);\n            (void) IsValidColormapIndex(image,(ssize_t) (*p & 0x0f),&index,\n              exception);\n            SetPixelIndex(indexes+x+1,index);\n            p++;\n          }\n          if ((image->columns % 2) != 0)\n            {\n              (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0xf),\n                &index,exception);\n              SetPixelIndex(indexes+(x++),index);\n              p++;\n            }\n          if (x < (ssize_t) image->columns)\n            break;\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        (void) SyncImage(image);\n        break;\n      }\n      case 8:\n      {\n        /*\n          Convert PseudoColor scanline.\n        */\n        if ((bmp_info.compression == BI_RLE8) ||\n            (bmp_info.compression == BI_RLE4))\n          bytes_per_line=image->columns;\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          for (x=(ssize_t) image->columns; x != 0; --x)\n          {\n            (void) IsValidColormapIndex(image,(ssize_t) *p,&index,exception);\n            SetPixelIndex(indexes,index);\n            indexes++;\n            p++;\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        (void) SyncImage(image);\n        break;\n      }\n      case 16:\n      {\n        unsigned int\n          alpha,\n          pixel;\n\n        /*\n          Convert bitfield encoded 16-bit PseudoColor scanline.\n        */\n        if (bmp_info.compression != BI_RGB &&\n            bmp_info.compression != BI_BITFIELDS)\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"UnrecognizedImageCompression\");\n          }\n        bytes_per_line=2*(image->columns+image->columns % 2);\n        image->storage_class=DirectClass;\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            pixel=(unsigned int) (*p++);\n            pixel|=(*p++) << 8;\n            red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n            if (quantum_bits.red == 5)\n              red|=((red & 0xe000) >> 5);\n            if (quantum_bits.red <= 8)\n              red|=((red & 0xff00) >> 8);\n            green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n            if (quantum_bits.green == 5)\n              green|=((green & 0xe000) >> 5);\n            if (quantum_bits.green == 6)\n              green|=((green & 0xc000) >> 6);\n            if (quantum_bits.green <= 8)\n              green|=((green & 0xff00) >> 8);\n            blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n            if (quantum_bits.blue == 5)\n              blue|=((blue & 0xe000) >> 5);\n            if (quantum_bits.blue <= 8)\n              blue|=((blue & 0xff00) >> 8);\n            SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n            SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n            SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n            SetPixelOpacity(q,OpaqueOpacity);\n            if (image->matte != MagickFalse)\n              {\n                alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n                if (quantum_bits.opacity <= 8)\n                  alpha|=((alpha & 0xff00) >> 8);\n                SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n              }\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      case 24:\n      {\n        /*\n          Convert DirectColor scanline.\n        */\n        bytes_per_line=4*((image->columns*24+31)/32);\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            SetPixelBlue(q,ScaleCharToQuantum(*p++));\n            SetPixelGreen(q,ScaleCharToQuantum(*p++));\n            SetPixelRed(q,ScaleCharToQuantum(*p++));\n            SetPixelOpacity(q,OpaqueOpacity);\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      case 32:\n      {\n        /*\n          Convert bitfield encoded DirectColor scanline.\n        */\n        if ((bmp_info.compression != BI_RGB) &&\n            (bmp_info.compression != BI_BITFIELDS))\n          {\n            pixel_info=RelinquishVirtualMemory(pixel_info);\n            ThrowReaderException(CorruptImageError,\n              \"UnrecognizedImageCompression\");\n          }\n        bytes_per_line=4*(image->columns);\n        for (y=(ssize_t) image->rows-1; y >= 0; y--)\n        {\n          unsigned int\n            alpha,\n            pixel;\n\n          p=pixels+(image->rows-y-1)*bytes_per_line;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            pixel=(unsigned int) (*p++);\n            pixel|=((unsigned int) *p++ << 8);\n            pixel|=((unsigned int) *p++ << 16);\n            pixel|=((unsigned int) *p++ << 24);\n            red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n            if (quantum_bits.red == 8)\n              red|=(red >> 8);\n            green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n            if (quantum_bits.green == 8)\n              green|=(green >> 8);\n            blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n            if (quantum_bits.blue == 8)\n              blue|=(blue >> 8);\n            SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));\n            SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));\n            SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));\n            SetPixelAlpha(q,OpaqueOpacity);\n            if (image->matte != MagickFalse)\n              {\n                alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;\n                if (quantum_bits.opacity == 8)\n                  alpha|=(alpha >> 8);\n                SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));\n              }\n            q++;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          offset=(MagickOffsetType) (image->rows-y-1);\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n                (image->rows-y),image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      default:\n      {\n        pixel_info=RelinquishVirtualMemory(pixel_info);\n        ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n    }\n    pixel_info=RelinquishVirtualMemory(pixel_info);\n    if (y > 0)\n      break;\n    if (EOFBlob(image) != MagickFalse)\n      {\n        ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n          image->filename);\n        break;\n      }\n    if (bmp_info.height < 0)\n      {\n        Image\n          *flipped_image;\n\n        /*\n          Correct image orientation.\n        */\n        flipped_image=FlipImage(image,exception);\n        if (flipped_image != (Image *) NULL)\n          {\n            DuplicateBlob(flipped_image,image);\n            ReplaceImageInList(&image, flipped_image);\n            image=flipped_image;\n          }\n      }\n    /*\n      Proceed to next image.\n    */\n    if (image_info->number_scenes != 0)\n      if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n        break;\n    *magick='\\0';\n    if (bmp_info.ba_offset != 0)\n      {\n        offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);\n        if (offset < 0)\n          ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n    count=ReadBlob(image,2,magick);\n    if ((count == 2) && (IsBMP(magick,2) != MagickFalse))\n      {\n        /*\n          Acquire next image structure.\n        */\n        AcquireNextImage(image_info,image);\n        if (GetNextImageInList(image) == (Image *) NULL)\n          {\n            status=MagickFalse;\n            break;\n          }\n        image=SyncNextImageInList(image);\n        status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n          GetBlobSize(image));\n        if (status == MagickFalse)\n          break;\n      }\n  } while (IsBMP(magick,2) != MagickFalse);\n  (void) CloseBlob(image);\n  if (status == MagickFalse)\n    return(DestroyImageList(image));\n  return(GetFirstImageInList(image));\n}", "func_hash": 66356813508609166160965332796532041768, "file_name": "bmp.c", "file_hash": 262370016928103197032695947461982198206, "cwe": ["CWE-835"], "cve": "CVE-2018-18024", "cve_desc": "In ImageMagick 7.0.8-13 Q16, there is an infinite loop in the ReadBMPImage function of the coders/bmp.c file. Remote attackers could leverage this vulnerability to cause a denial of service via a crafted bmp file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-18024"}
{"idx": 210700, "project": "squashfs-tools", "commit_id": "79b5a555058eef4e1e7ff220c344d39f8cd09646", "project_url": "https://github.com/plougher/squashfs-tools", "commit_url": "https://github.com/plougher/squashfs-tools/commit/79b5a555058eef4e1e7ff220c344d39f8cd09646", "commit_message": "Unsquashfs: fix write outside destination directory exploit\n\nAn issue on Github (https://github.com/plougher/squashfs-tools/issues/72)\nshows how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and ..) can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nThis commit fixes this exploit by checking all names for\nvalidity.\n\nIn doing so I have also added checks for '.' and for names that\nare shorter than they should be (names in the file system should\nnot have '\\0' terminators).\n\nSigned-off-by: Phillip Lougher ", "target": 1, "func": "static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tsquashfs_dir_header_2 dirh;\n\tchar buffer[sizeof(squashfs_dir_entry_2) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tsquashfs_dir_entry_2 *dire = (squashfs_dir_entry_2 *) buffer;\n\tlong long start;\n\tint bytes;\n\tint dir_count, size;\n\tstruct dir_ent *new_dir;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: malloc failed!\\n\");\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = 0;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 0)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\t\t\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\tbytes = lookup_entry(directory_table_hash, start);\n\tif(bytes == -1)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: directory block %d not \"\n\t\t\t\"found!\\n\", block_start);\n\n\tbytes += (*i)->offset;\n\tsize = (*i)->data + bytes;\n\n\twhile(bytes < size) {\t\t\t\n\t\tif(swap) {\n\t\t\tsquashfs_dir_header_2 sdirh;\n\t\t\tmemcpy(&sdirh, directory_table + bytes, sizeof(sdirh));\n\t\t\tSQUASHFS_SWAP_DIR_HEADER_2(&dirh, &sdirh);\n\t\t} else\n\t\t\tmemcpy(&dirh, directory_table + bytes, sizeof(dirh));\n\t\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tif(swap) {\n\t\t\t\tsquashfs_dir_entry_2 sdire;\n\t\t\t\tmemcpy(&sdire, directory_table + bytes,\n\t\t\t\t\tsizeof(sdire));\n\t\t\t\tSQUASHFS_SWAP_DIR_ENTRY_2(dire, &sdire);\n\t\t\t} else\n\t\t\t\tmemcpy(dire, directory_table + bytes,\n\t\t\t\t\tsizeof(*dire));\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tmemcpy(dire->name, directory_table + bytes,\n\t\t\t\tdire->size + 1);\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\t\t\tif((dir->dir_count % DIR_ENT_SIZE) == 0) {\n\t\t\t\tnew_dir = realloc(dir->dirs, (dir->dir_count +\n\t\t\t\t\tDIR_ENT_SIZE) * sizeof(struct dir_ent));\n\t\t\t\tif(new_dir == NULL)\n\t\t\t\t\tEXIT_UNSQUASH(\"squashfs_opendir: \"\n\t\t\t\t\t\t\"realloc failed!\\n\");\n\t\t\t\tdir->dirs = new_dir;\n\t\t\t}\n\t\t\tstrcpy(dir->dirs[dir->dir_count].name, dire->name);\n\t\t\tdir->dirs[dir->dir_count].start_block =\n\t\t\t\tdirh.start_block;\n\t\t\tdir->dirs[dir->dir_count].offset = dire->offset;\n\t\t\tdir->dirs[dir->dir_count].type = dire->type;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tfree(dir->dirs);\n\tfree(dir);\n\treturn NULL;\n}", "func_hash": 337353141626678057542635238119408606270, "file_name": "None", "file_hash": null, "cwe": ["CWE-22"], "cve": "CVE-2021-40153", "cve_desc": "squashfs_opendir in unsquash-1.c in Squashfs-Tools 4.5 stores the filename in the directory entry; this is then used by unsquashfs to create the new file during the unsquash. The filename is not validated for traversal outside of the destination directory, and thus allows writing to locations outside of the destination.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40153"}
{"idx": 439495, "project": "squashfs-tools", "commit_id": "79b5a555058eef4e1e7ff220c344d39f8cd09646", "project_url": "https://github.com/plougher/squashfs-tools", "commit_url": "https://github.com/plougher/squashfs-tools/commit/79b5a555058eef4e1e7ff220c344d39f8cd09646", "commit_message": "Unsquashfs: fix write outside destination directory exploit\n\nAn issue on Github (https://github.com/plougher/squashfs-tools/issues/72)\nshows how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and ..) can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nThis commit fixes this exploit by checking all names for\nvalidity.\n\nIn doing so I have also added checks for '.' and for names that\nare shorter than they should be (names in the file system should\nnot have '\\0' terminators).\n\nSigned-off-by: Phillip Lougher ", "target": 0, "func": "static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tsquashfs_dir_header_2 dirh;\n\tchar buffer[sizeof(squashfs_dir_entry_2) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tsquashfs_dir_entry_2 *dire = (squashfs_dir_entry_2 *) buffer;\n\tlong long start;\n\tint bytes;\n\tint dir_count, size;\n\tstruct dir_ent *new_dir;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: malloc failed!\\n\");\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = 0;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 0)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\t\t\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\tbytes = lookup_entry(directory_table_hash, start);\n\tif(bytes == -1)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: directory block %d not \"\n\t\t\t\"found!\\n\", block_start);\n\n\tbytes += (*i)->offset;\n\tsize = (*i)->data + bytes;\n\n\twhile(bytes < size) {\t\t\t\n\t\tif(swap) {\n\t\t\tsquashfs_dir_header_2 sdirh;\n\t\t\tmemcpy(&sdirh, directory_table + bytes, sizeof(sdirh));\n\t\t\tSQUASHFS_SWAP_DIR_HEADER_2(&dirh, &sdirh);\n\t\t} else\n\t\t\tmemcpy(&dirh, directory_table + bytes, sizeof(dirh));\n\t\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tif(swap) {\n\t\t\t\tsquashfs_dir_entry_2 sdire;\n\t\t\t\tmemcpy(&sdire, directory_table + bytes,\n\t\t\t\t\tsizeof(sdire));\n\t\t\t\tSQUASHFS_SWAP_DIR_ENTRY_2(dire, &sdire);\n\t\t\t} else\n\t\t\t\tmemcpy(dire, directory_table + bytes,\n\t\t\t\t\tsizeof(*dire));\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tmemcpy(dire->name, directory_table + bytes,\n\t\t\t\tdire->size + 1);\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\n\t\t\t/* check name for invalid characters (i.e /, ., ..) */\n\t\t\tif(check_name(dire->name, dire->size + 1) == FALSE) {\n\t\t\t\tERROR(\"File system corrupted: invalid characters in name\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\t\t\tif((dir->dir_count % DIR_ENT_SIZE) == 0) {\n\t\t\t\tnew_dir = realloc(dir->dirs, (dir->dir_count +\n\t\t\t\t\tDIR_ENT_SIZE) * sizeof(struct dir_ent));\n\t\t\t\tif(new_dir == NULL)\n\t\t\t\t\tEXIT_UNSQUASH(\"squashfs_opendir: \"\n\t\t\t\t\t\t\"realloc failed!\\n\");\n\t\t\t\tdir->dirs = new_dir;\n\t\t\t}\n\t\t\tstrcpy(dir->dirs[dir->dir_count].name, dire->name);\n\t\t\tdir->dirs[dir->dir_count].start_block =\n\t\t\t\tdirh.start_block;\n\t\t\tdir->dirs[dir->dir_count].offset = dire->offset;\n\t\t\tdir->dirs[dir->dir_count].type = dire->type;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tfree(dir->dirs);\n\tfree(dir);\n\treturn NULL;\n}", "func_hash": 199340706190975735867110978341140950924, "file_name": "None", "file_hash": null, "cwe": ["CWE-22"], "cve": "CVE-2021-40153", "cve_desc": "squashfs_opendir in unsquash-1.c in Squashfs-Tools 4.5 stores the filename in the directory entry; this is then used by unsquashfs to create the new file during the unsquash. The filename is not validated for traversal outside of the destination directory, and thus allows writing to locations outside of the destination.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40153"}
{"idx": 210701, "project": "squashfs-tools", "commit_id": "79b5a555058eef4e1e7ff220c344d39f8cd09646", "project_url": "https://github.com/plougher/squashfs-tools", "commit_url": "https://github.com/plougher/squashfs-tools/commit/79b5a555058eef4e1e7ff220c344d39f8cd09646", "commit_message": "Unsquashfs: fix write outside destination directory exploit\n\nAn issue on Github (https://github.com/plougher/squashfs-tools/issues/72)\nshows how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and ..) can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nThis commit fixes this exploit by checking all names for\nvalidity.\n\nIn doing so I have also added checks for '.' and for names that\nare shorter than they should be (names in the file system should\nnot have '\\0' terminators).\n\nSigned-off-by: Phillip Lougher ", "target": 1, "func": "static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tsquashfs_dir_header_3 dirh;\n\tchar buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tsquashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer;\n\tlong long start;\n\tint bytes;\n\tint dir_count, size;\n\tstruct dir_ent *new_dir;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: malloc failed!\\n\");\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = 0;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 3)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\tbytes = lookup_entry(directory_table_hash, start);\n\n\tif(bytes == -1)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: directory block %d not \"\n\t\t\t\"found!\\n\", block_start);\n\n\tbytes += (*i)->offset;\n\tsize = (*i)->data + bytes - 3;\n\n\twhile(bytes < size) {\t\t\t\n\t\tif(swap) {\n\t\t\tsquashfs_dir_header_3 sdirh;\n\t\t\tmemcpy(&sdirh, directory_table + bytes, sizeof(sdirh));\n\t\t\tSQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh);\n\t\t} else\n\t\t\tmemcpy(&dirh, directory_table + bytes, sizeof(dirh));\n\t\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tif(swap) {\n\t\t\t\tsquashfs_dir_entry_3 sdire;\n\t\t\t\tmemcpy(&sdire, directory_table + bytes,\n\t\t\t\t\tsizeof(sdire));\n\t\t\t\tSQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire);\n\t\t\t} else\n\t\t\t\tmemcpy(dire, directory_table + bytes,\n\t\t\t\t\tsizeof(*dire));\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tmemcpy(dire->name, directory_table + bytes,\n\t\t\t\tdire->size + 1);\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\t\t\tif((dir->dir_count % DIR_ENT_SIZE) == 0) {\n\t\t\t\tnew_dir = realloc(dir->dirs, (dir->dir_count +\n\t\t\t\t\tDIR_ENT_SIZE) * sizeof(struct dir_ent));\n\t\t\t\tif(new_dir == NULL)\n\t\t\t\t\tEXIT_UNSQUASH(\"squashfs_opendir: \"\n\t\t\t\t\t\t\"realloc failed!\\n\");\n\t\t\t\tdir->dirs = new_dir;\n\t\t\t}\n\t\t\tstrcpy(dir->dirs[dir->dir_count].name, dire->name);\n\t\t\tdir->dirs[dir->dir_count].start_block =\n\t\t\t\tdirh.start_block;\n\t\t\tdir->dirs[dir->dir_count].offset = dire->offset;\n\t\t\tdir->dirs[dir->dir_count].type = dire->type;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tfree(dir->dirs);\n\tfree(dir);\n\treturn NULL;\n}", "func_hash": 116402969943084287107249411216213408317, "file_name": "None", "file_hash": null, "cwe": ["CWE-22"], "cve": "CVE-2021-40153", "cve_desc": "squashfs_opendir in unsquash-1.c in Squashfs-Tools 4.5 stores the filename in the directory entry; this is then used by unsquashfs to create the new file during the unsquash. The filename is not validated for traversal outside of the destination directory, and thus allows writing to locations outside of the destination.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40153"}
{"idx": 439495, "project": "squashfs-tools", "commit_id": "79b5a555058eef4e1e7ff220c344d39f8cd09646", "project_url": "https://github.com/plougher/squashfs-tools", "commit_url": "https://github.com/plougher/squashfs-tools/commit/79b5a555058eef4e1e7ff220c344d39f8cd09646", "commit_message": "Unsquashfs: fix write outside destination directory exploit\n\nAn issue on Github (https://github.com/plougher/squashfs-tools/issues/72)\nshows how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and ..) can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nThis commit fixes this exploit by checking all names for\nvalidity.\n\nIn doing so I have also added checks for '.' and for names that\nare shorter than they should be (names in the file system should\nnot have '\\0' terminators).\n\nSigned-off-by: Phillip Lougher ", "target": 0, "func": "static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tsquashfs_dir_header_2 dirh;\n\tchar buffer[sizeof(squashfs_dir_entry_2) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tsquashfs_dir_entry_2 *dire = (squashfs_dir_entry_2 *) buffer;\n\tlong long start;\n\tint bytes;\n\tint dir_count, size;\n\tstruct dir_ent *new_dir;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: malloc failed!\\n\");\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = 0;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 0)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\t\t\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\tbytes = lookup_entry(directory_table_hash, start);\n\tif(bytes == -1)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: directory block %d not \"\n\t\t\t\"found!\\n\", block_start);\n\n\tbytes += (*i)->offset;\n\tsize = (*i)->data + bytes;\n\n\twhile(bytes < size) {\t\t\t\n\t\tif(swap) {\n\t\t\tsquashfs_dir_header_2 sdirh;\n\t\t\tmemcpy(&sdirh, directory_table + bytes, sizeof(sdirh));\n\t\t\tSQUASHFS_SWAP_DIR_HEADER_2(&dirh, &sdirh);\n\t\t} else\n\t\t\tmemcpy(&dirh, directory_table + bytes, sizeof(dirh));\n\t\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tif(swap) {\n\t\t\t\tsquashfs_dir_entry_2 sdire;\n\t\t\t\tmemcpy(&sdire, directory_table + bytes,\n\t\t\t\t\tsizeof(sdire));\n\t\t\t\tSQUASHFS_SWAP_DIR_ENTRY_2(dire, &sdire);\n\t\t\t} else\n\t\t\t\tmemcpy(dire, directory_table + bytes,\n\t\t\t\t\tsizeof(*dire));\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tmemcpy(dire->name, directory_table + bytes,\n\t\t\t\tdire->size + 1);\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\n\t\t\t/* check name for invalid characters (i.e /, ., ..) */\n\t\t\tif(check_name(dire->name, dire->size + 1) == FALSE) {\n\t\t\t\tERROR(\"File system corrupted: invalid characters in name\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\t\t\tif((dir->dir_count % DIR_ENT_SIZE) == 0) {\n\t\t\t\tnew_dir = realloc(dir->dirs, (dir->dir_count +\n\t\t\t\t\tDIR_ENT_SIZE) * sizeof(struct dir_ent));\n\t\t\t\tif(new_dir == NULL)\n\t\t\t\t\tEXIT_UNSQUASH(\"squashfs_opendir: \"\n\t\t\t\t\t\t\"realloc failed!\\n\");\n\t\t\t\tdir->dirs = new_dir;\n\t\t\t}\n\t\t\tstrcpy(dir->dirs[dir->dir_count].name, dire->name);\n\t\t\tdir->dirs[dir->dir_count].start_block =\n\t\t\t\tdirh.start_block;\n\t\t\tdir->dirs[dir->dir_count].offset = dire->offset;\n\t\t\tdir->dirs[dir->dir_count].type = dire->type;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tfree(dir->dirs);\n\tfree(dir);\n\treturn NULL;\n}", "func_hash": 199340706190975735867110978341140950924, "file_name": "None", "file_hash": null, "cwe": ["CWE-22"], "cve": "CVE-2021-40153", "cve_desc": "squashfs_opendir in unsquash-1.c in Squashfs-Tools 4.5 stores the filename in the directory entry; this is then used by unsquashfs to create the new file during the unsquash. The filename is not validated for traversal outside of the destination directory, and thus allows writing to locations outside of the destination.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40153"}
{"idx": 210702, "project": "squashfs-tools", "commit_id": "79b5a555058eef4e1e7ff220c344d39f8cd09646", "project_url": "https://github.com/plougher/squashfs-tools", "commit_url": "https://github.com/plougher/squashfs-tools/commit/79b5a555058eef4e1e7ff220c344d39f8cd09646", "commit_message": "Unsquashfs: fix write outside destination directory exploit\n\nAn issue on Github (https://github.com/plougher/squashfs-tools/issues/72)\nshows how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and ..) can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nThis commit fixes this exploit by checking all names for\nvalidity.\n\nIn doing so I have also added checks for '.' and for names that\nare shorter than they should be (names in the file system should\nnot have '\\0' terminators).\n\nSigned-off-by: Phillip Lougher ", "target": 1, "func": "static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tstruct squashfs_dir_header dirh;\n\tchar buffer[sizeof(struct squashfs_dir_entry) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tstruct squashfs_dir_entry *dire = (struct squashfs_dir_entry *) buffer;\n\tlong long start;\n\tlong long bytes;\n\tint dir_count, size;\n\tstruct dir_ent *new_dir;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: malloc failed!\\n\");\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = 0;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 3)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\tbytes = lookup_entry(directory_table_hash, start);\n\n\tif(bytes == -1)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: directory block %lld not \"\n\t\t\t\"found!\\n\", start);\n\n\tbytes += (*i)->offset;\n\tsize = (*i)->data + bytes - 3;\n\n\twhile(bytes < size) {\t\t\t\n\t\tSQUASHFS_SWAP_DIR_HEADER(directory_table + bytes, &dirh);\n\t\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tSQUASHFS_SWAP_DIR_ENTRY(directory_table + bytes, dire);\n\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tmemcpy(dire->name, directory_table + bytes,\n\t\t\t\tdire->size + 1);\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\t\t\tif((dir->dir_count % DIR_ENT_SIZE) == 0) {\n\t\t\t\tnew_dir = realloc(dir->dirs, (dir->dir_count +\n\t\t\t\t\tDIR_ENT_SIZE) * sizeof(struct dir_ent));\n\t\t\t\tif(new_dir == NULL)\n\t\t\t\t\tEXIT_UNSQUASH(\"squashfs_opendir: \"\n\t\t\t\t\t\t\"realloc failed!\\n\");\n\t\t\t\tdir->dirs = new_dir;\n\t\t\t}\n\t\t\tstrcpy(dir->dirs[dir->dir_count].name, dire->name);\n\t\t\tdir->dirs[dir->dir_count].start_block =\n\t\t\t\tdirh.start_block;\n\t\t\tdir->dirs[dir->dir_count].offset = dire->offset;\n\t\t\tdir->dirs[dir->dir_count].type = dire->type;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tfree(dir->dirs);\n\tfree(dir);\n\treturn NULL;\n}", "func_hash": 154561395254122138545216205310820189651, "file_name": "None", "file_hash": null, "cwe": ["CWE-22"], "cve": "CVE-2021-40153", "cve_desc": "squashfs_opendir in unsquash-1.c in Squashfs-Tools 4.5 stores the filename in the directory entry; this is then used by unsquashfs to create the new file during the unsquash. The filename is not validated for traversal outside of the destination directory, and thus allows writing to locations outside of the destination.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40153"}
{"idx": 439500, "project": "squashfs-tools", "commit_id": "79b5a555058eef4e1e7ff220c344d39f8cd09646", "project_url": "https://github.com/plougher/squashfs-tools", "commit_url": "https://github.com/plougher/squashfs-tools/commit/79b5a555058eef4e1e7ff220c344d39f8cd09646", "commit_message": "Unsquashfs: fix write outside destination directory exploit\n\nAn issue on Github (https://github.com/plougher/squashfs-tools/issues/72)\nshows how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and ..) can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nThis commit fixes this exploit by checking all names for\nvalidity.\n\nIn doing so I have also added checks for '.' and for names that\nare shorter than they should be (names in the file system should\nnot have '\\0' terminators).\n\nSigned-off-by: Phillip Lougher ", "target": 0, "func": "static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tstruct squashfs_dir_header dirh;\n\tchar buffer[sizeof(struct squashfs_dir_entry) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tstruct squashfs_dir_entry *dire = (struct squashfs_dir_entry *) buffer;\n\tlong long start;\n\tlong long bytes;\n\tint dir_count, size;\n\tstruct dir_ent *new_dir;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: malloc failed!\\n\");\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = 0;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 3)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\tbytes = lookup_entry(directory_table_hash, start);\n\n\tif(bytes == -1)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: directory block %lld not \"\n\t\t\t\"found!\\n\", start);\n\n\tbytes += (*i)->offset;\n\tsize = (*i)->data + bytes - 3;\n\n\twhile(bytes < size) {\t\t\t\n\t\tSQUASHFS_SWAP_DIR_HEADER(directory_table + bytes, &dirh);\n\t\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tSQUASHFS_SWAP_DIR_ENTRY(directory_table + bytes, dire);\n\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tmemcpy(dire->name, directory_table + bytes,\n\t\t\t\tdire->size + 1);\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\n\t\t\t/* check name for invalid characters (i.e /, ., ..) */\n\t\t\tif(check_name(dire->name, dire->size + 1) == FALSE) {\n\t\t\t\tERROR(\"File system corrupted: invalid characters in name\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\t\t\tif((dir->dir_count % DIR_ENT_SIZE) == 0) {\n\t\t\t\tnew_dir = realloc(dir->dirs, (dir->dir_count +\n\t\t\t\t\tDIR_ENT_SIZE) * sizeof(struct dir_ent));\n\t\t\t\tif(new_dir == NULL)\n\t\t\t\t\tEXIT_UNSQUASH(\"squashfs_opendir: \"\n\t\t\t\t\t\t\"realloc failed!\\n\");\n\t\t\t\tdir->dirs = new_dir;\n\t\t\t}\n\t\t\tstrcpy(dir->dirs[dir->dir_count].name, dire->name);\n\t\t\tdir->dirs[dir->dir_count].start_block =\n\t\t\t\tdirh.start_block;\n\t\t\tdir->dirs[dir->dir_count].offset = dire->offset;\n\t\t\tdir->dirs[dir->dir_count].type = dire->type;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tfree(dir->dirs);\n\tfree(dir);\n\treturn NULL;\n}", "func_hash": 43120172755872228262829058526345637532, "file_name": "None", "file_hash": null, "cwe": ["CWE-22"], "cve": "CVE-2021-40153", "cve_desc": "squashfs_opendir in unsquash-1.c in Squashfs-Tools 4.5 stores the filename in the directory entry; this is then used by unsquashfs to create the new file during the unsquash. The filename is not validated for traversal outside of the destination directory, and thus allows writing to locations outside of the destination.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-40153"}
{"idx": 210834, "project": "xserver", "commit_id": "da15c7413916f754708c62c2089265528cd661e2", "project_url": "http://gitweb.freedesktop.org/?p=xorg/xserver", "commit_url": "https://gitlab.freedesktop.org/xorg/xserver/commit/da15c7413916f754708c62c2089265528cd661e2", "commit_message": "LogFilePrep: add a comment to the unsafe format string.\n\nCVE-2018-14665 also made it possible to exploit this to access\nmemory. With -logfile forbidden when running with elevated privileges\nthis is no longer an issue.\n\nSigned-off-by: Matthieu Herrb \nReviewed-by: Adam Jackson \n(cherry picked from commit 248d164eae27f1f310266d78e52f13f64362f81e)", "target": 1, "func": "LogFilePrep(const char *fname, const char *backup, const char *idstring)\n{\n    char *logFileName = NULL;\n\n    if (asprintf(&logFileName, fname, idstring) == -1)\n        FatalError(\"Cannot allocate space for the log file name\\n\");\n\n    if (backup && *backup) {\n        struct stat buf;\n\n        if (!stat(logFileName, &buf) && S_ISREG(buf.st_mode)) {\n            char *suffix;\n            char *oldLog;\n\n            if ((asprintf(&suffix, backup, idstring) == -1) ||\n                (asprintf(&oldLog, \"%s%s\", logFileName, suffix) == -1)) {\n                FatalError(\"Cannot allocate space for the log file name\\n\");\n            }\n            free(suffix);\n\n            if (rename(logFileName, oldLog) == -1) {\n                FatalError(\"Cannot move old log file \\\"%s\\\" to \\\"%s\\\"\\n\",\n                           logFileName, oldLog);\n            }\n            free(oldLog);\n        }\n    }\n    else {\n        if (remove(logFileName) != 0 && errno != ENOENT) {\n            FatalError(\"Cannot remove old log file \\\"%s\\\": %s\\n\",\n                       logFileName, strerror(errno));\n        }\n    }\n\n    return logFileName;\n}", "func_hash": 277712603100280804771479435923197051078, "file_name": "log.c", "file_hash": 167553120578038740767387284849222115292, "cwe": ["CWE-863"], "cve": "CVE-2018-14665", "cve_desc": "A flaw was found in xorg-x11-server before 1.20.3. An incorrect permission check for -modulepath and -logfile options when starting Xorg. X server allows unprivileged users with the ability to log in to the system via physical console to escalate their privileges and run arbitrary code under root privileges.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-14665"}
{"idx": 440872, "project": "xserver", "commit_id": "da15c7413916f754708c62c2089265528cd661e2", "project_url": "http://gitweb.freedesktop.org/?p=xorg/xserver", "commit_url": "https://gitlab.freedesktop.org/xorg/xserver/commit/da15c7413916f754708c62c2089265528cd661e2", "commit_message": "LogFilePrep: add a comment to the unsafe format string.\n\nCVE-2018-14665 also made it possible to exploit this to access\nmemory. With -logfile forbidden when running with elevated privileges\nthis is no longer an issue.\n\nSigned-off-by: Matthieu Herrb \nReviewed-by: Adam Jackson \n(cherry picked from commit 248d164eae27f1f310266d78e52f13f64362f81e)", "target": 0, "func": "LogFilePrep(const char *fname, const char *backup, const char *idstring)\n{\n    char *logFileName = NULL;\n\n    /* the format string below is controlled by the user,\n       this code should never be called with elevated privileges */\n    if (asprintf(&logFileName, fname, idstring) == -1)\n        FatalError(\"Cannot allocate space for the log file name\\n\");\n\n    if (backup && *backup) {\n        struct stat buf;\n\n        if (!stat(logFileName, &buf) && S_ISREG(buf.st_mode)) {\n            char *suffix;\n            char *oldLog;\n\n            if ((asprintf(&suffix, backup, idstring) == -1) ||\n                (asprintf(&oldLog, \"%s%s\", logFileName, suffix) == -1)) {\n                FatalError(\"Cannot allocate space for the log file name\\n\");\n            }\n            free(suffix);\n\n            if (rename(logFileName, oldLog) == -1) {\n                FatalError(\"Cannot move old log file \\\"%s\\\" to \\\"%s\\\"\\n\",\n                           logFileName, oldLog);\n            }\n            free(oldLog);\n        }\n    }\n    else {\n        if (remove(logFileName) != 0 && errno != ENOENT) {\n            FatalError(\"Cannot remove old log file \\\"%s\\\": %s\\n\",\n                       logFileName, strerror(errno));\n        }\n    }\n\n    return logFileName;\n}", "func_hash": 85184341830214931807730036188005624601, "file_name": "log.c", "file_hash": 179282942128446717145205180547721530846, "cwe": ["CWE-863"], "cve": "CVE-2018-14665", "cve_desc": "A flaw was found in xorg-x11-server before 1.20.3. An incorrect permission check for -modulepath and -logfile options when starting Xorg. X server allows unprivileged users with the ability to log in to the system via physical console to escalate their privileges and run arbitrary code under root privileges.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-14665"}
{"idx": 210866, "project": "xserver", "commit_id": "144849ea27230962227e62a943b399e2ab304787", "project_url": "http://gitweb.freedesktop.org/?p=xorg/xserver", "commit_url": "https://gitlab.freedesktop.org/xorg/xserver/-/commit/144849ea27230962227e62a943b399e2ab304787", "commit_message": "Fix XkbSelectEvents() integer underflow\n\nCVE-2020-14361 ZDI-CAN 11573\n\nThis vulnerability was discovered by:\nJan-Niklas Sohn working with Trend Micro Zero Day Initiative\n\nSigned-off-by: Matthieu Herrb ", "target": 1, "func": "SProcXkbSelectEvents(ClientPtr client)\n{\n    REQUEST(xkbSelectEventsReq);\n\n    swaps(&stuff->length);\n    REQUEST_AT_LEAST_SIZE(xkbSelectEventsReq);\n    swaps(&stuff->deviceSpec);\n    swaps(&stuff->affectWhich);\n    swaps(&stuff->clear);\n    swaps(&stuff->selectAll);\n    swaps(&stuff->affectMap);\n    swaps(&stuff->map);\n    if ((stuff->affectWhich & (~XkbMapNotifyMask)) != 0) {\n        union {\n            BOOL *b;\n            CARD8 *c8;\n            CARD16 *c16;\n            CARD32 *c32;\n        } from;\n        register unsigned bit, ndx, maskLeft, dataLeft, size;\n\n        from.c8 = (CARD8 *) &stuff[1];\n        dataLeft = (stuff->length * 4) - SIZEOF(xkbSelectEventsReq);\n        maskLeft = (stuff->affectWhich & (~XkbMapNotifyMask));\n        for (ndx = 0, bit = 1; (maskLeft != 0); ndx++, bit <<= 1) {\n            if (((bit & maskLeft) == 0) || (ndx == XkbMapNotify))\n                continue;\n            maskLeft &= ~bit;\n            if ((stuff->selectAll & bit) || (stuff->clear & bit))\n                continue;\n            switch (ndx) {\n            case XkbNewKeyboardNotify:\n            case XkbStateNotify:\n            case XkbNamesNotify:\n            case XkbAccessXNotify:\n            case XkbExtensionDeviceNotify:\n                size = 2;\n                break;\n            case XkbControlsNotify:\n            case XkbIndicatorStateNotify:\n            case XkbIndicatorMapNotify:\n                size = 4;\n                break;\n            case XkbBellNotify:\n            case XkbActionMessage:\n            case XkbCompatMapNotify:\n                size = 1;\n                break;\n            default:\n                client->errorValue = _XkbErrCode2(0x1, bit);\n                return BadValue;\n            }\n            if (dataLeft < (size * 2))\n                return BadLength;\n            if (size == 2) {\n                swaps(&from.c16[0]);\n                swaps(&from.c16[1]);\n            }\n            else if (size == 4) {\n                swapl(&from.c32[0]);\n                swapl(&from.c32[1]);\n            }\n            else {\n                size = 2;\n            }\n            from.c8 += (size * 2);\n            dataLeft -= (size * 2);\n        }\n        if (dataLeft > 2) {\n            ErrorF(\"[xkb] Extra data (%d bytes) after SelectEvents\\n\",\n                   dataLeft);\n            return BadLength;\n        }\n    }\n    return ProcXkbSelectEvents(client);\n}", "func_hash": 49390769000512777763270194535836546170, "file_name": "xkbSwap.c", "file_hash": 248954015122387054723435955727908433288, "cwe": ["CWE-191"], "cve": "CVE-2020-14361", "cve_desc": "A flaw was found in X.Org Server before xorg-x11-server 1.20.9. An Integer underflow leading to heap-buffer overflow may lead to a privilege escalation vulnerability. The highest threat from this vulnerability is to data confidentiality and integrity as well as system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-14361"}
{"idx": 441822, "project": "xserver", "commit_id": "144849ea27230962227e62a943b399e2ab304787", "project_url": "http://gitweb.freedesktop.org/?p=xorg/xserver", "commit_url": "https://gitlab.freedesktop.org/xorg/xserver/-/commit/144849ea27230962227e62a943b399e2ab304787", "commit_message": "Fix XkbSelectEvents() integer underflow\n\nCVE-2020-14361 ZDI-CAN 11573\n\nThis vulnerability was discovered by:\nJan-Niklas Sohn working with Trend Micro Zero Day Initiative\n\nSigned-off-by: Matthieu Herrb ", "target": 0, "func": "SProcXkbSelectEvents(ClientPtr client)\n{\n    REQUEST(xkbSelectEventsReq);\n\n    swaps(&stuff->length);\n    REQUEST_AT_LEAST_SIZE(xkbSelectEventsReq);\n    swaps(&stuff->deviceSpec);\n    swaps(&stuff->affectWhich);\n    swaps(&stuff->clear);\n    swaps(&stuff->selectAll);\n    swaps(&stuff->affectMap);\n    swaps(&stuff->map);\n    if ((stuff->affectWhich & (~XkbMapNotifyMask)) != 0) {\n        union {\n            BOOL *b;\n            CARD8 *c8;\n            CARD16 *c16;\n            CARD32 *c32;\n        } from;\n        register unsigned bit, ndx, maskLeft, dataLeft, size;\n\n        from.c8 = (CARD8 *) &stuff[1];\n        dataLeft = (client->req_len * 4) - SIZEOF(xkbSelectEventsReq);\n        maskLeft = (stuff->affectWhich & (~XkbMapNotifyMask));\n        for (ndx = 0, bit = 1; (maskLeft != 0); ndx++, bit <<= 1) {\n            if (((bit & maskLeft) == 0) || (ndx == XkbMapNotify))\n                continue;\n            maskLeft &= ~bit;\n            if ((stuff->selectAll & bit) || (stuff->clear & bit))\n                continue;\n            switch (ndx) {\n            case XkbNewKeyboardNotify:\n            case XkbStateNotify:\n            case XkbNamesNotify:\n            case XkbAccessXNotify:\n            case XkbExtensionDeviceNotify:\n                size = 2;\n                break;\n            case XkbControlsNotify:\n            case XkbIndicatorStateNotify:\n            case XkbIndicatorMapNotify:\n                size = 4;\n                break;\n            case XkbBellNotify:\n            case XkbActionMessage:\n            case XkbCompatMapNotify:\n                size = 1;\n                break;\n            default:\n                client->errorValue = _XkbErrCode2(0x1, bit);\n                return BadValue;\n            }\n            if (dataLeft < (size * 2))\n                return BadLength;\n            if (size == 2) {\n                swaps(&from.c16[0]);\n                swaps(&from.c16[1]);\n            }\n            else if (size == 4) {\n                swapl(&from.c32[0]);\n                swapl(&from.c32[1]);\n            }\n            else {\n                size = 2;\n            }\n            from.c8 += (size * 2);\n            dataLeft -= (size * 2);\n        }\n        if (dataLeft > 2) {\n            ErrorF(\"[xkb] Extra data (%d bytes) after SelectEvents\\n\",\n                   dataLeft);\n            return BadLength;\n        }\n    }\n    return ProcXkbSelectEvents(client);\n}", "func_hash": 168019691135253524576440591667545390332, "file_name": "xkbSwap.c", "file_hash": 269646087598713036939088933146683136630, "cwe": ["CWE-191"], "cve": "CVE-2020-14361", "cve_desc": "A flaw was found in X.Org Server before xorg-x11-server 1.20.9. An Integer underflow leading to heap-buffer overflow may lead to a privilege escalation vulnerability. The highest threat from this vulnerability is to data confidentiality and integrity as well as system availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-14361"}
{"idx": 210887, "project": "qemu", "commit_id": "1caff0340f49c93d535c6558a5138d20d475315c", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://git.qemu.org/?p=qemu.git;a=commit;h=1caff0340f49c93d535c6558a5138d20d475315c", "commit_message": "e1000: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Jason Wang ", "target": 1, "func": "e1000_send_packet(E1000State *s, const uint8_t *buf, int size)\n{\n    static const int PTCregs[6] = { PTC64, PTC127, PTC255, PTC511,\n                                    PTC1023, PTC1522 };\n\n    NetClientState *nc = qemu_get_queue(s->nic);\n    if (s->phy_reg[PHY_CTRL] & MII_CR_LOOPBACK) {\n        nc->info->receive(nc, buf, size);\n    } else {\n        qemu_send_packet(nc, buf, size);\n    }\n    inc_tx_bcast_or_mcast_count(s, buf);\n    e1000x_increase_size_stats(s->mac_reg, PTCregs, size);\n}", "func_hash": 230013883840968138268073793174320435209, "file_name": "e1000.c", "file_hash": 176409209781362413917058775514144703306, "cwe": ["CWE-835"], "cve": "CVE-2021-3416", "cve_desc": "A potential stack overflow via infinite loop issue was found in various NIC emulators of QEMU in versions up to and including 5.2.0. The issue occurs in loopback mode of a NIC wherein reentrant DMA checks get bypassed. A guest user/process may use this flaw to consume CPU cycles or crash the QEMU process on the host resulting in DoS scenario.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3416"}
{"idx": 442189, "project": "qemu", "commit_id": "1caff0340f49c93d535c6558a5138d20d475315c", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://git.qemu.org/?p=qemu.git;a=commit;h=1caff0340f49c93d535c6558a5138d20d475315c", "commit_message": "e1000: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Jason Wang ", "target": 0, "func": "e1000_send_packet(E1000State *s, const uint8_t *buf, int size)\n{\n    static const int PTCregs[6] = { PTC64, PTC127, PTC255, PTC511,\n                                    PTC1023, PTC1522 };\n\n    NetClientState *nc = qemu_get_queue(s->nic);\n    if (s->phy_reg[PHY_CTRL] & MII_CR_LOOPBACK) {\n        qemu_receive_packet(nc, buf, size);\n    } else {\n        qemu_send_packet(nc, buf, size);\n    }\n    inc_tx_bcast_or_mcast_count(s, buf);\n    e1000x_increase_size_stats(s->mac_reg, PTCregs, size);\n}", "func_hash": 300536712775088152847906693971285564175, "file_name": "e1000.c", "file_hash": 47410790699069024700445146821057200888, "cwe": ["CWE-835"], "cve": "CVE-2021-3416", "cve_desc": "A potential stack overflow via infinite loop issue was found in various NIC emulators of QEMU in versions up to and including 5.2.0. The issue occurs in loopback mode of a NIC wherein reentrant DMA checks get bypassed. A guest user/process may use this flaw to consume CPU cycles or crash the QEMU process on the host resulting in DoS scenario.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3416"}
{"idx": 210896, "project": "spice", "commit_id": "a4a16ac42d2f19a17e36556546aa94d5cd83745f", "project_url": "https://gitlab.freedesktop.org/spice/spice", "commit_url": "https://gitlab.freedesktop.org/spice/spice/commit/a4a16ac42d2f19a17e36556546aa94d5cd83745f", "commit_message": "memslot: Fix off-by-one error in group/slot boundary check\n\nRedMemSlotInfo keeps an array of groups, and each group contains an\narray of slots. Unfortunately, these checks are off by 1, they check\nthat the index is greater or equal to the number of elements in the\narray, while these arrays are 0 based. The check should only check for\nstrictly greater than the number of elements.\n\nFor the group array, this is not a big issue, as these memslot groups\nare created by spice-server users (eg QEMU), and the group ids used to\nindex that array are also generated by the spice-server user, so it\nshould not be possible for the guest to set them to arbitrary values.\n\nThe slot id is more problematic, as it's calculated from a QXLPHYSICAL\naddress, and such addresses are usually set by the guest QXL driver, so\nthe guest can set these to arbitrary values, including malicious values,\nwhich are probably easy to build from the guest PCI configuration.\n\nThis patch fixes the arrays bound check, and adds a test case for this.\nThis fixes CVE-2019-3813.\n\nSigned-off-by: Christophe Fergeau \nAcked-by: Frediano Ziglio ", "target": 1, "func": "void *memslot_get_virt(RedMemSlotInfo *info, QXLPHYSICAL addr, uint32_t add_size,\n                       int group_id)\n{\n    int slot_id;\n    int generation;\n    unsigned long h_virt;\n\n    MemSlot *slot;\n\n    if (group_id > info->num_memslots_groups) {\n        spice_critical(\"group_id too big\");\n        return NULL;\n    }\n\n    slot_id = memslot_get_id(info, addr);\n    if (slot_id > info->num_memslots) {\n        print_memslots(info);\n        spice_critical(\"slot_id %d too big, addr=%\" PRIx64, slot_id, addr);\n        return NULL;\n    }\n\n    slot = &info->mem_slots[group_id][slot_id];\n\n    generation = memslot_get_generation(info, addr);\n    if (generation != slot->generation) {\n        print_memslots(info);\n        spice_critical(\"address generation is not valid, group_id %d, slot_id %d, \"\n                       \"gen %d, slot_gen %d\",\n                       group_id, slot_id,\n                       generation, slot->generation);\n        return NULL;\n    }\n\n    h_virt = __get_clean_virt(info, addr);\n    h_virt += slot->address_delta;\n\n    if (!memslot_validate_virt(info, h_virt, slot_id, add_size, group_id)) {\n        return NULL;\n    }\n\n    return (void*)(uintptr_t)h_virt;\n}", "func_hash": 339666083531536346198123409033012275535, "file_name": "memslot.c", "file_hash": 314430538622797217223560939109800616180, "cwe": ["CWE-193"], "cve": "CVE-2019-3813", "cve_desc": "Spice, versions 0.5.2 through 0.14.1, are vulnerable to an out-of-bounds read due to an off-by-one error in memslot_get_virt. This may lead to a denial of service, or, in the worst case, code-execution by unauthenticated attackers.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-3813"}
{"idx": 442587, "project": "spice", "commit_id": "a4a16ac42d2f19a17e36556546aa94d5cd83745f", "project_url": "https://gitlab.freedesktop.org/spice/spice", "commit_url": "https://gitlab.freedesktop.org/spice/spice/commit/a4a16ac42d2f19a17e36556546aa94d5cd83745f", "commit_message": "memslot: Fix off-by-one error in group/slot boundary check\n\nRedMemSlotInfo keeps an array of groups, and each group contains an\narray of slots. Unfortunately, these checks are off by 1, they check\nthat the index is greater or equal to the number of elements in the\narray, while these arrays are 0 based. The check should only check for\nstrictly greater than the number of elements.\n\nFor the group array, this is not a big issue, as these memslot groups\nare created by spice-server users (eg QEMU), and the group ids used to\nindex that array are also generated by the spice-server user, so it\nshould not be possible for the guest to set them to arbitrary values.\n\nThe slot id is more problematic, as it's calculated from a QXLPHYSICAL\naddress, and such addresses are usually set by the guest QXL driver, so\nthe guest can set these to arbitrary values, including malicious values,\nwhich are probably easy to build from the guest PCI configuration.\n\nThis patch fixes the arrays bound check, and adds a test case for this.\nThis fixes CVE-2019-3813.\n\nSigned-off-by: Christophe Fergeau \nAcked-by: Frediano Ziglio ", "target": 0, "func": "void *memslot_get_virt(RedMemSlotInfo *info, QXLPHYSICAL addr, uint32_t add_size,\n                       int group_id)\n{\n    int slot_id;\n    int generation;\n    unsigned long h_virt;\n\n    MemSlot *slot;\n\n    if (group_id >= info->num_memslots_groups) {\n        spice_critical(\"group_id too big\");\n        return NULL;\n    }\n\n    slot_id = memslot_get_id(info, addr);\n    if (slot_id >= info->num_memslots) {\n        print_memslots(info);\n        spice_critical(\"slot_id %d too big, addr=%\" PRIx64, slot_id, addr);\n        return NULL;\n    }\n\n    slot = &info->mem_slots[group_id][slot_id];\n\n    generation = memslot_get_generation(info, addr);\n    if (generation != slot->generation) {\n        print_memslots(info);\n        spice_critical(\"address generation is not valid, group_id %d, slot_id %d, \"\n                       \"gen %d, slot_gen %d\",\n                       group_id, slot_id,\n                       generation, slot->generation);\n        return NULL;\n    }\n\n    h_virt = __get_clean_virt(info, addr);\n    h_virt += slot->address_delta;\n\n    if (!memslot_validate_virt(info, h_virt, slot_id, add_size, group_id)) {\n        return NULL;\n    }\n\n    return (void*)(uintptr_t)h_virt;\n}", "func_hash": 316300758635752588909124078674988704544, "file_name": "memslot.c", "file_hash": 44209429737432775835092242401604898921, "cwe": ["CWE-193"], "cve": "CVE-2019-3813", "cve_desc": "Spice, versions 0.5.2 through 0.14.1, are vulnerable to an out-of-bounds read due to an off-by-one error in memslot_get_virt. This may lead to a denial of service, or, in the worst case, code-execution by unauthenticated attackers.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-3813"}
{"idx": 210904, "project": "curl", "commit_id": "70b1900dd13d16f2e83f571407a614541d5ac9ba", "project_url": "https://github.com/curl/curl", "commit_url": "https://github.com/curl/curl/commit/70b1900dd13d16f2e83f571407a614541d5ac9ba", "commit_message": "'mytx' in bug report #1723194 (http://curl.haxx.se/bug/view.cgi?id=1723194)\npointed out that the warnf() function in the curl tool didn't properly deal\nwith the cases when excessively long words were used in the string to chop\nup.", "target": 1, "func": "static void warnf(struct Configurable *config, const char *fmt, ...)\n{\n  if(!(config->conf & CONF_MUTE)) {\n    va_list ap;\n    int len;\n    char *ptr;\n    char print_buffer[256];\n\n    va_start(ap, fmt);\n    va_start(ap, fmt);\n    len = vsnprintf(print_buffer, sizeof(print_buffer), fmt, ap);\n    va_end(ap);\n\n    ptr = print_buffer;\n    while(len > 0) {\n      fputs(WARN_PREFIX, config->errors);\n\n      if(len > (int)WARN_TEXTWIDTH) {\n        int cut = WARN_TEXTWIDTH-1;\n\n        while(!ISSPACE(ptr[cut]) && cut) {\n          cut--;\n        }\n\n        fwrite(ptr, cut + 1, 1, config->errors);\n        fputs(\"\\n\", config->errors);\n        ptr += cut+1; /* skip the space too */\n        len -= cut;\n      }\n      else {\n        fputs(ptr, config->errors);\n        len = 0;\n      }\n    }\n  }\n}", "func_hash": 84425875494863871647567570837033062033, "file_name": "main.c", "file_hash": 117508051074384799366027341072623749818, "cwe": ["CWE-125"], "cve": "CVE-2018-16842", "cve_desc": "Curl versions 7.14.1 through 7.61.1 are vulnerable to a heap-based buffer over-read in the tool_msgs.c:voutf() function that may result in information exposure and denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-16842"}
{"idx": 442815, "project": "curl", "commit_id": "70b1900dd13d16f2e83f571407a614541d5ac9ba", "project_url": "https://github.com/curl/curl", "commit_url": "https://github.com/curl/curl/commit/70b1900dd13d16f2e83f571407a614541d5ac9ba", "commit_message": "'mytx' in bug report #1723194 (http://curl.haxx.se/bug/view.cgi?id=1723194)\npointed out that the warnf() function in the curl tool didn't properly deal\nwith the cases when excessively long words were used in the string to chop\nup.", "target": 0, "func": "static void warnf(struct Configurable *config, const char *fmt, ...)\n{\n  if(!(config->conf & CONF_MUTE)) {\n    va_list ap;\n    int len;\n    char *ptr;\n    char print_buffer[256];\n\n    va_start(ap, fmt);\n    va_start(ap, fmt);\n    len = vsnprintf(print_buffer, sizeof(print_buffer), fmt, ap);\n    va_end(ap);\n\n    ptr = print_buffer;\n    while(len > 0) {\n      fputs(WARN_PREFIX, config->errors);\n\n      if(len > (int)WARN_TEXTWIDTH) {\n        int cut = WARN_TEXTWIDTH-1;\n\n        while(!ISSPACE(ptr[cut]) && cut) {\n          cut--;\n        }\n        if(0 == cut)\n          /* not a single cutting position was found, just cut it at the\n             max text width then! */\n          cut = WARN_TEXTWIDTH-1;\n\n        fwrite(ptr, cut + 1, 1, config->errors);\n        fputs(\"\\n\", config->errors);\n        ptr += cut+1; /* skip the space too */\n        len -= cut;\n      }\n      else {\n        fputs(ptr, config->errors);\n        len = 0;\n      }\n    }\n  }\n}", "func_hash": 253014912777777803689145200879767407638, "file_name": "main.c", "file_hash": 161085884624432597777110570993729624797, "cwe": ["CWE-125"], "cve": "CVE-2018-16842", "cve_desc": "Curl versions 7.14.1 through 7.61.1 are vulnerable to a heap-based buffer over-read in the tool_msgs.c:voutf() function that may result in information exposure and denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-16842"}
{"idx": 210910, "project": "vim", "commit_id": "de05bb25733c3319e18dca44e9b59c6ee389eb26", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/de05bb25733c3319e18dca44e9b59c6ee389eb26", "commit_message": "patch 8.2.4074: going over the end of NameBuff\n\nProblem:    Going over the end of NameBuff.\nSolution:   Check length when appending a space.", "target": 1, "func": "win_redr_status(win_T *wp, int ignore_pum UNUSED)\n{\n    int\t\trow;\n    char_u\t*p;\n    int\t\tlen;\n    int\t\tfillchar;\n    int\t\tattr;\n    int\t\tthis_ru_col;\n    static int  busy = FALSE;\n\n    // It's possible to get here recursively when 'statusline' (indirectly)\n    // invokes \":redrawstatus\".  Simply ignore the call then.\n    if (busy)\n\treturn;\n    busy = TRUE;\n\n    row = statusline_row(wp);\n\n    wp->w_redr_status = FALSE;\n    if (wp->w_status_height == 0)\n    {\n\t// no status line, can only be last window\n\tredraw_cmdline = TRUE;\n    }\n    else if (!redrawing()\n\t    // don't update status line when popup menu is visible and may be\n\t    // drawn over it, unless it will be redrawn later\n\t    || (!ignore_pum && pum_visible()))\n    {\n\t// Don't redraw right now, do it later.\n\twp->w_redr_status = TRUE;\n    }\n#ifdef FEAT_STL_OPT\n    else if (*p_stl != NUL || *wp->w_p_stl != NUL)\n    {\n\t// redraw custom status line\n\tredraw_custom_statusline(wp);\n    }\n#endif\n    else\n    {\n\tfillchar = fillchar_status(&attr, wp);\n\n\tget_trans_bufname(wp->w_buffer);\n\tp = NameBuff;\n\tlen = (int)STRLEN(p);\n\n\tif (bt_help(wp->w_buffer)\n#ifdef FEAT_QUICKFIX\n\t\t|| wp->w_p_pvw\n#endif\n\t\t|| bufIsChanged(wp->w_buffer)\n\t\t|| wp->w_buffer->b_p_ro)\n\t    *(p + len++) = ' ';\n\tif (bt_help(wp->w_buffer))\n\t{\n\t    vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[Help]\"));\n\t    len += (int)STRLEN(p + len);\n\t}\n#ifdef FEAT_QUICKFIX\n\tif (wp->w_p_pvw)\n\t{\n\t    vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[Preview]\"));\n\t    len += (int)STRLEN(p + len);\n\t}\n#endif\n\tif (bufIsChanged(wp->w_buffer)\n#ifdef FEAT_TERMINAL\n\t\t&& !bt_terminal(wp->w_buffer)\n#endif\n\t\t)\n\t{\n\t    vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", \"[+]\");\n\t    len += (int)STRLEN(p + len);\n\t}\n\tif (wp->w_buffer->b_p_ro)\n\t{\n\t    vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[RO]\"));\n\t    len += (int)STRLEN(p + len);\n\t}\n\n\tthis_ru_col = ru_col - (Columns - wp->w_width);\n\tif (this_ru_col < (wp->w_width + 1) / 2)\n\t    this_ru_col = (wp->w_width + 1) / 2;\n\tif (this_ru_col <= 1)\n\t{\n\t    p = (char_u *)\"<\";\t\t// No room for file name!\n\t    len = 1;\n\t}\n\telse if (has_mbyte)\n\t{\n\t    int\tclen = 0, i;\n\n\t    // Count total number of display cells.\n\t    clen = mb_string2cells(p, -1);\n\n\t    // Find first character that will fit.\n\t    // Going from start to end is much faster for DBCS.\n\t    for (i = 0; p[i] != NUL && clen >= this_ru_col - 1;\n\t\t    i += (*mb_ptr2len)(p + i))\n\t\tclen -= (*mb_ptr2cells)(p + i);\n\t    len = clen;\n\t    if (i > 0)\n\t    {\n\t\tp = p + i - 1;\n\t\t*p = '<';\n\t\t++len;\n\t    }\n\n\t}\n\telse if (len > this_ru_col - 1)\n\t{\n\t    p += len - (this_ru_col - 1);\n\t    *p = '<';\n\t    len = this_ru_col - 1;\n\t}\n\n\tscreen_puts(p, row, wp->w_wincol, attr);\n\tscreen_fill(row, row + 1, len + wp->w_wincol,\n\t\t\tthis_ru_col + wp->w_wincol, fillchar, fillchar, attr);\n\n\tif (get_keymap_str(wp, (char_u *)\"<%s>\", NameBuff, MAXPATHL)\n\t\t&& (int)(this_ru_col - len) > (int)(STRLEN(NameBuff) + 1))\n\t    screen_puts(NameBuff, row, (int)(this_ru_col - STRLEN(NameBuff)\n\t\t\t\t\t\t   - 1 + wp->w_wincol), attr);\n\n#ifdef FEAT_CMDL_INFO\n\twin_redr_ruler(wp, TRUE, ignore_pum);\n#endif\n    }\n\n    /*\n     * May need to draw the character below the vertical separator.\n     */\n    if (wp->w_vsep_width != 0 && wp->w_status_height != 0 && redrawing())\n    {\n\tif (stl_connected(wp))\n\t    fillchar = fillchar_status(&attr, wp);\n\telse\n\t    fillchar = fillchar_vsep(&attr);\n\tscreen_putchar(fillchar, row, W_ENDCOL(wp), attr);\n    }\n    busy = FALSE;\n}", "func_hash": 276232884514343858652101986950507308822, "file_name": "drawscreen.c", "file_hash": 10568928391803251582913255951861880853, "cwe": ["CWE-200"], "cve": "CVE-2022-0213", "cve_desc": "vim is vulnerable to Heap-based Buffer Overflow", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0213"}
{"idx": 442959, "project": "vim", "commit_id": "de05bb25733c3319e18dca44e9b59c6ee389eb26", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/de05bb25733c3319e18dca44e9b59c6ee389eb26", "commit_message": "patch 8.2.4074: going over the end of NameBuff\n\nProblem:    Going over the end of NameBuff.\nSolution:   Check length when appending a space.", "target": 0, "func": "win_redr_status(win_T *wp, int ignore_pum UNUSED)\n{\n    int\t\trow;\n    char_u\t*p;\n    int\t\tlen;\n    int\t\tfillchar;\n    int\t\tattr;\n    int\t\tthis_ru_col;\n    static int  busy = FALSE;\n\n    // It's possible to get here recursively when 'statusline' (indirectly)\n    // invokes \":redrawstatus\".  Simply ignore the call then.\n    if (busy)\n\treturn;\n    busy = TRUE;\n\n    row = statusline_row(wp);\n\n    wp->w_redr_status = FALSE;\n    if (wp->w_status_height == 0)\n    {\n\t// no status line, can only be last window\n\tredraw_cmdline = TRUE;\n    }\n    else if (!redrawing()\n\t    // don't update status line when popup menu is visible and may be\n\t    // drawn over it, unless it will be redrawn later\n\t    || (!ignore_pum && pum_visible()))\n    {\n\t// Don't redraw right now, do it later.\n\twp->w_redr_status = TRUE;\n    }\n#ifdef FEAT_STL_OPT\n    else if (*p_stl != NUL || *wp->w_p_stl != NUL)\n    {\n\t// redraw custom status line\n\tredraw_custom_statusline(wp);\n    }\n#endif\n    else\n    {\n\tfillchar = fillchar_status(&attr, wp);\n\n\tget_trans_bufname(wp->w_buffer);\n\tp = NameBuff;\n\tlen = (int)STRLEN(p);\n\n\tif ((bt_help(wp->w_buffer)\n#ifdef FEAT_QUICKFIX\n\t\t    || wp->w_p_pvw\n#endif\n\t\t    || bufIsChanged(wp->w_buffer)\n\t\t    || wp->w_buffer->b_p_ro)\n\t\t&& len < MAXPATHL - 1)\n\t    *(p + len++) = ' ';\n\tif (bt_help(wp->w_buffer))\n\t{\n\t    vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[Help]\"));\n\t    len += (int)STRLEN(p + len);\n\t}\n#ifdef FEAT_QUICKFIX\n\tif (wp->w_p_pvw)\n\t{\n\t    vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[Preview]\"));\n\t    len += (int)STRLEN(p + len);\n\t}\n#endif\n\tif (bufIsChanged(wp->w_buffer)\n#ifdef FEAT_TERMINAL\n\t\t&& !bt_terminal(wp->w_buffer)\n#endif\n\t\t)\n\t{\n\t    vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", \"[+]\");\n\t    len += (int)STRLEN(p + len);\n\t}\n\tif (wp->w_buffer->b_p_ro)\n\t{\n\t    vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[RO]\"));\n\t    len += (int)STRLEN(p + len);\n\t}\n\n\tthis_ru_col = ru_col - (Columns - wp->w_width);\n\tif (this_ru_col < (wp->w_width + 1) / 2)\n\t    this_ru_col = (wp->w_width + 1) / 2;\n\tif (this_ru_col <= 1)\n\t{\n\t    p = (char_u *)\"<\";\t\t// No room for file name!\n\t    len = 1;\n\t}\n\telse if (has_mbyte)\n\t{\n\t    int\tclen = 0, i;\n\n\t    // Count total number of display cells.\n\t    clen = mb_string2cells(p, -1);\n\n\t    // Find first character that will fit.\n\t    // Going from start to end is much faster for DBCS.\n\t    for (i = 0; p[i] != NUL && clen >= this_ru_col - 1;\n\t\t    i += (*mb_ptr2len)(p + i))\n\t\tclen -= (*mb_ptr2cells)(p + i);\n\t    len = clen;\n\t    if (i > 0)\n\t    {\n\t\tp = p + i - 1;\n\t\t*p = '<';\n\t\t++len;\n\t    }\n\n\t}\n\telse if (len > this_ru_col - 1)\n\t{\n\t    p += len - (this_ru_col - 1);\n\t    *p = '<';\n\t    len = this_ru_col - 1;\n\t}\n\n\tscreen_puts(p, row, wp->w_wincol, attr);\n\tscreen_fill(row, row + 1, len + wp->w_wincol,\n\t\t\tthis_ru_col + wp->w_wincol, fillchar, fillchar, attr);\n\n\tif (get_keymap_str(wp, (char_u *)\"<%s>\", NameBuff, MAXPATHL)\n\t\t&& (int)(this_ru_col - len) > (int)(STRLEN(NameBuff) + 1))\n\t    screen_puts(NameBuff, row, (int)(this_ru_col - STRLEN(NameBuff)\n\t\t\t\t\t\t   - 1 + wp->w_wincol), attr);\n\n#ifdef FEAT_CMDL_INFO\n\twin_redr_ruler(wp, TRUE, ignore_pum);\n#endif\n    }\n\n    /*\n     * May need to draw the character below the vertical separator.\n     */\n    if (wp->w_vsep_width != 0 && wp->w_status_height != 0 && redrawing())\n    {\n\tif (stl_connected(wp))\n\t    fillchar = fillchar_status(&attr, wp);\n\telse\n\t    fillchar = fillchar_vsep(&attr);\n\tscreen_putchar(fillchar, row, W_ENDCOL(wp), attr);\n    }\n    busy = FALSE;\n}", "func_hash": 176741267087496295201275228908142268974, "file_name": "drawscreen.c", "file_hash": 281263511995685251557666010606597186752, "cwe": ["CWE-200"], "cve": "CVE-2022-0213", "cve_desc": "vim is vulnerable to Heap-based Buffer Overflow", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0213"}
{"idx": 210928, "project": "linux", "commit_id": "a53046291020ec41e09181396c1e829287b48d47", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/a53046291020ec41e09181396c1e829287b48d47", "commit_message": "jfs: prevent NULL deref in diFree\n\nAdd validation check for JFS_IP(ipimap)->i_imap to prevent a NULL deref\nin diFree since diFree uses it without do any validations.\nWhen function jfs_mount calls diMount to initialize fileset inode\nallocation map, it can fail and JFS_IP(ipimap)->i_imap won't be\ninitialized. Then it calls diFreeSpecial to close fileset inode allocation\nmap inode and it will flow into jfs_evict_inode. Function jfs_evict_inode\njust validates JFS_SBI(inode->i_sb)->ipimap, then calls diFree. diFree use\nJFS_IP(ipimap)->i_imap directly, then it will cause a NULL deref.\n\nReported-by: TCS Robot \nSigned-off-by: Haimin Zhang \nSigned-off-by: Dave Kleikamp ", "target": 1, "func": "void jfs_evict_inode(struct inode *inode)\n{\n\tstruct jfs_inode_info *ji = JFS_IP(inode);\n\n\tjfs_info(\"In jfs_evict_inode, inode = 0x%p\", inode);\n\n\tif (!inode->i_nlink && !is_bad_inode(inode)) {\n\t\tdquot_initialize(inode);\n\n\t\tif (JFS_IP(inode)->fileset == FILESYSTEM_I) {\n\t\t\ttruncate_inode_pages_final(&inode->i_data);\n\n\t\t\tif (test_cflag(COMMIT_Freewmap, inode))\n\t\t\t\tjfs_free_zero_link(inode);\n\n\t\t\tif (JFS_SBI(inode->i_sb)->ipimap)\n\t\t\t\tdiFree(inode);\n\n\t\t\t/*\n\t\t\t * Free the inode from the quota allocation.\n\t\t\t */\n\t\t\tdquot_free_inode(inode);\n\t\t}\n\t} else {\n\t\ttruncate_inode_pages_final(&inode->i_data);\n\t}\n\tclear_inode(inode);\n\tdquot_drop(inode);\n\n\tBUG_ON(!list_empty(&ji->anon_inode_list));\n\n\tspin_lock_irq(&ji->ag_lock);\n\tif (ji->active_ag != -1) {\n\t\tstruct bmap *bmap = JFS_SBI(inode->i_sb)->bmap;\n\t\tatomic_dec(&bmap->db_active[ji->active_ag]);\n\t\tji->active_ag = -1;\n\t}\n\tspin_unlock_irq(&ji->ag_lock);\n}", "func_hash": 20578307712540502105112089793785958875, "file_name": "inode.c", "file_hash": 290805170238030320123014907894669021558, "cwe": ["CWE-476"], "cve": "CVE-2022-3202", "cve_desc": "A NULL pointer dereference flaw in diFree in fs/jfs/inode.c in Journaled File System (JFS)in the Linux kernel. This could allow a local attacker to crash the system or leak kernel internal information.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3202"}
{"idx": 443152, "project": "linux", "commit_id": "a53046291020ec41e09181396c1e829287b48d47", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/a53046291020ec41e09181396c1e829287b48d47", "commit_message": "jfs: prevent NULL deref in diFree\n\nAdd validation check for JFS_IP(ipimap)->i_imap to prevent a NULL deref\nin diFree since diFree uses it without do any validations.\nWhen function jfs_mount calls diMount to initialize fileset inode\nallocation map, it can fail and JFS_IP(ipimap)->i_imap won't be\ninitialized. Then it calls diFreeSpecial to close fileset inode allocation\nmap inode and it will flow into jfs_evict_inode. Function jfs_evict_inode\njust validates JFS_SBI(inode->i_sb)->ipimap, then calls diFree. diFree use\nJFS_IP(ipimap)->i_imap directly, then it will cause a NULL deref.\n\nReported-by: TCS Robot \nSigned-off-by: Haimin Zhang \nSigned-off-by: Dave Kleikamp ", "target": 0, "func": "void jfs_evict_inode(struct inode *inode)\n{\n\tstruct jfs_inode_info *ji = JFS_IP(inode);\n\n\tjfs_info(\"In jfs_evict_inode, inode = 0x%p\", inode);\n\n\tif (!inode->i_nlink && !is_bad_inode(inode)) {\n\t\tdquot_initialize(inode);\n\n\t\tif (JFS_IP(inode)->fileset == FILESYSTEM_I) {\n\t\t\tstruct inode *ipimap = JFS_SBI(inode->i_sb)->ipimap;\n\t\t\ttruncate_inode_pages_final(&inode->i_data);\n\n\t\t\tif (test_cflag(COMMIT_Freewmap, inode))\n\t\t\t\tjfs_free_zero_link(inode);\n\n\t\t\tif (ipimap && JFS_IP(ipimap)->i_imap)\n\t\t\t\tdiFree(inode);\n\n\t\t\t/*\n\t\t\t * Free the inode from the quota allocation.\n\t\t\t */\n\t\t\tdquot_free_inode(inode);\n\t\t}\n\t} else {\n\t\ttruncate_inode_pages_final(&inode->i_data);\n\t}\n\tclear_inode(inode);\n\tdquot_drop(inode);\n\n\tBUG_ON(!list_empty(&ji->anon_inode_list));\n\n\tspin_lock_irq(&ji->ag_lock);\n\tif (ji->active_ag != -1) {\n\t\tstruct bmap *bmap = JFS_SBI(inode->i_sb)->bmap;\n\t\tatomic_dec(&bmap->db_active[ji->active_ag]);\n\t\tji->active_ag = -1;\n\t}\n\tspin_unlock_irq(&ji->ag_lock);\n}", "func_hash": 19343683273845236904792229610406110241, "file_name": "inode.c", "file_hash": 328882647920718394331416110787337999080, "cwe": ["CWE-476"], "cve": "CVE-2022-3202", "cve_desc": "A NULL pointer dereference flaw in diFree in fs/jfs/inode.c in Journaled File System (JFS)in the Linux kernel. This could allow a local attacker to crash the system or leak kernel internal information.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3202"}
{"idx": 210944, "project": "vim", "commit_id": "35d21c6830fc2d68aca838424a0e786821c5891c", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/35d21c6830fc2d68aca838424a0e786821c5891c", "commit_message": "patch 9.0.0360: crash when invalid line number on :for is ignored\n\nProblem:    Crash when invalid line number on :for is ignored.\nSolution:   Do not check breakpoint for non-existing line.", "target": 1, "func": "do_cmdline(\n    char_u\t*cmdline,\n    char_u\t*(*fgetline)(int, void *, int, getline_opt_T),\n    void\t*cookie,\t\t// argument for fgetline()\n    int\t\tflags)\n{\n    char_u\t*next_cmdline;\t\t// next cmd to execute\n    char_u\t*cmdline_copy = NULL;\t// copy of cmd line\n    int\t\tused_getline = FALSE;\t// used \"fgetline\" to obtain command\n    static int\trecursive = 0;\t\t// recursive depth\n    int\t\tmsg_didout_before_start = 0;\n    int\t\tcount = 0;\t\t// line number count\n    int\t\tdid_inc = FALSE;\t// incremented RedrawingDisabled\n    int\t\tretval = OK;\n#ifdef FEAT_EVAL\n    cstack_T\tcstack;\t\t\t// conditional stack\n    garray_T\tlines_ga;\t\t// keep lines for \":while\"/\":for\"\n    int\t\tcurrent_line = 0;\t// active line in lines_ga\n    int\t\tcurrent_line_before = 0;\n    char_u\t*fname = NULL;\t\t// function or script name\n    linenr_T\t*breakpoint = NULL;\t// ptr to breakpoint field in cookie\n    int\t\t*dbg_tick = NULL;\t// ptr to dbg_tick field in cookie\n    struct dbg_stuff debug_saved;\t// saved things for debug mode\n    int\t\tinitial_trylevel;\n    msglist_T\t**saved_msg_list = NULL;\n    msglist_T\t*private_msg_list = NULL;\n\n    // \"fgetline\" and \"cookie\" passed to do_one_cmd()\n    char_u\t*(*cmd_getline)(int, void *, int, getline_opt_T);\n    void\t*cmd_cookie;\n    struct loop_cookie cmd_loop_cookie;\n    void\t*real_cookie;\n    int\t\tgetline_is_func;\n#else\n# define cmd_getline fgetline\n# define cmd_cookie cookie\n#endif\n    static int\tcall_depth = 0;\t\t// recursiveness\n#ifdef FEAT_EVAL\n    // For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory\n    // location for storing error messages to be converted to an exception.\n    // This ensures that the do_errthrow() call in do_one_cmd() does not\n    // combine the messages stored by an earlier invocation of do_one_cmd()\n    // with the command name of the later one.  This would happen when\n    // BufWritePost autocommands are executed after a write error.\n    saved_msg_list = msg_list;\n    msg_list = &private_msg_list;\n#endif\n\n    // It's possible to create an endless loop with \":execute\", catch that\n    // here.  The value of 200 allows nested function calls, \":source\", etc.\n    // Allow 200 or 'maxfuncdepth', whatever is larger.\n    if (call_depth >= 200\n#ifdef FEAT_EVAL\n\t    && call_depth >= p_mfd\n#endif\n\t    )\n    {\n\temsg(_(e_command_too_recursive));\n#ifdef FEAT_EVAL\n\t// When converting to an exception, we do not include the command name\n\t// since this is not an error of the specific command.\n\tdo_errthrow((cstack_T *)NULL, (char_u *)NULL);\n\tmsg_list = saved_msg_list;\n#endif\n\treturn FAIL;\n    }\n    ++call_depth;\n\n#ifdef FEAT_EVAL\n    CLEAR_FIELD(cstack);\n    cstack.cs_idx = -1;\n    ga_init2(&lines_ga, sizeof(wcmd_T), 10);\n\n    real_cookie = getline_cookie(fgetline, cookie);\n\n    // Inside a function use a higher nesting level.\n    getline_is_func = getline_equal(fgetline, cookie, get_func_line);\n    if (getline_is_func && ex_nesting_level == func_level(real_cookie))\n\t++ex_nesting_level;\n\n    // Get the function or script name and the address where the next breakpoint\n    // line and the debug tick for a function or script are stored.\n    if (getline_is_func)\n    {\n\tfname = func_name(real_cookie);\n\tbreakpoint = func_breakpoint(real_cookie);\n\tdbg_tick = func_dbg_tick(real_cookie);\n    }\n    else if (getline_equal(fgetline, cookie, getsourceline))\n    {\n\tfname = SOURCING_NAME;\n\tbreakpoint = source_breakpoint(real_cookie);\n\tdbg_tick = source_dbg_tick(real_cookie);\n    }\n\n    /*\n     * Initialize \"force_abort\"  and \"suppress_errthrow\" at the top level.\n     */\n    if (!recursive)\n    {\n\tforce_abort = FALSE;\n\tsuppress_errthrow = FALSE;\n    }\n\n    /*\n     * If requested, store and reset the global values controlling the\n     * exception handling (used when debugging).  Otherwise clear it to avoid\n     * a bogus compiler warning when the optimizer uses inline functions...\n     */\n    if (flags & DOCMD_EXCRESET)\n\tsave_dbg_stuff(&debug_saved);\n    else\n\tCLEAR_FIELD(debug_saved);\n\n    initial_trylevel = trylevel;\n\n    /*\n     * \"did_throw\" will be set to TRUE when an exception is being thrown.\n     */\n    did_throw = FALSE;\n#endif\n    /*\n     * \"did_emsg\" will be set to TRUE when emsg() is used, in which case we\n     * cancel the whole command line, and any if/endif or loop.\n     * If force_abort is set, we cancel everything.\n     */\n#ifdef FEAT_EVAL\n    did_emsg_cumul += did_emsg;\n#endif\n    did_emsg = FALSE;\n\n    /*\n     * KeyTyped is only set when calling vgetc().  Reset it here when not\n     * calling vgetc() (sourced command lines).\n     */\n    if (!(flags & DOCMD_KEYTYPED)\n\t\t\t       && !getline_equal(fgetline, cookie, getexline))\n\tKeyTyped = FALSE;\n\n    /*\n     * Continue executing command lines:\n     * - when inside an \":if\", \":while\" or \":for\"\n     * - for multiple commands on one line, separated with '|'\n     * - when repeating until there are no more lines (for \":source\")\n     */\n    next_cmdline = cmdline;\n    do\n    {\n#ifdef FEAT_EVAL\n\tgetline_is_func = getline_equal(fgetline, cookie, get_func_line);\n#endif\n\n\t// stop skipping cmds for an error msg after all endif/while/for\n\tif (next_cmdline == NULL\n#ifdef FEAT_EVAL\n\t\t&& !force_abort\n\t\t&& cstack.cs_idx < 0\n\t\t&& !(getline_is_func && func_has_abort(real_cookie))\n#endif\n\t\t\t\t\t\t\t)\n\t{\n#ifdef FEAT_EVAL\n\t    did_emsg_cumul += did_emsg;\n#endif\n\t    did_emsg = FALSE;\n\t}\n\n\t/*\n\t * 1. If repeating a line in a loop, get a line from lines_ga.\n\t * 2. If no line given: Get an allocated line with fgetline().\n\t * 3. If a line is given: Make a copy, so we can mess with it.\n\t */\n\n#ifdef FEAT_EVAL\n\t// 1. If repeating, get a previous line from lines_ga.\n\tif (cstack.cs_looplevel > 0 && current_line < lines_ga.ga_len)\n\t{\n\t    // Each '|' separated command is stored separately in lines_ga, to\n\t    // be able to jump to it.  Don't use next_cmdline now.\n\t    VIM_CLEAR(cmdline_copy);\n\n\t    // Check if a function has returned or, unless it has an unclosed\n\t    // try conditional, aborted.\n\t    if (getline_is_func)\n\t    {\n# ifdef FEAT_PROFILE\n\t\tif (do_profiling == PROF_YES)\n\t\t    func_line_end(real_cookie);\n# endif\n\t\tif (func_has_ended(real_cookie))\n\t\t{\n\t\t    retval = FAIL;\n\t\t    break;\n\t\t}\n\t    }\n#ifdef FEAT_PROFILE\n\t    else if (do_profiling == PROF_YES\n\t\t\t    && getline_equal(fgetline, cookie, getsourceline))\n\t\tscript_line_end();\n#endif\n\n\t    // Check if a sourced file hit a \":finish\" command.\n\t    if (source_finished(fgetline, cookie))\n\t    {\n\t\tretval = FAIL;\n\t\tbreak;\n\t    }\n\n\t    // If breakpoints have been added/deleted need to check for it.\n\t    if (breakpoint != NULL && dbg_tick != NULL\n\t\t\t\t\t\t   && *dbg_tick != debug_tick)\n\t    {\n\t\t*breakpoint = dbg_find_breakpoint(\n\t\t\t\tgetline_equal(fgetline, cookie, getsourceline),\n\t\t\t\t\t\t\tfname, SOURCING_LNUM);\n\t\t*dbg_tick = debug_tick;\n\t    }\n\n\t    next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line;\n\t    SOURCING_LNUM = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum;\n\n\t    // Did we encounter a breakpoint?\n\t    if (breakpoint != NULL && *breakpoint != 0\n\t\t\t\t\t      && *breakpoint <= SOURCING_LNUM)\n\t    {\n\t\tdbg_breakpoint(fname, SOURCING_LNUM);\n\t\t// Find next breakpoint.\n\t\t*breakpoint = dbg_find_breakpoint(\n\t\t\t       getline_equal(fgetline, cookie, getsourceline),\n\t\t\t\t\t\t\tfname, SOURCING_LNUM);\n\t\t*dbg_tick = debug_tick;\n\t    }\n# ifdef FEAT_PROFILE\n\t    if (do_profiling == PROF_YES)\n\t    {\n\t\tif (getline_is_func)\n\t\t    func_line_start(real_cookie, SOURCING_LNUM);\n\t\telse if (getline_equal(fgetline, cookie, getsourceline))\n\t\t    script_line_start();\n\t    }\n# endif\n\t}\n#endif\n\n\t// 2. If no line given, get an allocated line with fgetline().\n\tif (next_cmdline == NULL)\n\t{\n\t    /*\n\t     * Need to set msg_didout for the first line after an \":if\",\n\t     * otherwise the \":if\" will be overwritten.\n\t     */\n\t    if (count == 1 && getline_equal(fgetline, cookie, getexline))\n\t\tmsg_didout = TRUE;\n\t    if (fgetline == NULL || (next_cmdline = fgetline(':', cookie,\n#ifdef FEAT_EVAL\n\t\t    cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2\n#else\n\t\t    0\n#endif\n\t\t    , in_vim9script() ? GETLINE_CONCAT_CONTBAR\n\t\t\t\t\t       : GETLINE_CONCAT_CONT)) == NULL)\n\t    {\n\t\t// Don't call wait_return() for aborted command line.  The NULL\n\t\t// returned for the end of a sourced file or executed function\n\t\t// doesn't do this.\n\t\tif (KeyTyped && !(flags & DOCMD_REPEAT))\n\t\t    need_wait_return = FALSE;\n\t\tretval = FAIL;\n\t\tbreak;\n\t    }\n\t    used_getline = TRUE;\n\n\t    /*\n\t     * Keep the first typed line.  Clear it when more lines are typed.\n\t     */\n\t    if (flags & DOCMD_KEEPLINE)\n\t    {\n\t\tvim_free(repeat_cmdline);\n\t\tif (count == 0)\n\t\t    repeat_cmdline = vim_strsave(next_cmdline);\n\t\telse\n\t\t    repeat_cmdline = NULL;\n\t    }\n\t}\n\n\t// 3. Make a copy of the command so we can mess with it.\n\telse if (cmdline_copy == NULL)\n\t{\n\t    next_cmdline = vim_strsave(next_cmdline);\n\t    if (next_cmdline == NULL)\n\t    {\n\t\temsg(_(e_out_of_memory));\n\t\tretval = FAIL;\n\t\tbreak;\n\t    }\n\t}\n\tcmdline_copy = next_cmdline;\n\n#ifdef FEAT_EVAL\n\t/*\n\t * Inside a while/for loop, and when the command looks like a \":while\"\n\t * or \":for\", the line is stored, because we may need it later when\n\t * looping.\n\t *\n\t * When there is a '|' and another command, it is stored separately,\n\t * because we need to be able to jump back to it from an\n\t * :endwhile/:endfor.\n\t *\n\t * Pass a different \"fgetline\" function to do_one_cmd() below,\n\t * that it stores lines in or reads them from \"lines_ga\".  Makes it\n\t * possible to define a function inside a while/for loop and handles\n\t * line continuation.\n\t */\n\tif ((cstack.cs_looplevel > 0 || has_loop_cmd(next_cmdline)))\n\t{\n\t    cmd_getline = get_loop_line;\n\t    cmd_cookie = (void *)&cmd_loop_cookie;\n\t    cmd_loop_cookie.lines_gap = &lines_ga;\n\t    cmd_loop_cookie.current_line = current_line;\n\t    cmd_loop_cookie.getline = fgetline;\n\t    cmd_loop_cookie.cookie = cookie;\n\t    cmd_loop_cookie.repeating = (current_line < lines_ga.ga_len);\n\n\t    // Save the current line when encountering it the first time.\n\t    if (current_line == lines_ga.ga_len\n\t\t    && store_loop_line(&lines_ga, next_cmdline) == FAIL)\n\t    {\n\t\tretval = FAIL;\n\t\tbreak;\n\t    }\n\t    current_line_before = current_line;\n\t}\n\telse\n\t{\n\t    cmd_getline = fgetline;\n\t    cmd_cookie = cookie;\n\t}\n\n\tdid_endif = FALSE;\n#endif\n\n\tif (count++ == 0)\n\t{\n\t    /*\n\t     * All output from the commands is put below each other, without\n\t     * waiting for a return. Don't do this when executing commands\n\t     * from a script or when being called recursive (e.g. for \":e\n\t     * +command file\").\n\t     */\n\t    if (!(flags & DOCMD_NOWAIT) && !recursive)\n\t    {\n\t\tmsg_didout_before_start = msg_didout;\n\t\tmsg_didany = FALSE; // no output yet\n\t\tmsg_start();\n\t\tmsg_scroll = TRUE;  // put messages below each other\n\t\t++no_wait_return;   // don't wait for return until finished\n\t\t++RedrawingDisabled;\n\t\tdid_inc = TRUE;\n\t    }\n\t}\n\n\tif ((p_verbose >= 15 && SOURCING_NAME != NULL) || p_verbose >= 16)\n\t    msg_verbose_cmd(SOURCING_LNUM, cmdline_copy);\n\n\t/*\n\t * 2. Execute one '|' separated command.\n\t *    do_one_cmd() will return NULL if there is no trailing '|'.\n\t *    \"cmdline_copy\" can change, e.g. for '%' and '#' expansion.\n\t */\n\t++recursive;\n\tnext_cmdline = do_one_cmd(&cmdline_copy, flags,\n#ifdef FEAT_EVAL\n\t\t\t\t&cstack,\n#endif\n\t\t\t\tcmd_getline, cmd_cookie);\n\t--recursive;\n\n#ifdef FEAT_EVAL\n\tif (cmd_cookie == (void *)&cmd_loop_cookie)\n\t    // Use \"current_line\" from \"cmd_loop_cookie\", it may have been\n\t    // incremented when defining a function.\n\t    current_line = cmd_loop_cookie.current_line;\n#endif\n\n\tif (next_cmdline == NULL)\n\t{\n\t    VIM_CLEAR(cmdline_copy);\n\n\t    /*\n\t     * If the command was typed, remember it for the ':' register.\n\t     * Do this AFTER executing the command to make :@: work.\n\t     */\n\t    if (getline_equal(fgetline, cookie, getexline)\n\t\t\t\t\t\t  && new_last_cmdline != NULL)\n\t    {\n\t\tvim_free(last_cmdline);\n\t\tlast_cmdline = new_last_cmdline;\n\t\tnew_last_cmdline = NULL;\n\t    }\n\t}\n\telse\n\t{\n\t    // need to copy the command after the '|' to cmdline_copy, for the\n\t    // next do_one_cmd()\n\t    STRMOVE(cmdline_copy, next_cmdline);\n\t    next_cmdline = cmdline_copy;\n\t}\n\n\n#ifdef FEAT_EVAL\n\t// reset did_emsg for a function that is not aborted by an error\n\tif (did_emsg && !force_abort\n\t\t&& getline_equal(fgetline, cookie, get_func_line)\n\t\t\t\t\t      && !func_has_abort(real_cookie))\n\t{\n\t    // did_emsg_cumul is not set here\n\t    did_emsg = FALSE;\n\t}\n\n\tif (cstack.cs_looplevel > 0)\n\t{\n\t    ++current_line;\n\n\t    /*\n\t     * An \":endwhile\", \":endfor\" and \":continue\" is handled here.\n\t     * If we were executing commands, jump back to the \":while\" or\n\t     * \":for\".\n\t     * If we were not executing commands, decrement cs_looplevel.\n\t     */\n\t    if (cstack.cs_lflags & (CSL_HAD_CONT | CSL_HAD_ENDLOOP))\n\t    {\n\t\tcstack.cs_lflags &= ~(CSL_HAD_CONT | CSL_HAD_ENDLOOP);\n\n\t\t// Jump back to the matching \":while\" or \":for\".  Be careful\n\t\t// not to use a cs_line[] from an entry that isn't a \":while\"\n\t\t// or \":for\": It would make \"current_line\" invalid and can\n\t\t// cause a crash.\n\t\tif (!did_emsg && !got_int && !did_throw\n\t\t\t&& cstack.cs_idx >= 0\n\t\t\t&& (cstack.cs_flags[cstack.cs_idx]\n\t\t\t\t\t\t      & (CSF_WHILE | CSF_FOR))\n\t\t\t&& cstack.cs_line[cstack.cs_idx] >= 0\n\t\t\t&& (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE))\n\t\t{\n\t\t    current_line = cstack.cs_line[cstack.cs_idx];\n\t\t\t\t\t\t// remember we jumped there\n\t\t    cstack.cs_lflags |= CSL_HAD_LOOP;\n\t\t    line_breakcheck();\t\t// check if CTRL-C typed\n\n\t\t    // Check for the next breakpoint at or after the \":while\"\n\t\t    // or \":for\".\n\t\t    if (breakpoint != NULL)\n\t\t    {\n\t\t\t*breakpoint = dbg_find_breakpoint(\n\t\t\t       getline_equal(fgetline, cookie, getsourceline),\n\t\t\t\t\t\t\t\t\tfname,\n\t\t\t   ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1);\n\t\t\t*dbg_tick = debug_tick;\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    // can only get here with \":endwhile\" or \":endfor\"\n\t\t    if (cstack.cs_idx >= 0)\n\t\t\trewind_conditionals(&cstack, cstack.cs_idx - 1,\n\t\t\t\t   CSF_WHILE | CSF_FOR, &cstack.cs_looplevel);\n\t\t}\n\t    }\n\n\t    /*\n\t     * For a \":while\" or \":for\" we need to remember the line number.\n\t     */\n\t    else if (cstack.cs_lflags & CSL_HAD_LOOP)\n\t    {\n\t\tcstack.cs_lflags &= ~CSL_HAD_LOOP;\n\t\tcstack.cs_line[cstack.cs_idx] = current_line_before;\n\t    }\n\t}\n\n\t// Check for the next breakpoint after a watchexpression\n\tif (breakpoint != NULL && has_watchexpr())\n\t{\n\t    *breakpoint = dbg_find_breakpoint(FALSE, fname, SOURCING_LNUM);\n\t    *dbg_tick = debug_tick;\n\t}\n\n\t/*\n\t * When not inside any \":while\" loop, clear remembered lines.\n\t */\n\tif (cstack.cs_looplevel == 0)\n\t{\n\t    if (lines_ga.ga_len > 0)\n\t    {\n\t\tSOURCING_LNUM =\n\t\t       ((wcmd_T *)lines_ga.ga_data)[lines_ga.ga_len - 1].lnum;\n\t\tfree_cmdlines(&lines_ga);\n\t    }\n\t    current_line = 0;\n\t}\n\n\t/*\n\t * A \":finally\" makes did_emsg, got_int, and did_throw pending for\n\t * being restored at the \":endtry\".  Reset them here and set the\n\t * ACTIVE and FINALLY flags, so that the finally clause gets executed.\n\t * This includes the case where a missing \":endif\", \":endwhile\" or\n\t * \":endfor\" was detected by the \":finally\" itself.\n\t */\n\tif (cstack.cs_lflags & CSL_HAD_FINA)\n\t{\n\t    cstack.cs_lflags &= ~CSL_HAD_FINA;\n\t    report_make_pending(cstack.cs_pending[cstack.cs_idx]\n\t\t    & (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW),\n\t\t    did_throw ? (void *)current_exception : NULL);\n\t    did_emsg = got_int = did_throw = FALSE;\n\t    cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY;\n\t}\n\n\t// Update global \"trylevel\" for recursive calls to do_cmdline() from\n\t// within this loop.\n\ttrylevel = initial_trylevel + cstack.cs_trylevel;\n\n\t/*\n\t * If the outermost try conditional (across function calls and sourced\n\t * files) is aborted because of an error, an interrupt, or an uncaught\n\t * exception, cancel everything.  If it is left normally, reset\n\t * force_abort to get the non-EH compatible abortion behavior for\n\t * the rest of the script.\n\t */\n\tif (trylevel == 0 && !did_emsg && !got_int && !did_throw)\n\t    force_abort = FALSE;\n\n\t// Convert an interrupt to an exception if appropriate.\n\t(void)do_intthrow(&cstack);\n#endif // FEAT_EVAL\n\n    }\n    /*\n     * Continue executing command lines when:\n     * - no CTRL-C typed, no aborting error, no exception thrown or try\n     *   conditionals need to be checked for executing finally clauses or\n     *   catching an interrupt exception\n     * - didn't get an error message or lines are not typed\n     * - there is a command after '|', inside a :if, :while, :for or :try, or\n     *   looping for \":source\" command or function call.\n     */\n    while (!((got_int\n#ifdef FEAT_EVAL\n\t\t    || (did_emsg && (force_abort || in_vim9script()))\n\t\t    || did_throw\n#endif\n\t     )\n#ifdef FEAT_EVAL\n\t\t&& cstack.cs_trylevel == 0\n#endif\n\t    )\n\t    && !(did_emsg\n#ifdef FEAT_EVAL\n\t\t// Keep going when inside try/catch, so that the error can be\n\t\t// deal with, except when it is a syntax error, it may cause\n\t\t// the :endtry to be missed.\n\t\t&& (cstack.cs_trylevel == 0 || did_emsg_syntax)\n#endif\n\t\t&& used_getline\n\t\t\t    && (getline_equal(fgetline, cookie, getexmodeline)\n\t\t\t       || getline_equal(fgetline, cookie, getexline)))\n\t    && (next_cmdline != NULL\n#ifdef FEAT_EVAL\n\t\t\t|| cstack.cs_idx >= 0\n#endif\n\t\t\t|| (flags & DOCMD_REPEAT)));\n\n    vim_free(cmdline_copy);\n    did_emsg_syntax = FALSE;\n#ifdef FEAT_EVAL\n    free_cmdlines(&lines_ga);\n    ga_clear(&lines_ga);\n\n    if (cstack.cs_idx >= 0)\n    {\n\t/*\n\t * If a sourced file or executed function ran to its end, report the\n\t * unclosed conditional.\n\t * In Vim9 script do not give a second error, executing aborts after\n\t * the first one.\n\t */\n\tif (!got_int && !did_throw && !aborting()\n\t\t&& !(did_emsg && in_vim9script())\n\t\t&& ((getline_equal(fgetline, cookie, getsourceline)\n\t\t\t&& !source_finished(fgetline, cookie))\n\t\t    || (getline_equal(fgetline, cookie, get_func_line)\n\t\t\t\t\t    && !func_has_ended(real_cookie))))\n\t{\n\t    if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY)\n\t\temsg(_(e_missing_endtry));\n\t    else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE)\n\t\temsg(_(e_missing_endwhile));\n\t    else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR)\n\t\temsg(_(e_missing_endfor));\n\t    else\n\t\temsg(_(e_missing_endif));\n\t}\n\n\t/*\n\t * Reset \"trylevel\" in case of a \":finish\" or \":return\" or a missing\n\t * \":endtry\" in a sourced file or executed function.  If the try\n\t * conditional is in its finally clause, ignore anything pending.\n\t * If it is in a catch clause, finish the caught exception.\n\t * Also cleanup any \"cs_forinfo\" structures.\n\t */\n\tdo\n\t{\n\t    int idx = cleanup_conditionals(&cstack, 0, TRUE);\n\n\t    if (idx >= 0)\n\t\t--idx;\t    // remove try block not in its finally clause\n\t    rewind_conditionals(&cstack, idx, CSF_WHILE | CSF_FOR,\n\t\t\t\t\t\t\t&cstack.cs_looplevel);\n\t}\n\twhile (cstack.cs_idx >= 0);\n\ttrylevel = initial_trylevel;\n    }\n\n    // If a missing \":endtry\", \":endwhile\", \":endfor\", or \":endif\" or a memory\n    // lack was reported above and the error message is to be converted to an\n    // exception, do this now after rewinding the cstack.\n    do_errthrow(&cstack, getline_equal(fgetline, cookie, get_func_line)\n\t\t\t\t  ? (char_u *)\"endfunction\" : (char_u *)NULL);\n\n    if (trylevel == 0)\n    {\n\t// Just in case did_throw got set but current_exception wasn't.\n\tif (current_exception == NULL)\n\t    did_throw = FALSE;\n\n\t/*\n\t * When an exception is being thrown out of the outermost try\n\t * conditional, discard the uncaught exception, disable the conversion\n\t * of interrupts or errors to exceptions, and ensure that no more\n\t * commands are executed.\n\t */\n\tif (did_throw)\n\t    handle_did_throw();\n\n\t/*\n\t * On an interrupt or an aborting error not converted to an exception,\n\t * disable the conversion of errors to exceptions.  (Interrupts are not\n\t * converted anymore, here.) This enables also the interrupt message\n\t * when force_abort is set and did_emsg unset in case of an interrupt\n\t * from a finally clause after an error.\n\t */\n\telse if (got_int || (did_emsg && force_abort))\n\t    suppress_errthrow = TRUE;\n    }\n\n    /*\n     * The current cstack will be freed when do_cmdline() returns.  An uncaught\n     * exception will have to be rethrown in the previous cstack.  If a function\n     * has just returned or a script file was just finished and the previous\n     * cstack belongs to the same function or, respectively, script file, it\n     * will have to be checked for finally clauses to be executed due to the\n     * \":return\" or \":finish\".  This is done in do_one_cmd().\n     */\n    if (did_throw)\n\tneed_rethrow = TRUE;\n    if ((getline_equal(fgetline, cookie, getsourceline)\n\t\t&& ex_nesting_level > source_level(real_cookie))\n\t    || (getline_equal(fgetline, cookie, get_func_line)\n\t\t&& ex_nesting_level > func_level(real_cookie) + 1))\n    {\n\tif (!did_throw)\n\t    check_cstack = TRUE;\n    }\n    else\n    {\n\t// When leaving a function, reduce nesting level.\n\tif (getline_equal(fgetline, cookie, get_func_line))\n\t    --ex_nesting_level;\n\t/*\n\t * Go to debug mode when returning from a function in which we are\n\t * single-stepping.\n\t */\n\tif ((getline_equal(fgetline, cookie, getsourceline)\n\t\t    || getline_equal(fgetline, cookie, get_func_line))\n\t\t&& ex_nesting_level + 1 <= debug_break_level)\n\t    do_debug(getline_equal(fgetline, cookie, getsourceline)\n\t\t    ? (char_u *)_(\"End of sourced file\")\n\t\t    : (char_u *)_(\"End of function\"));\n    }\n\n    /*\n     * Restore the exception environment (done after returning from the\n     * debugger).\n     */\n    if (flags & DOCMD_EXCRESET)\n\trestore_dbg_stuff(&debug_saved);\n\n    msg_list = saved_msg_list;\n\n    // Cleanup if \"cs_emsg_silent_list\" remains.\n    if (cstack.cs_emsg_silent_list != NULL)\n    {\n\teslist_T *elem, *temp;\n\n\tfor (elem = cstack.cs_emsg_silent_list; elem != NULL; elem = temp)\n\t{\n\t    temp = elem->next;\n\t    vim_free(elem);\n\t}\n    }\n#endif // FEAT_EVAL\n\n    /*\n     * If there was too much output to fit on the command line, ask the user to\n     * hit return before redrawing the screen. With the \":global\" command we do\n     * this only once after the command is finished.\n     */\n    if (did_inc)\n    {\n\t--RedrawingDisabled;\n\t--no_wait_return;\n\tmsg_scroll = FALSE;\n\n\t/*\n\t * When just finished an \":if\"-\":else\" which was typed, no need to\n\t * wait for hit-return.  Also for an error situation.\n\t */\n\tif (retval == FAIL\n#ifdef FEAT_EVAL\n\t\t|| (did_endif && KeyTyped && !did_emsg)\n#endif\n\t\t\t\t\t    )\n\t{\n\t    need_wait_return = FALSE;\n\t    msg_didany = FALSE;\t\t// don't wait when restarting edit\n\t}\n\telse if (need_wait_return)\n\t{\n\t    /*\n\t     * The msg_start() above clears msg_didout. The wait_return() we do\n\t     * here should not overwrite the command that may be shown before\n\t     * doing that.\n\t     */\n\t    msg_didout |= msg_didout_before_start;\n\t    wait_return(FALSE);\n\t}\n    }\n\n#ifdef FEAT_EVAL\n    did_endif = FALSE;  // in case do_cmdline used recursively\n#else\n    /*\n     * Reset if_level, in case a sourced script file contains more \":if\" than\n     * \":endif\" (could be \":if x | foo | endif\").\n     */\n    if_level = 0;\n#endif\n\n    --call_depth;\n    return retval;\n}", "func_hash": 18276376041085945144974490585203596149, "file_name": "ex_docmd.c", "file_hash": 295000933203185103325291624331253822836, "cwe": ["CWE-416"], "cve": "CVE-2022-3099", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 9.0.0360.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3099"}
{"idx": 443298, "project": "vim", "commit_id": "35d21c6830fc2d68aca838424a0e786821c5891c", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/35d21c6830fc2d68aca838424a0e786821c5891c", "commit_message": "patch 9.0.0360: crash when invalid line number on :for is ignored\n\nProblem:    Crash when invalid line number on :for is ignored.\nSolution:   Do not check breakpoint for non-existing line.", "target": 0, "func": "do_cmdline(\n    char_u\t*cmdline,\n    char_u\t*(*fgetline)(int, void *, int, getline_opt_T),\n    void\t*cookie,\t\t// argument for fgetline()\n    int\t\tflags)\n{\n    char_u\t*next_cmdline;\t\t// next cmd to execute\n    char_u\t*cmdline_copy = NULL;\t// copy of cmd line\n    int\t\tused_getline = FALSE;\t// used \"fgetline\" to obtain command\n    static int\trecursive = 0;\t\t// recursive depth\n    int\t\tmsg_didout_before_start = 0;\n    int\t\tcount = 0;\t\t// line number count\n    int\t\tdid_inc = FALSE;\t// incremented RedrawingDisabled\n    int\t\tretval = OK;\n#ifdef FEAT_EVAL\n    cstack_T\tcstack;\t\t\t// conditional stack\n    garray_T\tlines_ga;\t\t// keep lines for \":while\"/\":for\"\n    int\t\tcurrent_line = 0;\t// active line in lines_ga\n    int\t\tcurrent_line_before = 0;\n    char_u\t*fname = NULL;\t\t// function or script name\n    linenr_T\t*breakpoint = NULL;\t// ptr to breakpoint field in cookie\n    int\t\t*dbg_tick = NULL;\t// ptr to dbg_tick field in cookie\n    struct dbg_stuff debug_saved;\t// saved things for debug mode\n    int\t\tinitial_trylevel;\n    msglist_T\t**saved_msg_list = NULL;\n    msglist_T\t*private_msg_list = NULL;\n\n    // \"fgetline\" and \"cookie\" passed to do_one_cmd()\n    char_u\t*(*cmd_getline)(int, void *, int, getline_opt_T);\n    void\t*cmd_cookie;\n    struct loop_cookie cmd_loop_cookie;\n    void\t*real_cookie;\n    int\t\tgetline_is_func;\n#else\n# define cmd_getline fgetline\n# define cmd_cookie cookie\n#endif\n    static int\tcall_depth = 0;\t\t// recursiveness\n#ifdef FEAT_EVAL\n    // For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory\n    // location for storing error messages to be converted to an exception.\n    // This ensures that the do_errthrow() call in do_one_cmd() does not\n    // combine the messages stored by an earlier invocation of do_one_cmd()\n    // with the command name of the later one.  This would happen when\n    // BufWritePost autocommands are executed after a write error.\n    saved_msg_list = msg_list;\n    msg_list = &private_msg_list;\n#endif\n\n    // It's possible to create an endless loop with \":execute\", catch that\n    // here.  The value of 200 allows nested function calls, \":source\", etc.\n    // Allow 200 or 'maxfuncdepth', whatever is larger.\n    if (call_depth >= 200\n#ifdef FEAT_EVAL\n\t    && call_depth >= p_mfd\n#endif\n\t    )\n    {\n\temsg(_(e_command_too_recursive));\n#ifdef FEAT_EVAL\n\t// When converting to an exception, we do not include the command name\n\t// since this is not an error of the specific command.\n\tdo_errthrow((cstack_T *)NULL, (char_u *)NULL);\n\tmsg_list = saved_msg_list;\n#endif\n\treturn FAIL;\n    }\n    ++call_depth;\n\n#ifdef FEAT_EVAL\n    CLEAR_FIELD(cstack);\n    cstack.cs_idx = -1;\n    ga_init2(&lines_ga, sizeof(wcmd_T), 10);\n\n    real_cookie = getline_cookie(fgetline, cookie);\n\n    // Inside a function use a higher nesting level.\n    getline_is_func = getline_equal(fgetline, cookie, get_func_line);\n    if (getline_is_func && ex_nesting_level == func_level(real_cookie))\n\t++ex_nesting_level;\n\n    // Get the function or script name and the address where the next breakpoint\n    // line and the debug tick for a function or script are stored.\n    if (getline_is_func)\n    {\n\tfname = func_name(real_cookie);\n\tbreakpoint = func_breakpoint(real_cookie);\n\tdbg_tick = func_dbg_tick(real_cookie);\n    }\n    else if (getline_equal(fgetline, cookie, getsourceline))\n    {\n\tfname = SOURCING_NAME;\n\tbreakpoint = source_breakpoint(real_cookie);\n\tdbg_tick = source_dbg_tick(real_cookie);\n    }\n\n    /*\n     * Initialize \"force_abort\"  and \"suppress_errthrow\" at the top level.\n     */\n    if (!recursive)\n    {\n\tforce_abort = FALSE;\n\tsuppress_errthrow = FALSE;\n    }\n\n    /*\n     * If requested, store and reset the global values controlling the\n     * exception handling (used when debugging).  Otherwise clear it to avoid\n     * a bogus compiler warning when the optimizer uses inline functions...\n     */\n    if (flags & DOCMD_EXCRESET)\n\tsave_dbg_stuff(&debug_saved);\n    else\n\tCLEAR_FIELD(debug_saved);\n\n    initial_trylevel = trylevel;\n\n    /*\n     * \"did_throw\" will be set to TRUE when an exception is being thrown.\n     */\n    did_throw = FALSE;\n#endif\n    /*\n     * \"did_emsg\" will be set to TRUE when emsg() is used, in which case we\n     * cancel the whole command line, and any if/endif or loop.\n     * If force_abort is set, we cancel everything.\n     */\n#ifdef FEAT_EVAL\n    did_emsg_cumul += did_emsg;\n#endif\n    did_emsg = FALSE;\n\n    /*\n     * KeyTyped is only set when calling vgetc().  Reset it here when not\n     * calling vgetc() (sourced command lines).\n     */\n    if (!(flags & DOCMD_KEYTYPED)\n\t\t\t       && !getline_equal(fgetline, cookie, getexline))\n\tKeyTyped = FALSE;\n\n    /*\n     * Continue executing command lines:\n     * - when inside an \":if\", \":while\" or \":for\"\n     * - for multiple commands on one line, separated with '|'\n     * - when repeating until there are no more lines (for \":source\")\n     */\n    next_cmdline = cmdline;\n    do\n    {\n#ifdef FEAT_EVAL\n\tgetline_is_func = getline_equal(fgetline, cookie, get_func_line);\n#endif\n\n\t// stop skipping cmds for an error msg after all endif/while/for\n\tif (next_cmdline == NULL\n#ifdef FEAT_EVAL\n\t\t&& !force_abort\n\t\t&& cstack.cs_idx < 0\n\t\t&& !(getline_is_func && func_has_abort(real_cookie))\n#endif\n\t\t\t\t\t\t\t)\n\t{\n#ifdef FEAT_EVAL\n\t    did_emsg_cumul += did_emsg;\n#endif\n\t    did_emsg = FALSE;\n\t}\n\n\t/*\n\t * 1. If repeating a line in a loop, get a line from lines_ga.\n\t * 2. If no line given: Get an allocated line with fgetline().\n\t * 3. If a line is given: Make a copy, so we can mess with it.\n\t */\n\n#ifdef FEAT_EVAL\n\t// 1. If repeating, get a previous line from lines_ga.\n\tif (cstack.cs_looplevel > 0 && current_line < lines_ga.ga_len)\n\t{\n\t    // Each '|' separated command is stored separately in lines_ga, to\n\t    // be able to jump to it.  Don't use next_cmdline now.\n\t    VIM_CLEAR(cmdline_copy);\n\n\t    // Check if a function has returned or, unless it has an unclosed\n\t    // try conditional, aborted.\n\t    if (getline_is_func)\n\t    {\n# ifdef FEAT_PROFILE\n\t\tif (do_profiling == PROF_YES)\n\t\t    func_line_end(real_cookie);\n# endif\n\t\tif (func_has_ended(real_cookie))\n\t\t{\n\t\t    retval = FAIL;\n\t\t    break;\n\t\t}\n\t    }\n#ifdef FEAT_PROFILE\n\t    else if (do_profiling == PROF_YES\n\t\t\t    && getline_equal(fgetline, cookie, getsourceline))\n\t\tscript_line_end();\n#endif\n\n\t    // Check if a sourced file hit a \":finish\" command.\n\t    if (source_finished(fgetline, cookie))\n\t    {\n\t\tretval = FAIL;\n\t\tbreak;\n\t    }\n\n\t    // If breakpoints have been added/deleted need to check for it.\n\t    if (breakpoint != NULL && dbg_tick != NULL\n\t\t\t\t\t\t   && *dbg_tick != debug_tick)\n\t    {\n\t\t*breakpoint = dbg_find_breakpoint(\n\t\t\t\tgetline_equal(fgetline, cookie, getsourceline),\n\t\t\t\t\t\t\tfname, SOURCING_LNUM);\n\t\t*dbg_tick = debug_tick;\n\t    }\n\n\t    next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line;\n\t    SOURCING_LNUM = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum;\n\n\t    // Did we encounter a breakpoint?\n\t    if (breakpoint != NULL && *breakpoint != 0\n\t\t\t\t\t      && *breakpoint <= SOURCING_LNUM)\n\t    {\n\t\tdbg_breakpoint(fname, SOURCING_LNUM);\n\t\t// Find next breakpoint.\n\t\t*breakpoint = dbg_find_breakpoint(\n\t\t\t       getline_equal(fgetline, cookie, getsourceline),\n\t\t\t\t\t\t\tfname, SOURCING_LNUM);\n\t\t*dbg_tick = debug_tick;\n\t    }\n# ifdef FEAT_PROFILE\n\t    if (do_profiling == PROF_YES)\n\t    {\n\t\tif (getline_is_func)\n\t\t    func_line_start(real_cookie, SOURCING_LNUM);\n\t\telse if (getline_equal(fgetline, cookie, getsourceline))\n\t\t    script_line_start();\n\t    }\n# endif\n\t}\n#endif\n\n\t// 2. If no line given, get an allocated line with fgetline().\n\tif (next_cmdline == NULL)\n\t{\n\t    /*\n\t     * Need to set msg_didout for the first line after an \":if\",\n\t     * otherwise the \":if\" will be overwritten.\n\t     */\n\t    if (count == 1 && getline_equal(fgetline, cookie, getexline))\n\t\tmsg_didout = TRUE;\n\t    if (fgetline == NULL || (next_cmdline = fgetline(':', cookie,\n#ifdef FEAT_EVAL\n\t\t    cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2\n#else\n\t\t    0\n#endif\n\t\t    , in_vim9script() ? GETLINE_CONCAT_CONTBAR\n\t\t\t\t\t       : GETLINE_CONCAT_CONT)) == NULL)\n\t    {\n\t\t// Don't call wait_return() for aborted command line.  The NULL\n\t\t// returned for the end of a sourced file or executed function\n\t\t// doesn't do this.\n\t\tif (KeyTyped && !(flags & DOCMD_REPEAT))\n\t\t    need_wait_return = FALSE;\n\t\tretval = FAIL;\n\t\tbreak;\n\t    }\n\t    used_getline = TRUE;\n\n\t    /*\n\t     * Keep the first typed line.  Clear it when more lines are typed.\n\t     */\n\t    if (flags & DOCMD_KEEPLINE)\n\t    {\n\t\tvim_free(repeat_cmdline);\n\t\tif (count == 0)\n\t\t    repeat_cmdline = vim_strsave(next_cmdline);\n\t\telse\n\t\t    repeat_cmdline = NULL;\n\t    }\n\t}\n\n\t// 3. Make a copy of the command so we can mess with it.\n\telse if (cmdline_copy == NULL)\n\t{\n\t    next_cmdline = vim_strsave(next_cmdline);\n\t    if (next_cmdline == NULL)\n\t    {\n\t\temsg(_(e_out_of_memory));\n\t\tretval = FAIL;\n\t\tbreak;\n\t    }\n\t}\n\tcmdline_copy = next_cmdline;\n\n#ifdef FEAT_EVAL\n\t/*\n\t * Inside a while/for loop, and when the command looks like a \":while\"\n\t * or \":for\", the line is stored, because we may need it later when\n\t * looping.\n\t *\n\t * When there is a '|' and another command, it is stored separately,\n\t * because we need to be able to jump back to it from an\n\t * :endwhile/:endfor.\n\t *\n\t * Pass a different \"fgetline\" function to do_one_cmd() below,\n\t * that it stores lines in or reads them from \"lines_ga\".  Makes it\n\t * possible to define a function inside a while/for loop and handles\n\t * line continuation.\n\t */\n\tif ((cstack.cs_looplevel > 0 || has_loop_cmd(next_cmdline)))\n\t{\n\t    cmd_getline = get_loop_line;\n\t    cmd_cookie = (void *)&cmd_loop_cookie;\n\t    cmd_loop_cookie.lines_gap = &lines_ga;\n\t    cmd_loop_cookie.current_line = current_line;\n\t    cmd_loop_cookie.getline = fgetline;\n\t    cmd_loop_cookie.cookie = cookie;\n\t    cmd_loop_cookie.repeating = (current_line < lines_ga.ga_len);\n\n\t    // Save the current line when encountering it the first time.\n\t    if (current_line == lines_ga.ga_len\n\t\t    && store_loop_line(&lines_ga, next_cmdline) == FAIL)\n\t    {\n\t\tretval = FAIL;\n\t\tbreak;\n\t    }\n\t    current_line_before = current_line;\n\t}\n\telse\n\t{\n\t    cmd_getline = fgetline;\n\t    cmd_cookie = cookie;\n\t}\n\n\tdid_endif = FALSE;\n#endif\n\n\tif (count++ == 0)\n\t{\n\t    /*\n\t     * All output from the commands is put below each other, without\n\t     * waiting for a return. Don't do this when executing commands\n\t     * from a script or when being called recursive (e.g. for \":e\n\t     * +command file\").\n\t     */\n\t    if (!(flags & DOCMD_NOWAIT) && !recursive)\n\t    {\n\t\tmsg_didout_before_start = msg_didout;\n\t\tmsg_didany = FALSE; // no output yet\n\t\tmsg_start();\n\t\tmsg_scroll = TRUE;  // put messages below each other\n\t\t++no_wait_return;   // don't wait for return until finished\n\t\t++RedrawingDisabled;\n\t\tdid_inc = TRUE;\n\t    }\n\t}\n\n\tif ((p_verbose >= 15 && SOURCING_NAME != NULL) || p_verbose >= 16)\n\t    msg_verbose_cmd(SOURCING_LNUM, cmdline_copy);\n\n\t/*\n\t * 2. Execute one '|' separated command.\n\t *    do_one_cmd() will return NULL if there is no trailing '|'.\n\t *    \"cmdline_copy\" can change, e.g. for '%' and '#' expansion.\n\t */\n\t++recursive;\n\tnext_cmdline = do_one_cmd(&cmdline_copy, flags,\n#ifdef FEAT_EVAL\n\t\t\t\t&cstack,\n#endif\n\t\t\t\tcmd_getline, cmd_cookie);\n\t--recursive;\n\n#ifdef FEAT_EVAL\n\tif (cmd_cookie == (void *)&cmd_loop_cookie)\n\t    // Use \"current_line\" from \"cmd_loop_cookie\", it may have been\n\t    // incremented when defining a function.\n\t    current_line = cmd_loop_cookie.current_line;\n#endif\n\n\tif (next_cmdline == NULL)\n\t{\n\t    VIM_CLEAR(cmdline_copy);\n\n\t    /*\n\t     * If the command was typed, remember it for the ':' register.\n\t     * Do this AFTER executing the command to make :@: work.\n\t     */\n\t    if (getline_equal(fgetline, cookie, getexline)\n\t\t\t\t\t\t  && new_last_cmdline != NULL)\n\t    {\n\t\tvim_free(last_cmdline);\n\t\tlast_cmdline = new_last_cmdline;\n\t\tnew_last_cmdline = NULL;\n\t    }\n\t}\n\telse\n\t{\n\t    // need to copy the command after the '|' to cmdline_copy, for the\n\t    // next do_one_cmd()\n\t    STRMOVE(cmdline_copy, next_cmdline);\n\t    next_cmdline = cmdline_copy;\n\t}\n\n\n#ifdef FEAT_EVAL\n\t// reset did_emsg for a function that is not aborted by an error\n\tif (did_emsg && !force_abort\n\t\t&& getline_equal(fgetline, cookie, get_func_line)\n\t\t\t\t\t      && !func_has_abort(real_cookie))\n\t{\n\t    // did_emsg_cumul is not set here\n\t    did_emsg = FALSE;\n\t}\n\n\tif (cstack.cs_looplevel > 0)\n\t{\n\t    ++current_line;\n\n\t    /*\n\t     * An \":endwhile\", \":endfor\" and \":continue\" is handled here.\n\t     * If we were executing commands, jump back to the \":while\" or\n\t     * \":for\".\n\t     * If we were not executing commands, decrement cs_looplevel.\n\t     */\n\t    if (cstack.cs_lflags & (CSL_HAD_CONT | CSL_HAD_ENDLOOP))\n\t    {\n\t\tcstack.cs_lflags &= ~(CSL_HAD_CONT | CSL_HAD_ENDLOOP);\n\n\t\t// Jump back to the matching \":while\" or \":for\".  Be careful\n\t\t// not to use a cs_line[] from an entry that isn't a \":while\"\n\t\t// or \":for\": It would make \"current_line\" invalid and can\n\t\t// cause a crash.\n\t\tif (!did_emsg && !got_int && !did_throw\n\t\t\t&& cstack.cs_idx >= 0\n\t\t\t&& (cstack.cs_flags[cstack.cs_idx]\n\t\t\t\t\t\t      & (CSF_WHILE | CSF_FOR))\n\t\t\t&& cstack.cs_line[cstack.cs_idx] >= 0\n\t\t\t&& (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE))\n\t\t{\n\t\t    current_line = cstack.cs_line[cstack.cs_idx];\n\t\t\t\t\t\t// remember we jumped there\n\t\t    cstack.cs_lflags |= CSL_HAD_LOOP;\n\t\t    line_breakcheck();\t\t// check if CTRL-C typed\n\n\t\t    // Check for the next breakpoint at or after the \":while\"\n\t\t    // or \":for\".\n\t\t    if (breakpoint != NULL && lines_ga.ga_len > current_line)\n\t\t    {\n\t\t\t*breakpoint = dbg_find_breakpoint(\n\t\t\t       getline_equal(fgetline, cookie, getsourceline),\n\t\t\t\t\t\t\t\t\tfname,\n\t\t\t   ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1);\n\t\t\t*dbg_tick = debug_tick;\n\t\t    }\n\t\t}\n\t\telse\n\t\t{\n\t\t    // can only get here with \":endwhile\" or \":endfor\"\n\t\t    if (cstack.cs_idx >= 0)\n\t\t\trewind_conditionals(&cstack, cstack.cs_idx - 1,\n\t\t\t\t   CSF_WHILE | CSF_FOR, &cstack.cs_looplevel);\n\t\t}\n\t    }\n\n\t    /*\n\t     * For a \":while\" or \":for\" we need to remember the line number.\n\t     */\n\t    else if (cstack.cs_lflags & CSL_HAD_LOOP)\n\t    {\n\t\tcstack.cs_lflags &= ~CSL_HAD_LOOP;\n\t\tcstack.cs_line[cstack.cs_idx] = current_line_before;\n\t    }\n\t}\n\n\t// Check for the next breakpoint after a watchexpression\n\tif (breakpoint != NULL && has_watchexpr())\n\t{\n\t    *breakpoint = dbg_find_breakpoint(FALSE, fname, SOURCING_LNUM);\n\t    *dbg_tick = debug_tick;\n\t}\n\n\t/*\n\t * When not inside any \":while\" loop, clear remembered lines.\n\t */\n\tif (cstack.cs_looplevel == 0)\n\t{\n\t    if (lines_ga.ga_len > 0)\n\t    {\n\t\tSOURCING_LNUM =\n\t\t       ((wcmd_T *)lines_ga.ga_data)[lines_ga.ga_len - 1].lnum;\n\t\tfree_cmdlines(&lines_ga);\n\t    }\n\t    current_line = 0;\n\t}\n\n\t/*\n\t * A \":finally\" makes did_emsg, got_int, and did_throw pending for\n\t * being restored at the \":endtry\".  Reset them here and set the\n\t * ACTIVE and FINALLY flags, so that the finally clause gets executed.\n\t * This includes the case where a missing \":endif\", \":endwhile\" or\n\t * \":endfor\" was detected by the \":finally\" itself.\n\t */\n\tif (cstack.cs_lflags & CSL_HAD_FINA)\n\t{\n\t    cstack.cs_lflags &= ~CSL_HAD_FINA;\n\t    report_make_pending(cstack.cs_pending[cstack.cs_idx]\n\t\t    & (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW),\n\t\t    did_throw ? (void *)current_exception : NULL);\n\t    did_emsg = got_int = did_throw = FALSE;\n\t    cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY;\n\t}\n\n\t// Update global \"trylevel\" for recursive calls to do_cmdline() from\n\t// within this loop.\n\ttrylevel = initial_trylevel + cstack.cs_trylevel;\n\n\t/*\n\t * If the outermost try conditional (across function calls and sourced\n\t * files) is aborted because of an error, an interrupt, or an uncaught\n\t * exception, cancel everything.  If it is left normally, reset\n\t * force_abort to get the non-EH compatible abortion behavior for\n\t * the rest of the script.\n\t */\n\tif (trylevel == 0 && !did_emsg && !got_int && !did_throw)\n\t    force_abort = FALSE;\n\n\t// Convert an interrupt to an exception if appropriate.\n\t(void)do_intthrow(&cstack);\n#endif // FEAT_EVAL\n\n    }\n    /*\n     * Continue executing command lines when:\n     * - no CTRL-C typed, no aborting error, no exception thrown or try\n     *   conditionals need to be checked for executing finally clauses or\n     *   catching an interrupt exception\n     * - didn't get an error message or lines are not typed\n     * - there is a command after '|', inside a :if, :while, :for or :try, or\n     *   looping for \":source\" command or function call.\n     */\n    while (!((got_int\n#ifdef FEAT_EVAL\n\t\t    || (did_emsg && (force_abort || in_vim9script()))\n\t\t    || did_throw\n#endif\n\t     )\n#ifdef FEAT_EVAL\n\t\t&& cstack.cs_trylevel == 0\n#endif\n\t    )\n\t    && !(did_emsg\n#ifdef FEAT_EVAL\n\t\t// Keep going when inside try/catch, so that the error can be\n\t\t// deal with, except when it is a syntax error, it may cause\n\t\t// the :endtry to be missed.\n\t\t&& (cstack.cs_trylevel == 0 || did_emsg_syntax)\n#endif\n\t\t&& used_getline\n\t\t\t    && (getline_equal(fgetline, cookie, getexmodeline)\n\t\t\t       || getline_equal(fgetline, cookie, getexline)))\n\t    && (next_cmdline != NULL\n#ifdef FEAT_EVAL\n\t\t\t|| cstack.cs_idx >= 0\n#endif\n\t\t\t|| (flags & DOCMD_REPEAT)));\n\n    vim_free(cmdline_copy);\n    did_emsg_syntax = FALSE;\n#ifdef FEAT_EVAL\n    free_cmdlines(&lines_ga);\n    ga_clear(&lines_ga);\n\n    if (cstack.cs_idx >= 0)\n    {\n\t/*\n\t * If a sourced file or executed function ran to its end, report the\n\t * unclosed conditional.\n\t * In Vim9 script do not give a second error, executing aborts after\n\t * the first one.\n\t */\n\tif (!got_int && !did_throw && !aborting()\n\t\t&& !(did_emsg && in_vim9script())\n\t\t&& ((getline_equal(fgetline, cookie, getsourceline)\n\t\t\t&& !source_finished(fgetline, cookie))\n\t\t    || (getline_equal(fgetline, cookie, get_func_line)\n\t\t\t\t\t    && !func_has_ended(real_cookie))))\n\t{\n\t    if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY)\n\t\temsg(_(e_missing_endtry));\n\t    else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE)\n\t\temsg(_(e_missing_endwhile));\n\t    else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR)\n\t\temsg(_(e_missing_endfor));\n\t    else\n\t\temsg(_(e_missing_endif));\n\t}\n\n\t/*\n\t * Reset \"trylevel\" in case of a \":finish\" or \":return\" or a missing\n\t * \":endtry\" in a sourced file or executed function.  If the try\n\t * conditional is in its finally clause, ignore anything pending.\n\t * If it is in a catch clause, finish the caught exception.\n\t * Also cleanup any \"cs_forinfo\" structures.\n\t */\n\tdo\n\t{\n\t    int idx = cleanup_conditionals(&cstack, 0, TRUE);\n\n\t    if (idx >= 0)\n\t\t--idx;\t    // remove try block not in its finally clause\n\t    rewind_conditionals(&cstack, idx, CSF_WHILE | CSF_FOR,\n\t\t\t\t\t\t\t&cstack.cs_looplevel);\n\t}\n\twhile (cstack.cs_idx >= 0);\n\ttrylevel = initial_trylevel;\n    }\n\n    // If a missing \":endtry\", \":endwhile\", \":endfor\", or \":endif\" or a memory\n    // lack was reported above and the error message is to be converted to an\n    // exception, do this now after rewinding the cstack.\n    do_errthrow(&cstack, getline_equal(fgetline, cookie, get_func_line)\n\t\t\t\t  ? (char_u *)\"endfunction\" : (char_u *)NULL);\n\n    if (trylevel == 0)\n    {\n\t// Just in case did_throw got set but current_exception wasn't.\n\tif (current_exception == NULL)\n\t    did_throw = FALSE;\n\n\t/*\n\t * When an exception is being thrown out of the outermost try\n\t * conditional, discard the uncaught exception, disable the conversion\n\t * of interrupts or errors to exceptions, and ensure that no more\n\t * commands are executed.\n\t */\n\tif (did_throw)\n\t    handle_did_throw();\n\n\t/*\n\t * On an interrupt or an aborting error not converted to an exception,\n\t * disable the conversion of errors to exceptions.  (Interrupts are not\n\t * converted anymore, here.) This enables also the interrupt message\n\t * when force_abort is set and did_emsg unset in case of an interrupt\n\t * from a finally clause after an error.\n\t */\n\telse if (got_int || (did_emsg && force_abort))\n\t    suppress_errthrow = TRUE;\n    }\n\n    /*\n     * The current cstack will be freed when do_cmdline() returns.  An uncaught\n     * exception will have to be rethrown in the previous cstack.  If a function\n     * has just returned or a script file was just finished and the previous\n     * cstack belongs to the same function or, respectively, script file, it\n     * will have to be checked for finally clauses to be executed due to the\n     * \":return\" or \":finish\".  This is done in do_one_cmd().\n     */\n    if (did_throw)\n\tneed_rethrow = TRUE;\n    if ((getline_equal(fgetline, cookie, getsourceline)\n\t\t&& ex_nesting_level > source_level(real_cookie))\n\t    || (getline_equal(fgetline, cookie, get_func_line)\n\t\t&& ex_nesting_level > func_level(real_cookie) + 1))\n    {\n\tif (!did_throw)\n\t    check_cstack = TRUE;\n    }\n    else\n    {\n\t// When leaving a function, reduce nesting level.\n\tif (getline_equal(fgetline, cookie, get_func_line))\n\t    --ex_nesting_level;\n\t/*\n\t * Go to debug mode when returning from a function in which we are\n\t * single-stepping.\n\t */\n\tif ((getline_equal(fgetline, cookie, getsourceline)\n\t\t    || getline_equal(fgetline, cookie, get_func_line))\n\t\t&& ex_nesting_level + 1 <= debug_break_level)\n\t    do_debug(getline_equal(fgetline, cookie, getsourceline)\n\t\t    ? (char_u *)_(\"End of sourced file\")\n\t\t    : (char_u *)_(\"End of function\"));\n    }\n\n    /*\n     * Restore the exception environment (done after returning from the\n     * debugger).\n     */\n    if (flags & DOCMD_EXCRESET)\n\trestore_dbg_stuff(&debug_saved);\n\n    msg_list = saved_msg_list;\n\n    // Cleanup if \"cs_emsg_silent_list\" remains.\n    if (cstack.cs_emsg_silent_list != NULL)\n    {\n\teslist_T *elem, *temp;\n\n\tfor (elem = cstack.cs_emsg_silent_list; elem != NULL; elem = temp)\n\t{\n\t    temp = elem->next;\n\t    vim_free(elem);\n\t}\n    }\n#endif // FEAT_EVAL\n\n    /*\n     * If there was too much output to fit on the command line, ask the user to\n     * hit return before redrawing the screen. With the \":global\" command we do\n     * this only once after the command is finished.\n     */\n    if (did_inc)\n    {\n\t--RedrawingDisabled;\n\t--no_wait_return;\n\tmsg_scroll = FALSE;\n\n\t/*\n\t * When just finished an \":if\"-\":else\" which was typed, no need to\n\t * wait for hit-return.  Also for an error situation.\n\t */\n\tif (retval == FAIL\n#ifdef FEAT_EVAL\n\t\t|| (did_endif && KeyTyped && !did_emsg)\n#endif\n\t\t\t\t\t    )\n\t{\n\t    need_wait_return = FALSE;\n\t    msg_didany = FALSE;\t\t// don't wait when restarting edit\n\t}\n\telse if (need_wait_return)\n\t{\n\t    /*\n\t     * The msg_start() above clears msg_didout. The wait_return() we do\n\t     * here should not overwrite the command that may be shown before\n\t     * doing that.\n\t     */\n\t    msg_didout |= msg_didout_before_start;\n\t    wait_return(FALSE);\n\t}\n    }\n\n#ifdef FEAT_EVAL\n    did_endif = FALSE;  // in case do_cmdline used recursively\n#else\n    /*\n     * Reset if_level, in case a sourced script file contains more \":if\" than\n     * \":endif\" (could be \":if x | foo | endif\").\n     */\n    if_level = 0;\n#endif\n\n    --call_depth;\n    return retval;\n}", "func_hash": 107220537599644166410978014776219092852, "file_name": "ex_docmd.c", "file_hash": 211799171285121877769856078715751754157, "cwe": ["CWE-416"], "cve": "CVE-2022-3099", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 9.0.0360.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3099"}
{"idx": 211090, "project": "cifs-utils", "commit_id": "f6eae44a3d05b6515a59651e6bed8b6dde689aec", "project_url": "https://github.com/piastry/cifs-utils", "commit_url": "http://git.samba.org/?p=cifs-utils.git;a=commitdiff;h=f6eae44a3d05b6515a59651e6bed8b6dde689aec", "commit_message": "mtab: handle ENOSPC/EFBIG condition properly when altering mtab\n\nIt's possible that when mount.cifs goes to append the mtab that there\nwon't be enough space to do so, and the mntent won't be appended to the\nfile in its entirety.\n\nAdd a my_endmntent routine that will fflush and then fsync the FILE if\nthat succeeds. If either fails then it will truncate the file back to\nits provided size. It will then call endmntent unconditionally.\n\nHave add_mtab call fstat on the opened mtab file in order to get the\nsize of the file before it has been appended. Assuming that that\nsucceeds, use my_endmntent to ensure that the file is not corrupted\nbefore closing it. It's possible that we'll have a small race window\nwhere the mtab is incorrect, but it should be quickly corrected.\n\nThis was reported some time ago as CVE-2011-1678:\n\n    http://openwall.com/lists/oss-security/2011/03/04/9\n\n...and it seems to fix the reproducer that I was able to come up with.\n\nSigned-off-by: Jeff Layton \nReviewed-by: Suresh Jayaraman ", "target": 1, "func": "add_mtab(char *devname, char *mountpoint, unsigned long flags, const char *fstype)\n{\n\tint rc = 0;\n\tuid_t uid;\n\tchar *mount_user = NULL;\n\tstruct mntent mountent;\n\tFILE *pmntfile;\n\tsigset_t mask, oldmask;\n\n\tuid = getuid();\n\tif (uid != 0)\n\t\tmount_user = getusername(uid);\n\n\t/*\n\t * Set the real uid to the effective uid. This prevents unprivileged\n\t * users from sending signals to this process, though ^c on controlling\n\t * terminal should still work.\n\t */\n\trc = setreuid(geteuid(), -1);\n\tif (rc != 0) {\n\t\tfprintf(stderr, \"Unable to set real uid to effective uid: %s\\n\",\n\t\t\t\tstrerror(errno));\n\t\treturn EX_FILEIO;\n\t}\n\n\trc = sigfillset(&mask);\n\tif (rc) {\n\t\tfprintf(stderr, \"Unable to set filled signal mask\\n\");\n\t\treturn EX_FILEIO;\n\t}\n\n\trc = sigprocmask(SIG_SETMASK, &mask, &oldmask);\n\tif (rc) {\n\t\tfprintf(stderr, \"Unable to make process ignore signals\\n\");\n\t\treturn EX_FILEIO;\n\t}\n\n\trc = toggle_dac_capability(1, 1);\n\tif (rc)\n\t\treturn EX_FILEIO;\n\n\tatexit(unlock_mtab);\n\trc = lock_mtab();\n\tif (rc) {\n\t\tfprintf(stderr, \"cannot lock mtab\");\n\t\trc = EX_FILEIO;\n\t\tgoto add_mtab_exit;\n\t}\n\n\tpmntfile = setmntent(MOUNTED, \"a+\");\n\tif (!pmntfile) {\n\t\tfprintf(stderr, \"could not update mount table\\n\");\n\t\tunlock_mtab();\n\t\trc = EX_FILEIO;\n\t\tgoto add_mtab_exit;\n\t}\n\n\tmountent.mnt_fsname = devname;\n\tmountent.mnt_dir = mountpoint;\n\tmountent.mnt_type = (char *)(void *)fstype;\n\tmountent.mnt_opts = (char *)calloc(MTAB_OPTIONS_LEN, 1);\n\tif (mountent.mnt_opts) {\n\t\tif (flags & MS_RDONLY)\n\t\t\tstrlcat(mountent.mnt_opts, \"ro\", MTAB_OPTIONS_LEN);\n\t\telse\n\t\t\tstrlcat(mountent.mnt_opts, \"rw\", MTAB_OPTIONS_LEN);\n\n\t\tif (flags & MS_MANDLOCK)\n\t\t\tstrlcat(mountent.mnt_opts, \",mand\", MTAB_OPTIONS_LEN);\n\t\tif (flags & MS_NOEXEC)\n\t\t\tstrlcat(mountent.mnt_opts, \",noexec\", MTAB_OPTIONS_LEN);\n\t\tif (flags & MS_NOSUID)\n\t\t\tstrlcat(mountent.mnt_opts, \",nosuid\", MTAB_OPTIONS_LEN);\n\t\tif (flags & MS_NODEV)\n\t\t\tstrlcat(mountent.mnt_opts, \",nodev\", MTAB_OPTIONS_LEN);\n\t\tif (flags & MS_SYNCHRONOUS)\n\t\t\tstrlcat(mountent.mnt_opts, \",sync\", MTAB_OPTIONS_LEN);\n\t\tif (mount_user) {\n\t\t\tstrlcat(mountent.mnt_opts, \",user=\", MTAB_OPTIONS_LEN);\n\t\t\tstrlcat(mountent.mnt_opts, mount_user,\n\t\t\t\tMTAB_OPTIONS_LEN);\n\t\t}\n\t}\n\tmountent.mnt_freq = 0;\n\tmountent.mnt_passno = 0;\n\trc = addmntent(pmntfile, &mountent);\n\tif (rc) {\n\t\tfprintf(stderr, \"unable to add mount entry to mtab\\n\");\n\t\trc = EX_FILEIO;\n\t}\n\tendmntent(pmntfile);\n\tunlock_mtab();\n\tSAFE_FREE(mountent.mnt_opts);\nadd_mtab_exit:\n\ttoggle_dac_capability(1, 0);\n\tsigprocmask(SIG_SETMASK, &oldmask, NULL);\n\n\treturn rc;\n}", "func_hash": 273553685691100796690999653932620048883, "file_name": "mount.cifs.c", "file_hash": 178835896677030263209716239403402725405, "cwe": ["CWE-20"], "cve": "CVE-2011-1678", "cve_desc": "smbfs in Samba 3.5.8 and earlier attempts to use (1) mount.cifs to append to the /etc/mtab file and (2) umount.cifs to append to the /etc/mtab.tmp file without first checking whether resource limits would interfere, which allows local users to trigger corruption of the /etc/mtab file via a process with a small RLIMIT_FSIZE value, a related issue to CVE-2011-1089.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2011-1678"}
{"idx": 444900, "project": "cifs-utils", "commit_id": "f6eae44a3d05b6515a59651e6bed8b6dde689aec", "project_url": "https://github.com/piastry/cifs-utils", "commit_url": "http://git.samba.org/?p=cifs-utils.git;a=commitdiff;h=f6eae44a3d05b6515a59651e6bed8b6dde689aec", "commit_message": "mtab: handle ENOSPC/EFBIG condition properly when altering mtab\n\nIt's possible that when mount.cifs goes to append the mtab that there\nwon't be enough space to do so, and the mntent won't be appended to the\nfile in its entirety.\n\nAdd a my_endmntent routine that will fflush and then fsync the FILE if\nthat succeeds. If either fails then it will truncate the file back to\nits provided size. It will then call endmntent unconditionally.\n\nHave add_mtab call fstat on the opened mtab file in order to get the\nsize of the file before it has been appended. Assuming that that\nsucceeds, use my_endmntent to ensure that the file is not corrupted\nbefore closing it. It's possible that we'll have a small race window\nwhere the mtab is incorrect, but it should be quickly corrected.\n\nThis was reported some time ago as CVE-2011-1678:\n\n    http://openwall.com/lists/oss-security/2011/03/04/9\n\n...and it seems to fix the reproducer that I was able to come up with.\n\nSigned-off-by: Jeff Layton \nReviewed-by: Suresh Jayaraman ", "target": 0, "func": "add_mtab(char *devname, char *mountpoint, unsigned long flags, const char *fstype)\n{\n\tint rc = 0, tmprc, fd;\n\tuid_t uid;\n\tchar *mount_user = NULL;\n\tstruct mntent mountent;\n\tstruct stat statbuf;\n\tFILE *pmntfile;\n\tsigset_t mask, oldmask;\n\n\tuid = getuid();\n\tif (uid != 0)\n\t\tmount_user = getusername(uid);\n\n\t/*\n\t * Set the real uid to the effective uid. This prevents unprivileged\n\t * users from sending signals to this process, though ^c on controlling\n\t * terminal should still work.\n\t */\n\trc = setreuid(geteuid(), -1);\n\tif (rc != 0) {\n\t\tfprintf(stderr, \"Unable to set real uid to effective uid: %s\\n\",\n\t\t\t\tstrerror(errno));\n\t\treturn EX_FILEIO;\n\t}\n\n\trc = sigfillset(&mask);\n\tif (rc) {\n\t\tfprintf(stderr, \"Unable to set filled signal mask\\n\");\n\t\treturn EX_FILEIO;\n\t}\n\n\trc = sigprocmask(SIG_SETMASK, &mask, &oldmask);\n\tif (rc) {\n\t\tfprintf(stderr, \"Unable to make process ignore signals\\n\");\n\t\treturn EX_FILEIO;\n\t}\n\n\trc = toggle_dac_capability(1, 1);\n\tif (rc)\n\t\treturn EX_FILEIO;\n\n\tatexit(unlock_mtab);\n\trc = lock_mtab();\n\tif (rc) {\n\t\tfprintf(stderr, \"cannot lock mtab\");\n\t\trc = EX_FILEIO;\n\t\tgoto add_mtab_exit;\n\t}\n\n\tpmntfile = setmntent(MOUNTED, \"a+\");\n\tif (!pmntfile) {\n\t\tfprintf(stderr, \"could not update mount table\\n\");\n\t\tunlock_mtab();\n\t\trc = EX_FILEIO;\n\t\tgoto add_mtab_exit;\n\t}\n\n\tfd = fileno(pmntfile);\n\tif (fd < 0) {\n\t\tfprintf(stderr, \"mntent does not appear to be valid\\n\");\n\t\tunlock_mtab();\n\t\trc = EX_FILEIO;\n\t\tgoto add_mtab_exit;\n\t}\n\n\trc = fstat(fd, &statbuf);\n\tif (rc != 0) {\n\t\tfprintf(stderr, \"unable to fstat open mtab\\n\");\n\t\tendmntent(pmntfile);\n\t\tunlock_mtab();\n\t\trc = EX_FILEIO;\n\t\tgoto add_mtab_exit;\n\t}\n\n\tmountent.mnt_fsname = devname;\n\tmountent.mnt_dir = mountpoint;\n\tmountent.mnt_type = (char *)(void *)fstype;\n\tmountent.mnt_opts = (char *)calloc(MTAB_OPTIONS_LEN, 1);\n\tif (mountent.mnt_opts) {\n\t\tif (flags & MS_RDONLY)\n\t\t\tstrlcat(mountent.mnt_opts, \"ro\", MTAB_OPTIONS_LEN);\n\t\telse\n\t\t\tstrlcat(mountent.mnt_opts, \"rw\", MTAB_OPTIONS_LEN);\n\n\t\tif (flags & MS_MANDLOCK)\n\t\t\tstrlcat(mountent.mnt_opts, \",mand\", MTAB_OPTIONS_LEN);\n\t\tif (flags & MS_NOEXEC)\n\t\t\tstrlcat(mountent.mnt_opts, \",noexec\", MTAB_OPTIONS_LEN);\n\t\tif (flags & MS_NOSUID)\n\t\t\tstrlcat(mountent.mnt_opts, \",nosuid\", MTAB_OPTIONS_LEN);\n\t\tif (flags & MS_NODEV)\n\t\t\tstrlcat(mountent.mnt_opts, \",nodev\", MTAB_OPTIONS_LEN);\n\t\tif (flags & MS_SYNCHRONOUS)\n\t\t\tstrlcat(mountent.mnt_opts, \",sync\", MTAB_OPTIONS_LEN);\n\t\tif (mount_user) {\n\t\t\tstrlcat(mountent.mnt_opts, \",user=\", MTAB_OPTIONS_LEN);\n\t\t\tstrlcat(mountent.mnt_opts, mount_user,\n\t\t\t\tMTAB_OPTIONS_LEN);\n\t\t}\n\t}\n\tmountent.mnt_freq = 0;\n\tmountent.mnt_passno = 0;\n\trc = addmntent(pmntfile, &mountent);\n\tif (rc) {\n\t\tfprintf(stderr, \"unable to add mount entry to mtab\\n\");\n\t\tftruncate(fd, statbuf.st_size);\n\t\trc = EX_FILEIO;\n\t}\n\ttmprc = my_endmntent(pmntfile, statbuf.st_size);\n\tif (tmprc) {\n\t\tfprintf(stderr, \"error %d detected on close of mtab\\n\", tmprc);\n\t\trc = EX_FILEIO;\n\t}\n\tunlock_mtab();\n\tSAFE_FREE(mountent.mnt_opts);\nadd_mtab_exit:\n\ttoggle_dac_capability(1, 0);\n\tsigprocmask(SIG_SETMASK, &oldmask, NULL);\n\n\treturn rc;\n}", "func_hash": 145620494366436562739751095487223645254, "file_name": "mount.cifs.c", "file_hash": 77793306769877718806811810196619780209, "cwe": ["CWE-20"], "cve": "CVE-2011-1678", "cve_desc": "smbfs in Samba 3.5.8 and earlier attempts to use (1) mount.cifs to append to the /etc/mtab file and (2) umount.cifs to append to the /etc/mtab.tmp file without first checking whether resource limits would interfere, which allows local users to trigger corruption of the /etc/mtab file via a process with a small RLIMIT_FSIZE value, a related issue to CVE-2011-1089.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2011-1678"}
{"idx": 211102, "project": "file-roller", "commit_id": "b147281293a8307808475e102a14857055f81631", "project_url": "https://git.gnome.org/browse/file-roller", "commit_url": "https://git.gnome.org/browse/file-roller/commit/?id=b147281293a8307808475e102a14857055f81631", "commit_message": "libarchive: sanitize filenames before extracting", "target": 1, "func": "extract_archive_thread (GSimpleAsyncResult *result,\n\t\t\tGObject            *object,\n\t\t\tGCancellable       *cancellable)\n{\n\tExtractData          *extract_data;\n\tLoadData             *load_data;\n\tGHashTable           *checked_folders;\n\tstruct archive       *a;\n\tstruct archive_entry *entry;\n\tint                   r;\n\n\textract_data = g_simple_async_result_get_op_res_gpointer (result);\n\tload_data = LOAD_DATA (extract_data);\n\n\tchecked_folders = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);\n\tfr_archive_progress_set_total_files (load_data->archive, extract_data->n_files_to_extract);\n\n\ta = archive_read_new ();\n\tarchive_read_support_filter_all (a);\n\tarchive_read_support_format_all (a);\n\tarchive_read_open (a, load_data, load_data_open, load_data_read, load_data_close);\n\twhile ((r = archive_read_next_header (a, &entry)) == ARCHIVE_OK) {\n\t\tconst char    *pathname;\n\t\tchar          *fullpath;\n\t\tGFile         *file;\n\t\tGFile         *parent;\n\t\tGOutputStream *ostream;\n\t\tconst void    *buffer;\n\t\tsize_t         buffer_size;\n\t\tint64_t        offset;\n\t\tGError        *local_error = NULL;\n\t\t__LA_MODE_T    filetype;\n\n\t\tif (g_cancellable_is_cancelled (cancellable))\n\t\t\tbreak;\n\n\t\tpathname = archive_entry_pathname (entry);\n\t\tif (! extract_data_get_extraction_requested (extract_data, pathname)) {\n\t\t\tarchive_read_data_skip (a);\n\t\t\tcontinue;\n\t\t}\n\n\t\tfullpath = (*pathname == '/') ? g_strdup (pathname) : g_strconcat (\"/\", pathname, NULL);\n\t\tfile = g_file_get_child (extract_data->destination, _g_path_get_relative_basename (fullpath, extract_data->base_dir, extract_data->junk_paths));\n\n\t\t/* honor the skip_older and overwrite options */\n\n\t\tif (extract_data->skip_older || ! extract_data->overwrite) {\n\t\t\tGFileInfo *info;\n\n\t\t\tinfo = g_file_query_info (file,\n\t\t\t\t\t\t  G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME \",\" G_FILE_ATTRIBUTE_TIME_MODIFIED,\n\t\t\t\t\t\t  G_FILE_QUERY_INFO_NONE,\n\t\t\t\t\t\t  cancellable,\n\t\t\t\t\t\t  &local_error);\n\t\t\tif (info != NULL) {\n\t\t\t\tgboolean skip = FALSE;\n\n\t\t\t\tif (! extract_data->overwrite) {\n\t\t\t\t\tskip = TRUE;\n\t\t\t\t}\n\t\t\t\telse if (extract_data->skip_older) {\n\t\t\t\t\tGTimeVal modification_time;\n\n\t\t\t\t\tg_file_info_get_modification_time (info, &modification_time);\n\t\t\t\t\tif (archive_entry_mtime (entry) < modification_time.tv_sec)\n\t\t\t\t\t\tskip = TRUE;\n\t\t\t\t}\n\n\t\t\t\tg_object_unref (info);\n\n\t\t\t\tif (skip) {\n\t\t\t\t\tg_object_unref (file);\n\n\t\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\t\tfr_archive_progress_inc_completed_bytes (load_data->archive, archive_entry_size_is_set (entry) ? archive_entry_size (entry) : 0);\n\n\t\t\t\t\tif ((extract_data->file_list != NULL) && (--extract_data->n_files_to_extract == 0)) {\n\t\t\t\t\t\tr = ARCHIVE_EOF;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {\n\t\t\t\t\tload_data->error = local_error;\n\t\t\t\t\tg_object_unref (info);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tg_error_free (local_error);\n\t\t\t}\n\t\t}\n\n\t\tfr_archive_progress_inc_completed_files (load_data->archive, 1);\n\n\t\t/* create the file parents */\n\n\t\tparent = g_file_get_parent (file);\n\n\t\tif ((parent != NULL)\n\t\t    && (g_hash_table_lookup (checked_folders, parent) == NULL)\n\t\t    && ! g_file_query_exists (parent, cancellable))\n\t\t{\n\t\t\tif (g_file_make_directory_with_parents (parent, cancellable, &load_data->error)) {\n\t\t\t\tGFile *grandparent;\n\n\t\t\t\tgrandparent = g_object_ref (parent);\n\t\t\t\twhile (grandparent != NULL) {\n\t\t\t\t\tif (g_hash_table_lookup (checked_folders, grandparent) == NULL)\n\t\t\t\t\t\tg_hash_table_insert (checked_folders, grandparent, GINT_TO_POINTER (1));\n\t\t\t\t\tgrandparent = g_file_get_parent (grandparent);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tg_object_unref (parent);\n\n\t\t/* create the file */\n\n\t\tfiletype = archive_entry_filetype (entry);\n\n\t\tif (load_data->error == NULL) {\n\t\t\tconst char  *linkname;\n\n\t\t\tlinkname = archive_entry_hardlink (entry);\n\t\t\tif (linkname != NULL) {\n\t\t\t\tchar  *link_fullpath;\n\t\t\t\tGFile *link_file;\n\t\t\t\tchar  *oldname;\n\t\t\t\tchar  *newname;\n\t\t\t\tint    r;\n\n\t\t\t\tlink_fullpath = (*linkname == '/') ? g_strdup (linkname) : g_strconcat (\"/\", linkname, NULL);\n\t\t\t\tlink_file = g_file_get_child (extract_data->destination, _g_path_get_relative_basename (link_fullpath, extract_data->base_dir, extract_data->junk_paths));\n\t\t\t\toldname = g_file_get_path (link_file);\n\t\t\t\tnewname = g_file_get_path (file);\n\n\t\t\t\tif ((oldname != NULL) && (newname != NULL))\n\t\t\t\t\tr = link (oldname, newname);\n\t\t\t\telse\n\t\t\t\t\tr = -1;\n\n\t\t\t\tif (r == 0) {\n\t\t\t\t\t__LA_INT64_T filesize;\n\n\t\t\t\t\tif (archive_entry_size_is_set (entry))\n\t\t\t\t\t\tfilesize = archive_entry_size (entry);\n\t\t\t\t\telse\n\t\t\t\t\t\tfilesize = -1;\n\n\t\t\t\t\tif (filesize > 0)\n\t\t\t\t\t\tfiletype = AE_IFREG; /* treat as a regular file to save the data */\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tchar *uri;\n\t\t\t\t\tchar *msg;\n\n\t\t\t\t\turi = g_file_get_uri (file);\n\t\t\t\t\tmsg = g_strdup_printf (\"Could not create the hard link %s\", uri);\n\t\t\t\t\tload_data->error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, msg);\n\n\t\t\t\t\tg_free (msg);\n\t\t\t\t\tg_free (uri);\n\t\t\t\t}\n\n\t\t\t\tg_free (newname);\n\t\t\t\tg_free (oldname);\n\t\t\t\tg_object_unref (link_file);\n\t\t\t\tg_free (link_fullpath);\n\t\t\t}\n\t\t}\n\n\t\tif (load_data->error == NULL) {\n\t\t\tswitch (filetype) {\n\t\t\tcase AE_IFDIR:\n\t\t\t\tif (! g_file_make_directory (file, cancellable, &local_error)) {\n\t\t\t\t\tif (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS))\n\t\t\t\t\t\tload_data->error = g_error_copy (local_error);\n\t\t\t\t\tg_error_free (local_error);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t_g_file_set_attributes_from_entry (file, entry, extract_data, cancellable);\n\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\tbreak;\n\n\t\t\tcase AE_IFREG:\n\t\t\t\tostream = (GOutputStream *) g_file_replace (file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, cancellable, &load_data->error);\n\t\t\t\tif (ostream == NULL)\n\t\t\t\t\tbreak;\n\n\t\t\t\twhile ((r = archive_read_data_block (a, &buffer, &buffer_size, &offset)) == ARCHIVE_OK) {\n\t\t\t\t\tif (g_output_stream_write (ostream, buffer, buffer_size, cancellable, &load_data->error) == -1)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tfr_archive_progress_inc_completed_bytes (load_data->archive, buffer_size);\n\t\t\t\t}\n\t\t\t\t_g_object_unref (ostream);\n\n\t\t\t\tif (r != ARCHIVE_EOF)\n\t\t\t\t\tload_data->error = g_error_new_literal (FR_ERROR, FR_ERROR_COMMAND_ERROR, archive_error_string (a));\n\t\t\t\telse\n\t\t\t\t\t_g_file_set_attributes_from_entry (file, entry, extract_data, cancellable);\n\t\t\t\tbreak;\n\n\t\t\tcase AE_IFLNK:\n\t\t\t\tif (! g_file_make_symbolic_link (file, archive_entry_symlink (entry), cancellable, &local_error)) {\n\t\t\t\t\tif (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS))\n\t\t\t\t\t\tload_data->error = g_error_copy (local_error);\n\t\t\t\t\tg_error_free (local_error);\n\t\t\t\t}\n\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tg_object_unref (file);\n\t\tg_free (fullpath);\n\n\t\tif (load_data->error != NULL)\n\t\t\tbreak;\n\n\t\tif ((extract_data->file_list != NULL) && (--extract_data->n_files_to_extract == 0)) {\n\t\t\tr = ARCHIVE_EOF;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif ((load_data->error == NULL) && (r != ARCHIVE_EOF))\n\t\tload_data->error = g_error_new_literal (FR_ERROR, FR_ERROR_COMMAND_ERROR, archive_error_string (a));\n\tif (load_data->error == NULL)\n\t\tg_cancellable_set_error_if_cancelled (cancellable, &load_data->error);\n\tif (load_data->error != NULL)\n\t\tg_simple_async_result_set_from_error (result, load_data->error);\n\n\tg_hash_table_unref (checked_folders);\n\tarchive_read_free (a);\n\textract_data_free (extract_data);\n}", "func_hash": 300010717892074286523463178152343343072, "file_name": "None", "file_hash": null, "cwe": ["CWE-22"], "cve": "CVE-2013-4668", "cve_desc": "Directory traversal vulnerability in File Roller 3.6.x before 3.6.4, 3.8.x before 3.8.3, and 3.9.x before 3.9.3, when libarchive is used, allows remote attackers to create arbitrary files via a crafted archive that is not properly handled in a \"Keep directory structure\" action, related to fr-archive-libarchive.c and fr-window.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-4668"}
{"idx": 445995, "project": "file-roller", "commit_id": "b147281293a8307808475e102a14857055f81631", "project_url": "https://git.gnome.org/browse/file-roller", "commit_url": "https://git.gnome.org/browse/file-roller/commit/?id=b147281293a8307808475e102a14857055f81631", "commit_message": "libarchive: sanitize filenames before extracting", "target": 0, "func": "extract_archive_thread (GSimpleAsyncResult *result,\n\t\t\tGObject            *object,\n\t\t\tGCancellable       *cancellable)\n{\n\tExtractData          *extract_data;\n\tLoadData             *load_data;\n\tGHashTable           *checked_folders;\n\tstruct archive       *a;\n\tstruct archive_entry *entry;\n\tint                   r;\n\n\textract_data = g_simple_async_result_get_op_res_gpointer (result);\n\tload_data = LOAD_DATA (extract_data);\n\n\tchecked_folders = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);\n\tfr_archive_progress_set_total_files (load_data->archive, extract_data->n_files_to_extract);\n\n\ta = archive_read_new ();\n\tarchive_read_support_filter_all (a);\n\tarchive_read_support_format_all (a);\n\tarchive_read_open (a, load_data, load_data_open, load_data_read, load_data_close);\n\twhile ((r = archive_read_next_header (a, &entry)) == ARCHIVE_OK) {\n\t\tconst char    *pathname;\n\t\tchar          *fullpath;\n\t\tconst char    *relative_path;\n\t\tGFile         *file;\n\t\tGFile         *parent;\n\t\tGOutputStream *ostream;\n\t\tconst void    *buffer;\n\t\tsize_t         buffer_size;\n\t\tint64_t        offset;\n\t\tGError        *local_error = NULL;\n\t\t__LA_MODE_T    filetype;\n\n\t\tif (g_cancellable_is_cancelled (cancellable))\n\t\t\tbreak;\n\n\t\tpathname = archive_entry_pathname (entry);\n\t\tif (! extract_data_get_extraction_requested (extract_data, pathname)) {\n\t\t\tarchive_read_data_skip (a);\n\t\t\tcontinue;\n\t\t}\n\n\t\tfullpath = (*pathname == '/') ? g_strdup (pathname) : g_strconcat (\"/\", pathname, NULL);\n\t\trelative_path = _g_path_get_relative_basename_safe (fullpath, extract_data->base_dir, extract_data->junk_paths);\n\t\tif (relative_path == NULL) {\n\t\t\tarchive_read_data_skip (a);\n\t\t\tcontinue;\n\t\t}\n\t\tfile = g_file_get_child (extract_data->destination, relative_path);\n\n\t\t/* honor the skip_older and overwrite options */\n\n\t\tif (extract_data->skip_older || ! extract_data->overwrite) {\n\t\t\tGFileInfo *info;\n\n\t\t\tinfo = g_file_query_info (file,\n\t\t\t\t\t\t  G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME \",\" G_FILE_ATTRIBUTE_TIME_MODIFIED,\n\t\t\t\t\t\t  G_FILE_QUERY_INFO_NONE,\n\t\t\t\t\t\t  cancellable,\n\t\t\t\t\t\t  &local_error);\n\t\t\tif (info != NULL) {\n\t\t\t\tgboolean skip = FALSE;\n\n\t\t\t\tif (! extract_data->overwrite) {\n\t\t\t\t\tskip = TRUE;\n\t\t\t\t}\n\t\t\t\telse if (extract_data->skip_older) {\n\t\t\t\t\tGTimeVal modification_time;\n\n\t\t\t\t\tg_file_info_get_modification_time (info, &modification_time);\n\t\t\t\t\tif (archive_entry_mtime (entry) < modification_time.tv_sec)\n\t\t\t\t\t\tskip = TRUE;\n\t\t\t\t}\n\n\t\t\t\tg_object_unref (info);\n\n\t\t\t\tif (skip) {\n\t\t\t\t\tg_object_unref (file);\n\n\t\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\t\tfr_archive_progress_inc_completed_bytes (load_data->archive, archive_entry_size_is_set (entry) ? archive_entry_size (entry) : 0);\n\n\t\t\t\t\tif ((extract_data->file_list != NULL) && (--extract_data->n_files_to_extract == 0)) {\n\t\t\t\t\t\tr = ARCHIVE_EOF;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {\n\t\t\t\t\tload_data->error = local_error;\n\t\t\t\t\tg_object_unref (info);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tg_error_free (local_error);\n\t\t\t}\n\t\t}\n\n\t\tfr_archive_progress_inc_completed_files (load_data->archive, 1);\n\n\t\t/* create the file parents */\n\n\t\tparent = g_file_get_parent (file);\n\n\t\tif ((parent != NULL)\n\t\t    && (g_hash_table_lookup (checked_folders, parent) == NULL)\n\t\t    && ! g_file_query_exists (parent, cancellable))\n\t\t{\n\t\t\tif (g_file_make_directory_with_parents (parent, cancellable, &load_data->error)) {\n\t\t\t\tGFile *grandparent;\n\n\t\t\t\tgrandparent = g_object_ref (parent);\n\t\t\t\twhile (grandparent != NULL) {\n\t\t\t\t\tif (g_hash_table_lookup (checked_folders, grandparent) == NULL)\n\t\t\t\t\t\tg_hash_table_insert (checked_folders, grandparent, GINT_TO_POINTER (1));\n\t\t\t\t\tgrandparent = g_file_get_parent (grandparent);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tg_object_unref (parent);\n\n\t\t/* create the file */\n\n\t\tfiletype = archive_entry_filetype (entry);\n\n\t\tif (load_data->error == NULL) {\n\t\t\tconst char  *linkname;\n\n\t\t\tlinkname = archive_entry_hardlink (entry);\n\t\t\tif (linkname != NULL) {\n\t\t\t\tchar        *link_fullpath;\n\t\t\t\tconst char  *relative_path;\n\t\t\t\tGFile       *link_file;\n\t\t\t\tchar        *oldname;\n\t\t\t\tchar        *newname;\n\t\t\t\tint          r;\n\n\t\t\t\tlink_fullpath = (*linkname == '/') ? g_strdup (linkname) : g_strconcat (\"/\", linkname, NULL);\n\t\t\t\trelative_path = _g_path_get_relative_basename_safe (link_fullpath, extract_data->base_dir, extract_data->junk_paths);\n\t\t\t\tif (relative_path == NULL) {\n\t\t\t\t\tg_free (link_fullpath);\n\t\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tlink_file = g_file_get_child (extract_data->destination, relative_path);\n\t\t\t\toldname = g_file_get_path (link_file);\n\t\t\t\tnewname = g_file_get_path (file);\n\n\t\t\t\tif ((oldname != NULL) && (newname != NULL))\n\t\t\t\t\tr = link (oldname, newname);\n\t\t\t\telse\n\t\t\t\t\tr = -1;\n\n\t\t\t\tif (r == 0) {\n\t\t\t\t\t__LA_INT64_T filesize;\n\n\t\t\t\t\tif (archive_entry_size_is_set (entry))\n\t\t\t\t\t\tfilesize = archive_entry_size (entry);\n\t\t\t\t\telse\n\t\t\t\t\t\tfilesize = -1;\n\n\t\t\t\t\tif (filesize > 0)\n\t\t\t\t\t\tfiletype = AE_IFREG; /* treat as a regular file to save the data */\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tchar *uri;\n\t\t\t\t\tchar *msg;\n\n\t\t\t\t\turi = g_file_get_uri (file);\n\t\t\t\t\tmsg = g_strdup_printf (\"Could not create the hard link %s\", uri);\n\t\t\t\t\tload_data->error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, msg);\n\n\t\t\t\t\tg_free (msg);\n\t\t\t\t\tg_free (uri);\n\t\t\t\t}\n\n\t\t\t\tg_free (newname);\n\t\t\t\tg_free (oldname);\n\t\t\t\tg_object_unref (link_file);\n\t\t\t\tg_free (link_fullpath);\n\t\t\t}\n\t\t}\n\n\t\tif (load_data->error == NULL) {\n\t\t\tswitch (filetype) {\n\t\t\tcase AE_IFDIR:\n\t\t\t\tif (! g_file_make_directory (file, cancellable, &local_error)) {\n\t\t\t\t\tif (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS))\n\t\t\t\t\t\tload_data->error = g_error_copy (local_error);\n\t\t\t\t\tg_error_free (local_error);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t_g_file_set_attributes_from_entry (file, entry, extract_data, cancellable);\n\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\tbreak;\n\n\t\t\tcase AE_IFREG:\n\t\t\t\tostream = (GOutputStream *) g_file_replace (file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, cancellable, &load_data->error);\n\t\t\t\tif (ostream == NULL)\n\t\t\t\t\tbreak;\n\n\t\t\t\twhile ((r = archive_read_data_block (a, &buffer, &buffer_size, &offset)) == ARCHIVE_OK) {\n\t\t\t\t\tif (g_output_stream_write (ostream, buffer, buffer_size, cancellable, &load_data->error) == -1)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tfr_archive_progress_inc_completed_bytes (load_data->archive, buffer_size);\n\t\t\t\t}\n\t\t\t\t_g_object_unref (ostream);\n\n\t\t\t\tif (r != ARCHIVE_EOF)\n\t\t\t\t\tload_data->error = g_error_new_literal (FR_ERROR, FR_ERROR_COMMAND_ERROR, archive_error_string (a));\n\t\t\t\telse\n\t\t\t\t\t_g_file_set_attributes_from_entry (file, entry, extract_data, cancellable);\n\t\t\t\tbreak;\n\n\t\t\tcase AE_IFLNK:\n\t\t\t\tif (! g_file_make_symbolic_link (file, archive_entry_symlink (entry), cancellable, &local_error)) {\n\t\t\t\t\tif (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS))\n\t\t\t\t\t\tload_data->error = g_error_copy (local_error);\n\t\t\t\t\tg_error_free (local_error);\n\t\t\t\t}\n\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tg_object_unref (file);\n\t\tg_free (fullpath);\n\n\t\tif (load_data->error != NULL)\n\t\t\tbreak;\n\n\t\tif ((extract_data->file_list != NULL) && (--extract_data->n_files_to_extract == 0)) {\n\t\t\tr = ARCHIVE_EOF;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif ((load_data->error == NULL) && (r != ARCHIVE_EOF))\n\t\tload_data->error = g_error_new_literal (FR_ERROR, FR_ERROR_COMMAND_ERROR, archive_error_string (a));\n\tif (load_data->error == NULL)\n\t\tg_cancellable_set_error_if_cancelled (cancellable, &load_data->error);\n\tif (load_data->error != NULL)\n\t\tg_simple_async_result_set_from_error (result, load_data->error);\n\n\tg_hash_table_unref (checked_folders);\n\tarchive_read_free (a);\n\textract_data_free (extract_data);\n}", "func_hash": 20085283241969979121864060999173899777, "file_name": "None", "file_hash": null, "cwe": ["CWE-22"], "cve": "CVE-2013-4668", "cve_desc": "Directory traversal vulnerability in File Roller 3.6.x before 3.6.4, 3.8.x before 3.8.3, and 3.9.x before 3.9.3, when libarchive is used, allows remote attackers to create arbitrary files via a crafted archive that is not properly handled in a \"Keep directory structure\" action, related to fr-archive-libarchive.c and fr-window.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-4668"}
{"idx": 211103, "project": "file-roller", "commit_id": "b147281293a8307808475e102a14857055f81631", "project_url": "https://git.gnome.org/browse/file-roller", "commit_url": "https://git.gnome.org/browse/file-roller/commit/?id=b147281293a8307808475e102a14857055f81631", "commit_message": "libarchive: sanitize filenames before extracting", "target": 1, "func": "_fr_window_ask_overwrite_dialog (OverwriteData *odata)\n{\n\tif ((odata->edata->overwrite == FR_OVERWRITE_ASK) && (odata->current_file != NULL)) {\n\t\tconst char *base_name;\n\t\tGFile      *destination;\n\n\t\tbase_name = _g_path_get_relative_basename ((char *) odata->current_file->data, odata->edata->base_dir, odata->edata->junk_paths);\n\t\tdestination = g_file_get_child (odata->edata->destination, base_name);\n\t\tg_file_query_info_async (destination,\n\t\t\t\t\t G_FILE_ATTRIBUTE_STANDARD_TYPE \",\" G_FILE_ATTRIBUTE_STANDARD_NAME \",\" G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,\n\t\t\t\t\t G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,\n\t\t\t\t\t G_PRIORITY_DEFAULT,\n\t\t\t\t\t odata->window->priv->cancellable,\n\t\t\t\t\t query_info_ready_for_overwrite_dialog_cb,\n\t\t\t\t\t odata);\n\n\t\tg_object_unref (destination);\n\n\t\treturn;\n\t}\n\n\tif (odata->edata->file_list != NULL) {\n\t\t/* speed optimization: passing NULL when extracting all the\n\t\t * files is faster if the command supports the\n\t\t * propCanExtractAll property. */\n\t\tif (odata->extract_all) {\n\t\t\t_g_string_list_free (odata->edata->file_list);\n\t\t\todata->edata->file_list = NULL;\n\t\t}\n\t\todata->edata->overwrite = FR_OVERWRITE_YES;\n\t\t_fr_window_archive_extract_from_edata (odata->window, odata->edata);\n\t}\n\telse {\n\t\tGtkWidget *d;\n\n\t\td = _gtk_message_dialog_new (GTK_WINDOW (odata->window),\n\t\t\t\t\t     0,\n\t\t\t\t\t     GTK_STOCK_DIALOG_WARNING,\n\t\t\t\t\t     _(\"Extraction not performed\"),\n\t\t\t\t\t     NULL,\n\t\t\t\t\t     GTK_STOCK_OK, GTK_RESPONSE_OK,\n\t\t\t\t\t     NULL);\n\t\tgtk_dialog_set_default_response (GTK_DIALOG (d), GTK_RESPONSE_OK);\n\t\tfr_window_show_error_dialog (odata->window, d, GTK_WINDOW (odata->window), _(\"Extraction not performed\"));\n\n\t\tfr_window_stop_batch (odata->window);\n\t}\n\n\tg_free (odata);\n}", "func_hash": 43802916187743556830964443535634417382, "file_name": "None", "file_hash": null, "cwe": ["CWE-22"], "cve": "CVE-2013-4668", "cve_desc": "Directory traversal vulnerability in File Roller 3.6.x before 3.6.4, 3.8.x before 3.8.3, and 3.9.x before 3.9.3, when libarchive is used, allows remote attackers to create arbitrary files via a crafted archive that is not properly handled in a \"Keep directory structure\" action, related to fr-archive-libarchive.c and fr-window.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-4668"}
{"idx": 445881, "project": "file-roller", "commit_id": "b147281293a8307808475e102a14857055f81631", "project_url": "https://git.gnome.org/browse/file-roller", "commit_url": "https://git.gnome.org/browse/file-roller/commit/?id=b147281293a8307808475e102a14857055f81631", "commit_message": "libarchive: sanitize filenames before extracting", "target": 0, "func": "_fr_window_ask_overwrite_dialog (OverwriteData *odata)\n{\n\tgboolean perform_extraction = TRUE;\n\n\tif ((odata->edata->overwrite == FR_OVERWRITE_ASK) && (odata->current_file != NULL)) {\n\t\tconst char *base_name;\n\t\tGFile      *destination;\n\n\t\tbase_name = _g_path_get_relative_basename_safe ((char *) odata->current_file->data, odata->edata->base_dir, odata->edata->junk_paths);\n\t\tif (base_name != NULL) {\n\t\t\tdestination = g_file_get_child (odata->edata->destination, base_name);\n\t\t\tg_file_query_info_async (destination,\n\t\t\t\t\t\t G_FILE_ATTRIBUTE_STANDARD_TYPE \",\" G_FILE_ATTRIBUTE_STANDARD_NAME \",\" G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,\n\t\t\t\t\t\t G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,\n\t\t\t\t\t\t G_PRIORITY_DEFAULT,\n\t\t\t\t\t\t odata->window->priv->cancellable,\n\t\t\t\t\t\t query_info_ready_for_overwrite_dialog_cb,\n\t\t\t\t\t\t odata);\n\n\t\t\tg_object_unref (destination);\n\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t\tperform_extraction = FALSE;\n\t}\n\n\tif (odata->edata->file_list == NULL)\n\t\tperform_extraction = FALSE;\n\n\tif (perform_extraction) {\n\t\t/* speed optimization: passing NULL when extracting all the\n\t\t * files is faster if the command supports the\n\t\t * propCanExtractAll property. */\n\t\tif (odata->extract_all) {\n\t\t\t_g_string_list_free (odata->edata->file_list);\n\t\t\todata->edata->file_list = NULL;\n\t\t}\n\t\todata->edata->overwrite = FR_OVERWRITE_YES;\n\t\t_fr_window_archive_extract_from_edata (odata->window, odata->edata);\n\t}\n\telse {\n\t\tGtkWidget *d;\n\n\t\td = _gtk_message_dialog_new (GTK_WINDOW (odata->window),\n\t\t\t\t\t     0,\n\t\t\t\t\t     GTK_STOCK_DIALOG_WARNING,\n\t\t\t\t\t     _(\"Extraction not performed\"),\n\t\t\t\t\t     NULL,\n\t\t\t\t\t     GTK_STOCK_OK, GTK_RESPONSE_OK,\n\t\t\t\t\t     NULL);\n\t\tgtk_dialog_set_default_response (GTK_DIALOG (d), GTK_RESPONSE_OK);\n\t\tfr_window_show_error_dialog (odata->window, d, GTK_WINDOW (odata->window), _(\"Extraction not performed\"));\n\n\t\tfr_window_stop_batch (odata->window);\n\t}\n\n\tg_free (odata);\n}", "func_hash": 277830468251766331393167920010876647951, "file_name": "None", "file_hash": null, "cwe": ["CWE-22"], "cve": "CVE-2013-4668", "cve_desc": "Directory traversal vulnerability in File Roller 3.6.x before 3.6.4, 3.8.x before 3.8.3, and 3.9.x before 3.9.3, when libarchive is used, allows remote attackers to create arbitrary files via a crafted archive that is not properly handled in a \"Keep directory structure\" action, related to fr-archive-libarchive.c and fr-window.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-4668"}
{"idx": 211110, "project": "libtiff", "commit_id": "58a898cb4459055bb488ca815c23b880c242a27d", "project_url": "https://github.com/vadz/libtiff", "commit_url": "https://gitlab.com/libtiff/libtiff/commit/58a898cb4459055bb488ca815c23b880c242a27d", "commit_message": "LZWDecodeCompat(): fix potential index-out-of-bounds write. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2780 / CVE-2018-8905\n\nThe fix consists in using the similar code LZWDecode() to validate we\ndon't write outside of the output buffer.", "target": 1, "func": "LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)\n{\n\tstatic const char module[] = \"LZWDecodeCompat\";\n\tLZWCodecState *sp = DecoderState(tif);\n\tchar *op = (char*) op0;\n\tlong occ = (long) occ0;\n\tchar *tp;\n\tunsigned char *bp;\n\tint code, nbits;\n\tlong nextbits, nextdata, nbitsmask;\n\tcode_t *codep, *free_entp, *maxcodep, *oldcodep;\n\n\t(void) s;\n\tassert(sp != NULL);\n\n\t/*\n\t  Fail if value does not fit in long.\n\t*/\n\tif ((tmsize_t) occ != occ0)\n\t        return (0);\n\n\t/*\n\t * Restart interrupted output operation.\n\t */\n\tif (sp->dec_restart) {\n\t\tlong residue;\n\n\t\tcodep = sp->dec_codep;\n\t\tresidue = codep->length - sp->dec_restart;\n\t\tif (residue > occ) {\n\t\t\t/*\n\t\t\t * Residue from previous decode is sufficient\n\t\t\t * to satisfy decode request.  Skip to the\n\t\t\t * start of the decoded string, place decoded\n\t\t\t * values in the output buffer, and return.\n\t\t\t */\n\t\t\tsp->dec_restart += occ;\n\t\t\tdo {\n\t\t\t\tcodep = codep->next;\n\t\t\t} while (--residue > occ);\n\t\t\ttp = op + occ;\n\t\t\tdo {\n\t\t\t\t*--tp = codep->value;\n\t\t\t\tcodep = codep->next;\n\t\t\t} while (--occ);\n\t\t\treturn (1);\n\t\t}\n\t\t/*\n\t\t * Residue satisfies only part of the decode request.\n\t\t */\n\t\top += residue;\n\t\tocc -= residue;\n\t\ttp = op;\n\t\tdo {\n\t\t\t*--tp = codep->value;\n\t\t\tcodep = codep->next;\n\t\t} while (--residue);\n\t\tsp->dec_restart = 0;\n\t}\n\n\tbp = (unsigned char *)tif->tif_rawcp;\n#ifdef LZW_CHECKEOS\n\tsp->dec_bitsleft = (((uint64)tif->tif_rawcc) << 3);\n#endif\n\tnbits = sp->lzw_nbits;\n\tnextdata = sp->lzw_nextdata;\n\tnextbits = sp->lzw_nextbits;\n\tnbitsmask = sp->dec_nbitsmask;\n\toldcodep = sp->dec_oldcodep;\n\tfree_entp = sp->dec_free_entp;\n\tmaxcodep = sp->dec_maxcodep;\n\n\twhile (occ > 0) {\n\t\tNextCode(tif, sp, bp, code, GetNextCodeCompat);\n\t\tif (code == CODE_EOI)\n\t\t\tbreak;\n\t\tif (code == CODE_CLEAR) {\n\t\t\tdo {\n\t\t\t\tfree_entp = sp->dec_codetab + CODE_FIRST;\n\t\t\t\t_TIFFmemset(free_entp, 0,\n\t\t\t\t\t    (CSIZE - CODE_FIRST) * sizeof (code_t));\n\t\t\t\tnbits = BITS_MIN;\n\t\t\t\tnbitsmask = MAXCODE(BITS_MIN);\n\t\t\t\tmaxcodep = sp->dec_codetab + nbitsmask;\n\t\t\t\tNextCode(tif, sp, bp, code, GetNextCodeCompat);\n\t\t\t} while (code == CODE_CLEAR);\t/* consecutive CODE_CLEAR codes */\n\t\t\tif (code == CODE_EOI)\n\t\t\t\tbreak;\n\t\t\tif (code > CODE_CLEAR) {\n\t\t\t\tTIFFErrorExt(tif->tif_clientdata, tif->tif_name,\n\t\t\t\t\"LZWDecode: Corrupted LZW table at scanline %d\",\n\t\t\t\t\t     tif->tif_row);\n\t\t\t\treturn (0);\n\t\t\t}\n\t\t\t*op++ = (char)code;\n\t\t\tocc--;\n\t\t\toldcodep = sp->dec_codetab + code;\n\t\t\tcontinue;\n\t\t}\n\t\tcodep = sp->dec_codetab + code;\n\n\t\t/*\n\t\t * Add the new entry to the code table.\n\t\t */\n\t\tif (free_entp < &sp->dec_codetab[0] ||\n\t\t    free_entp >= &sp->dec_codetab[CSIZE]) {\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t    \"Corrupted LZW table at scanline %d\", tif->tif_row);\n\t\t\treturn (0);\n\t\t}\n\n\t\tfree_entp->next = oldcodep;\n\t\tif (free_entp->next < &sp->dec_codetab[0] ||\n\t\t    free_entp->next >= &sp->dec_codetab[CSIZE]) {\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t    \"Corrupted LZW table at scanline %d\", tif->tif_row);\n\t\t\treturn (0);\n\t\t}\n\t\tfree_entp->firstchar = free_entp->next->firstchar;\n\t\tfree_entp->length = free_entp->next->length+1;\n\t\tfree_entp->value = (codep < free_entp) ?\n\t\t    codep->firstchar : free_entp->firstchar;\n\t\tif (++free_entp > maxcodep) {\n\t\t\tif (++nbits > BITS_MAX)\t\t/* should not happen */\n\t\t\t\tnbits = BITS_MAX;\n\t\t\tnbitsmask = MAXCODE(nbits);\n\t\t\tmaxcodep = sp->dec_codetab + nbitsmask;\n\t\t}\n\t\toldcodep = codep;\n\t\tif (code >= 256) {\n\t\t\t/*\n\t\t\t * Code maps to a string, copy string\n\t\t\t * value to output (written in reverse).\n\t\t\t */\n\t\t\tif(codep->length == 0) {\n\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t\t    \"Wrong length of decoded \"\n\t\t\t\t    \"string: data probably corrupted at scanline %d\",\n\t\t\t\t    tif->tif_row);\n\t\t\t\treturn (0);\n\t\t\t}\n\t\t\tif (codep->length > occ) {\n\t\t\t\t/*\n\t\t\t\t * String is too long for decode buffer,\n\t\t\t\t * locate portion that will fit, copy to\n\t\t\t\t * the decode buffer, and setup restart\n\t\t\t\t * logic for the next decoding call.\n\t\t\t\t */\n\t\t\t\tsp->dec_codep = codep;\n\t\t\t\tdo {\n\t\t\t\t\tcodep = codep->next;\n\t\t\t\t} while (codep->length > occ);\n\t\t\t\tsp->dec_restart = occ;\n\t\t\t\ttp = op + occ;\n\t\t\t\tdo  {\n\t\t\t\t\t*--tp = codep->value;\n\t\t\t\t\tcodep = codep->next;\n\t\t\t\t}  while (--occ);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tassert(occ >= codep->length);\n\t\t\top += codep->length;\n\t\t\tocc -= codep->length;\n\t\t\ttp = op;\n\t\t\tdo {\n\t\t\t\t*--tp = codep->value;\n\t\t\t} while( (codep = codep->next) != NULL );\n\t\t} else {\n\t\t\t*op++ = (char)code;\n\t\t\tocc--;\n\t\t}\n\t}\n\n\ttif->tif_rawcc -= (tmsize_t)( (uint8*) bp - tif->tif_rawcp );\n\ttif->tif_rawcp = (uint8*) bp;\n\tsp->lzw_nbits = (unsigned short)nbits;\n\tsp->lzw_nextdata = nextdata;\n\tsp->lzw_nextbits = nextbits;\n\tsp->dec_nbitsmask = nbitsmask;\n\tsp->dec_oldcodep = oldcodep;\n\tsp->dec_free_entp = free_entp;\n\tsp->dec_maxcodep = maxcodep;\n\n\tif (occ > 0) {\n#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))\n\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t\"Not enough data at scanline %d (short %I64d bytes)\",\n\t\t\t     tif->tif_row, (unsigned __int64) occ);\n#else\n\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t\"Not enough data at scanline %d (short %llu bytes)\",\n\t\t\t     tif->tif_row, (unsigned long long) occ);\n#endif\n\t\treturn (0);\n\t}\n\treturn (1);\n}", "func_hash": 313277325336766260875147349325046634490, "file_name": "tif_lzw.c", "file_hash": 85391227280686087069186499498544690694, "cwe": ["CWE-787"], "cve": "CVE-2018-8905", "cve_desc": "In LibTIFF 4.0.9, a heap-based buffer overflow occurs in the function LZWDecodeCompat in tif_lzw.c via a crafted TIFF file, as demonstrated by tiff2ps.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-8905"}
{"idx": 446058, "project": "libtiff", "commit_id": "58a898cb4459055bb488ca815c23b880c242a27d", "project_url": "https://github.com/vadz/libtiff", "commit_url": "https://gitlab.com/libtiff/libtiff/commit/58a898cb4459055bb488ca815c23b880c242a27d", "commit_message": "LZWDecodeCompat(): fix potential index-out-of-bounds write. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2780 / CVE-2018-8905\n\nThe fix consists in using the similar code LZWDecode() to validate we\ndon't write outside of the output buffer.", "target": 0, "func": "LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)\n{\n\tstatic const char module[] = \"LZWDecodeCompat\";\n\tLZWCodecState *sp = DecoderState(tif);\n\tchar *op = (char*) op0;\n\tlong occ = (long) occ0;\n\tchar *tp;\n\tunsigned char *bp;\n\tint code, nbits;\n\tint len;\n\tlong nextbits, nextdata, nbitsmask;\n\tcode_t *codep, *free_entp, *maxcodep, *oldcodep;\n\n\t(void) s;\n\tassert(sp != NULL);\n\n\t/*\n\t  Fail if value does not fit in long.\n\t*/\n\tif ((tmsize_t) occ != occ0)\n\t        return (0);\n\n\t/*\n\t * Restart interrupted output operation.\n\t */\n\tif (sp->dec_restart) {\n\t\tlong residue;\n\n\t\tcodep = sp->dec_codep;\n\t\tresidue = codep->length - sp->dec_restart;\n\t\tif (residue > occ) {\n\t\t\t/*\n\t\t\t * Residue from previous decode is sufficient\n\t\t\t * to satisfy decode request.  Skip to the\n\t\t\t * start of the decoded string, place decoded\n\t\t\t * values in the output buffer, and return.\n\t\t\t */\n\t\t\tsp->dec_restart += occ;\n\t\t\tdo {\n\t\t\t\tcodep = codep->next;\n\t\t\t} while (--residue > occ);\n\t\t\ttp = op + occ;\n\t\t\tdo {\n\t\t\t\t*--tp = codep->value;\n\t\t\t\tcodep = codep->next;\n\t\t\t} while (--occ);\n\t\t\treturn (1);\n\t\t}\n\t\t/*\n\t\t * Residue satisfies only part of the decode request.\n\t\t */\n\t\top += residue;\n\t\tocc -= residue;\n\t\ttp = op;\n\t\tdo {\n\t\t\t*--tp = codep->value;\n\t\t\tcodep = codep->next;\n\t\t} while (--residue);\n\t\tsp->dec_restart = 0;\n\t}\n\n\tbp = (unsigned char *)tif->tif_rawcp;\n#ifdef LZW_CHECKEOS\n\tsp->dec_bitsleft = (((uint64)tif->tif_rawcc) << 3);\n#endif\n\tnbits = sp->lzw_nbits;\n\tnextdata = sp->lzw_nextdata;\n\tnextbits = sp->lzw_nextbits;\n\tnbitsmask = sp->dec_nbitsmask;\n\toldcodep = sp->dec_oldcodep;\n\tfree_entp = sp->dec_free_entp;\n\tmaxcodep = sp->dec_maxcodep;\n\n\twhile (occ > 0) {\n\t\tNextCode(tif, sp, bp, code, GetNextCodeCompat);\n\t\tif (code == CODE_EOI)\n\t\t\tbreak;\n\t\tif (code == CODE_CLEAR) {\n\t\t\tdo {\n\t\t\t\tfree_entp = sp->dec_codetab + CODE_FIRST;\n\t\t\t\t_TIFFmemset(free_entp, 0,\n\t\t\t\t\t    (CSIZE - CODE_FIRST) * sizeof (code_t));\n\t\t\t\tnbits = BITS_MIN;\n\t\t\t\tnbitsmask = MAXCODE(BITS_MIN);\n\t\t\t\tmaxcodep = sp->dec_codetab + nbitsmask;\n\t\t\t\tNextCode(tif, sp, bp, code, GetNextCodeCompat);\n\t\t\t} while (code == CODE_CLEAR);\t/* consecutive CODE_CLEAR codes */\n\t\t\tif (code == CODE_EOI)\n\t\t\t\tbreak;\n\t\t\tif (code > CODE_CLEAR) {\n\t\t\t\tTIFFErrorExt(tif->tif_clientdata, tif->tif_name,\n\t\t\t\t\"LZWDecode: Corrupted LZW table at scanline %d\",\n\t\t\t\t\t     tif->tif_row);\n\t\t\t\treturn (0);\n\t\t\t}\n\t\t\t*op++ = (char)code;\n\t\t\tocc--;\n\t\t\toldcodep = sp->dec_codetab + code;\n\t\t\tcontinue;\n\t\t}\n\t\tcodep = sp->dec_codetab + code;\n\n\t\t/*\n\t\t * Add the new entry to the code table.\n\t\t */\n\t\tif (free_entp < &sp->dec_codetab[0] ||\n\t\t    free_entp >= &sp->dec_codetab[CSIZE]) {\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t    \"Corrupted LZW table at scanline %d\", tif->tif_row);\n\t\t\treturn (0);\n\t\t}\n\n\t\tfree_entp->next = oldcodep;\n\t\tif (free_entp->next < &sp->dec_codetab[0] ||\n\t\t    free_entp->next >= &sp->dec_codetab[CSIZE]) {\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t    \"Corrupted LZW table at scanline %d\", tif->tif_row);\n\t\t\treturn (0);\n\t\t}\n\t\tfree_entp->firstchar = free_entp->next->firstchar;\n\t\tfree_entp->length = free_entp->next->length+1;\n\t\tfree_entp->value = (codep < free_entp) ?\n\t\t    codep->firstchar : free_entp->firstchar;\n\t\tif (++free_entp > maxcodep) {\n\t\t\tif (++nbits > BITS_MAX)\t\t/* should not happen */\n\t\t\t\tnbits = BITS_MAX;\n\t\t\tnbitsmask = MAXCODE(nbits);\n\t\t\tmaxcodep = sp->dec_codetab + nbitsmask;\n\t\t}\n\t\toldcodep = codep;\n\t\tif (code >= 256) {\n\t\t\t/*\n\t\t\t * Code maps to a string, copy string\n\t\t\t * value to output (written in reverse).\n\t\t\t */\n\t\t\tif(codep->length == 0) {\n\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t\t    \"Wrong length of decoded \"\n\t\t\t\t    \"string: data probably corrupted at scanline %d\",\n\t\t\t\t    tif->tif_row);\n\t\t\t\treturn (0);\n\t\t\t}\n\t\t\tif (codep->length > occ) {\n\t\t\t\t/*\n\t\t\t\t * String is too long for decode buffer,\n\t\t\t\t * locate portion that will fit, copy to\n\t\t\t\t * the decode buffer, and setup restart\n\t\t\t\t * logic for the next decoding call.\n\t\t\t\t */\n\t\t\t\tsp->dec_codep = codep;\n\t\t\t\tdo {\n\t\t\t\t\tcodep = codep->next;\n\t\t\t\t} while (codep->length > occ);\n\t\t\t\tsp->dec_restart = occ;\n\t\t\t\ttp = op + occ;\n\t\t\t\tdo  {\n\t\t\t\t\t*--tp = codep->value;\n\t\t\t\t\tcodep = codep->next;\n\t\t\t\t}  while (--occ);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlen = codep->length;\n\t\t\ttp = op + len;\n\t\t\tdo {\n\t\t\t\tint t;\n\t\t\t\t--tp;\n\t\t\t\tt = codep->value;\n\t\t\t\tcodep = codep->next;\n\t\t\t\t*tp = (char)t;\n\t\t\t} while (codep && tp > op);\n\t\t\tassert(occ >= len);\n\t\t\top += len;\n\t\t\tocc -= len;\n\t\t} else {\n\t\t\t*op++ = (char)code;\n\t\t\tocc--;\n\t\t}\n\t}\n\n\ttif->tif_rawcc -= (tmsize_t)( (uint8*) bp - tif->tif_rawcp );\n\ttif->tif_rawcp = (uint8*) bp;\n\tsp->lzw_nbits = (unsigned short)nbits;\n\tsp->lzw_nextdata = nextdata;\n\tsp->lzw_nextbits = nextbits;\n\tsp->dec_nbitsmask = nbitsmask;\n\tsp->dec_oldcodep = oldcodep;\n\tsp->dec_free_entp = free_entp;\n\tsp->dec_maxcodep = maxcodep;\n\n\tif (occ > 0) {\n#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))\n\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t\"Not enough data at scanline %d (short %I64d bytes)\",\n\t\t\t     tif->tif_row, (unsigned __int64) occ);\n#else\n\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t\"Not enough data at scanline %d (short %llu bytes)\",\n\t\t\t     tif->tif_row, (unsigned long long) occ);\n#endif\n\t\treturn (0);\n\t}\n\treturn (1);\n}", "func_hash": 100265682824844738904136620855670307282, "file_name": "tif_lzw.c", "file_hash": 327511024295401908704037449464194011230, "cwe": ["CWE-787"], "cve": "CVE-2018-8905", "cve_desc": "In LibTIFF 4.0.9, a heap-based buffer overflow occurs in the function LZWDecodeCompat in tif_lzw.c via a crafted TIFF file, as demonstrated by tiff2ps.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-8905"}
{"idx": 211113, "project": "linux", "commit_id": "7fd25e6fc035f4b04b75bca6d7e8daa069603a76", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=7fd25e6fc035f4b04b75bca6d7e8daa069603a76", "commit_message": "ieee802154: atusb: fix use-after-free at disconnect\n\nThe disconnect callback was accessing the hardware-descriptor private\ndata after having having freed it.\n\nFixes: 7490b008d123 (\"ieee802154: add support for atusb transceiver\")\nCc: stable      # 4.2\nCc: Alexander Aring \nReported-by: syzbot+f4509a9138a1472e7e80@syzkaller.appspotmail.com\nSigned-off-by: Johan Hovold \nSigned-off-by: Stefan Schmidt ", "target": 1, "func": "static void atusb_disconnect(struct usb_interface *interface)\n{\n\tstruct atusb *atusb = usb_get_intfdata(interface);\n\n\tdev_dbg(&atusb->usb_dev->dev, \"%s\\n\", __func__);\n\n\tatusb->shutdown = 1;\n\tcancel_delayed_work_sync(&atusb->work);\n\n\tusb_kill_anchored_urbs(&atusb->rx_urbs);\n\tatusb_free_urbs(atusb);\n\tusb_kill_urb(atusb->tx_urb);\n\tusb_free_urb(atusb->tx_urb);\n\n\tieee802154_unregister_hw(atusb->hw);\n\n\tieee802154_free_hw(atusb->hw);\n\n\tusb_set_intfdata(interface, NULL);\n\tusb_put_dev(atusb->usb_dev);\n\n\tpr_debug(\"%s done\\n\", __func__);\n}", "func_hash": 299709833249026599914455726415271875676, "file_name": "atusb.c", "file_hash": 263846166810107854630006099143080706726, "cwe": ["CWE-416"], "cve": "CVE-2019-19525", "cve_desc": "In the Linux kernel before 5.3.6, there is a use-after-free bug that can be caused by a malicious USB device in the drivers/net/ieee802154/atusb.c driver, aka CID-7fd25e6fc035.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19525"}
{"idx": 446096, "project": "linux", "commit_id": "7fd25e6fc035f4b04b75bca6d7e8daa069603a76", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=7fd25e6fc035f4b04b75bca6d7e8daa069603a76", "commit_message": "ieee802154: atusb: fix use-after-free at disconnect\n\nThe disconnect callback was accessing the hardware-descriptor private\ndata after having having freed it.\n\nFixes: 7490b008d123 (\"ieee802154: add support for atusb transceiver\")\nCc: stable      # 4.2\nCc: Alexander Aring \nReported-by: syzbot+f4509a9138a1472e7e80@syzkaller.appspotmail.com\nSigned-off-by: Johan Hovold \nSigned-off-by: Stefan Schmidt ", "target": 0, "func": "static void atusb_disconnect(struct usb_interface *interface)\n{\n\tstruct atusb *atusb = usb_get_intfdata(interface);\n\n\tdev_dbg(&atusb->usb_dev->dev, \"%s\\n\", __func__);\n\n\tatusb->shutdown = 1;\n\tcancel_delayed_work_sync(&atusb->work);\n\n\tusb_kill_anchored_urbs(&atusb->rx_urbs);\n\tatusb_free_urbs(atusb);\n\tusb_kill_urb(atusb->tx_urb);\n\tusb_free_urb(atusb->tx_urb);\n\n\tieee802154_unregister_hw(atusb->hw);\n\n\tusb_put_dev(atusb->usb_dev);\n\n\tieee802154_free_hw(atusb->hw);\n\n\tusb_set_intfdata(interface, NULL);\n\n\tpr_debug(\"%s done\\n\", __func__);\n}", "func_hash": 293071923509968126139073732172721628591, "file_name": "atusb.c", "file_hash": 16875570992325006941870506429771552384, "cwe": ["CWE-416"], "cve": "CVE-2019-19525", "cve_desc": "In the Linux kernel before 5.3.6, there is a use-after-free bug that can be caused by a malicious USB device in the drivers/net/ieee802154/atusb.c driver, aka CID-7fd25e6fc035.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19525"}
{"idx": 211126, "project": "libmobi", "commit_id": "612562bc1ea38f1708b044e7a079c47a05b1291d", "project_url": "https://github.com/bfabiszewski/libmobi", "commit_url": "https://github.com/bfabiszewski/libmobi/commit/612562bc1ea38f1708b044e7a079c47a05b1291d", "commit_message": "Fix: index entry label not being zero-terminated with corrupt input", "target": 1, "func": "static MOBI_RET mobi_parse_index_entry(MOBIIndx *indx, const MOBIIdxt idxt, const MOBITagx *tagx, const MOBIOrdt *ordt, MOBIBuffer *buf, const size_t curr_number) {\n    if (indx == NULL) {\n        debug_print(\"%s\", \"INDX structure not initialized\\n\");\n        return MOBI_INIT_FAILED;\n    }\n    const size_t entry_offset = indx->entries_count;\n    const size_t entry_length = idxt.offsets[curr_number + 1] - idxt.offsets[curr_number];\n    mobi_buffer_setpos(buf, idxt.offsets[curr_number]);\n    size_t entry_number = curr_number + entry_offset;\n    if (entry_number >= indx->total_entries_count) {\n        debug_print(\"Entry number beyond array: %zu\\n\", entry_number);\n        return MOBI_DATA_CORRUPT;\n    }\n    /* save original record maxlen */\n    const size_t buf_maxlen = buf->maxlen;\n    if (buf->offset + entry_length >= buf_maxlen) {\n        debug_print(\"Entry length too long: %zu\\n\", entry_length);\n        return MOBI_DATA_CORRUPT;\n    }\n    buf->maxlen = buf->offset + entry_length;\n    size_t label_length = mobi_buffer_get8(buf);\n    if (label_length > entry_length) {\n        debug_print(\"Label length too long: %zu\\n\", label_length);\n        return MOBI_DATA_CORRUPT;\n    }\n    char text[INDX_LABEL_SIZEMAX];\n    /* FIXME: what is ORDT1 for? */\n    if (ordt->ordt2) {\n        label_length = mobi_getstring_ordt(ordt, buf, (unsigned char*) text, label_length);\n    } else {\n        label_length = mobi_indx_get_label((unsigned char*) text, buf, label_length, indx->ligt_entries_count);\n    }\n    indx->entries[entry_number].label = malloc(label_length + 1);\n    if (indx->entries[entry_number].label == NULL) {\n        debug_print(\"Memory allocation failed (%zu bytes)\\n\", label_length);\n        return MOBI_MALLOC_FAILED;\n    }\n    strncpy(indx->entries[entry_number].label, text, label_length + 1);\n    //debug_print(\"tag label[%zu]: %s\\n\", entry_number, indx->entries[entry_number].label);\n    unsigned char *control_bytes;\n    control_bytes = buf->data + buf->offset;\n    mobi_buffer_seek(buf, (int) tagx->control_byte_count);\n    indx->entries[entry_number].tags_count = 0;\n    indx->entries[entry_number].tags = NULL;\n    if (tagx->tags_count > 0) {\n        typedef struct {\n            uint8_t tag;\n            uint8_t tag_value_count;\n            uint32_t value_count;\n            uint32_t value_bytes;\n        } MOBIPtagx;\n        MOBIPtagx *ptagx = malloc(tagx->tags_count * sizeof(MOBIPtagx));\n        if (ptagx == NULL) {\n            debug_print(\"Memory allocation failed (%zu bytes)\\n\", tagx->tags_count * sizeof(MOBIPtagx));\n            return MOBI_MALLOC_FAILED;\n        }\n        uint32_t ptagx_count = 0;\n        size_t len;\n        size_t i = 0;\n        while (i < tagx->tags_count) {\n            if (tagx->tags[i].control_byte == 1) {\n                control_bytes++;\n                i++;\n                continue;\n            }\n            uint32_t value = control_bytes[0] & tagx->tags[i].bitmask;\n            if (value != 0) {\n                /* FIXME: is it safe to use MOBI_NOTSET? */\n                uint32_t value_count = MOBI_NOTSET;\n                uint32_t value_bytes = MOBI_NOTSET;\n                /* all bits of masked value are set */\n                if (value == tagx->tags[i].bitmask) {\n                    /* more than 1 bit set */\n                    if (mobi_bitcount(tagx->tags[i].bitmask) > 1) {\n                        /* read value bytes from entry */\n                        len = 0;\n                        value_bytes = mobi_buffer_get_varlen(buf, &len);\n                    } else {\n                        value_count = 1;\n                    }\n                } else {\n                    uint8_t mask = tagx->tags[i].bitmask;\n                    while ((mask & 1) == 0) {\n                        mask >>= 1;\n                        value >>= 1;\n                    }\n                    value_count = value;\n                }\n                ptagx[ptagx_count].tag = tagx->tags[i].tag;\n                ptagx[ptagx_count].tag_value_count = tagx->tags[i].values_count;\n                ptagx[ptagx_count].value_count = value_count;\n                ptagx[ptagx_count].value_bytes = value_bytes;\n                ptagx_count++;\n            }\n            i++;\n        }\n        indx->entries[entry_number].tags = malloc(tagx->tags_count * sizeof(MOBIIndexTag));\n        if (indx->entries[entry_number].tags == NULL) {\n            debug_print(\"Memory allocation failed (%zu bytes)\\n\", tagx->tags_count * sizeof(MOBIIndexTag));\n            free(ptagx);\n            return MOBI_MALLOC_FAILED;\n        }\n        i = 0;\n        while (i < ptagx_count) {\n            uint32_t tagvalues_count = 0;\n            /* FIXME: is it safe to use MOBI_NOTSET? */\n            /* value count is set */\n            uint32_t tagvalues[INDX_TAGVALUES_MAX];\n            if (ptagx[i].value_count != MOBI_NOTSET) {\n                size_t count = ptagx[i].value_count * ptagx[i].tag_value_count;\n                while (count-- && tagvalues_count < INDX_TAGVALUES_MAX) {\n                    len = 0;\n                    const uint32_t value_bytes = mobi_buffer_get_varlen(buf, &len);\n                    tagvalues[tagvalues_count++] = value_bytes;\n                }\n            /* value count is not set */\n            } else {\n                /* read value_bytes bytes */\n                len = 0;\n                while (len < ptagx[i].value_bytes && tagvalues_count < INDX_TAGVALUES_MAX) {\n                    const uint32_t value_bytes = mobi_buffer_get_varlen(buf, &len);\n                    tagvalues[tagvalues_count++] = value_bytes;\n                }\n            }\n            if (tagvalues_count) {\n                const size_t arr_size = tagvalues_count * sizeof(*indx->entries[entry_number].tags[i].tagvalues);\n                indx->entries[entry_number].tags[i].tagvalues = malloc(arr_size);\n                if (indx->entries[entry_number].tags[i].tagvalues == NULL) {\n                    debug_print(\"Memory allocation failed (%zu bytes)\\n\", arr_size);\n                    free(ptagx);\n                    return MOBI_MALLOC_FAILED;\n                }\n                memcpy(indx->entries[entry_number].tags[i].tagvalues, tagvalues, arr_size);\n            } else {\n                indx->entries[entry_number].tags[i].tagvalues = NULL;\n            }\n            indx->entries[entry_number].tags[i].tagid = ptagx[i].tag;\n            indx->entries[entry_number].tags[i].tagvalues_count = tagvalues_count;\n            indx->entries[entry_number].tags_count++;\n            i++;\n        }\n        free(ptagx);\n    }\n    /* restore buffer maxlen */\n    buf->maxlen = buf_maxlen;\n    return MOBI_SUCCESS;\n}", "func_hash": 251371537702901623564985735187675051869, "file_name": "index.c", "file_hash": 309095437889005741044332361577356993393, "cwe": ["CWE-125"], "cve": "CVE-2022-1987", "cve_desc": "Buffer Over-read in GitHub repository bfabiszewski/libmobi prior to 0.11.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1987"}
{"idx": 446279, "project": "libmobi", "commit_id": "612562bc1ea38f1708b044e7a079c47a05b1291d", "project_url": "https://github.com/bfabiszewski/libmobi", "commit_url": "https://github.com/bfabiszewski/libmobi/commit/612562bc1ea38f1708b044e7a079c47a05b1291d", "commit_message": "Fix: index entry label not being zero-terminated with corrupt input", "target": 0, "func": "static MOBI_RET mobi_parse_index_entry(MOBIIndx *indx, const MOBIIdxt idxt, const MOBITagx *tagx, const MOBIOrdt *ordt, MOBIBuffer *buf, const size_t curr_number) {\n    if (indx == NULL) {\n        debug_print(\"%s\", \"INDX structure not initialized\\n\");\n        return MOBI_INIT_FAILED;\n    }\n    const size_t entry_offset = indx->entries_count;\n    const size_t entry_length = idxt.offsets[curr_number + 1] - idxt.offsets[curr_number];\n    mobi_buffer_setpos(buf, idxt.offsets[curr_number]);\n    size_t entry_number = curr_number + entry_offset;\n    if (entry_number >= indx->total_entries_count) {\n        debug_print(\"Entry number beyond array: %zu\\n\", entry_number);\n        return MOBI_DATA_CORRUPT;\n    }\n    /* save original record maxlen */\n    const size_t buf_maxlen = buf->maxlen;\n    if (buf->offset + entry_length >= buf_maxlen) {\n        debug_print(\"Entry length too long: %zu\\n\", entry_length);\n        return MOBI_DATA_CORRUPT;\n    }\n    buf->maxlen = buf->offset + entry_length;\n    size_t label_length = mobi_buffer_get8(buf);\n    if (label_length > entry_length) {\n        debug_print(\"Label length too long: %zu\\n\", label_length);\n        return MOBI_DATA_CORRUPT;\n    }\n    char text[INDX_LABEL_SIZEMAX + 1];\n    /* FIXME: what is ORDT1 for? */\n    if (ordt->ordt2) {\n        label_length = mobi_getstring_ordt(ordt, buf, (unsigned char*) text, label_length);\n    } else {\n        label_length = mobi_indx_get_label((unsigned char*) text, buf, label_length, indx->ligt_entries_count);\n        if (buf->error != MOBI_SUCCESS) {\n            debug_print(\"Buffer error reading label: %d\\n\", buf->error);\n            return MOBI_DATA_CORRUPT;\n        }\n    }\n    indx->entries[entry_number].label = malloc(label_length + 1);\n    if (indx->entries[entry_number].label == NULL) {\n        debug_print(\"Memory allocation failed (%zu bytes)\\n\", label_length);\n        return MOBI_MALLOC_FAILED;\n    }\n    strncpy(indx->entries[entry_number].label, text, label_length + 1);\n    //debug_print(\"tag label[%zu]: %s\\n\", entry_number, indx->entries[entry_number].label);\n    unsigned char *control_bytes;\n    control_bytes = buf->data + buf->offset;\n    mobi_buffer_seek(buf, (int) tagx->control_byte_count);\n    indx->entries[entry_number].tags_count = 0;\n    indx->entries[entry_number].tags = NULL;\n    if (tagx->tags_count > 0) {\n        typedef struct {\n            uint8_t tag;\n            uint8_t tag_value_count;\n            uint32_t value_count;\n            uint32_t value_bytes;\n        } MOBIPtagx;\n        MOBIPtagx *ptagx = malloc(tagx->tags_count * sizeof(MOBIPtagx));\n        if (ptagx == NULL) {\n            debug_print(\"Memory allocation failed (%zu bytes)\\n\", tagx->tags_count * sizeof(MOBIPtagx));\n            return MOBI_MALLOC_FAILED;\n        }\n        uint32_t ptagx_count = 0;\n        size_t len;\n        size_t i = 0;\n        while (i < tagx->tags_count) {\n            if (tagx->tags[i].control_byte == 1) {\n                control_bytes++;\n                i++;\n                continue;\n            }\n            uint32_t value = control_bytes[0] & tagx->tags[i].bitmask;\n            if (value != 0) {\n                /* FIXME: is it safe to use MOBI_NOTSET? */\n                uint32_t value_count = MOBI_NOTSET;\n                uint32_t value_bytes = MOBI_NOTSET;\n                /* all bits of masked value are set */\n                if (value == tagx->tags[i].bitmask) {\n                    /* more than 1 bit set */\n                    if (mobi_bitcount(tagx->tags[i].bitmask) > 1) {\n                        /* read value bytes from entry */\n                        len = 0;\n                        value_bytes = mobi_buffer_get_varlen(buf, &len);\n                    } else {\n                        value_count = 1;\n                    }\n                } else {\n                    uint8_t mask = tagx->tags[i].bitmask;\n                    while ((mask & 1) == 0) {\n                        mask >>= 1;\n                        value >>= 1;\n                    }\n                    value_count = value;\n                }\n                ptagx[ptagx_count].tag = tagx->tags[i].tag;\n                ptagx[ptagx_count].tag_value_count = tagx->tags[i].values_count;\n                ptagx[ptagx_count].value_count = value_count;\n                ptagx[ptagx_count].value_bytes = value_bytes;\n                ptagx_count++;\n            }\n            i++;\n        }\n        indx->entries[entry_number].tags = malloc(tagx->tags_count * sizeof(MOBIIndexTag));\n        if (indx->entries[entry_number].tags == NULL) {\n            debug_print(\"Memory allocation failed (%zu bytes)\\n\", tagx->tags_count * sizeof(MOBIIndexTag));\n            free(ptagx);\n            return MOBI_MALLOC_FAILED;\n        }\n        i = 0;\n        while (i < ptagx_count) {\n            uint32_t tagvalues_count = 0;\n            /* FIXME: is it safe to use MOBI_NOTSET? */\n            /* value count is set */\n            uint32_t tagvalues[INDX_TAGVALUES_MAX];\n            if (ptagx[i].value_count != MOBI_NOTSET) {\n                size_t count = ptagx[i].value_count * ptagx[i].tag_value_count;\n                while (count-- && tagvalues_count < INDX_TAGVALUES_MAX) {\n                    len = 0;\n                    const uint32_t value_bytes = mobi_buffer_get_varlen(buf, &len);\n                    tagvalues[tagvalues_count++] = value_bytes;\n                }\n            /* value count is not set */\n            } else {\n                /* read value_bytes bytes */\n                len = 0;\n                while (len < ptagx[i].value_bytes && tagvalues_count < INDX_TAGVALUES_MAX) {\n                    const uint32_t value_bytes = mobi_buffer_get_varlen(buf, &len);\n                    tagvalues[tagvalues_count++] = value_bytes;\n                }\n            }\n            if (tagvalues_count) {\n                const size_t arr_size = tagvalues_count * sizeof(*indx->entries[entry_number].tags[i].tagvalues);\n                indx->entries[entry_number].tags[i].tagvalues = malloc(arr_size);\n                if (indx->entries[entry_number].tags[i].tagvalues == NULL) {\n                    debug_print(\"Memory allocation failed (%zu bytes)\\n\", arr_size);\n                    free(ptagx);\n                    return MOBI_MALLOC_FAILED;\n                }\n                memcpy(indx->entries[entry_number].tags[i].tagvalues, tagvalues, arr_size);\n            } else {\n                indx->entries[entry_number].tags[i].tagvalues = NULL;\n            }\n            indx->entries[entry_number].tags[i].tagid = ptagx[i].tag;\n            indx->entries[entry_number].tags[i].tagvalues_count = tagvalues_count;\n            indx->entries[entry_number].tags_count++;\n            i++;\n        }\n        free(ptagx);\n    }\n    /* restore buffer maxlen */\n    buf->maxlen = buf_maxlen;\n    return MOBI_SUCCESS;\n}", "func_hash": 15245136244377426883811242014385645170, "file_name": "index.c", "file_hash": 108195340824579059268746364836110051712, "cwe": ["CWE-125"], "cve": "CVE-2022-1987", "cve_desc": "Buffer Over-read in GitHub repository bfabiszewski/libmobi prior to 0.11.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1987"}
{"idx": 211136, "project": "rizin", "commit_id": "556ca2f9eef01ec0f4a76d1fbacfcf3a87a44810", "project_url": "https://github.com/rizinorg/rizin", "commit_url": "https://github.com/rizinorg/rizin/commit/556ca2f9eef01ec0f4a76d1fbacfcf3a87a44810", "commit_message": "Fix oob write in dyldcache\n\nWhen the individual n_slide_infos were too high, the sum would overflow\nand too few entries would be allocated.", "target": 1, "func": "static RzDyldRebaseInfos *get_rebase_infos(RzDyldCache *cache) {\n\tRzDyldRebaseInfos *result = RZ_NEW0(RzDyldRebaseInfos);\n\tif (!result) {\n\t\treturn NULL;\n\t}\n\n\tif (!cache->hdr->slideInfoOffset || !cache->hdr->slideInfoSize) {\n\t\tut32 total_slide_infos = 0;\n\t\tut32 n_slide_infos[MAX_N_HDR];\n\n\t\tut32 i;\n\t\tfor (i = 0; i < cache->n_hdr && i < MAX_N_HDR; i++) {\n\t\t\tut64 hdr_offset = cache->hdr_offset[i];\n\t\t\tif (!rz_buf_read_le32_at(cache->buf, 0x13c + hdr_offset, &n_slide_infos[i])) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\ttotal_slide_infos += n_slide_infos[i];\n\t\t}\n\n\t\tif (!total_slide_infos) {\n\t\t\tgoto beach;\n\t\t}\n\n\t\tRzDyldRebaseInfosEntry *infos = RZ_NEWS0(RzDyldRebaseInfosEntry, total_slide_infos);\n\t\tif (!infos) {\n\t\t\tgoto beach;\n\t\t}\n\n\t\tut32 k = 0;\n\t\tfor (i = 0; i < cache->n_hdr && i < MAX_N_HDR; i++) {\n\t\t\tut64 hdr_offset = cache->hdr_offset[i];\n\t\t\tif (!n_slide_infos[i]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tut32 sio;\n\t\t\tif (!rz_buf_read_le32_at(cache->buf, 0x138 + hdr_offset, &sio)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tut64 slide_infos_offset = sio;\n\t\t\tif (!slide_infos_offset) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tslide_infos_offset += hdr_offset;\n\n\t\t\tut32 j;\n\t\t\tRzDyldRebaseInfo *prev_info = NULL;\n\t\t\tfor (j = 0; j < n_slide_infos[i]; j++) {\n\t\t\t\tut64 offset = slide_infos_offset + j * sizeof(cache_mapping_slide);\n\t\t\t\tcache_mapping_slide entry;\n\t\t\t\tif (rz_buf_fread_at(cache->buf, offset, (ut8 *)&entry, \"6lii\", 1) != sizeof(cache_mapping_slide)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (entry.slideInfoOffset && entry.slideInfoSize) {\n\t\t\t\t\tinfos[k].start = entry.fileOffset + hdr_offset;\n\t\t\t\t\tinfos[k].end = infos[k].start + entry.size;\n\t\t\t\t\tut64 slide = prev_info ? prev_info->slide : UT64_MAX;\n\t\t\t\t\tinfos[k].info = get_rebase_info(cache, entry.slideInfoOffset + hdr_offset, entry.slideInfoSize, entry.fileOffset + hdr_offset, slide);\n\t\t\t\t\tprev_info = infos[k].info;\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!k) {\n\t\t\tfree(infos);\n\t\t\tgoto beach;\n\t\t}\n\n\t\tif (k < total_slide_infos) {\n\t\t\tRzDyldRebaseInfosEntry *pruned_infos = RZ_NEWS0(RzDyldRebaseInfosEntry, k);\n\t\t\tif (!pruned_infos) {\n\t\t\t\tfree(infos);\n\t\t\t\tgoto beach;\n\t\t\t}\n\n\t\t\tmemcpy(pruned_infos, infos, sizeof(RzDyldRebaseInfosEntry) * k);\n\t\t\tfree(infos);\n\t\t\tinfos = pruned_infos;\n\t\t}\n\n\t\tresult->entries = infos;\n\t\tresult->length = k;\n\t\treturn result;\n\t}\n\n\tif (cache->hdr->mappingCount > 1) {\n\t\tRzDyldRebaseInfosEntry *infos = RZ_NEWS0(RzDyldRebaseInfosEntry, 1);\n\t\tif (!infos) {\n\t\t\tgoto beach;\n\t\t}\n\n\t\tinfos[0].start = cache->maps[1].fileOffset;\n\t\tinfos[0].end = infos[0].start + cache->maps[1].size;\n\t\tinfos[0].info = get_rebase_info(cache, cache->hdr->slideInfoOffset, cache->hdr->slideInfoSize, infos[0].start, UT64_MAX);\n\n\t\tresult->entries = infos;\n\t\tresult->length = 1;\n\t\treturn result;\n\t}\n\nbeach:\n\tfree(result);\n\treturn NULL;\n}", "func_hash": 322670680444734680611953548583170676242, "file_name": "dyldcache.c", "file_hash": 282393003255280688273305906326648900280, "cwe": ["CWE-787"], "cve": "CVE-2022-36042", "cve_desc": "Rizin is a UNIX-like reverse engineering framework and command-line toolset. Versions 0.4.0 and prior are vulnerable to an out-of-bounds write when getting data from dyld cache files. A user opening a malicious dyld cache file could be affected by this vulnerability, allowing an attacker to execute code on the user's machine. Commit number 556ca2f9eef01ec0f4a76d1fbacfcf3a87a44810 contains a patch.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-36042"}
{"idx": 446416, "project": "rizin", "commit_id": "556ca2f9eef01ec0f4a76d1fbacfcf3a87a44810", "project_url": "https://github.com/rizinorg/rizin", "commit_url": "https://github.com/rizinorg/rizin/commit/556ca2f9eef01ec0f4a76d1fbacfcf3a87a44810", "commit_message": "Fix oob write in dyldcache\n\nWhen the individual n_slide_infos were too high, the sum would overflow\nand too few entries would be allocated.", "target": 0, "func": "static RzDyldRebaseInfos *get_rebase_infos(RzDyldCache *cache) {\n\tRzDyldRebaseInfos *result = RZ_NEW0(RzDyldRebaseInfos);\n\tif (!result) {\n\t\treturn NULL;\n\t}\n\n\tif (!cache->hdr->slideInfoOffset || !cache->hdr->slideInfoSize) {\n\t\tsize_t total_slide_infos = 0;\n\t\tut32 n_slide_infos[MAX_N_HDR];\n\n\t\tut32 i;\n\t\tfor (i = 0; i < cache->n_hdr && i < MAX_N_HDR; i++) {\n\t\t\tut64 hdr_offset = cache->hdr_offset[i];\n\t\t\tif (!rz_buf_read_le32_at(cache->buf, 0x13c + hdr_offset, &n_slide_infos[i])) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\tut32 total = total_slide_infos + n_slide_infos[i];\n\t\t\tif (total < total_slide_infos) {\n\t\t\t\t// overflow\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\ttotal_slide_infos = total;\n\t\t}\n\n\t\tif (!total_slide_infos) {\n\t\t\tgoto beach;\n\t\t}\n\n\t\tRzDyldRebaseInfosEntry *infos = RZ_NEWS0(RzDyldRebaseInfosEntry, total_slide_infos);\n\t\tif (!infos) {\n\t\t\tgoto beach;\n\t\t}\n\n\t\tut32 k = 0;\n\t\tfor (i = 0; i < cache->n_hdr && i < MAX_N_HDR; i++) {\n\t\t\tut64 hdr_offset = cache->hdr_offset[i];\n\t\t\tif (!n_slide_infos[i]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tut32 sio;\n\t\t\tif (!rz_buf_read_le32_at(cache->buf, 0x138 + hdr_offset, &sio)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tut64 slide_infos_offset = sio;\n\t\t\tif (!slide_infos_offset) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tslide_infos_offset += hdr_offset;\n\n\t\t\tut32 j;\n\t\t\tRzDyldRebaseInfo *prev_info = NULL;\n\t\t\tfor (j = 0; j < n_slide_infos[i]; j++) {\n\t\t\t\tut64 offset = slide_infos_offset + j * sizeof(cache_mapping_slide);\n\t\t\t\tcache_mapping_slide entry;\n\t\t\t\tif (rz_buf_fread_at(cache->buf, offset, (ut8 *)&entry, \"6lii\", 1) != sizeof(cache_mapping_slide)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (entry.slideInfoOffset && entry.slideInfoSize) {\n\t\t\t\t\tinfos[k].start = entry.fileOffset + hdr_offset;\n\t\t\t\t\tinfos[k].end = infos[k].start + entry.size;\n\t\t\t\t\tut64 slide = prev_info ? prev_info->slide : UT64_MAX;\n\t\t\t\t\tinfos[k].info = get_rebase_info(cache, entry.slideInfoOffset + hdr_offset, entry.slideInfoSize, entry.fileOffset + hdr_offset, slide);\n\t\t\t\t\tprev_info = infos[k].info;\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!k) {\n\t\t\tfree(infos);\n\t\t\tgoto beach;\n\t\t}\n\n\t\tif (k < total_slide_infos) {\n\t\t\tRzDyldRebaseInfosEntry *pruned_infos = RZ_NEWS0(RzDyldRebaseInfosEntry, k);\n\t\t\tif (!pruned_infos) {\n\t\t\t\tfree(infos);\n\t\t\t\tgoto beach;\n\t\t\t}\n\n\t\t\tmemcpy(pruned_infos, infos, sizeof(RzDyldRebaseInfosEntry) * k);\n\t\t\tfree(infos);\n\t\t\tinfos = pruned_infos;\n\t\t}\n\n\t\tresult->entries = infos;\n\t\tresult->length = k;\n\t\treturn result;\n\t}\n\n\tif (cache->hdr->mappingCount > 1) {\n\t\tRzDyldRebaseInfosEntry *infos = RZ_NEWS0(RzDyldRebaseInfosEntry, 1);\n\t\tif (!infos) {\n\t\t\tgoto beach;\n\t\t}\n\n\t\tinfos[0].start = cache->maps[1].fileOffset;\n\t\tinfos[0].end = infos[0].start + cache->maps[1].size;\n\t\tinfos[0].info = get_rebase_info(cache, cache->hdr->slideInfoOffset, cache->hdr->slideInfoSize, infos[0].start, UT64_MAX);\n\n\t\tresult->entries = infos;\n\t\tresult->length = 1;\n\t\treturn result;\n\t}\n\nbeach:\n\tfree(result);\n\treturn NULL;\n}", "func_hash": 118361840381472328590054655200772047943, "file_name": "dyldcache.c", "file_hash": 6264328448164427099716487918952046116, "cwe": ["CWE-787"], "cve": "CVE-2022-36042", "cve_desc": "Rizin is a UNIX-like reverse engineering framework and command-line toolset. Versions 0.4.0 and prior are vulnerable to an out-of-bounds write when getting data from dyld cache files. A user opening a malicious dyld cache file could be affected by this vulnerability, allowing an attacker to execute code on the user's machine. Commit number 556ca2f9eef01ec0f4a76d1fbacfcf3a87a44810 contains a patch.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-36042"}
{"idx": 211179, "project": "exiv2", "commit_id": "6e3855aed7ba8bb4731fc4087ca7f9078b2f3d97", "project_url": "https://github.com/Exiv2/exiv2", "commit_url": "https://github.com/Exiv2/exiv2/commit/6e3855aed7ba8bb4731fc4087ca7f9078b2f3d97", "commit_message": "Fix https://github.com/Exiv2/exiv2/issues/55", "target": 1, "func": "    void Image::printIFDStructure(BasicIo& io, std::ostream& out, Exiv2::PrintStructureOption option,uint32_t start,bool bSwap,char c,int depth)\n    {\n        depth++;\n        bool bFirst  = true  ;\n\n        // buffer\n        const size_t dirSize = 32;\n        DataBuf  dir(dirSize);\n        bool bPrint = option == kpsBasic || option == kpsRecursive;\n\n        do {\n            // Read top of directory\n            io.seek(start,BasicIo::beg);\n            io.read(dir.pData_, 2);\n            uint16_t   dirLength = byteSwap2(dir,0,bSwap);\n\n            bool tooBig = dirLength > 500;\n            if ( tooBig ) throw Error(55);\n\n            if ( bFirst && bPrint ) {\n                out << Internal::indent(depth) << Internal::stringFormat(\"STRUCTURE OF TIFF FILE (%c%c): \",c,c) << io.path() << std::endl;\n                if ( tooBig ) out << Internal::indent(depth) << \"dirLength = \" << dirLength << std::endl;\n            }\n\n            // Read the dictionary\n            for ( int i = 0 ; i < dirLength ; i ++ ) {\n                if ( bFirst && bPrint ) {\n                    out << Internal::indent(depth)\n                        << \" address |    tag                              |     \"\n                        << \" type |    count |    offset | value\\n\";\n                }\n                bFirst = false;\n\n                io.read(dir.pData_, 12);\n                uint16_t tag    = byteSwap2(dir,0,bSwap);\n                uint16_t type   = byteSwap2(dir,2,bSwap);\n                uint32_t count  = byteSwap4(dir,4,bSwap);\n                uint32_t offset = byteSwap4(dir,8,bSwap);\n\n                // Break for unknown tag types else we may segfault.\n                if ( !typeValid(type) ) {\n                    std::cerr << \"invalid type value detected in Image::printIFDStructure:  \" << type << std::endl;\n                    start = 0; // break from do loop\n                    throw Error(56);\n                    break; // break from for loop\n                }\n\n                std::string sp  = \"\" ; // output spacer\n\n                //prepare to print the value\n                uint32_t kount  = isPrintXMP(tag,option) ? count // haul in all the data\n                                : isPrintICC(tag,option) ? count // ditto\n                                : isStringType(type)     ? (count > 32 ? 32 : count) // restrict long arrays\n                                : count > 5              ? 5\n                                : count\n                                ;\n                uint32_t pad    = isStringType(type) ? 1 : 0;\n                uint32_t size   = isStringType(type) ? 1\n                                : is2ByteType(type)  ? 2\n                                : is4ByteType(type)  ? 4\n                                : is8ByteType(type)  ? 8\n                                : 1\n                                ;\n\n                // if ( offset > io.size() ) offset = 0; // Denial of service?\n                DataBuf  buf(size*count + pad+20);  // allocate a buffer\n                std::memcpy(buf.pData_,dir.pData_+8,4);  // copy dir[8:11] into buffer (short strings)\n                const bool bOffsetIsPointer = count*size > 4;\n\n                if ( bOffsetIsPointer ) {         // read into buffer\n                    size_t   restore = io.tell();  // save\n                    io.seek(offset,BasicIo::beg);  // position\n                    io.read(buf.pData_,count*size);// read\n                    io.seek(restore,BasicIo::beg); // restore\n                }\n\n                if ( bPrint ) {\n                    const uint32_t address = start + 2 + i*12 ;\n                    const std::string offsetString = bOffsetIsPointer?\n                        Internal::stringFormat(\"%10u\", offset):\n                        \"\";\n\n                    out << Internal::indent(depth)\n                    << Internal::stringFormat(\"%8u | %#06x %-28s |%10s |%9u |%10s | \"\n                                              ,address,tag,tagName(tag).c_str(),typeName(type),count,offsetString.c_str());\n                    if ( isShortType(type) ){\n                        for ( size_t k = 0 ; k < kount ; k++ ) {\n                            out << sp << byteSwap2(buf,k*size,bSwap);\n                            sp = \" \";\n                        }\n                    } else if ( isLongType(type) ){\n                        for ( size_t k = 0 ; k < kount ; k++ ) {\n                            out << sp << byteSwap4(buf,k*size,bSwap);\n                            sp = \" \";\n                        }\n\n                    } else if ( isRationalType(type) ){\n                        for ( size_t k = 0 ; k < kount ; k++ ) {\n                            uint32_t a = byteSwap4(buf,k*size+0,bSwap);\n                            uint32_t b = byteSwap4(buf,k*size+4,bSwap);\n                            out << sp << a << \"/\" << b;\n                            sp = \" \";\n                        }\n                    } else if ( isStringType(type) ) {\n                        out << sp << Internal::binaryToString(buf, kount);\n                    }\n\n                    sp = kount == count ? \"\" : \" ...\";\n                    out << sp << std::endl;\n\n                    if ( option == kpsRecursive && (tag == 0x8769 /* ExifTag */ || tag == 0x014a/*SubIFDs*/  || type == tiffIfd) ) {\n                        for ( size_t k = 0 ; k < count ; k++ ) {\n                            size_t   restore = io.tell();\n                            uint32_t offset = byteSwap4(buf,k*size,bSwap);\n                            printIFDStructure(io,out,option,offset,bSwap,c,depth);\n                            io.seek(restore,BasicIo::beg);\n                        }\n                    } else if ( option == kpsRecursive && tag == 0x83bb /* IPTCNAA */ ) {\n                        size_t   restore = io.tell();  // save\n                        io.seek(offset,BasicIo::beg);  // position\n                        byte* bytes=new byte[count] ;  // allocate memory\n                        io.read(bytes,count)        ;  // read\n                        io.seek(restore,BasicIo::beg); // restore\n                        IptcData::printStructure(out,bytes,count,depth);\n                        delete[] bytes;                // free\n                    }  else if ( option == kpsRecursive && tag == 0x927c /* MakerNote */ && count > 10) {\n                        size_t   restore = io.tell();  // save\n\n                        uint32_t jump= 10           ;\n                        byte     bytes[20]          ;\n                        const char* chars = (const char*) &bytes[0] ;\n                        io.seek(offset,BasicIo::beg);  // position\n                        io.read(bytes,jump    )     ;  // read\n                        bytes[jump]=0               ;\n                        if ( ::strcmp(\"Nikon\",chars) == 0 ) {\n                            // tag is an embedded tiff\n                            byte* bytes=new byte[count-jump] ;  // allocate memory\n                            io.read(bytes,count-jump)        ;  // read\n                            MemIo memIo(bytes,count-jump)    ;  // create a file\n                            printTiffStructure(memIo,out,option,depth);\n                            delete[] bytes                   ;  // free\n                        } else {\n                            // tag is an IFD\n                            io.seek(0,BasicIo::beg);  // position\n                            printIFDStructure(io,out,option,offset,bSwap,c,depth);\n                        }\n\n                        io.seek(restore,BasicIo::beg); // restore\n                    }\n                }\n\n                if ( isPrintXMP(tag,option) ) {\n                    buf.pData_[count]=0;\n                    out << (char*) buf.pData_;\n                }\n                if ( isPrintICC(tag,option) ) {\n                    out.write((const char*)buf.pData_,count);\n                }\n            }\n            if ( start ) {\n                io.read(dir.pData_, 4);\n                start = tooBig ? 0 : byteSwap4(dir,0,bSwap);\n            }\n        } while (start) ;\n\n        if ( bPrint ) {\n            out << Internal::indent(depth) << \"END \" << io.path() << std::endl;\n        }\n        out.flush();\n        depth--;\n    }", "func_hash": 34928413875325993015079651771204457360, "file_name": "image.cpp", "file_hash": 9570858013269078968090500181487179730, "cwe": ["CWE-125"], "cve": "CVE-2017-17723", "cve_desc": "In Exiv2 0.26, there is a heap-based buffer over-read in the Exiv2::Image::byteSwap4 function in image.cpp. Remote attackers can exploit this vulnerability to disclose memory data or cause a denial of service via a crafted TIFF file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-17723"}
{"idx": 447053, "project": "exiv2", "commit_id": "6e3855aed7ba8bb4731fc4087ca7f9078b2f3d97", "project_url": "https://github.com/Exiv2/exiv2", "commit_url": "https://github.com/Exiv2/exiv2/commit/6e3855aed7ba8bb4731fc4087ca7f9078b2f3d97", "commit_message": "Fix https://github.com/Exiv2/exiv2/issues/55", "target": 0, "func": "    void Image::printIFDStructure(BasicIo& io, std::ostream& out, Exiv2::PrintStructureOption option,uint32_t start,bool bSwap,char c,int depth)\n    {\n        depth++;\n        bool bFirst  = true  ;\n\n        // buffer\n        const size_t dirSize = 32;\n        DataBuf  dir(dirSize);\n        bool bPrint = option == kpsBasic || option == kpsRecursive;\n\n        do {\n            // Read top of directory\n            io.seek(start,BasicIo::beg);\n            io.read(dir.pData_, 2);\n            uint16_t   dirLength = byteSwap2(dir,0,bSwap);\n\n            bool tooBig = dirLength > 500;\n            if ( tooBig ) throw Error(55);\n\n            if ( bFirst && bPrint ) {\n                out << Internal::indent(depth) << Internal::stringFormat(\"STRUCTURE OF TIFF FILE (%c%c): \",c,c) << io.path() << std::endl;\n                if ( tooBig ) out << Internal::indent(depth) << \"dirLength = \" << dirLength << std::endl;\n            }\n\n            // Read the dictionary\n            for ( int i = 0 ; i < dirLength ; i ++ ) {\n                if ( bFirst && bPrint ) {\n                    out << Internal::indent(depth)\n                        << \" address |    tag                              |     \"\n                        << \" type |    count |    offset | value\\n\";\n                }\n                bFirst = false;\n\n                io.read(dir.pData_, 12);\n                uint16_t tag    = byteSwap2(dir,0,bSwap);\n                uint16_t type   = byteSwap2(dir,2,bSwap);\n                uint32_t count  = byteSwap4(dir,4,bSwap);\n                uint32_t offset = byteSwap4(dir,8,bSwap);\n\n                // Break for unknown tag types else we may segfault.\n                if ( !typeValid(type) ) {\n                    std::cerr << \"invalid type value detected in Image::printIFDStructure:  \" << type << std::endl;\n                    start = 0; // break from do loop\n                    throw Error(56);\n                    break; // break from for loop\n                }\n\n                std::string sp  = \"\" ; // output spacer\n\n                //prepare to print the value\n                uint32_t kount  = isPrintXMP(tag,option) ? count // haul in all the data\n                                : isPrintICC(tag,option) ? count // ditto\n                                : isStringType(type)     ? (count > 32 ? 32 : count) // restrict long arrays\n                                : count > 5              ? 5\n                                : count\n                                ;\n                uint32_t pad    = isStringType(type) ? 1 : 0;\n                uint32_t size   = isStringType(type) ? 1\n                                : is2ByteType(type)  ? 2\n                                : is4ByteType(type)  ? 4\n                                : is8ByteType(type)  ? 8\n                                : 1\n                                ;\n\n                // if ( offset > io.size() ) offset = 0; // Denial of service?\n\n                // #55 memory allocation crash test/data/POC8\n                long long allocate = (long long) (size*count + pad+20);\n                if ( allocate > (long long) io.size() ) {\n                    throw Error(57);\n                }\n                DataBuf  buf(allocate);  // allocate a buffer\n                std::memcpy(buf.pData_,dir.pData_+8,4);  // copy dir[8:11] into buffer (short strings)\n                const bool bOffsetIsPointer = count*size > 4;\n\n                if ( bOffsetIsPointer ) {         // read into buffer\n                    size_t   restore = io.tell();  // save\n                    io.seek(offset,BasicIo::beg);  // position\n                    io.read(buf.pData_,count*size);// read\n                    io.seek(restore,BasicIo::beg); // restore\n                }\n\n                if ( bPrint ) {\n                    const uint32_t address = start + 2 + i*12 ;\n                    const std::string offsetString = bOffsetIsPointer?\n                        Internal::stringFormat(\"%10u\", offset):\n                        \"\";\n\n                    out << Internal::indent(depth)\n                    << Internal::stringFormat(\"%8u | %#06x %-28s |%10s |%9u |%10s | \"\n                                              ,address,tag,tagName(tag).c_str(),typeName(type),count,offsetString.c_str());\n                    if ( isShortType(type) ){\n                        for ( size_t k = 0 ; k < kount ; k++ ) {\n                            out << sp << byteSwap2(buf,k*size,bSwap);\n                            sp = \" \";\n                        }\n                    } else if ( isLongType(type) ){\n                        for ( size_t k = 0 ; k < kount ; k++ ) {\n                            out << sp << byteSwap4(buf,k*size,bSwap);\n                            sp = \" \";\n                        }\n\n                    } else if ( isRationalType(type) ){\n                        for ( size_t k = 0 ; k < kount ; k++ ) {\n                            uint32_t a = byteSwap4(buf,k*size+0,bSwap);\n                            uint32_t b = byteSwap4(buf,k*size+4,bSwap);\n                            out << sp << a << \"/\" << b;\n                            sp = \" \";\n                        }\n                    } else if ( isStringType(type) ) {\n                        out << sp << Internal::binaryToString(buf, kount);\n                    }\n\n                    sp = kount == count ? \"\" : \" ...\";\n                    out << sp << std::endl;\n\n                    if ( option == kpsRecursive && (tag == 0x8769 /* ExifTag */ || tag == 0x014a/*SubIFDs*/  || type == tiffIfd) ) {\n                        for ( size_t k = 0 ; k < count ; k++ ) {\n                            size_t   restore = io.tell();\n                            uint32_t offset = byteSwap4(buf,k*size,bSwap);\n                            printIFDStructure(io,out,option,offset,bSwap,c,depth);\n                            io.seek(restore,BasicIo::beg);\n                        }\n                    } else if ( option == kpsRecursive && tag == 0x83bb /* IPTCNAA */ ) {\n                        size_t   restore = io.tell();  // save\n                        io.seek(offset,BasicIo::beg);  // position\n                        byte* bytes=new byte[count] ;  // allocate memory\n                        io.read(bytes,count)        ;  // read\n                        io.seek(restore,BasicIo::beg); // restore\n                        IptcData::printStructure(out,bytes,count,depth);\n                        delete[] bytes;                // free\n                    }  else if ( option == kpsRecursive && tag == 0x927c /* MakerNote */ && count > 10) {\n                        size_t   restore = io.tell();  // save\n\n                        uint32_t jump= 10           ;\n                        byte     bytes[20]          ;\n                        const char* chars = (const char*) &bytes[0] ;\n                        io.seek(offset,BasicIo::beg);  // position\n                        io.read(bytes,jump    )     ;  // read\n                        bytes[jump]=0               ;\n                        if ( ::strcmp(\"Nikon\",chars) == 0 ) {\n                            // tag is an embedded tiff\n                            byte* bytes=new byte[count-jump] ;  // allocate memory\n                            io.read(bytes,count-jump)        ;  // read\n                            MemIo memIo(bytes,count-jump)    ;  // create a file\n                            printTiffStructure(memIo,out,option,depth);\n                            delete[] bytes                   ;  // free\n                        } else {\n                            // tag is an IFD\n                            io.seek(0,BasicIo::beg);  // position\n                            printIFDStructure(io,out,option,offset,bSwap,c,depth);\n                        }\n\n                        io.seek(restore,BasicIo::beg); // restore\n                    }\n                }\n\n                if ( isPrintXMP(tag,option) ) {\n                    buf.pData_[count]=0;\n                    out << (char*) buf.pData_;\n                }\n                if ( isPrintICC(tag,option) ) {\n                    out.write((const char*)buf.pData_,count);\n                }\n            }\n            if ( start ) {\n                io.read(dir.pData_, 4);\n                start = tooBig ? 0 : byteSwap4(dir,0,bSwap);\n            }\n        } while (start) ;\n\n        if ( bPrint ) {\n            out << Internal::indent(depth) << \"END \" << io.path() << std::endl;\n        }\n        out.flush();\n        depth--;\n    }", "func_hash": 135908904515753765989749270271712491869, "file_name": "image.cpp", "file_hash": 158908380717507532391090050859668456498, "cwe": ["CWE-125"], "cve": "CVE-2017-17723", "cve_desc": "In Exiv2 0.26, there is a heap-based buffer over-read in the Exiv2::Image::byteSwap4 function in image.cpp. Remote attackers can exploit this vulnerability to disclose memory data or cause a denial of service via a crafted TIFF file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-17723"}
{"idx": 211181, "project": "php-src", "commit_id": "a72cd07f2983dc43a6bb35209dc4687852e53c09", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=a72cd07f2983dc43a6bb35209dc4687852e53c09", "commit_message": "Fixed bug #68665 (Invalid free)", "target": 1, "func": "apprentice_load(struct magic_set *ms, const char *fn, int action)\n{\n\tint errs = 0;\n\tuint32_t i, j;\n\tsize_t files = 0, maxfiles = 0;\n\tchar **filearr = NULL;\n\tstruct stat st;\n\tstruct magic_map *map;\n\tstruct magic_entry_set mset[MAGIC_SETS];\n\tphp_stream *dir;\n\tphp_stream_dirent d;\n \n\tTSRMLS_FETCH();\n\n\tmemset(mset, 0, sizeof(mset));\n\tms->flags |= MAGIC_CHECK;\t/* Enable checks for parsed files */\n\n\n\tif ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL)\n\t{\n\t\tfile_oomem(ms, sizeof(*map));\n\t\treturn NULL;\n\t}\n\n\t/* print silly verbose header for USG compat. */\n\tif (action == FILE_CHECK)\n\t\t(void)fprintf(stderr, \"%s\\n\", usg_hdr);\n\n\t/* load directory or file */\n\t/* FIXME: Read file names and sort them to prevent\n\t   non-determinism. See Debian bug #488562. */\n\tif (php_sys_stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {\n\t\tint mflen;\n\t\tchar mfn[MAXPATHLEN];\n\n\t\tdir = php_stream_opendir((char *)fn, REPORT_ERRORS, NULL);\n\t\tif (!dir) {\n\t\t\terrs++;\n\t\t\tgoto out;\n\t\t}\n\t\twhile (php_stream_readdir(dir, &d)) {\n\t\t\tif ((mflen = snprintf(mfn, sizeof(mfn), \"%s/%s\", fn, d.d_name)) < 0) {\n\t\t\t\tfile_oomem(ms,\n\t\t\t\tstrlen(fn) + strlen(d.d_name) + 2);\n\t\t\t\terrs++;\n\t\t\t\tphp_stream_closedir(dir);\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tif (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (files >= maxfiles) {\n\t\t\t\tsize_t mlen;\n\t\t\t\tmaxfiles = (maxfiles + 1) * 2;\n\t\t\t\tmlen = maxfiles * sizeof(*filearr);\n\t\t\t\tif ((filearr = CAST(char **,\n\t\t\t\t    erealloc(filearr, mlen))) == NULL) {\n\t\t\t\t\tfile_oomem(ms, mlen);\n\t\t\t\t\tefree(mfn);\n\t\t\t\t\tphp_stream_closedir(dir);\n\t\t\t\t\terrs++;\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfilearr[files++] = estrndup(mfn, (mflen > sizeof(mfn) - 1)? sizeof(mfn) - 1: mflen);\n\t\t}\n\t\tphp_stream_closedir(dir);\n\t\tqsort(filearr, files, sizeof(*filearr), cmpstrp);\n\t\tfor (i = 0; i < files; i++) {\n\t\t\tload_1(ms, action, filearr[i], &errs, mset);\n\t\t\tefree(filearr[i]);\n\t\t}\n\t\tefree(filearr);\n\t} else\n\t\tload_1(ms, action, fn, &errs, mset);\n\tif (errs)\n\t\tgoto out;\n\n\tfor (j = 0; j < MAGIC_SETS; j++) {\n\t\t/* Set types of tests */\n\t\tfor (i = 0; i < mset[j].count; ) {\n\t\t\tif (mset[j].me[i].mp->cont_level != 0) {\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ti = set_text_binary(ms, mset[j].me, mset[j].count, i);\n\t\t}\n\t\tqsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),\n\t\t    apprentice_sort);\n\n\t\t/*\n\t\t * Make sure that any level 0 \"default\" line is last\n\t\t * (if one exists).\n\t\t */\n\t\tset_last_default(ms, mset[j].me, mset[j].count);\n\n\t\t/* coalesce per file arrays into a single one */\n\t\tif (coalesce_entries(ms, mset[j].me, mset[j].count,\n\t\t    &map->magic[j], &map->nmagic[j]) == -1) {\n\t\t\terrs++;\n\t\t\tgoto out;\n\t\t}\n\t}\n\nout:\n\tfor (j = 0; j < MAGIC_SETS; j++)\n\t\tmagic_entry_free(mset[j].me, mset[j].count);\n\n\tif (errs) {\n\t\tfor (j = 0; j < MAGIC_SETS; j++) {\n\t\t\tif (map->magic[j])\n\t\t\t\tefree(map->magic[j]);\n\t\t}\n\t\tefree(map);\n\t\treturn NULL;\n\t}\n\treturn map;\n}", "func_hash": 215852170840415887446784967790257485070, "file_name": "apprentice.c", "file_hash": 136822894511518552455761565191570256868, "cwe": ["CWE-17"], "cve": "CVE-2014-9426", "cve_desc": "The apprentice_load function in libmagic/apprentice.c in the Fileinfo component in PHP through 5.6.4 attempts to perform a free operation on a stack-based character array, which allows remote attackers to cause a denial of service (memory corruption or application crash) or possibly have unspecified other impact via unknown vectors.  NOTE: this is disputed by the vendor because the standard erealloc behavior makes the free operation unreachable", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-9426"}
{"idx": 447231, "project": "php-src", "commit_id": "a72cd07f2983dc43a6bb35209dc4687852e53c09", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=a72cd07f2983dc43a6bb35209dc4687852e53c09", "commit_message": "Fixed bug #68665 (Invalid free)", "target": 0, "func": "apprentice_load(struct magic_set *ms, const char *fn, int action)\n{\n\tint errs = 0;\n\tuint32_t i, j;\n\tsize_t files = 0, maxfiles = 0;\n\tchar **filearr = NULL;\n\tstruct stat st;\n\tstruct magic_map *map;\n\tstruct magic_entry_set mset[MAGIC_SETS];\n\tphp_stream *dir;\n\tphp_stream_dirent d;\n \n\tTSRMLS_FETCH();\n\n\tmemset(mset, 0, sizeof(mset));\n\tms->flags |= MAGIC_CHECK;\t/* Enable checks for parsed files */\n\n\n\tif ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL)\n\t{\n\t\tfile_oomem(ms, sizeof(*map));\n\t\treturn NULL;\n\t}\n\n\t/* print silly verbose header for USG compat. */\n\tif (action == FILE_CHECK)\n\t\t(void)fprintf(stderr, \"%s\\n\", usg_hdr);\n\n\t/* load directory or file */\n\t/* FIXME: Read file names and sort them to prevent\n\t   non-determinism. See Debian bug #488562. */\n\tif (php_sys_stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {\n\t\tint mflen;\n\t\tchar mfn[MAXPATHLEN];\n\n\t\tdir = php_stream_opendir((char *)fn, REPORT_ERRORS, NULL);\n\t\tif (!dir) {\n\t\t\terrs++;\n\t\t\tgoto out;\n\t\t}\n\t\twhile (php_stream_readdir(dir, &d)) {\n\t\t\tif ((mflen = snprintf(mfn, sizeof(mfn), \"%s/%s\", fn, d.d_name)) < 0) {\n\t\t\t\tfile_oomem(ms,\n\t\t\t\tstrlen(fn) + strlen(d.d_name) + 2);\n\t\t\t\terrs++;\n\t\t\t\tphp_stream_closedir(dir);\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tif (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (files >= maxfiles) {\n\t\t\t\tsize_t mlen;\n\t\t\t\tmaxfiles = (maxfiles + 1) * 2;\n\t\t\t\tmlen = maxfiles * sizeof(*filearr);\n\t\t\t\tif ((filearr = CAST(char **,\n\t\t\t\t    erealloc(filearr, mlen))) == NULL) {\n\t\t\t\t\tfile_oomem(ms, mlen);\n\t\t\t\t\tphp_stream_closedir(dir);\n\t\t\t\t\terrs++;\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfilearr[files++] = estrndup(mfn, (mflen > sizeof(mfn) - 1)? sizeof(mfn) - 1: mflen);\n\t\t}\n\t\tphp_stream_closedir(dir);\n\t\tqsort(filearr, files, sizeof(*filearr), cmpstrp);\n\t\tfor (i = 0; i < files; i++) {\n\t\t\tload_1(ms, action, filearr[i], &errs, mset);\n\t\t\tefree(filearr[i]);\n\t\t}\n\t\tefree(filearr);\n\t} else\n\t\tload_1(ms, action, fn, &errs, mset);\n\tif (errs)\n\t\tgoto out;\n\n\tfor (j = 0; j < MAGIC_SETS; j++) {\n\t\t/* Set types of tests */\n\t\tfor (i = 0; i < mset[j].count; ) {\n\t\t\tif (mset[j].me[i].mp->cont_level != 0) {\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ti = set_text_binary(ms, mset[j].me, mset[j].count, i);\n\t\t}\n\t\tqsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),\n\t\t    apprentice_sort);\n\n\t\t/*\n\t\t * Make sure that any level 0 \"default\" line is last\n\t\t * (if one exists).\n\t\t */\n\t\tset_last_default(ms, mset[j].me, mset[j].count);\n\n\t\t/* coalesce per file arrays into a single one */\n\t\tif (coalesce_entries(ms, mset[j].me, mset[j].count,\n\t\t    &map->magic[j], &map->nmagic[j]) == -1) {\n\t\t\terrs++;\n\t\t\tgoto out;\n\t\t}\n\t}\n\nout:\n\tfor (j = 0; j < MAGIC_SETS; j++)\n\t\tmagic_entry_free(mset[j].me, mset[j].count);\n\n\tif (errs) {\n\t\tfor (j = 0; j < MAGIC_SETS; j++) {\n\t\t\tif (map->magic[j])\n\t\t\t\tefree(map->magic[j]);\n\t\t}\n\t\tefree(map);\n\t\treturn NULL;\n\t}\n\treturn map;\n}", "func_hash": 156454401926797998343757810189411499663, "file_name": "apprentice.c", "file_hash": 133128407981065524680771127461274572868, "cwe": ["CWE-17"], "cve": "CVE-2014-9426", "cve_desc": "The apprentice_load function in libmagic/apprentice.c in the Fileinfo component in PHP through 5.6.4 attempts to perform a free operation on a stack-based character array, which allows remote attackers to cause a denial of service (memory corruption or application crash) or possibly have unspecified other impact via unknown vectors.  NOTE: this is disputed by the vendor because the standard erealloc behavior makes the free operation unreachable", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2014-9426"}
{"idx": 211471, "project": "frr", "commit_id": "ff6db1027f8f36df657ff2e5ea167773752537ed", "project_url": "https://github.com/FRRouting/frr", "commit_url": "https://github.com/FRRouting/frr/commit/ff6db1027f8f36df657ff2e5ea167773752537ed", "commit_message": "bgpd: Make sure hdr length is at a minimum of what is expected\n\nEnsure that if the capability length specified is enough data.\n\nSigned-off-by: Donald Sharp ", "target": 1, "func": "static int bgp_capability_msg_parse(struct peer *peer, uint8_t *pnt,\n\t\t\t\t    bgp_size_t length)\n{\n\tuint8_t *end;\n\tstruct capability_mp_data mpc;\n\tstruct capability_header *hdr;\n\tuint8_t action;\n\tiana_afi_t pkt_afi;\n\tafi_t afi;\n\tiana_safi_t pkt_safi;\n\tsafi_t safi;\n\n\tend = pnt + length;\n\n\twhile (pnt < end) {\n\t\t/* We need at least action, capability code and capability\n\t\t * length. */\n\t\tif (pnt + 3 > end) {\n\t\t\tzlog_info(\"%s Capability length error\", peer->host);\n\t\t\tbgp_notify_send(peer, BGP_NOTIFY_CEASE,\n\t\t\t\t\tBGP_NOTIFY_SUBCODE_UNSPECIFIC);\n\t\t\treturn BGP_Stop;\n\t\t}\n\t\taction = *pnt;\n\t\thdr = (struct capability_header *)(pnt + 1);\n\n\t\t/* Action value check.  */\n\t\tif (action != CAPABILITY_ACTION_SET\n\t\t    && action != CAPABILITY_ACTION_UNSET) {\n\t\t\tzlog_info(\"%s Capability Action Value error %d\",\n\t\t\t\t  peer->host, action);\n\t\t\tbgp_notify_send(peer, BGP_NOTIFY_CEASE,\n\t\t\t\t\tBGP_NOTIFY_SUBCODE_UNSPECIFIC);\n\t\t\treturn BGP_Stop;\n\t\t}\n\n\t\tif (bgp_debug_neighbor_events(peer))\n\t\t\tzlog_debug(\n\t\t\t\t\"%s CAPABILITY has action: %d, code: %u, length %u\",\n\t\t\t\tpeer->host, action, hdr->code, hdr->length);\n\n\t\t/* Capability length check. */\n\t\tif ((pnt + hdr->length + 3) > end) {\n\t\t\tzlog_info(\"%s Capability length error\", peer->host);\n\t\t\tbgp_notify_send(peer, BGP_NOTIFY_CEASE,\n\t\t\t\t\tBGP_NOTIFY_SUBCODE_UNSPECIFIC);\n\t\t\treturn BGP_Stop;\n\t\t}\n\n\t\t/* Fetch structure to the byte stream. */\n\t\tmemcpy(&mpc, pnt + 3, sizeof(struct capability_mp_data));\n\t\tpnt += hdr->length + 3;\n\n\t\t/* We know MP Capability Code. */\n\t\tif (hdr->code == CAPABILITY_CODE_MP) {\n\t\t\tpkt_afi = ntohs(mpc.afi);\n\t\t\tpkt_safi = mpc.safi;\n\n\t\t\t/* Ignore capability when override-capability is set. */\n\t\t\tif (CHECK_FLAG(peer->flags,\n\t\t\t\t       PEER_FLAG_OVERRIDE_CAPABILITY))\n\t\t\t\tcontinue;\n\n\t\t\t/* Convert AFI, SAFI to internal values. */\n\t\t\tif (bgp_map_afi_safi_iana2int(pkt_afi, pkt_safi, &afi,\n\t\t\t\t\t\t      &safi)) {\n\t\t\t\tif (bgp_debug_neighbor_events(peer))\n\t\t\t\t\tzlog_debug(\n\t\t\t\t\t\t\"%s Dynamic Capability MP_EXT afi/safi invalid (%s/%s)\",\n\t\t\t\t\t\tpeer->host,\n\t\t\t\t\t\tiana_afi2str(pkt_afi),\n\t\t\t\t\t\tiana_safi2str(pkt_safi));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* Address family check.  */\n\t\t\tif (bgp_debug_neighbor_events(peer))\n\t\t\t\tzlog_debug(\n\t\t\t\t\t\"%s CAPABILITY has %s MP_EXT CAP for afi/safi: %s/%s\",\n\t\t\t\t\tpeer->host,\n\t\t\t\t\taction == CAPABILITY_ACTION_SET\n\t\t\t\t\t\t? \"Advertising\"\n\t\t\t\t\t\t: \"Removing\",\n\t\t\t\t\tiana_afi2str(pkt_afi),\n\t\t\t\t\tiana_safi2str(pkt_safi));\n\n\t\t\tif (action == CAPABILITY_ACTION_SET) {\n\t\t\t\tpeer->afc_recv[afi][safi] = 1;\n\t\t\t\tif (peer->afc[afi][safi]) {\n\t\t\t\t\tpeer->afc_nego[afi][safi] = 1;\n\t\t\t\t\tbgp_announce_route(peer, afi, safi,\n\t\t\t\t\t\t\t   false);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpeer->afc_recv[afi][safi] = 0;\n\t\t\t\tpeer->afc_nego[afi][safi] = 0;\n\n\t\t\t\tif (peer_active_nego(peer))\n\t\t\t\t\tbgp_clear_route(peer, afi, safi);\n\t\t\t\telse\n\t\t\t\t\treturn BGP_Stop;\n\t\t\t}\n\t\t} else {\n\t\t\tflog_warn(\n\t\t\t\tEC_BGP_UNRECOGNIZED_CAPABILITY,\n\t\t\t\t\"%s unrecognized capability code: %d - ignored\",\n\t\t\t\tpeer->host, hdr->code);\n\t\t}\n\t}\n\n\t/* No FSM action necessary */\n\treturn BGP_PACKET_NOOP;\n}", "func_hash": 113418745382629462505950696530283807291, "file_name": "bgp_packet.c", "file_hash": 315108406753805109859360755691559827205, "cwe": ["CWE-125"], "cve": "CVE-2022-37032", "cve_desc": "An out-of-bounds read in the BGP daemon of FRRouting FRR before 8.4 may lead to a segmentation fault and denial of service. This occurs in bgp_capability_msg_parse in bgpd/bgp_packet.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-37032"}
{"idx": 448562, "project": "frr", "commit_id": "ff6db1027f8f36df657ff2e5ea167773752537ed", "project_url": "https://github.com/FRRouting/frr", "commit_url": "https://github.com/FRRouting/frr/commit/ff6db1027f8f36df657ff2e5ea167773752537ed", "commit_message": "bgpd: Make sure hdr length is at a minimum of what is expected\n\nEnsure that if the capability length specified is enough data.\n\nSigned-off-by: Donald Sharp ", "target": 0, "func": "static int bgp_capability_msg_parse(struct peer *peer, uint8_t *pnt,\n\t\t\t\t    bgp_size_t length)\n{\n\tuint8_t *end;\n\tstruct capability_mp_data mpc;\n\tstruct capability_header *hdr;\n\tuint8_t action;\n\tiana_afi_t pkt_afi;\n\tafi_t afi;\n\tiana_safi_t pkt_safi;\n\tsafi_t safi;\n\n\tend = pnt + length;\n\n\twhile (pnt < end) {\n\t\t/* We need at least action, capability code and capability\n\t\t * length. */\n\t\tif (pnt + 3 > end) {\n\t\t\tzlog_info(\"%s Capability length error\", peer->host);\n\t\t\tbgp_notify_send(peer, BGP_NOTIFY_CEASE,\n\t\t\t\t\tBGP_NOTIFY_SUBCODE_UNSPECIFIC);\n\t\t\treturn BGP_Stop;\n\t\t}\n\t\taction = *pnt;\n\t\thdr = (struct capability_header *)(pnt + 1);\n\n\t\t/* Action value check.  */\n\t\tif (action != CAPABILITY_ACTION_SET\n\t\t    && action != CAPABILITY_ACTION_UNSET) {\n\t\t\tzlog_info(\"%s Capability Action Value error %d\",\n\t\t\t\t  peer->host, action);\n\t\t\tbgp_notify_send(peer, BGP_NOTIFY_CEASE,\n\t\t\t\t\tBGP_NOTIFY_SUBCODE_UNSPECIFIC);\n\t\t\treturn BGP_Stop;\n\t\t}\n\n\t\tif (bgp_debug_neighbor_events(peer))\n\t\t\tzlog_debug(\n\t\t\t\t\"%s CAPABILITY has action: %d, code: %u, length %u\",\n\t\t\t\tpeer->host, action, hdr->code, hdr->length);\n\n\t\tif (hdr->length < sizeof(struct capability_mp_data)) {\n\t\t\tzlog_info(\n\t\t\t\t\"%pBP Capability structure is not properly filled out, expected at least %zu bytes but header length specified is %d\",\n\t\t\t\tpeer, sizeof(struct capability_mp_data),\n\t\t\t\thdr->length);\n\t\t\treturn BGP_Stop;\n\t\t}\n\n\t\t/* Capability length check. */\n\t\tif ((pnt + hdr->length + 3) > end) {\n\t\t\tzlog_info(\"%s Capability length error\", peer->host);\n\t\t\tbgp_notify_send(peer, BGP_NOTIFY_CEASE,\n\t\t\t\t\tBGP_NOTIFY_SUBCODE_UNSPECIFIC);\n\t\t\treturn BGP_Stop;\n\t\t}\n\n\t\t/* Fetch structure to the byte stream. */\n\t\tmemcpy(&mpc, pnt + 3, sizeof(struct capability_mp_data));\n\t\tpnt += hdr->length + 3;\n\n\t\t/* We know MP Capability Code. */\n\t\tif (hdr->code == CAPABILITY_CODE_MP) {\n\t\t\tpkt_afi = ntohs(mpc.afi);\n\t\t\tpkt_safi = mpc.safi;\n\n\t\t\t/* Ignore capability when override-capability is set. */\n\t\t\tif (CHECK_FLAG(peer->flags,\n\t\t\t\t       PEER_FLAG_OVERRIDE_CAPABILITY))\n\t\t\t\tcontinue;\n\n\t\t\t/* Convert AFI, SAFI to internal values. */\n\t\t\tif (bgp_map_afi_safi_iana2int(pkt_afi, pkt_safi, &afi,\n\t\t\t\t\t\t      &safi)) {\n\t\t\t\tif (bgp_debug_neighbor_events(peer))\n\t\t\t\t\tzlog_debug(\n\t\t\t\t\t\t\"%s Dynamic Capability MP_EXT afi/safi invalid (%s/%s)\",\n\t\t\t\t\t\tpeer->host,\n\t\t\t\t\t\tiana_afi2str(pkt_afi),\n\t\t\t\t\t\tiana_safi2str(pkt_safi));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* Address family check.  */\n\t\t\tif (bgp_debug_neighbor_events(peer))\n\t\t\t\tzlog_debug(\n\t\t\t\t\t\"%s CAPABILITY has %s MP_EXT CAP for afi/safi: %s/%s\",\n\t\t\t\t\tpeer->host,\n\t\t\t\t\taction == CAPABILITY_ACTION_SET\n\t\t\t\t\t\t? \"Advertising\"\n\t\t\t\t\t\t: \"Removing\",\n\t\t\t\t\tiana_afi2str(pkt_afi),\n\t\t\t\t\tiana_safi2str(pkt_safi));\n\n\t\t\tif (action == CAPABILITY_ACTION_SET) {\n\t\t\t\tpeer->afc_recv[afi][safi] = 1;\n\t\t\t\tif (peer->afc[afi][safi]) {\n\t\t\t\t\tpeer->afc_nego[afi][safi] = 1;\n\t\t\t\t\tbgp_announce_route(peer, afi, safi,\n\t\t\t\t\t\t\t   false);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpeer->afc_recv[afi][safi] = 0;\n\t\t\t\tpeer->afc_nego[afi][safi] = 0;\n\n\t\t\t\tif (peer_active_nego(peer))\n\t\t\t\t\tbgp_clear_route(peer, afi, safi);\n\t\t\t\telse\n\t\t\t\t\treturn BGP_Stop;\n\t\t\t}\n\t\t} else {\n\t\t\tflog_warn(\n\t\t\t\tEC_BGP_UNRECOGNIZED_CAPABILITY,\n\t\t\t\t\"%s unrecognized capability code: %d - ignored\",\n\t\t\t\tpeer->host, hdr->code);\n\t\t}\n\t}\n\n\t/* No FSM action necessary */\n\treturn BGP_PACKET_NOOP;\n}", "func_hash": 234942557373387642090168685106076449546, "file_name": "bgp_packet.c", "file_hash": 265694254173833717279647335030884275361, "cwe": ["CWE-125"], "cve": "CVE-2022-37032", "cve_desc": "An out-of-bounds read in the BGP daemon of FRRouting FRR before 8.4 may lead to a segmentation fault and denial of service. This occurs in bgp_capability_msg_parse in bgpd/bgp_packet.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-37032"}
{"idx": 211473, "project": "gdk-pixbuf", "commit_id": "4f0f465f991cd454d03189497f923eb40c170c22", "project_url": "http://git.gnome.org/browse/gdk-pixbuf", "commit_url": "http://git.gnome.org/browse/gdk-pixbuf/commit/?id=4f0f465f991cd454d03189497f923eb40c170c22", "commit_message": "Avoid an integer overflow in the xbm loader\n\nAt the same time, reject some silly input, such as negative\nwidth or height.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=672811", "target": 1, "func": "read_bitmap_file_data (FILE    *fstream,\n\t\t       guint   *width, \n\t\t       guint   *height,\n\t\t       guchar **data,\n\t\t       int     *x_hot, \n\t\t       int     *y_hot)\n{\n\tguchar *bits = NULL;\t\t/* working variable */\n\tchar line[MAX_SIZE];\t\t/* input line from file */\n\tint size;\t\t\t/* number of bytes of data */\n\tchar name_and_type[MAX_SIZE];\t/* an input line */\n\tchar *type;\t\t\t/* for parsing */\n\tint value;\t\t\t/* from an input line */\n\tint version10p;\t\t\t/* boolean, old format */\n\tint padding;\t\t\t/* to handle alignment */\n\tint bytes_per_line;\t\t/* per scanline of data */\n\tguint ww = 0;\t\t\t/* width */\n\tguint hh = 0;\t\t\t/* height */\n\tint hx = -1;\t\t\t/* x hotspot */\n\tint hy = -1;\t\t\t/* y hotspot */\n\n\t/* first time initialization */\n\tif (!initialized) {\n\t\tinit_hex_table ();\n\t}\n\n\t/* error cleanup and return macro */\n#define\tRETURN(code) { g_free (bits); return code; }\n\n\twhile (fgets (line, MAX_SIZE, fstream)) {\n\t\tif (strlen (line) == MAX_SIZE-1)\n\t\t\tRETURN (FALSE);\n\t\tif (sscanf (line,\"#define %s %d\",name_and_type,&value) == 2) {\n\t\t\tif (!(type = strrchr (name_and_type, '_')))\n\t\t\t\ttype = name_and_type;\n\t\t\telse {\n\t\t\t\ttype++;\n\t\t\t}\n\n\t\t\tif (!strcmp (\"width\", type))\n\t\t\t\tww = (unsigned int) value;\n\t\t\tif (!strcmp (\"height\", type))\n\t\t\t\thh = (unsigned int) value;\n\t\t\tif (!strcmp (\"hot\", type)) {\n\t\t\t\tif (type-- == name_and_type\n\t\t\t\t    || type-- == name_and_type)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!strcmp (\"x_hot\", type))\n\t\t\t\t\thx = value;\n\t\t\t\tif (!strcmp (\"y_hot\", type))\n\t\t\t\t\thy = value;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n    \n\t\tif (sscanf (line, \"static short %s = {\", name_and_type) == 1)\n\t\t\tversion10p = 1;\n\t\telse if (sscanf (line,\"static const unsigned char %s = {\",name_and_type) == 1)\n\t\t\tversion10p = 0;\n\t\telse if (sscanf (line,\"static unsigned char %s = {\",name_and_type) == 1)\n\t\t\tversion10p = 0;\n\t\telse if (sscanf (line, \"static const char %s = {\", name_and_type) == 1)\n\t\t\tversion10p = 0;\n\t\telse if (sscanf (line, \"static char %s = {\", name_and_type) == 1)\n\t\t\tversion10p = 0;\n\t\telse\n\t\t\tcontinue;\n\n\t\tif (!(type = strrchr (name_and_type, '_')))\n\t\t\ttype = name_and_type;\n\t\telse\n\t\t\ttype++;\n\n\t\tif (strcmp (\"bits[]\", type))\n\t\t\tcontinue;\n    \n\t\tif (!ww || !hh)\n\t\t\tRETURN (FALSE);\n\n\t\tif ((ww % 16) && ((ww % 16) < 9) && version10p)\n\t\t\tpadding = 1;\n\t\telse\n\t\t\tpadding = 0;\n\n\t\tbytes_per_line = (ww+7)/8 + padding;\n\n\t\tsize = bytes_per_line * hh;\n\t\tbits = g_malloc (size);\n\n\t\tif (version10p) {\n\t\t\tunsigned char *ptr;\n\t\t\tint bytes;\n\n\t\t\tfor (bytes = 0, ptr = bits; bytes < size; (bytes += 2)) {\n\t\t\t\tif ((value = next_int (fstream)) < 0)\n\t\t\t\t\tRETURN (FALSE);\n\t\t\t\t*(ptr++) = value;\n\t\t\t\tif (!padding || ((bytes+2) % bytes_per_line))\n\t\t\t\t\t*(ptr++) = value >> 8;\n\t\t\t}\n\t\t} else {\n\t\t\tunsigned char *ptr;\n\t\t\tint bytes;\n\n\t\t\tfor (bytes = 0, ptr = bits; bytes < size; bytes++, ptr++) {\n\t\t\t\tif ((value = next_int (fstream)) < 0) \n\t\t\t\t\tRETURN (FALSE);\n\t\t\t\t*ptr=value;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n\tif (!bits)\n\t\tRETURN (FALSE);\n\n\t*data = bits;\n\t*width = ww;\n\t*height = hh;\n\tif (x_hot)\n\t\t*x_hot = hx;\n\tif (y_hot)\n\t\t*y_hot = hy;\n\n\treturn TRUE;\n}", "func_hash": 243317071642584588963963288402776213734, "file_name": "io-xbm.c", "file_hash": 331454281510719411806234723168878735596, "cwe": ["CWE-189"], "cve": "CVE-2012-2370", "cve_desc": "Multiple integer overflows in the read_bitmap_file_data function in io-xbm.c in gdk-pixbuf before 2.26.1 allow remote attackers to cause a denial of service (application crash) via a negative (1) height or (2) width in an XBM file, which triggers a heap-based buffer overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2012-2370"}
{"idx": 448584, "project": "gdk-pixbuf", "commit_id": "4f0f465f991cd454d03189497f923eb40c170c22", "project_url": "http://git.gnome.org/browse/gdk-pixbuf", "commit_url": "http://git.gnome.org/browse/gdk-pixbuf/commit/?id=4f0f465f991cd454d03189497f923eb40c170c22", "commit_message": "Avoid an integer overflow in the xbm loader\n\nAt the same time, reject some silly input, such as negative\nwidth or height.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=672811", "target": 0, "func": "read_bitmap_file_data (FILE    *fstream,\n\t\t       guint   *width, \n\t\t       guint   *height,\n\t\t       guchar **data,\n\t\t       int     *x_hot, \n\t\t       int     *y_hot)\n{\n\tguchar *bits = NULL;\t\t/* working variable */\n\tchar line[MAX_SIZE];\t\t/* input line from file */\n\tint size;\t\t\t/* number of bytes of data */\n\tchar name_and_type[MAX_SIZE];\t/* an input line */\n\tchar *type;\t\t\t/* for parsing */\n\tint value;\t\t\t/* from an input line */\n\tint version10p;\t\t\t/* boolean, old format */\n\tint padding;\t\t\t/* to handle alignment */\n\tint bytes_per_line;\t\t/* per scanline of data */\n\tguint ww = 0;\t\t\t/* width */\n\tguint hh = 0;\t\t\t/* height */\n\tint hx = -1;\t\t\t/* x hotspot */\n\tint hy = -1;\t\t\t/* y hotspot */\n\n\t/* first time initialization */\n\tif (!initialized) {\n\t\tinit_hex_table ();\n\t}\n\n\t/* error cleanup and return macro */\n#define\tRETURN(code) { g_free (bits); return code; }\n\n\twhile (fgets (line, MAX_SIZE, fstream)) {\n\t\tif (strlen (line) == MAX_SIZE-1)\n\t\t\tRETURN (FALSE);\n\t\tif (sscanf (line,\"#define %s %d\",name_and_type,&value) == 2) {\n\t\t\tif (!(type = strrchr (name_and_type, '_')))\n\t\t\t\ttype = name_and_type;\n\t\t\telse {\n\t\t\t\ttype++;\n\t\t\t}\n\n\t\t\tif (!strcmp (\"width\", type)) {\n                                if (value <= 0)\n                                        RETURN (FALSE);\n\t\t\t\tww = (unsigned int) value;\n                        }\n\t\t\tif (!strcmp (\"height\", type)) {\n                                if (value <= 0)\n                                        RETURN (FALSE);\n\t\t\t\thh = (unsigned int) value;\n                        }\n\t\t\tif (!strcmp (\"hot\", type)) {\n\t\t\t\tif (type-- == name_and_type\n\t\t\t\t    || type-- == name_and_type)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!strcmp (\"x_hot\", type))\n\t\t\t\t\thx = value;\n\t\t\t\tif (!strcmp (\"y_hot\", type))\n\t\t\t\t\thy = value;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n    \n\t\tif (sscanf (line, \"static short %s = {\", name_and_type) == 1)\n\t\t\tversion10p = 1;\n\t\telse if (sscanf (line,\"static const unsigned char %s = {\",name_and_type) == 1)\n\t\t\tversion10p = 0;\n\t\telse if (sscanf (line,\"static unsigned char %s = {\",name_and_type) == 1)\n\t\t\tversion10p = 0;\n\t\telse if (sscanf (line, \"static const char %s = {\", name_and_type) == 1)\n\t\t\tversion10p = 0;\n\t\telse if (sscanf (line, \"static char %s = {\", name_and_type) == 1)\n\t\t\tversion10p = 0;\n\t\telse\n\t\t\tcontinue;\n\n\t\tif (!(type = strrchr (name_and_type, '_')))\n\t\t\ttype = name_and_type;\n\t\telse\n\t\t\ttype++;\n\n\t\tif (strcmp (\"bits[]\", type))\n\t\t\tcontinue;\n    \n\t\tif (!ww || !hh)\n\t\t\tRETURN (FALSE);\n\n\t\tif ((ww % 16) && ((ww % 16) < 9) && version10p)\n\t\t\tpadding = 1;\n\t\telse\n\t\t\tpadding = 0;\n\n\t\tbytes_per_line = (ww+7)/8 + padding;\n\n\t\tsize = bytes_per_line * hh;\n                if (size / bytes_per_line != hh) /* overflow */\n                        RETURN (FALSE);\n\t\tbits = g_malloc (size);\n\n\t\tif (version10p) {\n\t\t\tunsigned char *ptr;\n\t\t\tint bytes;\n\n\t\t\tfor (bytes = 0, ptr = bits; bytes < size; (bytes += 2)) {\n\t\t\t\tif ((value = next_int (fstream)) < 0)\n\t\t\t\t\tRETURN (FALSE);\n\t\t\t\t*(ptr++) = value;\n\t\t\t\tif (!padding || ((bytes+2) % bytes_per_line))\n\t\t\t\t\t*(ptr++) = value >> 8;\n\t\t\t}\n\t\t} else {\n\t\t\tunsigned char *ptr;\n\t\t\tint bytes;\n\n\t\t\tfor (bytes = 0, ptr = bits; bytes < size; bytes++, ptr++) {\n\t\t\t\tif ((value = next_int (fstream)) < 0) \n\t\t\t\t\tRETURN (FALSE);\n\t\t\t\t*ptr=value;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n\tif (!bits)\n\t\tRETURN (FALSE);\n\n\t*data = bits;\n\t*width = ww;\n\t*height = hh;\n\tif (x_hot)\n\t\t*x_hot = hx;\n\tif (y_hot)\n\t\t*y_hot = hy;\n\n\treturn TRUE;\n}", "func_hash": 77339480051751804955061545708983319434, "file_name": "io-xbm.c", "file_hash": 72320400164573844701740100175045869458, "cwe": ["CWE-189"], "cve": "CVE-2012-2370", "cve_desc": "Multiple integer overflows in the read_bitmap_file_data function in io-xbm.c in gdk-pixbuf before 2.26.1 allow remote attackers to cause a denial of service (application crash) via a negative (1) height or (2) width in an XBM file, which triggers a heap-based buffer overflow.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2012-2370"}
{"idx": 211506, "project": "zlib", "commit_id": "eff308af425b67093bab25f80f1ae950166bece1", "project_url": "https://github.com/madler/zlib", "commit_url": "https://github.com/madler/zlib/commit/eff308af425b67093bab25f80f1ae950166bece1", "commit_message": "Fix a bug when getting a gzip header extra field with inflate().\n\nIf the extra field was larger than the space the user provided with\ninflateGetHeader(), and if multiple calls of inflate() delivered\nthe extra header data, then there could be a buffer overflow of the\nprovided space. This commit assures that provided space is not\nexceeded.", "target": 1, "func": "int ZEXPORT inflate(strm, flush)\nz_streamp strm;\nint flush;\n{\n    struct inflate_state FAR *state;\n    z_const unsigned char FAR *next;    /* next input */\n    unsigned char FAR *put;     /* next output */\n    unsigned have, left;        /* available input and output */\n    unsigned long hold;         /* bit buffer */\n    unsigned bits;              /* bits in bit buffer */\n    unsigned in, out;           /* save starting available input and output */\n    unsigned copy;              /* number of stored or match bytes to copy */\n    unsigned char FAR *from;    /* where to copy match bytes from */\n    code here;                  /* current decoding table entry */\n    code last;                  /* parent table entry */\n    unsigned len;               /* length to copy for repeats, bits to drop */\n    int ret;                    /* return code */\n#ifdef GUNZIP\n    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */\n#endif\n    static const unsigned short order[19] = /* permutation of code lengths */\n        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};\n\n    if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||\n        (strm->next_in == Z_NULL && strm->avail_in != 0))\n        return Z_STREAM_ERROR;\n\n    state = (struct inflate_state FAR *)strm->state;\n    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */\n    LOAD();\n    in = have;\n    out = left;\n    ret = Z_OK;\n    for (;;)\n        switch (state->mode) {\n        case HEAD:\n            if (state->wrap == 0) {\n                state->mode = TYPEDO;\n                break;\n            }\n            NEEDBITS(16);\n#ifdef GUNZIP\n            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */\n                if (state->wbits == 0)\n                    state->wbits = 15;\n                state->check = crc32(0L, Z_NULL, 0);\n                CRC2(state->check, hold);\n                INITBITS();\n                state->mode = FLAGS;\n                break;\n            }\n            if (state->head != Z_NULL)\n                state->head->done = -1;\n            if (!(state->wrap & 1) ||   /* check if zlib header allowed */\n#else\n            if (\n#endif\n                ((BITS(8) << 8) + (hold >> 8)) % 31) {\n                strm->msg = (char *)\"incorrect header check\";\n                state->mode = BAD;\n                break;\n            }\n            if (BITS(4) != Z_DEFLATED) {\n                strm->msg = (char *)\"unknown compression method\";\n                state->mode = BAD;\n                break;\n            }\n            DROPBITS(4);\n            len = BITS(4) + 8;\n            if (state->wbits == 0)\n                state->wbits = len;\n            if (len > 15 || len > state->wbits) {\n                strm->msg = (char *)\"invalid window size\";\n                state->mode = BAD;\n                break;\n            }\n            state->dmax = 1U << len;\n            state->flags = 0;               /* indicate zlib header */\n            Tracev((stderr, \"inflate:   zlib header ok\\n\"));\n            strm->adler = state->check = adler32(0L, Z_NULL, 0);\n            state->mode = hold & 0x200 ? DICTID : TYPE;\n            INITBITS();\n            break;\n#ifdef GUNZIP\n        case FLAGS:\n            NEEDBITS(16);\n            state->flags = (int)(hold);\n            if ((state->flags & 0xff) != Z_DEFLATED) {\n                strm->msg = (char *)\"unknown compression method\";\n                state->mode = BAD;\n                break;\n            }\n            if (state->flags & 0xe000) {\n                strm->msg = (char *)\"unknown header flags set\";\n                state->mode = BAD;\n                break;\n            }\n            if (state->head != Z_NULL)\n                state->head->text = (int)((hold >> 8) & 1);\n            if ((state->flags & 0x0200) && (state->wrap & 4))\n                CRC2(state->check, hold);\n            INITBITS();\n            state->mode = TIME;\n                /* fallthrough */\n        case TIME:\n            NEEDBITS(32);\n            if (state->head != Z_NULL)\n                state->head->time = hold;\n            if ((state->flags & 0x0200) && (state->wrap & 4))\n                CRC4(state->check, hold);\n            INITBITS();\n            state->mode = OS;\n                /* fallthrough */\n        case OS:\n            NEEDBITS(16);\n            if (state->head != Z_NULL) {\n                state->head->xflags = (int)(hold & 0xff);\n                state->head->os = (int)(hold >> 8);\n            }\n            if ((state->flags & 0x0200) && (state->wrap & 4))\n                CRC2(state->check, hold);\n            INITBITS();\n            state->mode = EXLEN;\n                /* fallthrough */\n        case EXLEN:\n            if (state->flags & 0x0400) {\n                NEEDBITS(16);\n                state->length = (unsigned)(hold);\n                if (state->head != Z_NULL)\n                    state->head->extra_len = (unsigned)hold;\n                if ((state->flags & 0x0200) && (state->wrap & 4))\n                    CRC2(state->check, hold);\n                INITBITS();\n            }\n            else if (state->head != Z_NULL)\n                state->head->extra = Z_NULL;\n            state->mode = EXTRA;\n                /* fallthrough */\n        case EXTRA:\n            if (state->flags & 0x0400) {\n                copy = state->length;\n                if (copy > have) copy = have;\n                if (copy) {\n                    if (state->head != Z_NULL &&\n                        state->head->extra != Z_NULL) {\n                        len = state->head->extra_len - state->length;\n                        zmemcpy(state->head->extra + len, next,\n                                len + copy > state->head->extra_max ?\n                                state->head->extra_max - len : copy);\n                    }\n                    if ((state->flags & 0x0200) && (state->wrap & 4))\n                        state->check = crc32(state->check, next, copy);\n                    have -= copy;\n                    next += copy;\n                    state->length -= copy;\n                }\n                if (state->length) goto inf_leave;\n            }\n            state->length = 0;\n            state->mode = NAME;\n                /* fallthrough */\n        case NAME:\n            if (state->flags & 0x0800) {\n                if (have == 0) goto inf_leave;\n                copy = 0;\n                do {\n                    len = (unsigned)(next[copy++]);\n                    if (state->head != Z_NULL &&\n                            state->head->name != Z_NULL &&\n                            state->length < state->head->name_max)\n                        state->head->name[state->length++] = (Bytef)len;\n                } while (len && copy < have);\n                if ((state->flags & 0x0200) && (state->wrap & 4))\n                    state->check = crc32(state->check, next, copy);\n                have -= copy;\n                next += copy;\n                if (len) goto inf_leave;\n            }\n            else if (state->head != Z_NULL)\n                state->head->name = Z_NULL;\n            state->length = 0;\n            state->mode = COMMENT;\n                /* fallthrough */\n        case COMMENT:\n            if (state->flags & 0x1000) {\n                if (have == 0) goto inf_leave;\n                copy = 0;\n                do {\n                    len = (unsigned)(next[copy++]);\n                    if (state->head != Z_NULL &&\n                            state->head->comment != Z_NULL &&\n                            state->length < state->head->comm_max)\n                        state->head->comment[state->length++] = (Bytef)len;\n                } while (len && copy < have);\n                if ((state->flags & 0x0200) && (state->wrap & 4))\n                    state->check = crc32(state->check, next, copy);\n                have -= copy;\n                next += copy;\n                if (len) goto inf_leave;\n            }\n            else if (state->head != Z_NULL)\n                state->head->comment = Z_NULL;\n            state->mode = HCRC;\n                /* fallthrough */\n        case HCRC:\n            if (state->flags & 0x0200) {\n                NEEDBITS(16);\n                if ((state->wrap & 4) && hold != (state->check & 0xffff)) {\n                    strm->msg = (char *)\"header crc mismatch\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n            }\n            if (state->head != Z_NULL) {\n                state->head->hcrc = (int)((state->flags >> 9) & 1);\n                state->head->done = 1;\n            }\n            strm->adler = state->check = crc32(0L, Z_NULL, 0);\n            state->mode = TYPE;\n            break;\n#endif\n        case DICTID:\n            NEEDBITS(32);\n            strm->adler = state->check = ZSWAP32(hold);\n            INITBITS();\n            state->mode = DICT;\n                /* fallthrough */\n        case DICT:\n            if (state->havedict == 0) {\n                RESTORE();\n                return Z_NEED_DICT;\n            }\n            strm->adler = state->check = adler32(0L, Z_NULL, 0);\n            state->mode = TYPE;\n                /* fallthrough */\n        case TYPE:\n            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;\n                /* fallthrough */\n        case TYPEDO:\n            if (state->last) {\n                BYTEBITS();\n                state->mode = CHECK;\n                break;\n            }\n            NEEDBITS(3);\n            state->last = BITS(1);\n            DROPBITS(1);\n            switch (BITS(2)) {\n            case 0:                             /* stored block */\n                Tracev((stderr, \"inflate:     stored block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = STORED;\n                break;\n            case 1:                             /* fixed block */\n                fixedtables(state);\n                Tracev((stderr, \"inflate:     fixed codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = LEN_;             /* decode codes */\n                if (flush == Z_TREES) {\n                    DROPBITS(2);\n                    goto inf_leave;\n                }\n                break;\n            case 2:                             /* dynamic block */\n                Tracev((stderr, \"inflate:     dynamic codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = TABLE;\n                break;\n            case 3:\n                strm->msg = (char *)\"invalid block type\";\n                state->mode = BAD;\n            }\n            DROPBITS(2);\n            break;\n        case STORED:\n            BYTEBITS();                         /* go to byte boundary */\n            NEEDBITS(32);\n            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {\n                strm->msg = (char *)\"invalid stored block lengths\";\n                state->mode = BAD;\n                break;\n            }\n            state->length = (unsigned)hold & 0xffff;\n            Tracev((stderr, \"inflate:       stored length %u\\n\",\n                    state->length));\n            INITBITS();\n            state->mode = COPY_;\n            if (flush == Z_TREES) goto inf_leave;\n                /* fallthrough */\n        case COPY_:\n            state->mode = COPY;\n                /* fallthrough */\n        case COPY:\n            copy = state->length;\n            if (copy) {\n                if (copy > have) copy = have;\n                if (copy > left) copy = left;\n                if (copy == 0) goto inf_leave;\n                zmemcpy(put, next, copy);\n                have -= copy;\n                next += copy;\n                left -= copy;\n                put += copy;\n                state->length -= copy;\n                break;\n            }\n            Tracev((stderr, \"inflate:       stored end\\n\"));\n            state->mode = TYPE;\n            break;\n        case TABLE:\n            NEEDBITS(14);\n            state->nlen = BITS(5) + 257;\n            DROPBITS(5);\n            state->ndist = BITS(5) + 1;\n            DROPBITS(5);\n            state->ncode = BITS(4) + 4;\n            DROPBITS(4);\n#ifndef PKZIP_BUG_WORKAROUND\n            if (state->nlen > 286 || state->ndist > 30) {\n                strm->msg = (char *)\"too many length or distance symbols\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracev((stderr, \"inflate:       table sizes ok\\n\"));\n            state->have = 0;\n            state->mode = LENLENS;\n                /* fallthrough */\n        case LENLENS:\n            while (state->have < state->ncode) {\n                NEEDBITS(3);\n                state->lens[order[state->have++]] = (unsigned short)BITS(3);\n                DROPBITS(3);\n            }\n            while (state->have < 19)\n                state->lens[order[state->have++]] = 0;\n            state->next = state->codes;\n            state->lencode = (const code FAR *)(state->next);\n            state->lenbits = 7;\n            ret = inflate_table(CODES, state->lens, 19, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid code lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       code lengths ok\\n\"));\n            state->have = 0;\n            state->mode = CODELENS;\n                /* fallthrough */\n        case CODELENS:\n            while (state->have < state->nlen + state->ndist) {\n                for (;;) {\n                    here = state->lencode[BITS(state->lenbits)];\n                    if ((unsigned)(here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                if (here.val < 16) {\n                    DROPBITS(here.bits);\n                    state->lens[state->have++] = here.val;\n                }\n                else {\n                    if (here.val == 16) {\n                        NEEDBITS(here.bits + 2);\n                        DROPBITS(here.bits);\n                        if (state->have == 0) {\n                            strm->msg = (char *)\"invalid bit length repeat\";\n                            state->mode = BAD;\n                            break;\n                        }\n                        len = state->lens[state->have - 1];\n                        copy = 3 + BITS(2);\n                        DROPBITS(2);\n                    }\n                    else if (here.val == 17) {\n                        NEEDBITS(here.bits + 3);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 3 + BITS(3);\n                        DROPBITS(3);\n                    }\n                    else {\n                        NEEDBITS(here.bits + 7);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 11 + BITS(7);\n                        DROPBITS(7);\n                    }\n                    if (state->have + copy > state->nlen + state->ndist) {\n                        strm->msg = (char *)\"invalid bit length repeat\";\n                        state->mode = BAD;\n                        break;\n                    }\n                    while (copy--)\n                        state->lens[state->have++] = (unsigned short)len;\n                }\n            }\n\n            /* handle error breaks in while */\n            if (state->mode == BAD) break;\n\n            /* check for end-of-block code (better have one) */\n            if (state->lens[256] == 0) {\n                strm->msg = (char *)\"invalid code -- missing end-of-block\";\n                state->mode = BAD;\n                break;\n            }\n\n            /* build code tables -- note: do not change the lenbits or distbits\n               values here (9 and 6) without reading the comments in inftrees.h\n               concerning the ENOUGH constants, which depend on those values */\n            state->next = state->codes;\n            state->lencode = (const code FAR *)(state->next);\n            state->lenbits = 9;\n            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid literal/lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            state->distcode = (const code FAR *)(state->next);\n            state->distbits = 6;\n            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,\n                            &(state->next), &(state->distbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid distances set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       codes ok\\n\"));\n            state->mode = LEN_;\n            if (flush == Z_TREES) goto inf_leave;\n                /* fallthrough */\n        case LEN_:\n            state->mode = LEN;\n                /* fallthrough */\n        case LEN:\n            if (have >= 6 && left >= 258) {\n                RESTORE();\n                inflate_fast(strm, out);\n                LOAD();\n                if (state->mode == TYPE)\n                    state->back = -1;\n                break;\n            }\n            state->back = 0;\n            for (;;) {\n                here = state->lencode[BITS(state->lenbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if (here.op && (here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->lencode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n                state->back += last.bits;\n            }\n            DROPBITS(here.bits);\n            state->back += here.bits;\n            state->length = (unsigned)here.val;\n            if ((int)(here.op) == 0) {\n                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n                        \"inflate:         literal '%c'\\n\" :\n                        \"inflate:         literal 0x%02x\\n\", here.val));\n                state->mode = LIT;\n                break;\n            }\n            if (here.op & 32) {\n                Tracevv((stderr, \"inflate:         end of block\\n\"));\n                state->back = -1;\n                state->mode = TYPE;\n                break;\n            }\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid literal/length code\";\n                state->mode = BAD;\n                break;\n            }\n            state->extra = (unsigned)(here.op) & 15;\n            state->mode = LENEXT;\n                /* fallthrough */\n        case LENEXT:\n            if (state->extra) {\n                NEEDBITS(state->extra);\n                state->length += BITS(state->extra);\n                DROPBITS(state->extra);\n                state->back += state->extra;\n            }\n            Tracevv((stderr, \"inflate:         length %u\\n\", state->length));\n            state->was = state->length;\n            state->mode = DIST;\n                /* fallthrough */\n        case DIST:\n            for (;;) {\n                here = state->distcode[BITS(state->distbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if ((here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->distcode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n                state->back += last.bits;\n            }\n            DROPBITS(here.bits);\n            state->back += here.bits;\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid distance code\";\n                state->mode = BAD;\n                break;\n            }\n            state->offset = (unsigned)here.val;\n            state->extra = (unsigned)(here.op) & 15;\n            state->mode = DISTEXT;\n                /* fallthrough */\n        case DISTEXT:\n            if (state->extra) {\n                NEEDBITS(state->extra);\n                state->offset += BITS(state->extra);\n                DROPBITS(state->extra);\n                state->back += state->extra;\n            }\n#ifdef INFLATE_STRICT\n            if (state->offset > state->dmax) {\n                strm->msg = (char *)\"invalid distance too far back\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracevv((stderr, \"inflate:         distance %u\\n\", state->offset));\n            state->mode = MATCH;\n                /* fallthrough */\n        case MATCH:\n            if (left == 0) goto inf_leave;\n            copy = out - left;\n            if (state->offset > copy) {         /* copy from window */\n                copy = state->offset - copy;\n                if (copy > state->whave) {\n                    if (state->sane) {\n                        strm->msg = (char *)\"invalid distance too far back\";\n                        state->mode = BAD;\n                        break;\n                    }\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n                    Trace((stderr, \"inflate.c too far\\n\"));\n                    copy -= state->whave;\n                    if (copy > state->length) copy = state->length;\n                    if (copy > left) copy = left;\n                    left -= copy;\n                    state->length -= copy;\n                    do {\n                        *put++ = 0;\n                    } while (--copy);\n                    if (state->length == 0) state->mode = LEN;\n                    break;\n#endif\n                }\n                if (copy > state->wnext) {\n                    copy -= state->wnext;\n                    from = state->window + (state->wsize - copy);\n                }\n                else\n                    from = state->window + (state->wnext - copy);\n                if (copy > state->length) copy = state->length;\n            }\n            else {                              /* copy from output */\n                from = put - state->offset;\n                copy = state->length;\n            }\n            if (copy > left) copy = left;\n            left -= copy;\n            state->length -= copy;\n            do {\n                *put++ = *from++;\n            } while (--copy);\n            if (state->length == 0) state->mode = LEN;\n            break;\n        case LIT:\n            if (left == 0) goto inf_leave;\n            *put++ = (unsigned char)(state->length);\n            left--;\n            state->mode = LEN;\n            break;\n        case CHECK:\n            if (state->wrap) {\n                NEEDBITS(32);\n                out -= left;\n                strm->total_out += out;\n                state->total += out;\n                if ((state->wrap & 4) && out)\n                    strm->adler = state->check =\n                        UPDATE_CHECK(state->check, put - out, out);\n                out = left;\n                if ((state->wrap & 4) && (\n#ifdef GUNZIP\n                     state->flags ? hold :\n#endif\n                     ZSWAP32(hold)) != state->check) {\n                    strm->msg = (char *)\"incorrect data check\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n                Tracev((stderr, \"inflate:   check matches trailer\\n\"));\n            }\n#ifdef GUNZIP\n            state->mode = LENGTH;\n                /* fallthrough */\n        case LENGTH:\n            if (state->wrap && state->flags) {\n                NEEDBITS(32);\n                if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) {\n                    strm->msg = (char *)\"incorrect length check\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n                Tracev((stderr, \"inflate:   length matches trailer\\n\"));\n            }\n#endif\n            state->mode = DONE;\n                /* fallthrough */\n        case DONE:\n            ret = Z_STREAM_END;\n            goto inf_leave;\n        case BAD:\n            ret = Z_DATA_ERROR;\n            goto inf_leave;\n        case MEM:\n            return Z_MEM_ERROR;\n        case SYNC:\n                /* fallthrough */\n        default:\n            return Z_STREAM_ERROR;\n        }\n\n    /*\n       Return from inflate(), updating the total counts and the check value.\n       If there was no progress during the inflate() call, return a buffer\n       error.  Call updatewindow() to create and/or update the window state.\n       Note: a memory error from inflate() is non-recoverable.\n     */\n  inf_leave:\n    RESTORE();\n    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&\n            (state->mode < CHECK || flush != Z_FINISH)))\n        if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {\n            state->mode = MEM;\n            return Z_MEM_ERROR;\n        }\n    in -= strm->avail_in;\n    out -= strm->avail_out;\n    strm->total_in += in;\n    strm->total_out += out;\n    state->total += out;\n    if ((state->wrap & 4) && out)\n        strm->adler = state->check =\n            UPDATE_CHECK(state->check, strm->next_out - out, out);\n    strm->data_type = (int)state->bits + (state->last ? 64 : 0) +\n                      (state->mode == TYPE ? 128 : 0) +\n                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);\n    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)\n        ret = Z_BUF_ERROR;\n    return ret;\n}", "func_hash": 308042126203552622330885717948323954753, "file_name": "inflate.c", "file_hash": 13307216410875362203864420162564887753, "cwe": ["CWE-787"], "cve": "CVE-2022-37434", "cve_desc": "zlib through 1.2.12 has a heap-based buffer over-read or buffer overflow in inflate in inflate.c via a large gzip header extra field. NOTE: only applications that call inflateGetHeader are affected. Some common applications bundle the affected zlib source code but may be unable to call inflateGetHeader (e.g., see the nodejs/node reference).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-37434"}
{"idx": 448912, "project": "zlib", "commit_id": "eff308af425b67093bab25f80f1ae950166bece1", "project_url": "https://github.com/madler/zlib", "commit_url": "https://github.com/madler/zlib/commit/eff308af425b67093bab25f80f1ae950166bece1", "commit_message": "Fix a bug when getting a gzip header extra field with inflate().\n\nIf the extra field was larger than the space the user provided with\ninflateGetHeader(), and if multiple calls of inflate() delivered\nthe extra header data, then there could be a buffer overflow of the\nprovided space. This commit assures that provided space is not\nexceeded.", "target": 0, "func": "int ZEXPORT inflate(strm, flush)\nz_streamp strm;\nint flush;\n{\n    struct inflate_state FAR *state;\n    z_const unsigned char FAR *next;    /* next input */\n    unsigned char FAR *put;     /* next output */\n    unsigned have, left;        /* available input and output */\n    unsigned long hold;         /* bit buffer */\n    unsigned bits;              /* bits in bit buffer */\n    unsigned in, out;           /* save starting available input and output */\n    unsigned copy;              /* number of stored or match bytes to copy */\n    unsigned char FAR *from;    /* where to copy match bytes from */\n    code here;                  /* current decoding table entry */\n    code last;                  /* parent table entry */\n    unsigned len;               /* length to copy for repeats, bits to drop */\n    int ret;                    /* return code */\n#ifdef GUNZIP\n    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */\n#endif\n    static const unsigned short order[19] = /* permutation of code lengths */\n        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};\n\n    if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||\n        (strm->next_in == Z_NULL && strm->avail_in != 0))\n        return Z_STREAM_ERROR;\n\n    state = (struct inflate_state FAR *)strm->state;\n    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */\n    LOAD();\n    in = have;\n    out = left;\n    ret = Z_OK;\n    for (;;)\n        switch (state->mode) {\n        case HEAD:\n            if (state->wrap == 0) {\n                state->mode = TYPEDO;\n                break;\n            }\n            NEEDBITS(16);\n#ifdef GUNZIP\n            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */\n                if (state->wbits == 0)\n                    state->wbits = 15;\n                state->check = crc32(0L, Z_NULL, 0);\n                CRC2(state->check, hold);\n                INITBITS();\n                state->mode = FLAGS;\n                break;\n            }\n            if (state->head != Z_NULL)\n                state->head->done = -1;\n            if (!(state->wrap & 1) ||   /* check if zlib header allowed */\n#else\n            if (\n#endif\n                ((BITS(8) << 8) + (hold >> 8)) % 31) {\n                strm->msg = (char *)\"incorrect header check\";\n                state->mode = BAD;\n                break;\n            }\n            if (BITS(4) != Z_DEFLATED) {\n                strm->msg = (char *)\"unknown compression method\";\n                state->mode = BAD;\n                break;\n            }\n            DROPBITS(4);\n            len = BITS(4) + 8;\n            if (state->wbits == 0)\n                state->wbits = len;\n            if (len > 15 || len > state->wbits) {\n                strm->msg = (char *)\"invalid window size\";\n                state->mode = BAD;\n                break;\n            }\n            state->dmax = 1U << len;\n            state->flags = 0;               /* indicate zlib header */\n            Tracev((stderr, \"inflate:   zlib header ok\\n\"));\n            strm->adler = state->check = adler32(0L, Z_NULL, 0);\n            state->mode = hold & 0x200 ? DICTID : TYPE;\n            INITBITS();\n            break;\n#ifdef GUNZIP\n        case FLAGS:\n            NEEDBITS(16);\n            state->flags = (int)(hold);\n            if ((state->flags & 0xff) != Z_DEFLATED) {\n                strm->msg = (char *)\"unknown compression method\";\n                state->mode = BAD;\n                break;\n            }\n            if (state->flags & 0xe000) {\n                strm->msg = (char *)\"unknown header flags set\";\n                state->mode = BAD;\n                break;\n            }\n            if (state->head != Z_NULL)\n                state->head->text = (int)((hold >> 8) & 1);\n            if ((state->flags & 0x0200) && (state->wrap & 4))\n                CRC2(state->check, hold);\n            INITBITS();\n            state->mode = TIME;\n                /* fallthrough */\n        case TIME:\n            NEEDBITS(32);\n            if (state->head != Z_NULL)\n                state->head->time = hold;\n            if ((state->flags & 0x0200) && (state->wrap & 4))\n                CRC4(state->check, hold);\n            INITBITS();\n            state->mode = OS;\n                /* fallthrough */\n        case OS:\n            NEEDBITS(16);\n            if (state->head != Z_NULL) {\n                state->head->xflags = (int)(hold & 0xff);\n                state->head->os = (int)(hold >> 8);\n            }\n            if ((state->flags & 0x0200) && (state->wrap & 4))\n                CRC2(state->check, hold);\n            INITBITS();\n            state->mode = EXLEN;\n                /* fallthrough */\n        case EXLEN:\n            if (state->flags & 0x0400) {\n                NEEDBITS(16);\n                state->length = (unsigned)(hold);\n                if (state->head != Z_NULL)\n                    state->head->extra_len = (unsigned)hold;\n                if ((state->flags & 0x0200) && (state->wrap & 4))\n                    CRC2(state->check, hold);\n                INITBITS();\n            }\n            else if (state->head != Z_NULL)\n                state->head->extra = Z_NULL;\n            state->mode = EXTRA;\n                /* fallthrough */\n        case EXTRA:\n            if (state->flags & 0x0400) {\n                copy = state->length;\n                if (copy > have) copy = have;\n                if (copy) {\n                    len = state->head->extra_len - state->length;\n                    if (state->head != Z_NULL &&\n                        state->head->extra != Z_NULL &&\n                        len < state->head->extra_max) {\n                        zmemcpy(state->head->extra + len, next,\n                                len + copy > state->head->extra_max ?\n                                state->head->extra_max - len : copy);\n                    }\n                    if ((state->flags & 0x0200) && (state->wrap & 4))\n                        state->check = crc32(state->check, next, copy);\n                    have -= copy;\n                    next += copy;\n                    state->length -= copy;\n                }\n                if (state->length) goto inf_leave;\n            }\n            state->length = 0;\n            state->mode = NAME;\n                /* fallthrough */\n        case NAME:\n            if (state->flags & 0x0800) {\n                if (have == 0) goto inf_leave;\n                copy = 0;\n                do {\n                    len = (unsigned)(next[copy++]);\n                    if (state->head != Z_NULL &&\n                            state->head->name != Z_NULL &&\n                            state->length < state->head->name_max)\n                        state->head->name[state->length++] = (Bytef)len;\n                } while (len && copy < have);\n                if ((state->flags & 0x0200) && (state->wrap & 4))\n                    state->check = crc32(state->check, next, copy);\n                have -= copy;\n                next += copy;\n                if (len) goto inf_leave;\n            }\n            else if (state->head != Z_NULL)\n                state->head->name = Z_NULL;\n            state->length = 0;\n            state->mode = COMMENT;\n                /* fallthrough */\n        case COMMENT:\n            if (state->flags & 0x1000) {\n                if (have == 0) goto inf_leave;\n                copy = 0;\n                do {\n                    len = (unsigned)(next[copy++]);\n                    if (state->head != Z_NULL &&\n                            state->head->comment != Z_NULL &&\n                            state->length < state->head->comm_max)\n                        state->head->comment[state->length++] = (Bytef)len;\n                } while (len && copy < have);\n                if ((state->flags & 0x0200) && (state->wrap & 4))\n                    state->check = crc32(state->check, next, copy);\n                have -= copy;\n                next += copy;\n                if (len) goto inf_leave;\n            }\n            else if (state->head != Z_NULL)\n                state->head->comment = Z_NULL;\n            state->mode = HCRC;\n                /* fallthrough */\n        case HCRC:\n            if (state->flags & 0x0200) {\n                NEEDBITS(16);\n                if ((state->wrap & 4) && hold != (state->check & 0xffff)) {\n                    strm->msg = (char *)\"header crc mismatch\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n            }\n            if (state->head != Z_NULL) {\n                state->head->hcrc = (int)((state->flags >> 9) & 1);\n                state->head->done = 1;\n            }\n            strm->adler = state->check = crc32(0L, Z_NULL, 0);\n            state->mode = TYPE;\n            break;\n#endif\n        case DICTID:\n            NEEDBITS(32);\n            strm->adler = state->check = ZSWAP32(hold);\n            INITBITS();\n            state->mode = DICT;\n                /* fallthrough */\n        case DICT:\n            if (state->havedict == 0) {\n                RESTORE();\n                return Z_NEED_DICT;\n            }\n            strm->adler = state->check = adler32(0L, Z_NULL, 0);\n            state->mode = TYPE;\n                /* fallthrough */\n        case TYPE:\n            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;\n                /* fallthrough */\n        case TYPEDO:\n            if (state->last) {\n                BYTEBITS();\n                state->mode = CHECK;\n                break;\n            }\n            NEEDBITS(3);\n            state->last = BITS(1);\n            DROPBITS(1);\n            switch (BITS(2)) {\n            case 0:                             /* stored block */\n                Tracev((stderr, \"inflate:     stored block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = STORED;\n                break;\n            case 1:                             /* fixed block */\n                fixedtables(state);\n                Tracev((stderr, \"inflate:     fixed codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = LEN_;             /* decode codes */\n                if (flush == Z_TREES) {\n                    DROPBITS(2);\n                    goto inf_leave;\n                }\n                break;\n            case 2:                             /* dynamic block */\n                Tracev((stderr, \"inflate:     dynamic codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = TABLE;\n                break;\n            case 3:\n                strm->msg = (char *)\"invalid block type\";\n                state->mode = BAD;\n            }\n            DROPBITS(2);\n            break;\n        case STORED:\n            BYTEBITS();                         /* go to byte boundary */\n            NEEDBITS(32);\n            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {\n                strm->msg = (char *)\"invalid stored block lengths\";\n                state->mode = BAD;\n                break;\n            }\n            state->length = (unsigned)hold & 0xffff;\n            Tracev((stderr, \"inflate:       stored length %u\\n\",\n                    state->length));\n            INITBITS();\n            state->mode = COPY_;\n            if (flush == Z_TREES) goto inf_leave;\n                /* fallthrough */\n        case COPY_:\n            state->mode = COPY;\n                /* fallthrough */\n        case COPY:\n            copy = state->length;\n            if (copy) {\n                if (copy > have) copy = have;\n                if (copy > left) copy = left;\n                if (copy == 0) goto inf_leave;\n                zmemcpy(put, next, copy);\n                have -= copy;\n                next += copy;\n                left -= copy;\n                put += copy;\n                state->length -= copy;\n                break;\n            }\n            Tracev((stderr, \"inflate:       stored end\\n\"));\n            state->mode = TYPE;\n            break;\n        case TABLE:\n            NEEDBITS(14);\n            state->nlen = BITS(5) + 257;\n            DROPBITS(5);\n            state->ndist = BITS(5) + 1;\n            DROPBITS(5);\n            state->ncode = BITS(4) + 4;\n            DROPBITS(4);\n#ifndef PKZIP_BUG_WORKAROUND\n            if (state->nlen > 286 || state->ndist > 30) {\n                strm->msg = (char *)\"too many length or distance symbols\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracev((stderr, \"inflate:       table sizes ok\\n\"));\n            state->have = 0;\n            state->mode = LENLENS;\n                /* fallthrough */\n        case LENLENS:\n            while (state->have < state->ncode) {\n                NEEDBITS(3);\n                state->lens[order[state->have++]] = (unsigned short)BITS(3);\n                DROPBITS(3);\n            }\n            while (state->have < 19)\n                state->lens[order[state->have++]] = 0;\n            state->next = state->codes;\n            state->lencode = (const code FAR *)(state->next);\n            state->lenbits = 7;\n            ret = inflate_table(CODES, state->lens, 19, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid code lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       code lengths ok\\n\"));\n            state->have = 0;\n            state->mode = CODELENS;\n                /* fallthrough */\n        case CODELENS:\n            while (state->have < state->nlen + state->ndist) {\n                for (;;) {\n                    here = state->lencode[BITS(state->lenbits)];\n                    if ((unsigned)(here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                if (here.val < 16) {\n                    DROPBITS(here.bits);\n                    state->lens[state->have++] = here.val;\n                }\n                else {\n                    if (here.val == 16) {\n                        NEEDBITS(here.bits + 2);\n                        DROPBITS(here.bits);\n                        if (state->have == 0) {\n                            strm->msg = (char *)\"invalid bit length repeat\";\n                            state->mode = BAD;\n                            break;\n                        }\n                        len = state->lens[state->have - 1];\n                        copy = 3 + BITS(2);\n                        DROPBITS(2);\n                    }\n                    else if (here.val == 17) {\n                        NEEDBITS(here.bits + 3);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 3 + BITS(3);\n                        DROPBITS(3);\n                    }\n                    else {\n                        NEEDBITS(here.bits + 7);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 11 + BITS(7);\n                        DROPBITS(7);\n                    }\n                    if (state->have + copy > state->nlen + state->ndist) {\n                        strm->msg = (char *)\"invalid bit length repeat\";\n                        state->mode = BAD;\n                        break;\n                    }\n                    while (copy--)\n                        state->lens[state->have++] = (unsigned short)len;\n                }\n            }\n\n            /* handle error breaks in while */\n            if (state->mode == BAD) break;\n\n            /* check for end-of-block code (better have one) */\n            if (state->lens[256] == 0) {\n                strm->msg = (char *)\"invalid code -- missing end-of-block\";\n                state->mode = BAD;\n                break;\n            }\n\n            /* build code tables -- note: do not change the lenbits or distbits\n               values here (9 and 6) without reading the comments in inftrees.h\n               concerning the ENOUGH constants, which depend on those values */\n            state->next = state->codes;\n            state->lencode = (const code FAR *)(state->next);\n            state->lenbits = 9;\n            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid literal/lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            state->distcode = (const code FAR *)(state->next);\n            state->distbits = 6;\n            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,\n                            &(state->next), &(state->distbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid distances set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       codes ok\\n\"));\n            state->mode = LEN_;\n            if (flush == Z_TREES) goto inf_leave;\n                /* fallthrough */\n        case LEN_:\n            state->mode = LEN;\n                /* fallthrough */\n        case LEN:\n            if (have >= 6 && left >= 258) {\n                RESTORE();\n                inflate_fast(strm, out);\n                LOAD();\n                if (state->mode == TYPE)\n                    state->back = -1;\n                break;\n            }\n            state->back = 0;\n            for (;;) {\n                here = state->lencode[BITS(state->lenbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if (here.op && (here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->lencode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n                state->back += last.bits;\n            }\n            DROPBITS(here.bits);\n            state->back += here.bits;\n            state->length = (unsigned)here.val;\n            if ((int)(here.op) == 0) {\n                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n                        \"inflate:         literal '%c'\\n\" :\n                        \"inflate:         literal 0x%02x\\n\", here.val));\n                state->mode = LIT;\n                break;\n            }\n            if (here.op & 32) {\n                Tracevv((stderr, \"inflate:         end of block\\n\"));\n                state->back = -1;\n                state->mode = TYPE;\n                break;\n            }\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid literal/length code\";\n                state->mode = BAD;\n                break;\n            }\n            state->extra = (unsigned)(here.op) & 15;\n            state->mode = LENEXT;\n                /* fallthrough */\n        case LENEXT:\n            if (state->extra) {\n                NEEDBITS(state->extra);\n                state->length += BITS(state->extra);\n                DROPBITS(state->extra);\n                state->back += state->extra;\n            }\n            Tracevv((stderr, \"inflate:         length %u\\n\", state->length));\n            state->was = state->length;\n            state->mode = DIST;\n                /* fallthrough */\n        case DIST:\n            for (;;) {\n                here = state->distcode[BITS(state->distbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if ((here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->distcode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n                state->back += last.bits;\n            }\n            DROPBITS(here.bits);\n            state->back += here.bits;\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid distance code\";\n                state->mode = BAD;\n                break;\n            }\n            state->offset = (unsigned)here.val;\n            state->extra = (unsigned)(here.op) & 15;\n            state->mode = DISTEXT;\n                /* fallthrough */\n        case DISTEXT:\n            if (state->extra) {\n                NEEDBITS(state->extra);\n                state->offset += BITS(state->extra);\n                DROPBITS(state->extra);\n                state->back += state->extra;\n            }\n#ifdef INFLATE_STRICT\n            if (state->offset > state->dmax) {\n                strm->msg = (char *)\"invalid distance too far back\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracevv((stderr, \"inflate:         distance %u\\n\", state->offset));\n            state->mode = MATCH;\n                /* fallthrough */\n        case MATCH:\n            if (left == 0) goto inf_leave;\n            copy = out - left;\n            if (state->offset > copy) {         /* copy from window */\n                copy = state->offset - copy;\n                if (copy > state->whave) {\n                    if (state->sane) {\n                        strm->msg = (char *)\"invalid distance too far back\";\n                        state->mode = BAD;\n                        break;\n                    }\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n                    Trace((stderr, \"inflate.c too far\\n\"));\n                    copy -= state->whave;\n                    if (copy > state->length) copy = state->length;\n                    if (copy > left) copy = left;\n                    left -= copy;\n                    state->length -= copy;\n                    do {\n                        *put++ = 0;\n                    } while (--copy);\n                    if (state->length == 0) state->mode = LEN;\n                    break;\n#endif\n                }\n                if (copy > state->wnext) {\n                    copy -= state->wnext;\n                    from = state->window + (state->wsize - copy);\n                }\n                else\n                    from = state->window + (state->wnext - copy);\n                if (copy > state->length) copy = state->length;\n            }\n            else {                              /* copy from output */\n                from = put - state->offset;\n                copy = state->length;\n            }\n            if (copy > left) copy = left;\n            left -= copy;\n            state->length -= copy;\n            do {\n                *put++ = *from++;\n            } while (--copy);\n            if (state->length == 0) state->mode = LEN;\n            break;\n        case LIT:\n            if (left == 0) goto inf_leave;\n            *put++ = (unsigned char)(state->length);\n            left--;\n            state->mode = LEN;\n            break;\n        case CHECK:\n            if (state->wrap) {\n                NEEDBITS(32);\n                out -= left;\n                strm->total_out += out;\n                state->total += out;\n                if ((state->wrap & 4) && out)\n                    strm->adler = state->check =\n                        UPDATE_CHECK(state->check, put - out, out);\n                out = left;\n                if ((state->wrap & 4) && (\n#ifdef GUNZIP\n                     state->flags ? hold :\n#endif\n                     ZSWAP32(hold)) != state->check) {\n                    strm->msg = (char *)\"incorrect data check\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n                Tracev((stderr, \"inflate:   check matches trailer\\n\"));\n            }\n#ifdef GUNZIP\n            state->mode = LENGTH;\n                /* fallthrough */\n        case LENGTH:\n            if (state->wrap && state->flags) {\n                NEEDBITS(32);\n                if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) {\n                    strm->msg = (char *)\"incorrect length check\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n                Tracev((stderr, \"inflate:   length matches trailer\\n\"));\n            }\n#endif\n            state->mode = DONE;\n                /* fallthrough */\n        case DONE:\n            ret = Z_STREAM_END;\n            goto inf_leave;\n        case BAD:\n            ret = Z_DATA_ERROR;\n            goto inf_leave;\n        case MEM:\n            return Z_MEM_ERROR;\n        case SYNC:\n                /* fallthrough */\n        default:\n            return Z_STREAM_ERROR;\n        }\n\n    /*\n       Return from inflate(), updating the total counts and the check value.\n       If there was no progress during the inflate() call, return a buffer\n       error.  Call updatewindow() to create and/or update the window state.\n       Note: a memory error from inflate() is non-recoverable.\n     */\n  inf_leave:\n    RESTORE();\n    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&\n            (state->mode < CHECK || flush != Z_FINISH)))\n        if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {\n            state->mode = MEM;\n            return Z_MEM_ERROR;\n        }\n    in -= strm->avail_in;\n    out -= strm->avail_out;\n    strm->total_in += in;\n    strm->total_out += out;\n    state->total += out;\n    if ((state->wrap & 4) && out)\n        strm->adler = state->check =\n            UPDATE_CHECK(state->check, strm->next_out - out, out);\n    strm->data_type = (int)state->bits + (state->last ? 64 : 0) +\n                      (state->mode == TYPE ? 128 : 0) +\n                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);\n    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)\n        ret = Z_BUF_ERROR;\n    return ret;\n}", "func_hash": 77680460964707773234667939079956613143, "file_name": "inflate.c", "file_hash": 53439547439920310595361050781327807541, "cwe": ["CWE-787"], "cve": "CVE-2022-37434", "cve_desc": "zlib through 1.2.12 has a heap-based buffer over-read or buffer overflow in inflate in inflate.c via a large gzip header extra field. NOTE: only applications that call inflateGetHeader are affected. Some common applications bundle the affected zlib source code but may be unable to call inflateGetHeader (e.g., see the nodejs/node reference).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-37434"}
{"idx": 211563, "project": "vim", "commit_id": "a062006b9de0b2947ab5fb376c6e67ef92a8cd69", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/a062006b9de0b2947ab5fb376c6e67ef92a8cd69", "commit_message": "patch 8.2.3610: crash when ModeChanged triggered too early\n\nProblem:    Crash when ModeChanged triggered too early.\nSolution:   Trigger ModeChanged after setting VIsual.", "target": 1, "func": "n_start_visual_mode(int c)\n{\n#ifdef FEAT_CONCEAL\n    int cursor_line_was_concealed = curwin->w_p_cole > 0\n\t\t\t\t\t\t&& conceal_cursor_line(curwin);\n#endif\n\n    VIsual_mode = c;\n    VIsual_active = TRUE;\n    VIsual_reselect = TRUE;\n    trigger_modechanged();\n\n    // Corner case: the 0 position in a tab may change when going into\n    // virtualedit.  Recalculate curwin->w_cursor to avoid bad highlighting.\n    if (c == Ctrl_V && (get_ve_flags() & VE_BLOCK) && gchar_cursor() == TAB)\n    {\n\tvalidate_virtcol();\n\tcoladvance(curwin->w_virtcol);\n    }\n    VIsual = curwin->w_cursor;\n\n#ifdef FEAT_FOLDING\n    foldAdjustVisual();\n#endif\n\n    setmouse();\n#ifdef FEAT_CONCEAL\n    // Check if redraw is needed after changing the state.\n    conceal_check_cursor_line(cursor_line_was_concealed);\n#endif\n\n    if (p_smd && msg_silent == 0)\n\tredraw_cmdline = TRUE;\t// show visual mode later\n#ifdef FEAT_CLIPBOARD\n    // Make sure the clipboard gets updated.  Needed because start and\n    // end may still be the same, and the selection needs to be owned\n    clip_star.vmode = NUL;\n#endif\n\n    // Only need to redraw this line, unless still need to redraw an old\n    // Visual area (when 'lazyredraw' is set).\n    if (curwin->w_redr_type < INVERTED)\n    {\n\tcurwin->w_old_cursor_lnum = curwin->w_cursor.lnum;\n\tcurwin->w_old_visual_lnum = curwin->w_cursor.lnum;\n    }\n}", "func_hash": 184740522957607059139984101996502665794, "file_name": "None", "file_hash": null, "cwe": ["CWE-122"], "cve": "CVE-2021-3968", "cve_desc": "vim is vulnerable to Heap-based Buffer Overflow", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3968"}
{"idx": 449294, "project": "vim", "commit_id": "a062006b9de0b2947ab5fb376c6e67ef92a8cd69", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/a062006b9de0b2947ab5fb376c6e67ef92a8cd69", "commit_message": "patch 8.2.3610: crash when ModeChanged triggered too early\n\nProblem:    Crash when ModeChanged triggered too early.\nSolution:   Trigger ModeChanged after setting VIsual.", "target": 0, "func": "n_start_visual_mode(int c)\n{\n#ifdef FEAT_CONCEAL\n    int cursor_line_was_concealed = curwin->w_p_cole > 0\n\t\t\t\t\t\t&& conceal_cursor_line(curwin);\n#endif\n\n    VIsual_mode = c;\n    VIsual_active = TRUE;\n    VIsual_reselect = TRUE;\n\n    // Corner case: the 0 position in a tab may change when going into\n    // virtualedit.  Recalculate curwin->w_cursor to avoid bad highlighting.\n    if (c == Ctrl_V && (get_ve_flags() & VE_BLOCK) && gchar_cursor() == TAB)\n    {\n\tvalidate_virtcol();\n\tcoladvance(curwin->w_virtcol);\n    }\n    VIsual = curwin->w_cursor;\n\n#ifdef FEAT_FOLDING\n    foldAdjustVisual();\n#endif\n\n    trigger_modechanged();\n    setmouse();\n#ifdef FEAT_CONCEAL\n    // Check if redraw is needed after changing the state.\n    conceal_check_cursor_line(cursor_line_was_concealed);\n#endif\n\n    if (p_smd && msg_silent == 0)\n\tredraw_cmdline = TRUE;\t// show visual mode later\n#ifdef FEAT_CLIPBOARD\n    // Make sure the clipboard gets updated.  Needed because start and\n    // end may still be the same, and the selection needs to be owned\n    clip_star.vmode = NUL;\n#endif\n\n    // Only need to redraw this line, unless still need to redraw an old\n    // Visual area (when 'lazyredraw' is set).\n    if (curwin->w_redr_type < INVERTED)\n    {\n\tcurwin->w_old_cursor_lnum = curwin->w_cursor.lnum;\n\tcurwin->w_old_visual_lnum = curwin->w_cursor.lnum;\n    }\n}", "func_hash": 18013964164383096631914378209665418022, "file_name": "None", "file_hash": null, "cwe": ["CWE-122"], "cve": "CVE-2021-3968", "cve_desc": "vim is vulnerable to Heap-based Buffer Overflow", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3968"}
{"idx": 211567, "project": "clamav-devel", "commit_id": "c6870a6c857dd722dffaf6d37ae52ec259d12492", "project_url": "https://github.com/vrtadmin/clamav-devel", "commit_url": "https://github.com/vrtadmin/clamav-devel/commit/c6870a6c857dd722dffaf6d37ae52ec259d12492", "commit_message": "bb #6808", "target": 1, "func": "static char *getsistring(FILE *f, uint32_t ptr, uint32_t len) {\n  char *name;\n  uint32_t i;\n\n  if (!len) return NULL;\n  if (len>400) len=400;\n  name = cli_malloc(len);\n  if (!name) {\n    cli_dbgmsg(\"SIS: OOM\\n\");\n    return NULL;\n  }\n  fseek(f, ptr, SEEK_SET);\n  if (fread(name, len, 1, f)!=1) {\n    cli_dbgmsg(\"SIS: Unable to read string\\n\");\n    free(name);\n    return NULL;\n  }\n  for (i = 0 ; i < len; i+=2) name[i/2] = name[i];\n  name[i/2]='\\0';\n  return name;\n}", "func_hash": 249475827060217450801946160071587171974, "file_name": "sis.c", "file_hash": 74416937580759661752528557759080505362, "cwe": ["CWE-189"], "cve": "CVE-2013-2020", "cve_desc": "Integer underflow in the cli_scanpe function in pe.c in ClamAV before 0.97.8 allows remote attackers to cause a denial of service (crash) via a skewed offset larger than the size of the PE section in a UPX packed executable, which triggers an out-of-bounds read.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-2020"}
{"idx": 449321, "project": "clamav-devel", "commit_id": "c6870a6c857dd722dffaf6d37ae52ec259d12492", "project_url": "https://github.com/vrtadmin/clamav-devel", "commit_url": "https://github.com/vrtadmin/clamav-devel/commit/c6870a6c857dd722dffaf6d37ae52ec259d12492", "commit_message": "bb #6808", "target": 0, "func": "static char *getsistring(FILE *f, uint32_t ptr, uint32_t len) {\n  char *name;\n  uint32_t i;\n\n  if (!len) return NULL;\n  if (len>400) len=400;\n  name = cli_malloc(len+1);\n  if (!name) {\n    cli_dbgmsg(\"SIS: OOM\\n\");\n    return NULL;\n  }\n  fseek(f, ptr, SEEK_SET);\n  if (fread(name, len, 1, f)!=1) {\n    cli_dbgmsg(\"SIS: Unable to read string\\n\");\n    free(name);\n    return NULL;\n  }\n  for (i = 0 ; i < len; i+=2) name[i/2] = name[i];\n  name[i/2]='\\0';\n  return name;\n}", "func_hash": 103287413099842266713052785251008739113, "file_name": "sis.c", "file_hash": 220725720240675887606122374077538393241, "cwe": ["CWE-189"], "cve": "CVE-2013-2020", "cve_desc": "Integer underflow in the cli_scanpe function in pe.c in ClamAV before 0.97.8 allows remote attackers to cause a denial of service (crash) via a skewed offset larger than the size of the PE section in a UPX packed executable, which triggers an out-of-bounds read.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2013-2020"}
{"idx": 211695, "project": "vim", "commit_id": "4c13e5e6763c6eb36a343a2b8235ea227202e952", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/4c13e5e6763c6eb36a343a2b8235ea227202e952", "commit_message": "patch 8.2.3949: using freed memory with /\\%V\n\nProblem:    Using freed memory with /\\%V.\nSolution:   Get the line again after getvvcol().", "target": 1, "func": "reg_match_visual(void)\n{\n    pos_T\ttop, bot;\n    linenr_T    lnum;\n    colnr_T\tcol;\n    win_T\t*wp = rex.reg_win == NULL ? curwin : rex.reg_win;\n    int\t\tmode;\n    colnr_T\tstart, end;\n    colnr_T\tstart2, end2;\n    colnr_T\tcols;\n    colnr_T\tcurswant;\n\n    // Check if the buffer is the current buffer.\n    if (rex.reg_buf != curbuf || VIsual.lnum == 0)\n\treturn FALSE;\n\n    if (VIsual_active)\n    {\n\tif (LT_POS(VIsual, wp->w_cursor))\n\t{\n\t    top = VIsual;\n\t    bot = wp->w_cursor;\n\t}\n\telse\n\t{\n\t    top = wp->w_cursor;\n\t    bot = VIsual;\n\t}\n\tmode = VIsual_mode;\n\tcurswant = wp->w_curswant;\n    }\n    else\n    {\n\tif (LT_POS(curbuf->b_visual.vi_start, curbuf->b_visual.vi_end))\n\t{\n\t    top = curbuf->b_visual.vi_start;\n\t    bot = curbuf->b_visual.vi_end;\n\t}\n\telse\n\t{\n\t    top = curbuf->b_visual.vi_end;\n\t    bot = curbuf->b_visual.vi_start;\n\t}\n\tmode = curbuf->b_visual.vi_mode;\n\tcurswant = curbuf->b_visual.vi_curswant;\n    }\n    lnum = rex.lnum + rex.reg_firstlnum;\n    if (lnum < top.lnum || lnum > bot.lnum)\n\treturn FALSE;\n\n    if (mode == 'v')\n    {\n\tcol = (colnr_T)(rex.input - rex.line);\n\tif ((lnum == top.lnum && col < top.col)\n\t\t|| (lnum == bot.lnum && col >= bot.col + (*p_sel != 'e')))\n\t    return FALSE;\n    }\n    else if (mode == Ctrl_V)\n    {\n\tgetvvcol(wp, &top, &start, NULL, &end);\n\tgetvvcol(wp, &bot, &start2, NULL, &end2);\n\tif (start2 < start)\n\t    start = start2;\n\tif (end2 > end)\n\t    end = end2;\n\tif (top.col == MAXCOL || bot.col == MAXCOL || curswant == MAXCOL)\n\t    end = MAXCOL;\n\tcols = win_linetabsize(wp, rex.line, (colnr_T)(rex.input - rex.line));\n\tif (cols < start || cols > end - (*p_sel == 'e'))\n\t    return FALSE;\n    }\n    return TRUE;\n}", "func_hash": 213127434587581742033304075177767787021, "file_name": "regexp.c", "file_hash": 154178765544405999260732501141990227321, "cwe": ["CWE-416"], "cve": "CVE-2021-4192", "cve_desc": "vim is vulnerable to Use After Free", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-4192"}
{"idx": 450764, "project": "vim", "commit_id": "4c13e5e6763c6eb36a343a2b8235ea227202e952", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/4c13e5e6763c6eb36a343a2b8235ea227202e952", "commit_message": "patch 8.2.3949: using freed memory with /\\%V\n\nProblem:    Using freed memory with /\\%V.\nSolution:   Get the line again after getvvcol().", "target": 0, "func": "reg_match_visual(void)\n{\n    pos_T\ttop, bot;\n    linenr_T    lnum;\n    colnr_T\tcol;\n    win_T\t*wp = rex.reg_win == NULL ? curwin : rex.reg_win;\n    int\t\tmode;\n    colnr_T\tstart, end;\n    colnr_T\tstart2, end2;\n    colnr_T\tcols;\n    colnr_T\tcurswant;\n\n    // Check if the buffer is the current buffer.\n    if (rex.reg_buf != curbuf || VIsual.lnum == 0)\n\treturn FALSE;\n\n    if (VIsual_active)\n    {\n\tif (LT_POS(VIsual, wp->w_cursor))\n\t{\n\t    top = VIsual;\n\t    bot = wp->w_cursor;\n\t}\n\telse\n\t{\n\t    top = wp->w_cursor;\n\t    bot = VIsual;\n\t}\n\tmode = VIsual_mode;\n\tcurswant = wp->w_curswant;\n    }\n    else\n    {\n\tif (LT_POS(curbuf->b_visual.vi_start, curbuf->b_visual.vi_end))\n\t{\n\t    top = curbuf->b_visual.vi_start;\n\t    bot = curbuf->b_visual.vi_end;\n\t}\n\telse\n\t{\n\t    top = curbuf->b_visual.vi_end;\n\t    bot = curbuf->b_visual.vi_start;\n\t}\n\tmode = curbuf->b_visual.vi_mode;\n\tcurswant = curbuf->b_visual.vi_curswant;\n    }\n    lnum = rex.lnum + rex.reg_firstlnum;\n    if (lnum < top.lnum || lnum > bot.lnum)\n\treturn FALSE;\n\n    col = (colnr_T)(rex.input - rex.line);\n    if (mode == 'v')\n    {\n\tif ((lnum == top.lnum && col < top.col)\n\t\t|| (lnum == bot.lnum && col >= bot.col + (*p_sel != 'e')))\n\t    return FALSE;\n    }\n    else if (mode == Ctrl_V)\n    {\n\tgetvvcol(wp, &top, &start, NULL, &end);\n\tgetvvcol(wp, &bot, &start2, NULL, &end2);\n\tif (start2 < start)\n\t    start = start2;\n\tif (end2 > end)\n\t    end = end2;\n\tif (top.col == MAXCOL || bot.col == MAXCOL || curswant == MAXCOL)\n\t    end = MAXCOL;\n\n\t// getvvcol() flushes rex.line, need to get it again\n\trex.line = reg_getline(rex.lnum);\n\trex.input = rex.line + col;\n\n\tcols = win_linetabsize(wp, rex.line, col);\n\tif (cols < start || cols > end - (*p_sel == 'e'))\n\t    return FALSE;\n    }\n    return TRUE;\n}", "func_hash": 273404837920170490390239404652231965596, "file_name": "regexp.c", "file_hash": 323022444375597496724509829879656182542, "cwe": ["CWE-416"], "cve": "CVE-2021-4192", "cve_desc": "vim is vulnerable to Use After Free", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-4192"}
{"idx": 211699, "project": "gnulib", "commit_id": "2d1bd71ec70a31b01d01b734faa66bb1ed28961f", "project_url": "https://github.com/coreutils/gnulib", "commit_url": "http://git.savannah.gnu.org/cgit/gnulib.git/commit/?id=2d1bd71ec70a31b01d01b734faa66bb1ed28961f", "commit_message": "glob: fix heap buffer overflow\n\n* lib/glob.c (glob): Fix off-by-one error introduced into\nglibc in commit dd7d45e838a42b0ed470c44b55901ea98d0c2bab\ndated 1997-10-29 20:33:40.  Problem reported by Tim R\u00fchsen in:\nhttps://sourceware.org/bugzilla/show_bug.cgi?id=22320\nFix suggested by Bruno Haible.", "target": 1, "func": "glob (const char *pattern, int flags, int (*errfunc) (const char *, int),\n      glob_t *pglob)\n{\n  const char *filename;\n  char *dirname = NULL;\n  size_t dirlen;\n  int status;\n  size_t oldcount;\n  int meta;\n  int dirname_modified;\n  int malloc_dirname = 0;\n  glob_t dirs;\n  int retval = 0;\n  size_t alloca_used = 0;\n\n  if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)\n    {\n      __set_errno (EINVAL);\n      return -1;\n    }\n\n  /* POSIX requires all slashes to be matched.  This means that with\n     a trailing slash we must match only directories.  */\n  if (pattern[0] && pattern[strlen (pattern) - 1] == '/')\n    flags |= GLOB_ONLYDIR;\n\n  if (!(flags & GLOB_DOOFFS))\n    /* Have to do this so 'globfree' knows where to start freeing.  It\n       also makes all the code that uses gl_offs simpler. */\n    pglob->gl_offs = 0;\n\n  if (!(flags & GLOB_APPEND))\n    {\n      pglob->gl_pathc = 0;\n      if (!(flags & GLOB_DOOFFS))\n        pglob->gl_pathv = NULL;\n      else\n        {\n          size_t i;\n\n          if (pglob->gl_offs >= ~((size_t) 0) / sizeof (char *))\n            return GLOB_NOSPACE;\n\n          pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1)\n                                              * sizeof (char *));\n          if (pglob->gl_pathv == NULL)\n            return GLOB_NOSPACE;\n\n          for (i = 0; i <= pglob->gl_offs; ++i)\n            pglob->gl_pathv[i] = NULL;\n        }\n    }\n\n  if (flags & GLOB_BRACE)\n    {\n      const char *begin;\n\n      if (flags & GLOB_NOESCAPE)\n        begin = strchr (pattern, '{');\n      else\n        {\n          begin = pattern;\n          while (1)\n            {\n              if (*begin == '\\0')\n                {\n                  begin = NULL;\n                  break;\n                }\n\n              if (*begin == '\\\\' && begin[1] != '\\0')\n                ++begin;\n              else if (*begin == '{')\n                break;\n\n              ++begin;\n            }\n        }\n\n      if (begin != NULL)\n        {\n          /* Allocate working buffer large enough for our work.  Note that\n             we have at least an opening and closing brace.  */\n          size_t firstc;\n          char *alt_start;\n          const char *p;\n          const char *next;\n          const char *rest;\n          size_t rest_len;\n          char *onealt;\n          size_t pattern_len = strlen (pattern) - 1;\n          int alloca_onealt = glob_use_alloca (alloca_used, pattern_len);\n          if (alloca_onealt)\n            onealt = alloca_account (pattern_len, alloca_used);\n          else\n            {\n              onealt = malloc (pattern_len);\n              if (onealt == NULL)\n                return GLOB_NOSPACE;\n            }\n\n          /* We know the prefix for all sub-patterns.  */\n          alt_start = mempcpy (onealt, pattern, begin - pattern);\n\n          /* Find the first sub-pattern and at the same time find the\n             rest after the closing brace.  */\n          next = next_brace_sub (begin + 1, flags);\n          if (next == NULL)\n            {\n              /* It is an invalid expression.  */\n            illegal_brace:\n              if (__glibc_unlikely (!alloca_onealt))\n                free (onealt);\n              flags &= ~GLOB_BRACE;\n              goto no_brace;\n            }\n\n          /* Now find the end of the whole brace expression.  */\n          rest = next;\n          while (*rest != '}')\n            {\n              rest = next_brace_sub (rest + 1, flags);\n              if (rest == NULL)\n                /* It is an illegal expression.  */\n                goto illegal_brace;\n            }\n          /* Please note that we now can be sure the brace expression\n             is well-formed.  */\n          rest_len = strlen (++rest) + 1;\n\n          /* We have a brace expression.  BEGIN points to the opening {,\n             NEXT points past the terminator of the first element, and END\n             points past the final }.  We will accumulate result names from\n             recursive runs for each brace alternative in the buffer using\n             GLOB_APPEND.  */\n          firstc = pglob->gl_pathc;\n\n          p = begin + 1;\n          while (1)\n            {\n              int result;\n\n              /* Construct the new glob expression.  */\n              mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);\n\n              result = glob (onealt,\n                             ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))\n                              | GLOB_APPEND), errfunc, pglob);\n\n              /* If we got an error, return it.  */\n              if (result && result != GLOB_NOMATCH)\n                {\n                  if (__glibc_unlikely (!alloca_onealt))\n                    free (onealt);\n                  if (!(flags & GLOB_APPEND))\n                    {\n                      globfree (pglob);\n                      pglob->gl_pathc = 0;\n                    }\n                  return result;\n                }\n\n              if (*next == '}')\n                /* We saw the last entry.  */\n                break;\n\n              p = next + 1;\n              next = next_brace_sub (p, flags);\n              assert (next != NULL);\n            }\n\n          if (__glibc_unlikely (!alloca_onealt))\n            free (onealt);\n\n          if (pglob->gl_pathc != firstc)\n            /* We found some entries.  */\n            return 0;\n          else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))\n            return GLOB_NOMATCH;\n        }\n    }\n\n no_brace:\n  oldcount = pglob->gl_pathc + pglob->gl_offs;\n\n  /* Find the filename.  */\n  filename = strrchr (pattern, '/');\n\n#if defined __MSDOS__ || defined WINDOWS32\n  /* The case of \"d:pattern\".  Since ':' is not allowed in\n     file names, we can safely assume that wherever it\n     happens in pattern, it signals the filename part.  This\n     is so we could some day support patterns like \"[a-z]:foo\".  */\n  if (filename == NULL)\n    filename = strchr (pattern, ':');\n#endif /* __MSDOS__ || WINDOWS32 */\n\n  dirname_modified = 0;\n  if (filename == NULL)\n    {\n      /* This can mean two things: a simple name or \"~name\".  The latter\n         case is nothing but a notation for a directory.  */\n      if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')\n        {\n          dirname = (char *) pattern;\n          dirlen = strlen (pattern);\n\n          /* Set FILENAME to NULL as a special flag.  This is ugly but\n             other solutions would require much more code.  We test for\n             this special case below.  */\n          filename = NULL;\n        }\n      else\n        {\n          if (__glibc_unlikely (pattern[0] == '\\0'))\n            {\n              dirs.gl_pathv = NULL;\n              goto no_matches;\n            }\n\n          filename = pattern;\n          dirname = (char *) \".\";\n          dirlen = 0;\n        }\n    }\n  else if (filename == pattern\n           || (filename == pattern + 1 && pattern[0] == '\\\\'\n               && (flags & GLOB_NOESCAPE) == 0))\n    {\n      /* \"/pattern\" or \"\\\\/pattern\".  */\n      dirname = (char *) \"/\";\n      dirlen = 1;\n      ++filename;\n    }\n  else\n    {\n      char *newp;\n      dirlen = filename - pattern;\n\n#if defined __MSDOS__ || defined WINDOWS32\n      if (*filename == ':'\n          || (filename > pattern + 1 && filename[-1] == ':'))\n        {\n          char *drive_spec;\n\n          ++dirlen;\n          drive_spec = __alloca (dirlen + 1);\n          *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\\0';\n          /* For now, disallow wildcards in the drive spec, to\n             prevent infinite recursion in glob.  */\n          if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))\n            return GLOB_NOMATCH;\n          /* If this is \"d:pattern\", we need to copy ':' to DIRNAME\n             as well.  If it's \"d:/pattern\", don't remove the slash\n             from \"d:/\", since \"d:\" and \"d:/\" are not the same.*/\n        }\n#endif\n\n      if (glob_use_alloca (alloca_used, dirlen + 1))\n        newp = alloca_account (dirlen + 1, alloca_used);\n      else\n        {\n          newp = malloc (dirlen + 1);\n          if (newp == NULL)\n            return GLOB_NOSPACE;\n          malloc_dirname = 1;\n        }\n      *((char *) mempcpy (newp, pattern, dirlen)) = '\\0';\n      dirname = newp;\n      ++filename;\n\n#if defined __MSDOS__ || defined WINDOWS32\n      bool drive_root = (dirlen > 1\n                         && (dirname[dirlen - 1] == ':'\n                             || (dirlen > 2 && dirname[dirlen - 2] == ':'\n                                 && dirname[dirlen - 1] == '/')));\n#else\n      bool drive_root = false;\n#endif\n\n      if (filename[0] == '\\0' && dirlen > 1 && !drive_root)\n        /* \"pattern/\".  Expand \"pattern\", appending slashes.  */\n        {\n          int orig_flags = flags;\n          if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\\\')\n            {\n              /* \"pattern\\\\/\".  Remove the final backslash if it hasn't\n                 been quoted.  */\n              char *p = (char *) &dirname[dirlen - 1];\n\n              while (p > dirname && p[-1] == '\\\\') --p;\n              if ((&dirname[dirlen] - p) & 1)\n                {\n                  *(char *) &dirname[--dirlen] = '\\0';\n                  flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);\n                }\n            }\n          int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);\n          if (val == 0)\n            pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)\n                               | (flags & GLOB_MARK));\n          else if (val == GLOB_NOMATCH && flags != orig_flags)\n            {\n              /* Make sure globfree (&dirs); is a nop.  */\n              dirs.gl_pathv = NULL;\n              flags = orig_flags;\n              oldcount = pglob->gl_pathc + pglob->gl_offs;\n              goto no_matches;\n            }\n          retval = val;\n          goto out;\n        }\n    }\n\n  if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')\n    {\n      if (dirname[1] == '\\0' || dirname[1] == '/'\n          || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\\\'\n              && (dirname[2] == '\\0' || dirname[2] == '/')))\n        {\n          /* Look up home directory.  */\n          char *home_dir = getenv (\"HOME\");\n          int malloc_home_dir = 0;\n          if (home_dir == NULL || home_dir[0] == '\\0')\n            {\n#ifdef WINDOWS32\n              /* Windows NT defines HOMEDRIVE and HOMEPATH.  But give\n                 preference to HOME, because the user can change HOME.  */\n              const char *home_drive = getenv (\"HOMEDRIVE\");\n              const char *home_path = getenv (\"HOMEPATH\");\n\n              if (home_drive != NULL && home_path != NULL)\n                {\n                  size_t home_drive_len = strlen (home_drive);\n                  size_t home_path_len = strlen (home_path);\n                  char *mem = alloca (home_drive_len + home_path_len + 1);\n\n                  memcpy (mem, home_drive, home_drive_len);\n                  memcpy (mem + home_drive_len, home_path, home_path_len + 1);\n                  home_dir = mem;\n                }\n              else\n                home_dir = \"c:/users/default\"; /* poor default */\n#else\n              int err;\n              struct passwd *p;\n              struct passwd pwbuf;\n              struct scratch_buffer s;\n              scratch_buffer_init (&s);\n              while (true)\n                {\n                  p = NULL;\n                  err = __getlogin_r (s.data, s.length);\n                  if (err == 0)\n                    {\n# if defined HAVE_GETPWNAM_R || defined _LIBC\n                      size_t ssize = strlen (s.data) + 1;\n                      err = getpwnam_r (s.data, &pwbuf, s.data + ssize,\n                                        s.length - ssize, &p);\n# else\n                      p = getpwnam (s.data);\n                      if (p == NULL)\n                        err = errno;\n# endif\n                    }\n                  if (err != ERANGE)\n                    break;\n                  if (!scratch_buffer_grow (&s))\n                    {\n                      retval = GLOB_NOSPACE;\n                      goto out;\n                    }\n                }\n              if (err == 0)\n                {\n                  home_dir = strdup (p->pw_dir);\n                  malloc_home_dir = 1;\n                }\n              scratch_buffer_free (&s);\n              if (err == 0 && home_dir == NULL)\n                {\n                  retval = GLOB_NOSPACE;\n                  goto out;\n                }\n#endif /* WINDOWS32 */\n            }\n          if (home_dir == NULL || home_dir[0] == '\\0')\n            {\n              if (__glibc_unlikely (malloc_home_dir))\n                free (home_dir);\n              if (flags & GLOB_TILDE_CHECK)\n                {\n                  retval = GLOB_NOMATCH;\n                  goto out;\n                }\n              else\n                {\n                  home_dir = (char *) \"~\"; /* No luck.  */\n                  malloc_home_dir = 0;\n                }\n            }\n          /* Now construct the full directory.  */\n          if (dirname[1] == '\\0')\n            {\n              if (__glibc_unlikely (malloc_dirname))\n                free (dirname);\n\n              dirname = home_dir;\n              dirlen = strlen (dirname);\n              malloc_dirname = malloc_home_dir;\n            }\n          else\n            {\n              char *newp;\n              size_t home_len = strlen (home_dir);\n              int use_alloca = glob_use_alloca (alloca_used, home_len + dirlen);\n              if (use_alloca)\n                newp = alloca_account (home_len + dirlen, alloca_used);\n              else\n                {\n                  newp = malloc (home_len + dirlen);\n                  if (newp == NULL)\n                    {\n                      if (__glibc_unlikely (malloc_home_dir))\n                        free (home_dir);\n                      retval = GLOB_NOSPACE;\n                      goto out;\n                    }\n                }\n\n              mempcpy (mempcpy (newp, home_dir, home_len),\n                       &dirname[1], dirlen);\n\n              if (__glibc_unlikely (malloc_dirname))\n                free (dirname);\n\n              dirname = newp;\n              dirlen += home_len - 1;\n              malloc_dirname = !use_alloca;\n\n              if (__glibc_unlikely (malloc_home_dir))\n                free (home_dir);\n            }\n          dirname_modified = 1;\n        }\n      else\n        {\n#ifndef WINDOWS32\n          char *end_name = strchr (dirname, '/');\n          char *user_name;\n          int malloc_user_name = 0;\n          char *unescape = NULL;\n\n          if (!(flags & GLOB_NOESCAPE))\n            {\n              if (end_name == NULL)\n                {\n                  unescape = strchr (dirname, '\\\\');\n                  if (unescape)\n                    end_name = strchr (unescape, '\\0');\n                }\n              else\n                unescape = memchr (dirname, '\\\\', end_name - dirname);\n            }\n          if (end_name == NULL)\n            user_name = dirname + 1;\n          else\n            {\n              char *newp;\n              if (glob_use_alloca (alloca_used, end_name - dirname))\n                newp = alloca_account (end_name - dirname, alloca_used);\n              else\n                {\n                  newp = malloc (end_name - dirname);\n                  if (newp == NULL)\n                    {\n                      retval = GLOB_NOSPACE;\n                      goto out;\n                    }\n                  malloc_user_name = 1;\n                }\n              if (unescape != NULL)\n                {\n                  char *p = mempcpy (newp, dirname + 1,\n                                     unescape - dirname - 1);\n                  char *q = unescape;\n                  while (*q != '\\0')\n                    {\n                      if (*q == '\\\\')\n                        {\n                          if (q[1] == '\\0')\n                            {\n                              /* \"~fo\\\\o\\\\\" unescape to user_name \"foo\\\\\",\n                                 but \"~fo\\\\o\\\\/\" unescape to user_name\n                                 \"foo\".  */\n                              if (filename == NULL)\n                                *p++ = '\\\\';\n                              break;\n                            }\n                          ++q;\n                        }\n                      *p++ = *q++;\n                    }\n                  *p = '\\0';\n                }\n              else\n                *((char *) mempcpy (newp, dirname + 1, end_name - dirname))\n                  = '\\0';\n              user_name = newp;\n            }\n\n          /* Look up specific user's home directory.  */\n          {\n            struct passwd *p;\n            struct scratch_buffer pwtmpbuf;\n            scratch_buffer_init (&pwtmpbuf);\n\n#  if defined HAVE_GETPWNAM_R || defined _LIBC\n            struct passwd pwbuf;\n\n            while (getpwnam_r (user_name, &pwbuf,\n                               pwtmpbuf.data, pwtmpbuf.length, &p)\n                   == ERANGE)\n              {\n                if (!scratch_buffer_grow (&pwtmpbuf))\n                  {\n                    retval = GLOB_NOSPACE;\n                    goto out;\n                  }\n              }\n#  else\n            p = getpwnam (user_name);\n#  endif\n\n            if (__glibc_unlikely (malloc_user_name))\n              free (user_name);\n\n            /* If we found a home directory use this.  */\n            if (p != NULL)\n              {\n                size_t home_len = strlen (p->pw_dir);\n                size_t rest_len = end_name == NULL ? 0 : strlen (end_name);\n                char *d;\n\n                if (__glibc_unlikely (malloc_dirname))\n                  free (dirname);\n                malloc_dirname = 0;\n\n                if (glob_use_alloca (alloca_used, home_len + rest_len + 1))\n                  dirname = alloca_account (home_len + rest_len + 1,\n                                            alloca_used);\n                else\n                  {\n                    dirname = malloc (home_len + rest_len + 1);\n                    if (dirname == NULL)\n                      {\n                        scratch_buffer_free (&pwtmpbuf);\n                        retval = GLOB_NOSPACE;\n                        goto out;\n                      }\n                    malloc_dirname = 1;\n                  }\n                d = mempcpy (dirname, p->pw_dir, home_len);\n                if (end_name != NULL)\n                  d = mempcpy (d, end_name, rest_len);\n                *d = '\\0';\n\n                dirlen = home_len + rest_len;\n                dirname_modified = 1;\n              }\n            else\n              {\n                if (flags & GLOB_TILDE_CHECK)\n                  {\n                    /* We have to regard it as an error if we cannot find the\n                       home directory.  */\n                    retval = GLOB_NOMATCH;\n                    goto out;\n                  }\n              }\n            scratch_buffer_free (&pwtmpbuf);\n          }\n#endif /* !WINDOWS32 */\n        }\n    }\n\n  /* Now test whether we looked for \"~\" or \"~NAME\".  In this case we\n     can give the answer now.  */\n  if (filename == NULL)\n    {\n      size_t newcount = pglob->gl_pathc + pglob->gl_offs;\n      char **new_gl_pathv;\n\n      if (newcount > SIZE_MAX / sizeof (char *) - 2)\n        {\n        nospace:\n          free (pglob->gl_pathv);\n          pglob->gl_pathv = NULL;\n          pglob->gl_pathc = 0;\n          retval = GLOB_NOSPACE;\n          goto out;\n        }\n\n      new_gl_pathv = realloc (pglob->gl_pathv,\n                              (newcount + 2) * sizeof (char *));\n      if (new_gl_pathv == NULL)\n        goto nospace;\n      pglob->gl_pathv = new_gl_pathv;\n\n      if (flags & GLOB_MARK && is_dir (dirname, flags, pglob))\n        {\n          char *p;\n          pglob->gl_pathv[newcount] = malloc (dirlen + 2);\n          if (pglob->gl_pathv[newcount] == NULL)\n            goto nospace;\n          p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);\n          p[0] = '/';\n          p[1] = '\\0';\n          if (__glibc_unlikely (malloc_dirname))\n            free (dirname);\n        }\n      else\n        {\n          if (__glibc_unlikely (malloc_dirname))\n            pglob->gl_pathv[newcount] = dirname;\n          else\n            {\n              pglob->gl_pathv[newcount] = strdup (dirname);\n              if (pglob->gl_pathv[newcount] == NULL)\n                goto nospace;\n            }\n        }\n      pglob->gl_pathv[++newcount] = NULL;\n      ++pglob->gl_pathc;\n      pglob->gl_flags = flags;\n\n      return 0;\n    }\n\n  meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));\n  /* meta is 1 if correct glob pattern containing metacharacters.\n     If meta has bit (1 << 2) set, it means there was an unterminated\n     [ which we handle the same, using fnmatch.  Broken unterminated\n     pattern bracket expressions ought to be rare enough that it is\n     not worth special casing them, fnmatch will do the right thing.  */\n  if (meta & (GLOBPAT_SPECIAL | GLOBPAT_BRACKET))\n    {\n      /* The directory name contains metacharacters, so we\n         have to glob for the directory, and then glob for\n         the pattern in each directory found.  */\n      size_t i;\n\n      if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\\\')\n        {\n          /* \"foo\\\\/bar\".  Remove the final backslash from dirname\n             if it has not been quoted.  */\n          char *p = (char *) &dirname[dirlen - 1];\n\n          while (p > dirname && p[-1] == '\\\\') --p;\n          if ((&dirname[dirlen] - p) & 1)\n            *(char *) &dirname[--dirlen] = '\\0';\n        }\n\n      if (__glibc_unlikely ((flags & GLOB_ALTDIRFUNC) != 0))\n        {\n          /* Use the alternative access functions also in the recursive\n             call.  */\n          dirs.gl_opendir = pglob->gl_opendir;\n          dirs.gl_readdir = pglob->gl_readdir;\n          dirs.gl_closedir = pglob->gl_closedir;\n          dirs.gl_stat = pglob->gl_stat;\n          dirs.gl_lstat = pglob->gl_lstat;\n        }\n\n      status = glob (dirname,\n                     ((flags & (GLOB_ERR | GLOB_NOESCAPE\n                                | GLOB_ALTDIRFUNC))\n                      | GLOB_NOSORT | GLOB_ONLYDIR),\n                     errfunc, &dirs);\n      if (status != 0)\n        {\n          if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)\n            {\n              retval = status;\n              goto out;\n            }\n          goto no_matches;\n        }\n\n      /* We have successfully globbed the preceding directory name.\n         For each name we found, call glob_in_dir on it and FILENAME,\n         appending the results to PGLOB.  */\n      for (i = 0; i < dirs.gl_pathc; ++i)\n        {\n          size_t old_pathc;\n\n          old_pathc = pglob->gl_pathc;\n          status = glob_in_dir (filename, dirs.gl_pathv[i],\n                                ((flags | GLOB_APPEND)\n                                 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),\n                                errfunc, pglob, alloca_used);\n          if (status == GLOB_NOMATCH)\n            /* No matches in this directory.  Try the next.  */\n            continue;\n\n          if (status != 0)\n            {\n              globfree (&dirs);\n              globfree (pglob);\n              pglob->gl_pathc = 0;\n              retval = status;\n              goto out;\n            }\n\n          /* Stick the directory on the front of each name.  */\n          if (prefix_array (dirs.gl_pathv[i],\n                            &pglob->gl_pathv[old_pathc + pglob->gl_offs],\n                            pglob->gl_pathc - old_pathc))\n            {\n              globfree (&dirs);\n              globfree (pglob);\n              pglob->gl_pathc = 0;\n              retval = GLOB_NOSPACE;\n              goto out;\n            }\n        }\n\n      flags |= GLOB_MAGCHAR;\n\n      /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls.\n         But if we have not found any matching entry and the GLOB_NOCHECK\n         flag was set we must return the input pattern itself.  */\n      if (pglob->gl_pathc + pglob->gl_offs == oldcount)\n        {\n        no_matches:\n          /* No matches.  */\n          if (flags & GLOB_NOCHECK)\n            {\n              size_t newcount = pglob->gl_pathc + pglob->gl_offs;\n              char **new_gl_pathv;\n\n              if (newcount > SIZE_MAX / sizeof (char *) - 2)\n                {\n                nospace2:\n                  globfree (&dirs);\n                  retval = GLOB_NOSPACE;\n                  goto out;\n                }\n\n              new_gl_pathv = realloc (pglob->gl_pathv,\n                                      (newcount + 2) * sizeof (char *));\n              if (new_gl_pathv == NULL)\n                goto nospace2;\n              pglob->gl_pathv = new_gl_pathv;\n\n              pglob->gl_pathv[newcount] = strdup (pattern);\n              if (pglob->gl_pathv[newcount] == NULL)\n                {\n                  globfree (&dirs);\n                  globfree (pglob);\n                  pglob->gl_pathc = 0;\n                  retval = GLOB_NOSPACE;\n                  goto out;\n                }\n\n              ++pglob->gl_pathc;\n              ++newcount;\n\n              pglob->gl_pathv[newcount] = NULL;\n              pglob->gl_flags = flags;\n            }\n          else\n            {\n              globfree (&dirs);\n              retval = GLOB_NOMATCH;\n              goto out;\n            }\n        }\n\n      globfree (&dirs);\n    }\n  else\n    {\n      size_t old_pathc = pglob->gl_pathc;\n      int orig_flags = flags;\n\n      if (meta & GLOBPAT_BACKSLASH)\n        {\n          char *p = strchr (dirname, '\\\\'), *q;\n          /* We need to unescape the dirname string.  It is certainly\n             allocated by alloca, as otherwise filename would be NULL\n             or dirname wouldn't contain backslashes.  */\n          q = p;\n          do\n            {\n              if (*p == '\\\\')\n                {\n                  *q = *++p;\n                  --dirlen;\n                }\n              else\n                *q = *p;\n              ++q;\n            }\n          while (*p++ != '\\0');\n          dirname_modified = 1;\n        }\n      if (dirname_modified)\n        flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);\n      status = glob_in_dir (filename, dirname, flags, errfunc, pglob,\n                            alloca_used);\n      if (status != 0)\n        {\n          if (status == GLOB_NOMATCH && flags != orig_flags\n              && pglob->gl_pathc + pglob->gl_offs == oldcount)\n            {\n              /* Make sure globfree (&dirs); is a nop.  */\n              dirs.gl_pathv = NULL;\n              flags = orig_flags;\n              goto no_matches;\n            }\n          retval = status;\n          goto out;\n        }\n\n      if (dirlen > 0)\n        {\n          /* Stick the directory on the front of each name.  */\n          if (prefix_array (dirname,\n                            &pglob->gl_pathv[old_pathc + pglob->gl_offs],\n                            pglob->gl_pathc - old_pathc))\n            {\n              globfree (pglob);\n              pglob->gl_pathc = 0;\n              retval = GLOB_NOSPACE;\n              goto out;\n            }\n        }\n    }\n\n  if (flags & GLOB_MARK)\n    {\n      /* Append slashes to directory names.  */\n      size_t i;\n\n      for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)\n        if (is_dir (pglob->gl_pathv[i], flags, pglob))\n          {\n            size_t len = strlen (pglob->gl_pathv[i]) + 2;\n            char *new = realloc (pglob->gl_pathv[i], len);\n            if (new == NULL)\n              {\n                globfree (pglob);\n                pglob->gl_pathc = 0;\n                retval = GLOB_NOSPACE;\n                goto out;\n              }\n            strcpy (&new[len - 2], \"/\");\n            pglob->gl_pathv[i] = new;\n          }\n    }\n\n  if (!(flags & GLOB_NOSORT))\n    {\n      /* Sort the vector.  */\n      qsort (&pglob->gl_pathv[oldcount],\n             pglob->gl_pathc + pglob->gl_offs - oldcount,\n             sizeof (char *), collated_compare);\n    }\n\n out:\n  if (__glibc_unlikely (malloc_dirname))\n    free (dirname);\n\n  return retval;\n}", "func_hash": 298881576183169213772402868020196569538, "file_name": "glob.c", "file_hash": 266244104923592097115880749593499653391, "cwe": ["CWE-119"], "cve": "CVE-2017-15670", "cve_desc": "The GNU C Library (aka glibc or libc6) before 2.27 contains an off-by-one error leading to a heap-based buffer overflow in the glob function in glob.c, related to the processing of home directories using the ~ operator followed by a long string.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-15670"}
{"idx": 450812, "project": "gnulib", "commit_id": "2d1bd71ec70a31b01d01b734faa66bb1ed28961f", "project_url": "https://github.com/coreutils/gnulib", "commit_url": "http://git.savannah.gnu.org/cgit/gnulib.git/commit/?id=2d1bd71ec70a31b01d01b734faa66bb1ed28961f", "commit_message": "glob: fix heap buffer overflow\n\n* lib/glob.c (glob): Fix off-by-one error introduced into\nglibc in commit dd7d45e838a42b0ed470c44b55901ea98d0c2bab\ndated 1997-10-29 20:33:40.  Problem reported by Tim R\u00fchsen in:\nhttps://sourceware.org/bugzilla/show_bug.cgi?id=22320\nFix suggested by Bruno Haible.", "target": 0, "func": "glob (const char *pattern, int flags, int (*errfunc) (const char *, int),\n      glob_t *pglob)\n{\n  const char *filename;\n  char *dirname = NULL;\n  size_t dirlen;\n  int status;\n  size_t oldcount;\n  int meta;\n  int dirname_modified;\n  int malloc_dirname = 0;\n  glob_t dirs;\n  int retval = 0;\n  size_t alloca_used = 0;\n\n  if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)\n    {\n      __set_errno (EINVAL);\n      return -1;\n    }\n\n  /* POSIX requires all slashes to be matched.  This means that with\n     a trailing slash we must match only directories.  */\n  if (pattern[0] && pattern[strlen (pattern) - 1] == '/')\n    flags |= GLOB_ONLYDIR;\n\n  if (!(flags & GLOB_DOOFFS))\n    /* Have to do this so 'globfree' knows where to start freeing.  It\n       also makes all the code that uses gl_offs simpler. */\n    pglob->gl_offs = 0;\n\n  if (!(flags & GLOB_APPEND))\n    {\n      pglob->gl_pathc = 0;\n      if (!(flags & GLOB_DOOFFS))\n        pglob->gl_pathv = NULL;\n      else\n        {\n          size_t i;\n\n          if (pglob->gl_offs >= ~((size_t) 0) / sizeof (char *))\n            return GLOB_NOSPACE;\n\n          pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1)\n                                              * sizeof (char *));\n          if (pglob->gl_pathv == NULL)\n            return GLOB_NOSPACE;\n\n          for (i = 0; i <= pglob->gl_offs; ++i)\n            pglob->gl_pathv[i] = NULL;\n        }\n    }\n\n  if (flags & GLOB_BRACE)\n    {\n      const char *begin;\n\n      if (flags & GLOB_NOESCAPE)\n        begin = strchr (pattern, '{');\n      else\n        {\n          begin = pattern;\n          while (1)\n            {\n              if (*begin == '\\0')\n                {\n                  begin = NULL;\n                  break;\n                }\n\n              if (*begin == '\\\\' && begin[1] != '\\0')\n                ++begin;\n              else if (*begin == '{')\n                break;\n\n              ++begin;\n            }\n        }\n\n      if (begin != NULL)\n        {\n          /* Allocate working buffer large enough for our work.  Note that\n             we have at least an opening and closing brace.  */\n          size_t firstc;\n          char *alt_start;\n          const char *p;\n          const char *next;\n          const char *rest;\n          size_t rest_len;\n          char *onealt;\n          size_t pattern_len = strlen (pattern) - 1;\n          int alloca_onealt = glob_use_alloca (alloca_used, pattern_len);\n          if (alloca_onealt)\n            onealt = alloca_account (pattern_len, alloca_used);\n          else\n            {\n              onealt = malloc (pattern_len);\n              if (onealt == NULL)\n                return GLOB_NOSPACE;\n            }\n\n          /* We know the prefix for all sub-patterns.  */\n          alt_start = mempcpy (onealt, pattern, begin - pattern);\n\n          /* Find the first sub-pattern and at the same time find the\n             rest after the closing brace.  */\n          next = next_brace_sub (begin + 1, flags);\n          if (next == NULL)\n            {\n              /* It is an invalid expression.  */\n            illegal_brace:\n              if (__glibc_unlikely (!alloca_onealt))\n                free (onealt);\n              flags &= ~GLOB_BRACE;\n              goto no_brace;\n            }\n\n          /* Now find the end of the whole brace expression.  */\n          rest = next;\n          while (*rest != '}')\n            {\n              rest = next_brace_sub (rest + 1, flags);\n              if (rest == NULL)\n                /* It is an illegal expression.  */\n                goto illegal_brace;\n            }\n          /* Please note that we now can be sure the brace expression\n             is well-formed.  */\n          rest_len = strlen (++rest) + 1;\n\n          /* We have a brace expression.  BEGIN points to the opening {,\n             NEXT points past the terminator of the first element, and END\n             points past the final }.  We will accumulate result names from\n             recursive runs for each brace alternative in the buffer using\n             GLOB_APPEND.  */\n          firstc = pglob->gl_pathc;\n\n          p = begin + 1;\n          while (1)\n            {\n              int result;\n\n              /* Construct the new glob expression.  */\n              mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);\n\n              result = glob (onealt,\n                             ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))\n                              | GLOB_APPEND), errfunc, pglob);\n\n              /* If we got an error, return it.  */\n              if (result && result != GLOB_NOMATCH)\n                {\n                  if (__glibc_unlikely (!alloca_onealt))\n                    free (onealt);\n                  if (!(flags & GLOB_APPEND))\n                    {\n                      globfree (pglob);\n                      pglob->gl_pathc = 0;\n                    }\n                  return result;\n                }\n\n              if (*next == '}')\n                /* We saw the last entry.  */\n                break;\n\n              p = next + 1;\n              next = next_brace_sub (p, flags);\n              assert (next != NULL);\n            }\n\n          if (__glibc_unlikely (!alloca_onealt))\n            free (onealt);\n\n          if (pglob->gl_pathc != firstc)\n            /* We found some entries.  */\n            return 0;\n          else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))\n            return GLOB_NOMATCH;\n        }\n    }\n\n no_brace:\n  oldcount = pglob->gl_pathc + pglob->gl_offs;\n\n  /* Find the filename.  */\n  filename = strrchr (pattern, '/');\n\n#if defined __MSDOS__ || defined WINDOWS32\n  /* The case of \"d:pattern\".  Since ':' is not allowed in\n     file names, we can safely assume that wherever it\n     happens in pattern, it signals the filename part.  This\n     is so we could some day support patterns like \"[a-z]:foo\".  */\n  if (filename == NULL)\n    filename = strchr (pattern, ':');\n#endif /* __MSDOS__ || WINDOWS32 */\n\n  dirname_modified = 0;\n  if (filename == NULL)\n    {\n      /* This can mean two things: a simple name or \"~name\".  The latter\n         case is nothing but a notation for a directory.  */\n      if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')\n        {\n          dirname = (char *) pattern;\n          dirlen = strlen (pattern);\n\n          /* Set FILENAME to NULL as a special flag.  This is ugly but\n             other solutions would require much more code.  We test for\n             this special case below.  */\n          filename = NULL;\n        }\n      else\n        {\n          if (__glibc_unlikely (pattern[0] == '\\0'))\n            {\n              dirs.gl_pathv = NULL;\n              goto no_matches;\n            }\n\n          filename = pattern;\n          dirname = (char *) \".\";\n          dirlen = 0;\n        }\n    }\n  else if (filename == pattern\n           || (filename == pattern + 1 && pattern[0] == '\\\\'\n               && (flags & GLOB_NOESCAPE) == 0))\n    {\n      /* \"/pattern\" or \"\\\\/pattern\".  */\n      dirname = (char *) \"/\";\n      dirlen = 1;\n      ++filename;\n    }\n  else\n    {\n      char *newp;\n      dirlen = filename - pattern;\n\n#if defined __MSDOS__ || defined WINDOWS32\n      if (*filename == ':'\n          || (filename > pattern + 1 && filename[-1] == ':'))\n        {\n          char *drive_spec;\n\n          ++dirlen;\n          drive_spec = __alloca (dirlen + 1);\n          *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\\0';\n          /* For now, disallow wildcards in the drive spec, to\n             prevent infinite recursion in glob.  */\n          if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))\n            return GLOB_NOMATCH;\n          /* If this is \"d:pattern\", we need to copy ':' to DIRNAME\n             as well.  If it's \"d:/pattern\", don't remove the slash\n             from \"d:/\", since \"d:\" and \"d:/\" are not the same.*/\n        }\n#endif\n\n      if (glob_use_alloca (alloca_used, dirlen + 1))\n        newp = alloca_account (dirlen + 1, alloca_used);\n      else\n        {\n          newp = malloc (dirlen + 1);\n          if (newp == NULL)\n            return GLOB_NOSPACE;\n          malloc_dirname = 1;\n        }\n      *((char *) mempcpy (newp, pattern, dirlen)) = '\\0';\n      dirname = newp;\n      ++filename;\n\n#if defined __MSDOS__ || defined WINDOWS32\n      bool drive_root = (dirlen > 1\n                         && (dirname[dirlen - 1] == ':'\n                             || (dirlen > 2 && dirname[dirlen - 2] == ':'\n                                 && dirname[dirlen - 1] == '/')));\n#else\n      bool drive_root = false;\n#endif\n\n      if (filename[0] == '\\0' && dirlen > 1 && !drive_root)\n        /* \"pattern/\".  Expand \"pattern\", appending slashes.  */\n        {\n          int orig_flags = flags;\n          if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\\\')\n            {\n              /* \"pattern\\\\/\".  Remove the final backslash if it hasn't\n                 been quoted.  */\n              char *p = (char *) &dirname[dirlen - 1];\n\n              while (p > dirname && p[-1] == '\\\\') --p;\n              if ((&dirname[dirlen] - p) & 1)\n                {\n                  *(char *) &dirname[--dirlen] = '\\0';\n                  flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);\n                }\n            }\n          int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);\n          if (val == 0)\n            pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)\n                               | (flags & GLOB_MARK));\n          else if (val == GLOB_NOMATCH && flags != orig_flags)\n            {\n              /* Make sure globfree (&dirs); is a nop.  */\n              dirs.gl_pathv = NULL;\n              flags = orig_flags;\n              oldcount = pglob->gl_pathc + pglob->gl_offs;\n              goto no_matches;\n            }\n          retval = val;\n          goto out;\n        }\n    }\n\n  if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')\n    {\n      if (dirname[1] == '\\0' || dirname[1] == '/'\n          || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\\\'\n              && (dirname[2] == '\\0' || dirname[2] == '/')))\n        {\n          /* Look up home directory.  */\n          char *home_dir = getenv (\"HOME\");\n          int malloc_home_dir = 0;\n          if (home_dir == NULL || home_dir[0] == '\\0')\n            {\n#ifdef WINDOWS32\n              /* Windows NT defines HOMEDRIVE and HOMEPATH.  But give\n                 preference to HOME, because the user can change HOME.  */\n              const char *home_drive = getenv (\"HOMEDRIVE\");\n              const char *home_path = getenv (\"HOMEPATH\");\n\n              if (home_drive != NULL && home_path != NULL)\n                {\n                  size_t home_drive_len = strlen (home_drive);\n                  size_t home_path_len = strlen (home_path);\n                  char *mem = alloca (home_drive_len + home_path_len + 1);\n\n                  memcpy (mem, home_drive, home_drive_len);\n                  memcpy (mem + home_drive_len, home_path, home_path_len + 1);\n                  home_dir = mem;\n                }\n              else\n                home_dir = \"c:/users/default\"; /* poor default */\n#else\n              int err;\n              struct passwd *p;\n              struct passwd pwbuf;\n              struct scratch_buffer s;\n              scratch_buffer_init (&s);\n              while (true)\n                {\n                  p = NULL;\n                  err = __getlogin_r (s.data, s.length);\n                  if (err == 0)\n                    {\n# if defined HAVE_GETPWNAM_R || defined _LIBC\n                      size_t ssize = strlen (s.data) + 1;\n                      err = getpwnam_r (s.data, &pwbuf, s.data + ssize,\n                                        s.length - ssize, &p);\n# else\n                      p = getpwnam (s.data);\n                      if (p == NULL)\n                        err = errno;\n# endif\n                    }\n                  if (err != ERANGE)\n                    break;\n                  if (!scratch_buffer_grow (&s))\n                    {\n                      retval = GLOB_NOSPACE;\n                      goto out;\n                    }\n                }\n              if (err == 0)\n                {\n                  home_dir = strdup (p->pw_dir);\n                  malloc_home_dir = 1;\n                }\n              scratch_buffer_free (&s);\n              if (err == 0 && home_dir == NULL)\n                {\n                  retval = GLOB_NOSPACE;\n                  goto out;\n                }\n#endif /* WINDOWS32 */\n            }\n          if (home_dir == NULL || home_dir[0] == '\\0')\n            {\n              if (__glibc_unlikely (malloc_home_dir))\n                free (home_dir);\n              if (flags & GLOB_TILDE_CHECK)\n                {\n                  retval = GLOB_NOMATCH;\n                  goto out;\n                }\n              else\n                {\n                  home_dir = (char *) \"~\"; /* No luck.  */\n                  malloc_home_dir = 0;\n                }\n            }\n          /* Now construct the full directory.  */\n          if (dirname[1] == '\\0')\n            {\n              if (__glibc_unlikely (malloc_dirname))\n                free (dirname);\n\n              dirname = home_dir;\n              dirlen = strlen (dirname);\n              malloc_dirname = malloc_home_dir;\n            }\n          else\n            {\n              char *newp;\n              size_t home_len = strlen (home_dir);\n              int use_alloca = glob_use_alloca (alloca_used, home_len + dirlen);\n              if (use_alloca)\n                newp = alloca_account (home_len + dirlen, alloca_used);\n              else\n                {\n                  newp = malloc (home_len + dirlen);\n                  if (newp == NULL)\n                    {\n                      if (__glibc_unlikely (malloc_home_dir))\n                        free (home_dir);\n                      retval = GLOB_NOSPACE;\n                      goto out;\n                    }\n                }\n\n              mempcpy (mempcpy (newp, home_dir, home_len),\n                       &dirname[1], dirlen);\n\n              if (__glibc_unlikely (malloc_dirname))\n                free (dirname);\n\n              dirname = newp;\n              dirlen += home_len - 1;\n              malloc_dirname = !use_alloca;\n\n              if (__glibc_unlikely (malloc_home_dir))\n                free (home_dir);\n            }\n          dirname_modified = 1;\n        }\n      else\n        {\n#ifndef WINDOWS32\n          char *end_name = strchr (dirname, '/');\n          char *user_name;\n          int malloc_user_name = 0;\n          char *unescape = NULL;\n\n          if (!(flags & GLOB_NOESCAPE))\n            {\n              if (end_name == NULL)\n                {\n                  unescape = strchr (dirname, '\\\\');\n                  if (unescape)\n                    end_name = strchr (unescape, '\\0');\n                }\n              else\n                unescape = memchr (dirname, '\\\\', end_name - dirname);\n            }\n          if (end_name == NULL)\n            user_name = dirname + 1;\n          else\n            {\n              char *newp;\n              if (glob_use_alloca (alloca_used, end_name - dirname))\n                newp = alloca_account (end_name - dirname, alloca_used);\n              else\n                {\n                  newp = malloc (end_name - dirname);\n                  if (newp == NULL)\n                    {\n                      retval = GLOB_NOSPACE;\n                      goto out;\n                    }\n                  malloc_user_name = 1;\n                }\n              if (unescape != NULL)\n                {\n                  char *p = mempcpy (newp, dirname + 1,\n                                     unescape - dirname - 1);\n                  char *q = unescape;\n                  while (*q != '\\0')\n                    {\n                      if (*q == '\\\\')\n                        {\n                          if (q[1] == '\\0')\n                            {\n                              /* \"~fo\\\\o\\\\\" unescape to user_name \"foo\\\\\",\n                                 but \"~fo\\\\o\\\\/\" unescape to user_name\n                                 \"foo\".  */\n                              if (filename == NULL)\n                                *p++ = '\\\\';\n                              break;\n                            }\n                          ++q;\n                        }\n                      *p++ = *q++;\n                    }\n                  *p = '\\0';\n                }\n              else\n                *((char *) mempcpy (newp, dirname + 1, end_name - dirname - 1))\n                  = '\\0';\n              user_name = newp;\n            }\n\n          /* Look up specific user's home directory.  */\n          {\n            struct passwd *p;\n            struct scratch_buffer pwtmpbuf;\n            scratch_buffer_init (&pwtmpbuf);\n\n#  if defined HAVE_GETPWNAM_R || defined _LIBC\n            struct passwd pwbuf;\n\n            while (getpwnam_r (user_name, &pwbuf,\n                               pwtmpbuf.data, pwtmpbuf.length, &p)\n                   == ERANGE)\n              {\n                if (!scratch_buffer_grow (&pwtmpbuf))\n                  {\n                    retval = GLOB_NOSPACE;\n                    goto out;\n                  }\n              }\n#  else\n            p = getpwnam (user_name);\n#  endif\n\n            if (__glibc_unlikely (malloc_user_name))\n              free (user_name);\n\n            /* If we found a home directory use this.  */\n            if (p != NULL)\n              {\n                size_t home_len = strlen (p->pw_dir);\n                size_t rest_len = end_name == NULL ? 0 : strlen (end_name);\n                char *d;\n\n                if (__glibc_unlikely (malloc_dirname))\n                  free (dirname);\n                malloc_dirname = 0;\n\n                if (glob_use_alloca (alloca_used, home_len + rest_len + 1))\n                  dirname = alloca_account (home_len + rest_len + 1,\n                                            alloca_used);\n                else\n                  {\n                    dirname = malloc (home_len + rest_len + 1);\n                    if (dirname == NULL)\n                      {\n                        scratch_buffer_free (&pwtmpbuf);\n                        retval = GLOB_NOSPACE;\n                        goto out;\n                      }\n                    malloc_dirname = 1;\n                  }\n                d = mempcpy (dirname, p->pw_dir, home_len);\n                if (end_name != NULL)\n                  d = mempcpy (d, end_name, rest_len);\n                *d = '\\0';\n\n                dirlen = home_len + rest_len;\n                dirname_modified = 1;\n              }\n            else\n              {\n                if (flags & GLOB_TILDE_CHECK)\n                  {\n                    /* We have to regard it as an error if we cannot find the\n                       home directory.  */\n                    retval = GLOB_NOMATCH;\n                    goto out;\n                  }\n              }\n            scratch_buffer_free (&pwtmpbuf);\n          }\n#endif /* !WINDOWS32 */\n        }\n    }\n\n  /* Now test whether we looked for \"~\" or \"~NAME\".  In this case we\n     can give the answer now.  */\n  if (filename == NULL)\n    {\n      size_t newcount = pglob->gl_pathc + pglob->gl_offs;\n      char **new_gl_pathv;\n\n      if (newcount > SIZE_MAX / sizeof (char *) - 2)\n        {\n        nospace:\n          free (pglob->gl_pathv);\n          pglob->gl_pathv = NULL;\n          pglob->gl_pathc = 0;\n          retval = GLOB_NOSPACE;\n          goto out;\n        }\n\n      new_gl_pathv = realloc (pglob->gl_pathv,\n                              (newcount + 2) * sizeof (char *));\n      if (new_gl_pathv == NULL)\n        goto nospace;\n      pglob->gl_pathv = new_gl_pathv;\n\n      if (flags & GLOB_MARK && is_dir (dirname, flags, pglob))\n        {\n          char *p;\n          pglob->gl_pathv[newcount] = malloc (dirlen + 2);\n          if (pglob->gl_pathv[newcount] == NULL)\n            goto nospace;\n          p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);\n          p[0] = '/';\n          p[1] = '\\0';\n          if (__glibc_unlikely (malloc_dirname))\n            free (dirname);\n        }\n      else\n        {\n          if (__glibc_unlikely (malloc_dirname))\n            pglob->gl_pathv[newcount] = dirname;\n          else\n            {\n              pglob->gl_pathv[newcount] = strdup (dirname);\n              if (pglob->gl_pathv[newcount] == NULL)\n                goto nospace;\n            }\n        }\n      pglob->gl_pathv[++newcount] = NULL;\n      ++pglob->gl_pathc;\n      pglob->gl_flags = flags;\n\n      return 0;\n    }\n\n  meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));\n  /* meta is 1 if correct glob pattern containing metacharacters.\n     If meta has bit (1 << 2) set, it means there was an unterminated\n     [ which we handle the same, using fnmatch.  Broken unterminated\n     pattern bracket expressions ought to be rare enough that it is\n     not worth special casing them, fnmatch will do the right thing.  */\n  if (meta & (GLOBPAT_SPECIAL | GLOBPAT_BRACKET))\n    {\n      /* The directory name contains metacharacters, so we\n         have to glob for the directory, and then glob for\n         the pattern in each directory found.  */\n      size_t i;\n\n      if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\\\')\n        {\n          /* \"foo\\\\/bar\".  Remove the final backslash from dirname\n             if it has not been quoted.  */\n          char *p = (char *) &dirname[dirlen - 1];\n\n          while (p > dirname && p[-1] == '\\\\') --p;\n          if ((&dirname[dirlen] - p) & 1)\n            *(char *) &dirname[--dirlen] = '\\0';\n        }\n\n      if (__glibc_unlikely ((flags & GLOB_ALTDIRFUNC) != 0))\n        {\n          /* Use the alternative access functions also in the recursive\n             call.  */\n          dirs.gl_opendir = pglob->gl_opendir;\n          dirs.gl_readdir = pglob->gl_readdir;\n          dirs.gl_closedir = pglob->gl_closedir;\n          dirs.gl_stat = pglob->gl_stat;\n          dirs.gl_lstat = pglob->gl_lstat;\n        }\n\n      status = glob (dirname,\n                     ((flags & (GLOB_ERR | GLOB_NOESCAPE\n                                | GLOB_ALTDIRFUNC))\n                      | GLOB_NOSORT | GLOB_ONLYDIR),\n                     errfunc, &dirs);\n      if (status != 0)\n        {\n          if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)\n            {\n              retval = status;\n              goto out;\n            }\n          goto no_matches;\n        }\n\n      /* We have successfully globbed the preceding directory name.\n         For each name we found, call glob_in_dir on it and FILENAME,\n         appending the results to PGLOB.  */\n      for (i = 0; i < dirs.gl_pathc; ++i)\n        {\n          size_t old_pathc;\n\n          old_pathc = pglob->gl_pathc;\n          status = glob_in_dir (filename, dirs.gl_pathv[i],\n                                ((flags | GLOB_APPEND)\n                                 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),\n                                errfunc, pglob, alloca_used);\n          if (status == GLOB_NOMATCH)\n            /* No matches in this directory.  Try the next.  */\n            continue;\n\n          if (status != 0)\n            {\n              globfree (&dirs);\n              globfree (pglob);\n              pglob->gl_pathc = 0;\n              retval = status;\n              goto out;\n            }\n\n          /* Stick the directory on the front of each name.  */\n          if (prefix_array (dirs.gl_pathv[i],\n                            &pglob->gl_pathv[old_pathc + pglob->gl_offs],\n                            pglob->gl_pathc - old_pathc))\n            {\n              globfree (&dirs);\n              globfree (pglob);\n              pglob->gl_pathc = 0;\n              retval = GLOB_NOSPACE;\n              goto out;\n            }\n        }\n\n      flags |= GLOB_MAGCHAR;\n\n      /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls.\n         But if we have not found any matching entry and the GLOB_NOCHECK\n         flag was set we must return the input pattern itself.  */\n      if (pglob->gl_pathc + pglob->gl_offs == oldcount)\n        {\n        no_matches:\n          /* No matches.  */\n          if (flags & GLOB_NOCHECK)\n            {\n              size_t newcount = pglob->gl_pathc + pglob->gl_offs;\n              char **new_gl_pathv;\n\n              if (newcount > SIZE_MAX / sizeof (char *) - 2)\n                {\n                nospace2:\n                  globfree (&dirs);\n                  retval = GLOB_NOSPACE;\n                  goto out;\n                }\n\n              new_gl_pathv = realloc (pglob->gl_pathv,\n                                      (newcount + 2) * sizeof (char *));\n              if (new_gl_pathv == NULL)\n                goto nospace2;\n              pglob->gl_pathv = new_gl_pathv;\n\n              pglob->gl_pathv[newcount] = strdup (pattern);\n              if (pglob->gl_pathv[newcount] == NULL)\n                {\n                  globfree (&dirs);\n                  globfree (pglob);\n                  pglob->gl_pathc = 0;\n                  retval = GLOB_NOSPACE;\n                  goto out;\n                }\n\n              ++pglob->gl_pathc;\n              ++newcount;\n\n              pglob->gl_pathv[newcount] = NULL;\n              pglob->gl_flags = flags;\n            }\n          else\n            {\n              globfree (&dirs);\n              retval = GLOB_NOMATCH;\n              goto out;\n            }\n        }\n\n      globfree (&dirs);\n    }\n  else\n    {\n      size_t old_pathc = pglob->gl_pathc;\n      int orig_flags = flags;\n\n      if (meta & GLOBPAT_BACKSLASH)\n        {\n          char *p = strchr (dirname, '\\\\'), *q;\n          /* We need to unescape the dirname string.  It is certainly\n             allocated by alloca, as otherwise filename would be NULL\n             or dirname wouldn't contain backslashes.  */\n          q = p;\n          do\n            {\n              if (*p == '\\\\')\n                {\n                  *q = *++p;\n                  --dirlen;\n                }\n              else\n                *q = *p;\n              ++q;\n            }\n          while (*p++ != '\\0');\n          dirname_modified = 1;\n        }\n      if (dirname_modified)\n        flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);\n      status = glob_in_dir (filename, dirname, flags, errfunc, pglob,\n                            alloca_used);\n      if (status != 0)\n        {\n          if (status == GLOB_NOMATCH && flags != orig_flags\n              && pglob->gl_pathc + pglob->gl_offs == oldcount)\n            {\n              /* Make sure globfree (&dirs); is a nop.  */\n              dirs.gl_pathv = NULL;\n              flags = orig_flags;\n              goto no_matches;\n            }\n          retval = status;\n          goto out;\n        }\n\n      if (dirlen > 0)\n        {\n          /* Stick the directory on the front of each name.  */\n          if (prefix_array (dirname,\n                            &pglob->gl_pathv[old_pathc + pglob->gl_offs],\n                            pglob->gl_pathc - old_pathc))\n            {\n              globfree (pglob);\n              pglob->gl_pathc = 0;\n              retval = GLOB_NOSPACE;\n              goto out;\n            }\n        }\n    }\n\n  if (flags & GLOB_MARK)\n    {\n      /* Append slashes to directory names.  */\n      size_t i;\n\n      for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)\n        if (is_dir (pglob->gl_pathv[i], flags, pglob))\n          {\n            size_t len = strlen (pglob->gl_pathv[i]) + 2;\n            char *new = realloc (pglob->gl_pathv[i], len);\n            if (new == NULL)\n              {\n                globfree (pglob);\n                pglob->gl_pathc = 0;\n                retval = GLOB_NOSPACE;\n                goto out;\n              }\n            strcpy (&new[len - 2], \"/\");\n            pglob->gl_pathv[i] = new;\n          }\n    }\n\n  if (!(flags & GLOB_NOSORT))\n    {\n      /* Sort the vector.  */\n      qsort (&pglob->gl_pathv[oldcount],\n             pglob->gl_pathc + pglob->gl_offs - oldcount,\n             sizeof (char *), collated_compare);\n    }\n\n out:\n  if (__glibc_unlikely (malloc_dirname))\n    free (dirname);\n\n  return retval;\n}", "func_hash": 117294583205769293929285722462366033294, "file_name": "glob.c", "file_hash": 86657842076081720969928155936908511288, "cwe": ["CWE-119"], "cve": "CVE-2017-15670", "cve_desc": "The GNU C Library (aka glibc or libc6) before 2.27 contains an off-by-one error leading to a heap-based buffer overflow in the glob function in glob.c, related to the processing of home directories using the ~ operator followed by a long string.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-15670"}
{"idx": 211700, "project": "linux", "commit_id": "4fbcc1a4cb20fe26ad0225679c536c80f1648221", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/4fbcc1a4cb20fe26ad0225679c536c80f1648221", "commit_message": "nfc: st21nfca: Fix potential buffer overflows in EVT_TRANSACTION\n\nIt appears that there are some buffer overflows in EVT_TRANSACTION.\nThis happens because the length parameters that are passed to memcpy\ncome directly from skb->data and are not guarded in any way.\n\nSigned-off-by: Jordy Zomer \nReviewed-by: Krzysztof Kozlowski \nSigned-off-by: David S. Miller ", "target": 1, "func": "int st21nfca_connectivity_event_received(struct nfc_hci_dev *hdev, u8 host,\n\t\t\t\tu8 event, struct sk_buff *skb)\n{\n\tint r = 0;\n\tstruct device *dev = &hdev->ndev->dev;\n\tstruct nfc_evt_transaction *transaction;\n\n\tpr_debug(\"connectivity gate event: %x\\n\", event);\n\n\tswitch (event) {\n\tcase ST21NFCA_EVT_CONNECTIVITY:\n\t\tr = nfc_se_connectivity(hdev->ndev, host);\n\tbreak;\n\tcase ST21NFCA_EVT_TRANSACTION:\n\t\t/*\n\t\t * According to specification etsi 102 622\n\t\t * 11.2.2.4 EVT_TRANSACTION Table 52\n\t\t * Description\tTag\tLength\n\t\t * AID\t\t81\t5 to 16\n\t\t * PARAMETERS\t82\t0 to 255\n\t\t */\n\t\tif (skb->len < NFC_MIN_AID_LENGTH + 2 &&\n\t\t    skb->data[0] != NFC_EVT_TRANSACTION_AID_TAG)\n\t\t\treturn -EPROTO;\n\n\t\ttransaction = devm_kzalloc(dev, skb->len - 2, GFP_KERNEL);\n\t\tif (!transaction)\n\t\t\treturn -ENOMEM;\n\n\t\ttransaction->aid_len = skb->data[1];\n\t\tmemcpy(transaction->aid, &skb->data[2],\n\t\t       transaction->aid_len);\n\n\t\t/* Check next byte is PARAMETERS tag (82) */\n\t\tif (skb->data[transaction->aid_len + 2] !=\n\t\t    NFC_EVT_TRANSACTION_PARAMS_TAG)\n\t\t\treturn -EPROTO;\n\n\t\ttransaction->params_len = skb->data[transaction->aid_len + 3];\n\t\tmemcpy(transaction->params, skb->data +\n\t\t       transaction->aid_len + 4, transaction->params_len);\n\n\t\tr = nfc_se_transaction(hdev->ndev, host, transaction);\n\tbreak;\n\tdefault:\n\t\tnfc_err(&hdev->ndev->dev, \"Unexpected event on connectivity gate\\n\");\n\t\treturn 1;\n\t}\n\tkfree_skb(skb);\n\treturn r;\n}", "func_hash": 253634808738614127513017365541725702270, "file_name": "se.c", "file_hash": 262088554020527485810277505080130104803, "cwe": ["CWE-120"], "cve": "CVE-2022-26490", "cve_desc": "st21nfca_connectivity_event_received in drivers/nfc/st21nfca/se.c in the Linux kernel through 5.16.12 has EVT_TRANSACTION buffer overflows because of untrusted length parameters.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-26490"}
{"idx": 450830, "project": "linux", "commit_id": "4fbcc1a4cb20fe26ad0225679c536c80f1648221", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/4fbcc1a4cb20fe26ad0225679c536c80f1648221", "commit_message": "nfc: st21nfca: Fix potential buffer overflows in EVT_TRANSACTION\n\nIt appears that there are some buffer overflows in EVT_TRANSACTION.\nThis happens because the length parameters that are passed to memcpy\ncome directly from skb->data and are not guarded in any way.\n\nSigned-off-by: Jordy Zomer \nReviewed-by: Krzysztof Kozlowski \nSigned-off-by: David S. Miller ", "target": 0, "func": "int st21nfca_connectivity_event_received(struct nfc_hci_dev *hdev, u8 host,\n\t\t\t\tu8 event, struct sk_buff *skb)\n{\n\tint r = 0;\n\tstruct device *dev = &hdev->ndev->dev;\n\tstruct nfc_evt_transaction *transaction;\n\n\tpr_debug(\"connectivity gate event: %x\\n\", event);\n\n\tswitch (event) {\n\tcase ST21NFCA_EVT_CONNECTIVITY:\n\t\tr = nfc_se_connectivity(hdev->ndev, host);\n\tbreak;\n\tcase ST21NFCA_EVT_TRANSACTION:\n\t\t/*\n\t\t * According to specification etsi 102 622\n\t\t * 11.2.2.4 EVT_TRANSACTION Table 52\n\t\t * Description\tTag\tLength\n\t\t * AID\t\t81\t5 to 16\n\t\t * PARAMETERS\t82\t0 to 255\n\t\t */\n\t\tif (skb->len < NFC_MIN_AID_LENGTH + 2 &&\n\t\t    skb->data[0] != NFC_EVT_TRANSACTION_AID_TAG)\n\t\t\treturn -EPROTO;\n\n\t\ttransaction = devm_kzalloc(dev, skb->len - 2, GFP_KERNEL);\n\t\tif (!transaction)\n\t\t\treturn -ENOMEM;\n\n\t\ttransaction->aid_len = skb->data[1];\n\n\t\t/* Checking if the length of the AID is valid */\n\t\tif (transaction->aid_len > sizeof(transaction->aid))\n\t\t\treturn -EINVAL;\n\n\t\tmemcpy(transaction->aid, &skb->data[2],\n\t\t       transaction->aid_len);\n\n\t\t/* Check next byte is PARAMETERS tag (82) */\n\t\tif (skb->data[transaction->aid_len + 2] !=\n\t\t    NFC_EVT_TRANSACTION_PARAMS_TAG)\n\t\t\treturn -EPROTO;\n\n\t\ttransaction->params_len = skb->data[transaction->aid_len + 3];\n\n\t\t/* Total size is allocated (skb->len - 2) minus fixed array members */\n\t\tif (transaction->params_len > ((skb->len - 2) - sizeof(struct nfc_evt_transaction)))\n\t\t\treturn -EINVAL;\n\n\t\tmemcpy(transaction->params, skb->data +\n\t\t       transaction->aid_len + 4, transaction->params_len);\n\n\t\tr = nfc_se_transaction(hdev->ndev, host, transaction);\n\tbreak;\n\tdefault:\n\t\tnfc_err(&hdev->ndev->dev, \"Unexpected event on connectivity gate\\n\");\n\t\treturn 1;\n\t}\n\tkfree_skb(skb);\n\treturn r;\n}", "func_hash": 192395528803862067074725666985010866676, "file_name": "se.c", "file_hash": 50941829261793889476158524684428564511, "cwe": ["CWE-120"], "cve": "CVE-2022-26490", "cve_desc": "st21nfca_connectivity_event_received in drivers/nfc/st21nfca/se.c in the Linux kernel through 5.16.12 has EVT_TRANSACTION buffer overflows because of untrusted length parameters.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-26490"}
{"idx": 211773, "project": "ntp", "commit_id": "07a5b8141e354a998a52994c3c9cd547927e56ce", "project_url": "https://github.com/ntp-project/ntp", "commit_url": "https://github.com/ntp-project/ntp/commit/07a5b8141e354a998a52994c3c9cd547927e56ce", "commit_message": "[TALOS-CAN-0063] avoid buffer overrun in ntpq", "target": 1, "func": "cookedprint(\n\tint datatype,\n\tint length,\n\tconst char *data,\n\tint status,\n\tint quiet,\n\tFILE *fp\n\t)\n{\n\tchar *name;\n\tchar *value;\n\tchar output_raw;\n\tint fmt;\n\tl_fp lfp;\n\tsockaddr_u hval;\n\tu_long uval;\n\tint narr;\n\tsize_t len;\n\tl_fp lfparr[8];\n\tchar b[12];\n\tchar bn[2 * MAXVARLEN];\n\tchar bv[2 * MAXVALLEN];\n\n\tUNUSED_ARG(datatype);\n\n\tif (!quiet)\n\t\tfprintf(fp, \"status=%04x %s,\\n\", status,\n\t\t\tstatustoa(datatype, status));\n\n\tstartoutput();\n\twhile (nextvar(&length, &data, &name, &value)) {\n\t\tfmt = varfmt(name);\n\t\toutput_raw = 0;\n\t\tswitch (fmt) {\n\n\t\tcase PADDING:\n\t\t\toutput_raw = '*';\n\t\t\tbreak;\n\n\t\tcase TS:\n\t\t\tif (!decodets(value, &lfp))\n\t\t\t\toutput_raw = '?';\n\t\t\telse\n\t\t\t\toutput(fp, name, prettydate(&lfp));\n\t\t\tbreak;\n\n\t\tcase HA:\t/* fallthru */\n\t\tcase NA:\n\t\t\tif (!decodenetnum(value, &hval)) {\n\t\t\t\toutput_raw = '?';\n\t\t\t} else if (fmt == HA){\n\t\t\t\toutput(fp, name, nntohost(&hval));\n\t\t\t} else {\n\t\t\t\toutput(fp, name, stoa(&hval));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase RF:\n\t\t\tif (decodenetnum(value, &hval)) {\n\t\t\t\tif (ISREFCLOCKADR(&hval))\n\t\t\t\t\toutput(fp, name,\n\t\t\t\t\t       refnumtoa(&hval));\n\t\t\t\telse\n\t\t\t\t\toutput(fp, name, stoa(&hval));\n\t\t\t} else if (strlen(value) <= 4) {\n\t\t\t\toutput(fp, name, value);\n\t\t\t} else {\n\t\t\t\toutput_raw = '?';\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase LP:\n\t\t\tif (!decodeuint(value, &uval) || uval > 3) {\n\t\t\t\toutput_raw = '?';\n\t\t\t} else {\n\t\t\t\tb[0] = (0x2 & uval)\n\t\t\t\t\t   ? '1'\n\t\t\t\t\t   : '0';\n\t\t\t\tb[1] = (0x1 & uval)\n\t\t\t\t\t   ? '1'\n\t\t\t\t\t   : '0';\n\t\t\t\tb[2] = '\\0';\n\t\t\t\toutput(fp, name, b);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OC:\n\t\t\tif (!decodeuint(value, &uval)) {\n\t\t\t\toutput_raw = '?';\n\t\t\t} else {\n\t\t\t\tsnprintf(b, sizeof(b), \"%03lo\", uval);\n\t\t\t\toutput(fp, name, b);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase AR:\n\t\t\tif (!decodearr(value, &narr, lfparr))\n\t\t\t\toutput_raw = '?';\n\t\t\telse\n\t\t\t\toutputarr(fp, name, narr, lfparr);\n\t\t\tbreak;\n\n\t\tcase FX:\n\t\t\tif (!decodeuint(value, &uval))\n\t\t\t\toutput_raw = '?';\n\t\t\telse\n\t\t\t\toutput(fp, name, tstflags(uval));\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Internal error in cookedprint, %s=%s, fmt %d\\n\",\n\t\t\t\tname, value, fmt);\n\t\t\toutput_raw = '?';\n\t\t\tbreak;\n\t\t}\n\n\t\tif (output_raw != 0) {\n\t\t\tatoascii(name, MAXVARLEN, bn, sizeof(bn));\n\t\t\tatoascii(value, MAXVALLEN, bv, sizeof(bv));\n\t\t\tif (output_raw != '*') {\n\t\t\t\tlen = strlen(bv);\n\t\t\t\tbv[len] = output_raw;\n\t\t\t\tbv[len+1] = '\\0';\n\t\t\t}\n\t\t\toutput(fp, bn, bv);\n\t\t}\n\t}\n\tendoutput(fp);\n}", "func_hash": 117019892599870517074003591750988787973, "file_name": "ntpq.c", "file_hash": 263164452008239257044928277190655422420, "cwe": ["CWE-20"], "cve": "CVE-2015-7852", "cve_desc": "ntpq in NTP 4.2.x before 4.2.8p4, and 4.3.x before 4.3.77 allows remote attackers to cause a denial of service (crash) via crafted mode 6 response packets.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-7852"}
{"idx": 451731, "project": "ntp", "commit_id": "07a5b8141e354a998a52994c3c9cd547927e56ce", "project_url": "https://github.com/ntp-project/ntp", "commit_url": "https://github.com/ntp-project/ntp/commit/07a5b8141e354a998a52994c3c9cd547927e56ce", "commit_message": "[TALOS-CAN-0063] avoid buffer overrun in ntpq", "target": 0, "func": "cookedprint(\n\tint datatype,\n\tint length,\n\tconst char *data,\n\tint status,\n\tint quiet,\n\tFILE *fp\n\t)\n{\n\tchar *name;\n\tchar *value;\n\tchar output_raw;\n\tint fmt;\n\tl_fp lfp;\n\tsockaddr_u hval;\n\tu_long uval;\n\tint narr;\n\tsize_t len;\n\tl_fp lfparr[8];\n\tchar b[12];\n\tchar bn[2 * MAXVARLEN];\n\tchar bv[2 * MAXVALLEN];\n\n\tUNUSED_ARG(datatype);\n\n\tif (!quiet)\n\t\tfprintf(fp, \"status=%04x %s,\\n\", status,\n\t\t\tstatustoa(datatype, status));\n\n\tstartoutput();\n\twhile (nextvar(&length, &data, &name, &value)) {\n\t\tfmt = varfmt(name);\n\t\toutput_raw = 0;\n\t\tswitch (fmt) {\n\n\t\tcase PADDING:\n\t\t\toutput_raw = '*';\n\t\t\tbreak;\n\n\t\tcase TS:\n\t\t\tif (!decodets(value, &lfp))\n\t\t\t\toutput_raw = '?';\n\t\t\telse\n\t\t\t\toutput(fp, name, prettydate(&lfp));\n\t\t\tbreak;\n\n\t\tcase HA:\t/* fallthru */\n\t\tcase NA:\n\t\t\tif (!decodenetnum(value, &hval)) {\n\t\t\t\toutput_raw = '?';\n\t\t\t} else if (fmt == HA){\n\t\t\t\toutput(fp, name, nntohost(&hval));\n\t\t\t} else {\n\t\t\t\toutput(fp, name, stoa(&hval));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase RF:\n\t\t\tif (decodenetnum(value, &hval)) {\n\t\t\t\tif (ISREFCLOCKADR(&hval))\n\t\t\t\t\toutput(fp, name,\n\t\t\t\t\t       refnumtoa(&hval));\n\t\t\t\telse\n\t\t\t\t\toutput(fp, name, stoa(&hval));\n\t\t\t} else if (strlen(value) <= 4) {\n\t\t\t\toutput(fp, name, value);\n\t\t\t} else {\n\t\t\t\toutput_raw = '?';\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase LP:\n\t\t\tif (!decodeuint(value, &uval) || uval > 3) {\n\t\t\t\toutput_raw = '?';\n\t\t\t} else {\n\t\t\t\tb[0] = (0x2 & uval)\n\t\t\t\t\t   ? '1'\n\t\t\t\t\t   : '0';\n\t\t\t\tb[1] = (0x1 & uval)\n\t\t\t\t\t   ? '1'\n\t\t\t\t\t   : '0';\n\t\t\t\tb[2] = '\\0';\n\t\t\t\toutput(fp, name, b);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OC:\n\t\t\tif (!decodeuint(value, &uval)) {\n\t\t\t\toutput_raw = '?';\n\t\t\t} else {\n\t\t\t\tsnprintf(b, sizeof(b), \"%03lo\", uval);\n\t\t\t\toutput(fp, name, b);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase AR:\n\t\t\tif (!decodearr(value, &narr, lfparr))\n\t\t\t\toutput_raw = '?';\n\t\t\telse\n\t\t\t\toutputarr(fp, name, narr, lfparr);\n\t\t\tbreak;\n\n\t\tcase FX:\n\t\t\tif (!decodeuint(value, &uval))\n\t\t\t\toutput_raw = '?';\n\t\t\telse\n\t\t\t\toutput(fp, name, tstflags(uval));\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Internal error in cookedprint, %s=%s, fmt %d\\n\",\n\t\t\t\tname, value, fmt);\n\t\t\toutput_raw = '?';\n\t\t\tbreak;\n\t\t}\n\n\t\tif (output_raw != 0) {\n\t\t\t/* TALOS-CAN-0063: avoid buffer overrun */\n\t\t\tatoascii(name, MAXVARLEN, bn, sizeof(bn));\n\t\t\tif (output_raw != '*') {\n\t\t\t\tatoascii(value, MAXVALLEN,\n\t\t\t\t\t bv, sizeof(bv) - 1);\n\t\t\t\tlen = strlen(bv);\n\t\t\t\tbv[len] = output_raw;\n\t\t\t\tbv[len+1] = '\\0';\n\t\t\t} else {\n\t\t\t\tatoascii(value, MAXVALLEN,\n\t\t\t\t\t bv, sizeof(bv));\n\t\t\t}\n\t\t\toutput(fp, bn, bv);\n\t\t}\n\t}\n\tendoutput(fp);\n}", "func_hash": 286888330459003026331284434605345848005, "file_name": "ntpq.c", "file_hash": 291788569529258980351890148746025724022, "cwe": ["CWE-20"], "cve": "CVE-2015-7852", "cve_desc": "ntpq in NTP 4.2.x before 4.2.8p4, and 4.3.x before 4.3.77 allows remote attackers to cause a denial of service (crash) via crafted mode 6 response packets.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-7852"}
{"idx": 211785, "project": "jasper", "commit_id": "4cd52b5daac62b00a0a328451544807ddecf775f", "project_url": "https://github.com/mdadams/jasper", "commit_url": "https://github.com/jasper-software/jasper/commit/4cd52b5daac62b00a0a328451544807ddecf775f", "commit_message": "Avoid maxrlvls more than upper bound to cause heap-buffer-overflow", "target": 1, "func": "static jpc_enc_cp_t *cp_create(const char *optstr, jas_image_t *image)\n{\n\tjpc_enc_cp_t *cp;\n\tjas_tvparser_t *tvp;\n\tint ret;\n\tint numilyrrates;\n\tdouble *ilyrrates;\n\tint i;\n\tint tagid;\n\tjpc_enc_tcp_t *tcp;\n\tjpc_enc_tccp_t *tccp;\n\tjpc_enc_ccp_t *ccp;\n\tuint_fast16_t rlvlno;\n\tuint_fast16_t prcwidthexpn;\n\tuint_fast16_t prcheightexpn;\n\tbool enablemct;\n\tuint_fast32_t jp2overhead;\n\tuint_fast16_t lyrno;\n\tuint_fast32_t hsteplcm;\n\tuint_fast32_t vsteplcm;\n\tbool mctvalid;\n\n\ttvp = 0;\n\tcp = 0;\n\tilyrrates = 0;\n\tnumilyrrates = 0;\n\n\tif (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) {\n\t\tgoto error;\n\t}\n\n\tprcwidthexpn = 15;\n\tprcheightexpn = 15;\n\tenablemct = true;\n\tjp2overhead = 0;\n\n\tcp->ccps = 0;\n\tcp->debug = 0;\n\tcp->imgareatlx = UINT_FAST32_MAX;\n\tcp->imgareatly = UINT_FAST32_MAX;\n\tcp->refgrdwidth = 0;\n\tcp->refgrdheight = 0;\n\tcp->tilegrdoffx = UINT_FAST32_MAX;\n\tcp->tilegrdoffy = UINT_FAST32_MAX;\n\tcp->tilewidth = 0;\n\tcp->tileheight = 0;\n\tcp->numcmpts = jas_image_numcmpts(image);\n\n\thsteplcm = 1;\n\tvsteplcm = 1;\n\tfor (unsigned cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {\n\t\tif (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <=\n\t\t  jas_image_brx(image) || jas_image_cmptbry(image, cmptno) +\n\t\t  jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) {\n\t\t\tjas_eprintf(\"unsupported image type\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\t/* Note: We ought to be calculating the LCMs here.  Fix some day. */\n\t\thsteplcm *= jas_image_cmpthstep(image, cmptno);\n\t\tvsteplcm *= jas_image_cmptvstep(image, cmptno);\n\t}\n\n\tif (!(cp->ccps = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_ccp_t)))) {\n\t\tgoto error;\n\t}\n\tunsigned cmptno;\n\tfor (cmptno = 0, ccp = cp->ccps; cmptno < cp->numcmpts; ++cmptno,\n\t  ++ccp) {\n\t\tccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno);\n\t\tccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno);\n\t\t/* XXX - this isn't quite correct for more general image */\n\t\tccp->sampgrdsubstepx = 0;\n\t\tccp->sampgrdsubstepx = 0;\n\t\tccp->prec = jas_image_cmptprec(image, cmptno);\n\t\tccp->sgnd = jas_image_cmptsgnd(image, cmptno);\n\t\tccp->numstepsizes = 0;\n\t\tmemset(ccp->stepsizes, 0, sizeof(ccp->stepsizes));\n\t}\n\n\tcp->rawsize = jas_image_rawsize(image);\n\tif (cp->rawsize == 0) {\n\t\t/* prevent division by zero in cp_create() */\n\t\tgoto error;\n\t}\n\tcp->totalsize = UINT_FAST32_MAX;\n\n\ttcp = &cp->tcp;\n\ttcp->csty = 0;\n\ttcp->intmode = true;\n\ttcp->prg = JPC_COD_LRCPPRG;\n\ttcp->numlyrs = 1;\n\ttcp->ilyrrates = 0;\n\n\ttccp = &cp->tccp;\n\ttccp->csty = 0;\n\ttccp->maxrlvls = 6;\n\ttccp->cblkwidthexpn = 6;\n\ttccp->cblkheightexpn = 6;\n\ttccp->cblksty = 0;\n\ttccp->numgbits = 2;\n\n\tif (!(tvp = jas_tvparser_create(optstr ? optstr : \"\"))) {\n\t\tgoto error;\n\t}\n\n\twhile (!(ret = jas_tvparser_next(tvp))) {\n\t\tswitch (jas_taginfo_nonull(jas_taginfos_lookup(encopts,\n\t\t  jas_tvparser_gettag(tvp)))->id) {\n\t\tcase OPT_DEBUG:\n\t\t\tcp->debug = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_IMGAREAOFFX:\n\t\t\tcp->imgareatlx = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_IMGAREAOFFY:\n\t\t\tcp->imgareatly = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_TILEGRDOFFX:\n\t\t\tcp->tilegrdoffx = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_TILEGRDOFFY:\n\t\t\tcp->tilegrdoffy = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_TILEWIDTH:\n\t\t\tcp->tilewidth = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_TILEHEIGHT:\n\t\t\tcp->tileheight = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_PRCWIDTH:\n\t\t\tprcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));\n\t\t\tbreak;\n\t\tcase OPT_PRCHEIGHT:\n\t\t\tprcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));\n\t\t\tbreak;\n\t\tcase OPT_CBLKWIDTH:\n\t\t\ttccp->cblkwidthexpn =\n\t\t\t  jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));\n\t\t\tbreak;\n\t\tcase OPT_CBLKHEIGHT:\n\t\t\ttccp->cblkheightexpn =\n\t\t\t  jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));\n\t\t\tbreak;\n\t\tcase OPT_MODE:\n\t\t\tif ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab,\n\t\t\t  jas_tvparser_getval(tvp)))->id) < 0) {\n\t\t\t\tjas_eprintf(\"ignoring invalid mode %s\\n\",\n\t\t\t\t  jas_tvparser_getval(tvp));\n\t\t\t} else {\n\t\t\t\ttcp->intmode = (tagid == MODE_INT);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OPT_PRG:\n\t\t\tif ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab,\n\t\t\t  jas_tvparser_getval(tvp)))->id) < 0) {\n\t\t\t\tjas_eprintf(\"ignoring invalid progression order %s\\n\",\n\t\t\t\t  jas_tvparser_getval(tvp));\n\t\t\t} else {\n\t\t\t\ttcp->prg = tagid;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OPT_NOMCT:\n\t\t\tenablemct = false;\n\t\t\tbreak;\n\t\tcase OPT_MAXRLVLS:\n\t\t\ttccp->maxrlvls = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_SOP:\n\t\t\tcp->tcp.csty |= JPC_COD_SOP;\n\t\t\tbreak;\n\t\tcase OPT_EPH:\n\t\t\tcp->tcp.csty |= JPC_COD_EPH;\n\t\t\tbreak;\n\t\tcase OPT_LAZY:\n\t\t\ttccp->cblksty |= JPC_COX_LAZY;\n\t\t\tbreak;\n\t\tcase OPT_TERMALL:\n\t\t\ttccp->cblksty |= JPC_COX_TERMALL;\n\t\t\tbreak;\n\t\tcase OPT_SEGSYM:\n\t\t\ttccp->cblksty |= JPC_COX_SEGSYM;\n\t\t\tbreak;\n\t\tcase OPT_VCAUSAL:\n\t\t\ttccp->cblksty |= JPC_COX_VSC;\n\t\t\tbreak;\n\t\tcase OPT_RESET:\n\t\t\ttccp->cblksty |= JPC_COX_RESET;\n\t\t\tbreak;\n\t\tcase OPT_PTERM:\n\t\t\ttccp->cblksty |= JPC_COX_PTERM;\n\t\t\tbreak;\n\t\tcase OPT_NUMGBITS:\n\t\t\tcp->tccp.numgbits = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_RATE:\n\t\t\tif (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize,\n\t\t\t  &cp->totalsize)) {\n\t\t\t\tjas_eprintf(\"ignoring bad rate specifier %s\\n\",\n\t\t\t\t  jas_tvparser_getval(tvp));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OPT_ILYRRATES:\n\t\t\tif (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates,\n\t\t\t  &ilyrrates)) {\n\t\t\t\tjas_eprintf(\"warning: invalid intermediate layer rates specifier ignored (%s)\\n\",\n\t\t\t\t  jas_tvparser_getval(tvp));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OPT_JP2OVERHEAD:\n\t\t\tjp2overhead = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tjas_eprintf(\"warning: ignoring invalid option %s\\n\",\n\t\t\t jas_tvparser_gettag(tvp));\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tjas_tvparser_destroy(tvp);\n\ttvp = 0;\n\n\tif (cp->totalsize != UINT_FAST32_MAX) {\n\t\tcp->totalsize = (cp->totalsize > jp2overhead) ?\n\t\t  (cp->totalsize - jp2overhead) : 0;\n\t}\n\n\tif (cp->imgareatlx == UINT_FAST32_MAX) {\n\t\tcp->imgareatlx = 0;\n\t} else {\n\t\tif (hsteplcm != 1) {\n\t\t\tjas_eprintf(\"warning: overriding imgareatlx value\\n\");\n\t\t}\n\t\tcp->imgareatlx *= hsteplcm;\n\t}\n\tif (cp->imgareatly == UINT_FAST32_MAX) {\n\t\tcp->imgareatly = 0;\n\t} else {\n\t\tif (vsteplcm != 1) {\n\t\t\tjas_eprintf(\"warning: overriding imgareatly value\\n\");\n\t\t}\n\t\tcp->imgareatly *= vsteplcm;\n\t}\n\tcp->refgrdwidth = cp->imgareatlx + jas_image_width(image);\n\tcp->refgrdheight = cp->imgareatly + jas_image_height(image);\n\tif (cp->tilegrdoffx == UINT_FAST32_MAX) {\n\t\tcp->tilegrdoffx = cp->imgareatlx;\n\t}\n\tif (cp->tilegrdoffy == UINT_FAST32_MAX) {\n\t\tcp->tilegrdoffy = cp->imgareatly;\n\t}\n\tif (!cp->tilewidth) {\n\t\tcp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx;\n\t}\n\tif (!cp->tileheight) {\n\t\tcp->tileheight = cp->refgrdheight - cp->tilegrdoffy;\n\t}\n\n\tif (cp->numcmpts == 3) {\n\t\tmctvalid = true;\n\t\tfor (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {\n\t\t\tif (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) ||\n\t\t\t  jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) ||\n\t\t\t  jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) ||\n\t\t\t  jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) {\n\t\t\t\tmctvalid = false;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tmctvalid = false;\n\t}\n\tif (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) {\n\t\tjas_eprintf(\"warning: color space apparently not RGB\\n\");\n\t}\n\tif (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) {\n\t\ttcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT);\n\t} else {\n\t\ttcp->mctid = JPC_MCT_NONE;\n\t}\n\ttccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS);\n\n\tfor (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {\n\t\ttccp->prcwidthexpns[rlvlno] = prcwidthexpn;\n\t\ttccp->prcheightexpns[rlvlno] = prcheightexpn;\n\t}\n\tif (prcwidthexpn != 15 || prcheightexpn != 15) {\n\t\ttccp->csty |= JPC_COX_PRT;\n\t}\n\n\t/* Ensure that the tile width and height is valid. */\n\tif (!cp->tilewidth) {\n\t\tjas_eprintf(\"invalid tile width %lu\\n\", (unsigned long)\n\t\t  cp->tilewidth);\n\t\tgoto error;\n\t}\n\tif (!cp->tileheight) {\n\t\tjas_eprintf(\"invalid tile height %lu\\n\", (unsigned long)\n\t\t  cp->tileheight);\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the tile grid offset is valid. */\n\tif (cp->tilegrdoffx > cp->imgareatlx ||\n\t  cp->tilegrdoffy > cp->imgareatly ||\n\t  cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx ||\n\t  cp->tilegrdoffy + cp->tileheight < cp->imgareatly) {\n\t\tjas_eprintf(\"invalid tile grid offset (%lu, %lu)\\n\",\n\t\t  (unsigned long) cp->tilegrdoffx, (unsigned long)\n\t\t  cp->tilegrdoffy);\n\t\tgoto error;\n\t}\n\n\tcp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx,\n\t  cp->tilewidth);\n\tcp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy,\n\t  cp->tileheight);\n\tcp->numtiles = cp->numhtiles * cp->numvtiles;\n\n\tif (ilyrrates && numilyrrates > 0) {\n\t\ttcp->numlyrs = numilyrrates + 1;\n\t\tif (!(tcp->ilyrrates = jas_alloc2((tcp->numlyrs - 1),\n\t\t  sizeof(jpc_fix_t)))) {\n\t\t\tgoto error;\n\t\t}\n\t\tfor (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) {\n\t\t\ttcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]);\n\t\t}\n\t}\n\n\t/* Ensure that the integer mode is used in the case of lossless\n\t  coding. */\n\tif (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) {\n\t\tjas_eprintf(\"cannot use real mode for lossless coding\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the precinct width is valid. */\n\tif (prcwidthexpn > 15) {\n\t\tjas_eprintf(\"invalid precinct width\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the precinct height is valid. */\n\tif (prcheightexpn > 15) {\n\t\tjas_eprintf(\"invalid precinct height\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the code block width is valid. */\n\tif (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) {\n\t\tjas_eprintf(\"invalid code block width %d\\n\",\n\t\t  JPC_POW2(cp->tccp.cblkwidthexpn));\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the code block height is valid. */\n\tif (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) {\n\t\tjas_eprintf(\"invalid code block height %d\\n\",\n\t\t  JPC_POW2(cp->tccp.cblkheightexpn));\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the code block size is not too large. */\n\tif (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) {\n\t\tjas_eprintf(\"code block size too large\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the number of layers is valid. */\n\tif (cp->tcp.numlyrs > 16384) {\n\t\tjas_eprintf(\"too many layers\\n\");\n\t\tgoto error;\n\t}\n\n\t/* There must be at least one resolution level. */\n\tif (cp->tccp.maxrlvls < 1) {\n\t\tjas_eprintf(\"must be at least one resolution level\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the number of guard bits is valid. */\n\tif (cp->tccp.numgbits > 8) {\n\t\tjas_eprintf(\"invalid number of guard bits\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the rate is within the legal range. */\n\tif (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) {\n\t\tjas_eprintf(\"warning: specified rate is unreasonably large (%lu > %lu)\\n\", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize);\n\t}\n\n\t/* Ensure that the intermediate layer rates are valid. */\n\tif (tcp->numlyrs > 1) {\n\t\t/* The intermediate layers rates must increase monotonically. */\n\t\tfor (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) {\n\t\t\tif (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) {\n\t\t\t\tjas_eprintf(\"intermediate layer rates must increase monotonically\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t\t/* The intermediate layer rates must be less than the overall rate. */\n\t\tif (cp->totalsize != UINT_FAST32_MAX) {\n\t\t\tfor (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) {\n\t\t\t\tif (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize)\n\t\t\t\t  / cp->rawsize) {\n\t\t\t\t\tjas_eprintf(\"warning: intermediate layer rates must be less than overall rate\\n\");\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (ilyrrates) {\n\t\tjas_free(ilyrrates);\n\t}\n\n\treturn cp;\n\nerror:\n\n\tif (ilyrrates) {\n\t\tjas_free(ilyrrates);\n\t}\n\tif (tvp) {\n\t\tjas_tvparser_destroy(tvp);\n\t}\n\tif (cp) {\n\t\tjpc_enc_cp_destroy(cp);\n\t}\n\treturn 0;\n}", "func_hash": 179213511260070262932724370978685731129, "file_name": "jpc_enc.c", "file_hash": 285191290025689593258555638021323781658, "cwe": ["CWE-20"], "cve": "CVE-2020-27828", "cve_desc": "There's a flaw in jasper's jpc encoder in versions prior to 2.0.23. Crafted input provided to jasper by an attacker could cause an arbitrary out-of-bounds write. This could potentially affect data confidentiality, integrity, or application availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27828"}
{"idx": 451888, "project": "jasper", "commit_id": "4cd52b5daac62b00a0a328451544807ddecf775f", "project_url": "https://github.com/mdadams/jasper", "commit_url": "https://github.com/jasper-software/jasper/commit/4cd52b5daac62b00a0a328451544807ddecf775f", "commit_message": "Avoid maxrlvls more than upper bound to cause heap-buffer-overflow", "target": 0, "func": "static jpc_enc_cp_t *cp_create(const char *optstr, jas_image_t *image)\n{\n\tjpc_enc_cp_t *cp;\n\tjas_tvparser_t *tvp;\n\tint ret;\n\tint numilyrrates;\n\tdouble *ilyrrates;\n\tint i;\n\tint tagid;\n\tjpc_enc_tcp_t *tcp;\n\tjpc_enc_tccp_t *tccp;\n\tjpc_enc_ccp_t *ccp;\n\tuint_fast16_t rlvlno;\n\tuint_fast16_t prcwidthexpn;\n\tuint_fast16_t prcheightexpn;\n\tbool enablemct;\n\tuint_fast32_t jp2overhead;\n\tuint_fast16_t lyrno;\n\tuint_fast32_t hsteplcm;\n\tuint_fast32_t vsteplcm;\n\tbool mctvalid;\n\n\ttvp = 0;\n\tcp = 0;\n\tilyrrates = 0;\n\tnumilyrrates = 0;\n\n\tif (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) {\n\t\tgoto error;\n\t}\n\n\tprcwidthexpn = 15;\n\tprcheightexpn = 15;\n\tenablemct = true;\n\tjp2overhead = 0;\n\n\tcp->ccps = 0;\n\tcp->debug = 0;\n\tcp->imgareatlx = UINT_FAST32_MAX;\n\tcp->imgareatly = UINT_FAST32_MAX;\n\tcp->refgrdwidth = 0;\n\tcp->refgrdheight = 0;\n\tcp->tilegrdoffx = UINT_FAST32_MAX;\n\tcp->tilegrdoffy = UINT_FAST32_MAX;\n\tcp->tilewidth = 0;\n\tcp->tileheight = 0;\n\tcp->numcmpts = jas_image_numcmpts(image);\n\n\thsteplcm = 1;\n\tvsteplcm = 1;\n\tfor (unsigned cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {\n\t\tif (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <=\n\t\t  jas_image_brx(image) || jas_image_cmptbry(image, cmptno) +\n\t\t  jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) {\n\t\t\tjas_eprintf(\"unsupported image type\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\t/* Note: We ought to be calculating the LCMs here.  Fix some day. */\n\t\thsteplcm *= jas_image_cmpthstep(image, cmptno);\n\t\tvsteplcm *= jas_image_cmptvstep(image, cmptno);\n\t}\n\n\tif (!(cp->ccps = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_ccp_t)))) {\n\t\tgoto error;\n\t}\n\tunsigned cmptno;\n\tfor (cmptno = 0, ccp = cp->ccps; cmptno < cp->numcmpts; ++cmptno,\n\t  ++ccp) {\n\t\tccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno);\n\t\tccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno);\n\t\t/* XXX - this isn't quite correct for more general image */\n\t\tccp->sampgrdsubstepx = 0;\n\t\tccp->sampgrdsubstepx = 0;\n\t\tccp->prec = jas_image_cmptprec(image, cmptno);\n\t\tccp->sgnd = jas_image_cmptsgnd(image, cmptno);\n\t\tccp->numstepsizes = 0;\n\t\tmemset(ccp->stepsizes, 0, sizeof(ccp->stepsizes));\n\t}\n\n\tcp->rawsize = jas_image_rawsize(image);\n\tif (cp->rawsize == 0) {\n\t\t/* prevent division by zero in cp_create() */\n\t\tgoto error;\n\t}\n\tcp->totalsize = UINT_FAST32_MAX;\n\n\ttcp = &cp->tcp;\n\ttcp->csty = 0;\n\ttcp->intmode = true;\n\ttcp->prg = JPC_COD_LRCPPRG;\n\ttcp->numlyrs = 1;\n\ttcp->ilyrrates = 0;\n\n\ttccp = &cp->tccp;\n\ttccp->csty = 0;\n\ttccp->maxrlvls = 6;\n\ttccp->cblkwidthexpn = 6;\n\ttccp->cblkheightexpn = 6;\n\ttccp->cblksty = 0;\n\ttccp->numgbits = 2;\n\n\tif (!(tvp = jas_tvparser_create(optstr ? optstr : \"\"))) {\n\t\tgoto error;\n\t}\n\n\twhile (!(ret = jas_tvparser_next(tvp))) {\n\t\tswitch (jas_taginfo_nonull(jas_taginfos_lookup(encopts,\n\t\t  jas_tvparser_gettag(tvp)))->id) {\n\t\tcase OPT_DEBUG:\n\t\t\tcp->debug = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_IMGAREAOFFX:\n\t\t\tcp->imgareatlx = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_IMGAREAOFFY:\n\t\t\tcp->imgareatly = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_TILEGRDOFFX:\n\t\t\tcp->tilegrdoffx = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_TILEGRDOFFY:\n\t\t\tcp->tilegrdoffy = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_TILEWIDTH:\n\t\t\tcp->tilewidth = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_TILEHEIGHT:\n\t\t\tcp->tileheight = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_PRCWIDTH:\n\t\t\tprcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));\n\t\t\tbreak;\n\t\tcase OPT_PRCHEIGHT:\n\t\t\tprcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));\n\t\t\tbreak;\n\t\tcase OPT_CBLKWIDTH:\n\t\t\ttccp->cblkwidthexpn =\n\t\t\t  jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));\n\t\t\tbreak;\n\t\tcase OPT_CBLKHEIGHT:\n\t\t\ttccp->cblkheightexpn =\n\t\t\t  jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));\n\t\t\tbreak;\n\t\tcase OPT_MODE:\n\t\t\tif ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab,\n\t\t\t  jas_tvparser_getval(tvp)))->id) < 0) {\n\t\t\t\tjas_eprintf(\"ignoring invalid mode %s\\n\",\n\t\t\t\t  jas_tvparser_getval(tvp));\n\t\t\t} else {\n\t\t\t\ttcp->intmode = (tagid == MODE_INT);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OPT_PRG:\n\t\t\tif ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab,\n\t\t\t  jas_tvparser_getval(tvp)))->id) < 0) {\n\t\t\t\tjas_eprintf(\"ignoring invalid progression order %s\\n\",\n\t\t\t\t  jas_tvparser_getval(tvp));\n\t\t\t} else {\n\t\t\t\ttcp->prg = tagid;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OPT_NOMCT:\n\t\t\tenablemct = false;\n\t\t\tbreak;\n\t\tcase OPT_MAXRLVLS:\n\t\t\ttccp->maxrlvls = atoi(jas_tvparser_getval(tvp));\n\t\t\tif(tccp->maxrlvls > JPC_MAXRLVLS) {\n\t\t\t\tjas_eprintf(\"invalid number of resolution levels upper than %d\\n\",JPC_MAXRLVLS);\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OPT_SOP:\n\t\t\tcp->tcp.csty |= JPC_COD_SOP;\n\t\t\tbreak;\n\t\tcase OPT_EPH:\n\t\t\tcp->tcp.csty |= JPC_COD_EPH;\n\t\t\tbreak;\n\t\tcase OPT_LAZY:\n\t\t\ttccp->cblksty |= JPC_COX_LAZY;\n\t\t\tbreak;\n\t\tcase OPT_TERMALL:\n\t\t\ttccp->cblksty |= JPC_COX_TERMALL;\n\t\t\tbreak;\n\t\tcase OPT_SEGSYM:\n\t\t\ttccp->cblksty |= JPC_COX_SEGSYM;\n\t\t\tbreak;\n\t\tcase OPT_VCAUSAL:\n\t\t\ttccp->cblksty |= JPC_COX_VSC;\n\t\t\tbreak;\n\t\tcase OPT_RESET:\n\t\t\ttccp->cblksty |= JPC_COX_RESET;\n\t\t\tbreak;\n\t\tcase OPT_PTERM:\n\t\t\ttccp->cblksty |= JPC_COX_PTERM;\n\t\t\tbreak;\n\t\tcase OPT_NUMGBITS:\n\t\t\tcp->tccp.numgbits = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase OPT_RATE:\n\t\t\tif (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize,\n\t\t\t  &cp->totalsize)) {\n\t\t\t\tjas_eprintf(\"ignoring bad rate specifier %s\\n\",\n\t\t\t\t  jas_tvparser_getval(tvp));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OPT_ILYRRATES:\n\t\t\tif (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates,\n\t\t\t  &ilyrrates)) {\n\t\t\t\tjas_eprintf(\"warning: invalid intermediate layer rates specifier ignored (%s)\\n\",\n\t\t\t\t  jas_tvparser_getval(tvp));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OPT_JP2OVERHEAD:\n\t\t\tjp2overhead = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tjas_eprintf(\"warning: ignoring invalid option %s\\n\",\n\t\t\t jas_tvparser_gettag(tvp));\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tjas_tvparser_destroy(tvp);\n\ttvp = 0;\n\n\tif (cp->totalsize != UINT_FAST32_MAX) {\n\t\tcp->totalsize = (cp->totalsize > jp2overhead) ?\n\t\t  (cp->totalsize - jp2overhead) : 0;\n\t}\n\n\tif (cp->imgareatlx == UINT_FAST32_MAX) {\n\t\tcp->imgareatlx = 0;\n\t} else {\n\t\tif (hsteplcm != 1) {\n\t\t\tjas_eprintf(\"warning: overriding imgareatlx value\\n\");\n\t\t}\n\t\tcp->imgareatlx *= hsteplcm;\n\t}\n\tif (cp->imgareatly == UINT_FAST32_MAX) {\n\t\tcp->imgareatly = 0;\n\t} else {\n\t\tif (vsteplcm != 1) {\n\t\t\tjas_eprintf(\"warning: overriding imgareatly value\\n\");\n\t\t}\n\t\tcp->imgareatly *= vsteplcm;\n\t}\n\tcp->refgrdwidth = cp->imgareatlx + jas_image_width(image);\n\tcp->refgrdheight = cp->imgareatly + jas_image_height(image);\n\tif (cp->tilegrdoffx == UINT_FAST32_MAX) {\n\t\tcp->tilegrdoffx = cp->imgareatlx;\n\t}\n\tif (cp->tilegrdoffy == UINT_FAST32_MAX) {\n\t\tcp->tilegrdoffy = cp->imgareatly;\n\t}\n\tif (!cp->tilewidth) {\n\t\tcp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx;\n\t}\n\tif (!cp->tileheight) {\n\t\tcp->tileheight = cp->refgrdheight - cp->tilegrdoffy;\n\t}\n\n\tif (cp->numcmpts == 3) {\n\t\tmctvalid = true;\n\t\tfor (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {\n\t\t\tif (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) ||\n\t\t\t  jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) ||\n\t\t\t  jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) ||\n\t\t\t  jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) {\n\t\t\t\tmctvalid = false;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tmctvalid = false;\n\t}\n\tif (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) {\n\t\tjas_eprintf(\"warning: color space apparently not RGB\\n\");\n\t}\n\tif (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) {\n\t\ttcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT);\n\t} else {\n\t\ttcp->mctid = JPC_MCT_NONE;\n\t}\n\ttccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS);\n\n\tfor (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {\n\t\ttccp->prcwidthexpns[rlvlno] = prcwidthexpn;\n\t\ttccp->prcheightexpns[rlvlno] = prcheightexpn;\n\t}\n\tif (prcwidthexpn != 15 || prcheightexpn != 15) {\n\t\ttccp->csty |= JPC_COX_PRT;\n\t}\n\n\t/* Ensure that the tile width and height is valid. */\n\tif (!cp->tilewidth) {\n\t\tjas_eprintf(\"invalid tile width %lu\\n\", (unsigned long)\n\t\t  cp->tilewidth);\n\t\tgoto error;\n\t}\n\tif (!cp->tileheight) {\n\t\tjas_eprintf(\"invalid tile height %lu\\n\", (unsigned long)\n\t\t  cp->tileheight);\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the tile grid offset is valid. */\n\tif (cp->tilegrdoffx > cp->imgareatlx ||\n\t  cp->tilegrdoffy > cp->imgareatly ||\n\t  cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx ||\n\t  cp->tilegrdoffy + cp->tileheight < cp->imgareatly) {\n\t\tjas_eprintf(\"invalid tile grid offset (%lu, %lu)\\n\",\n\t\t  (unsigned long) cp->tilegrdoffx, (unsigned long)\n\t\t  cp->tilegrdoffy);\n\t\tgoto error;\n\t}\n\n\tcp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx,\n\t  cp->tilewidth);\n\tcp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy,\n\t  cp->tileheight);\n\tcp->numtiles = cp->numhtiles * cp->numvtiles;\n\n\tif (ilyrrates && numilyrrates > 0) {\n\t\ttcp->numlyrs = numilyrrates + 1;\n\t\tif (!(tcp->ilyrrates = jas_alloc2((tcp->numlyrs - 1),\n\t\t  sizeof(jpc_fix_t)))) {\n\t\t\tgoto error;\n\t\t}\n\t\tfor (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) {\n\t\t\ttcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]);\n\t\t}\n\t}\n\n\t/* Ensure that the integer mode is used in the case of lossless\n\t  coding. */\n\tif (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) {\n\t\tjas_eprintf(\"cannot use real mode for lossless coding\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the precinct width is valid. */\n\tif (prcwidthexpn > 15) {\n\t\tjas_eprintf(\"invalid precinct width\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the precinct height is valid. */\n\tif (prcheightexpn > 15) {\n\t\tjas_eprintf(\"invalid precinct height\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the code block width is valid. */\n\tif (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) {\n\t\tjas_eprintf(\"invalid code block width %d\\n\",\n\t\t  JPC_POW2(cp->tccp.cblkwidthexpn));\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the code block height is valid. */\n\tif (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) {\n\t\tjas_eprintf(\"invalid code block height %d\\n\",\n\t\t  JPC_POW2(cp->tccp.cblkheightexpn));\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the code block size is not too large. */\n\tif (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) {\n\t\tjas_eprintf(\"code block size too large\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the number of layers is valid. */\n\tif (cp->tcp.numlyrs > 16384) {\n\t\tjas_eprintf(\"too many layers\\n\");\n\t\tgoto error;\n\t}\n\n\t/* There must be at least one resolution level. */\n\tif (cp->tccp.maxrlvls < 1) {\n\t\tjas_eprintf(\"must be at least one resolution level\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the number of guard bits is valid. */\n\tif (cp->tccp.numgbits > 8) {\n\t\tjas_eprintf(\"invalid number of guard bits\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Ensure that the rate is within the legal range. */\n\tif (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) {\n\t\tjas_eprintf(\"warning: specified rate is unreasonably large (%lu > %lu)\\n\", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize);\n\t}\n\n\t/* Ensure that the intermediate layer rates are valid. */\n\tif (tcp->numlyrs > 1) {\n\t\t/* The intermediate layers rates must increase monotonically. */\n\t\tfor (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) {\n\t\t\tif (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) {\n\t\t\t\tjas_eprintf(\"intermediate layer rates must increase monotonically\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t\t/* The intermediate layer rates must be less than the overall rate. */\n\t\tif (cp->totalsize != UINT_FAST32_MAX) {\n\t\t\tfor (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) {\n\t\t\t\tif (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize)\n\t\t\t\t  / cp->rawsize) {\n\t\t\t\t\tjas_eprintf(\"warning: intermediate layer rates must be less than overall rate\\n\");\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (ilyrrates) {\n\t\tjas_free(ilyrrates);\n\t}\n\n\treturn cp;\n\nerror:\n\n\tif (ilyrrates) {\n\t\tjas_free(ilyrrates);\n\t}\n\tif (tvp) {\n\t\tjas_tvparser_destroy(tvp);\n\t}\n\tif (cp) {\n\t\tjpc_enc_cp_destroy(cp);\n\t}\n\treturn 0;\n}", "func_hash": 258879101783368514234166952366199989021, "file_name": "jpc_enc.c", "file_hash": 134316338883827501672124248295180144242, "cwe": ["CWE-20"], "cve": "CVE-2020-27828", "cve_desc": "There's a flaw in jasper's jpc encoder in versions prior to 2.0.23. Crafted input provided to jasper by an attacker could cause an arbitrary out-of-bounds write. This could potentially affect data confidentiality, integrity, or application availability.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-27828"}
{"idx": 211842, "project": "vim", "commit_id": "4e889f98e95ac05d7c8bd3ee933ab4d47820fdfa", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/4e889f98e95ac05d7c8bd3ee933ab4d47820fdfa", "commit_message": "patch 8.2.4436: crash with weird 'vartabstop' value\n\nProblem:    Crash with weird 'vartabstop' value.\nSolution:   Check for running into the end of the line.", "target": 1, "func": "change_indent(\n    int\t\ttype,\n    int\t\tamount,\n    int\t\tround,\n    int\t\treplaced,\t// replaced character, put on replace stack\n    int\t\tcall_changed_bytes)\t// call changed_bytes()\n{\n    int\t\tvcol;\n    int\t\tlast_vcol;\n    int\t\tinsstart_less;\t\t// reduction for Insstart.col\n    int\t\tnew_cursor_col;\n    int\t\ti;\n    char_u\t*ptr;\n    int\t\tsave_p_list;\n    int\t\tstart_col;\n    colnr_T\tvc;\n    colnr_T\torig_col = 0;\t\t// init for GCC\n    char_u\t*new_line, *orig_line = NULL;\t// init for GCC\n\n    // VREPLACE mode needs to know what the line was like before changing\n    if (State & VREPLACE_FLAG)\n    {\n\torig_line = vim_strsave(ml_get_curline());  // Deal with NULL below\n\torig_col = curwin->w_cursor.col;\n    }\n\n    // for the following tricks we don't want list mode\n    save_p_list = curwin->w_p_list;\n    curwin->w_p_list = FALSE;\n    vc = getvcol_nolist(&curwin->w_cursor);\n    vcol = vc;\n\n    // For Replace mode we need to fix the replace stack later, which is only\n    // possible when the cursor is in the indent.  Remember the number of\n    // characters before the cursor if it's possible.\n    start_col = curwin->w_cursor.col;\n\n    // determine offset from first non-blank\n    new_cursor_col = curwin->w_cursor.col;\n    beginline(BL_WHITE);\n    new_cursor_col -= curwin->w_cursor.col;\n\n    insstart_less = curwin->w_cursor.col;\n\n    // If the cursor is in the indent, compute how many screen columns the\n    // cursor is to the left of the first non-blank.\n    if (new_cursor_col < 0)\n\tvcol = get_indent() - vcol;\n\n    if (new_cursor_col > 0)\t    // can't fix replace stack\n\tstart_col = -1;\n\n    // Set the new indent.  The cursor will be put on the first non-blank.\n    if (type == INDENT_SET)\n\t(void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0);\n    else\n    {\n\tint\tsave_State = State;\n\n\t// Avoid being called recursively.\n\tif (State & VREPLACE_FLAG)\n\t    State = INSERT;\n\tshift_line(type == INDENT_DEC, round, 1, call_changed_bytes);\n\tState = save_State;\n    }\n    insstart_less -= curwin->w_cursor.col;\n\n    // Try to put cursor on same character.\n    // If the cursor is at or after the first non-blank in the line,\n    // compute the cursor column relative to the column of the first\n    // non-blank character.\n    // If we are not in insert mode, leave the cursor on the first non-blank.\n    // If the cursor is before the first non-blank, position it relative\n    // to the first non-blank, counted in screen columns.\n    if (new_cursor_col >= 0)\n    {\n\t// When changing the indent while the cursor is touching it, reset\n\t// Insstart_col to 0.\n\tif (new_cursor_col == 0)\n\t    insstart_less = MAXCOL;\n\tnew_cursor_col += curwin->w_cursor.col;\n    }\n    else if (!(State & INSERT))\n\tnew_cursor_col = curwin->w_cursor.col;\n    else\n    {\n\t// Compute the screen column where the cursor should be.\n\tvcol = get_indent() - vcol;\n\tcurwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol);\n\n\t// Advance the cursor until we reach the right screen column.\n\tvcol = last_vcol = 0;\n\tnew_cursor_col = -1;\n\tptr = ml_get_curline();\n\twhile (vcol <= (int)curwin->w_virtcol)\n\t{\n\t    last_vcol = vcol;\n\t    if (has_mbyte && new_cursor_col >= 0)\n\t\tnew_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col);\n\t    else\n\t\t++new_cursor_col;\n\t    vcol += lbr_chartabsize(ptr, ptr + new_cursor_col, (colnr_T)vcol);\n\t}\n\tvcol = last_vcol;\n\n\t// May need to insert spaces to be able to position the cursor on\n\t// the right screen column.\n\tif (vcol != (int)curwin->w_virtcol)\n\t{\n\t    curwin->w_cursor.col = (colnr_T)new_cursor_col;\n\t    i = (int)curwin->w_virtcol - vcol;\n\t    ptr = alloc(i + 1);\n\t    if (ptr != NULL)\n\t    {\n\t\tnew_cursor_col += i;\n\t\tptr[i] = NUL;\n\t\twhile (--i >= 0)\n\t\t    ptr[i] = ' ';\n\t\tins_str(ptr);\n\t\tvim_free(ptr);\n\t    }\n\t}\n\n\t// When changing the indent while the cursor is in it, reset\n\t// Insstart_col to 0.\n\tinsstart_less = MAXCOL;\n    }\n\n    curwin->w_p_list = save_p_list;\n\n    if (new_cursor_col <= 0)\n\tcurwin->w_cursor.col = 0;\n    else\n\tcurwin->w_cursor.col = (colnr_T)new_cursor_col;\n    curwin->w_set_curswant = TRUE;\n    changed_cline_bef_curs();\n\n    // May have to adjust the start of the insert.\n    if (State & INSERT)\n    {\n\tif (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0)\n\t{\n\t    if ((int)Insstart.col <= insstart_less)\n\t\tInsstart.col = 0;\n\t    else\n\t\tInsstart.col -= insstart_less;\n\t}\n\tif ((int)ai_col <= insstart_less)\n\t    ai_col = 0;\n\telse\n\t    ai_col -= insstart_less;\n    }\n\n    // For REPLACE mode, may have to fix the replace stack, if it's possible.\n    // If the number of characters before the cursor decreased, need to pop a\n    // few characters from the replace stack.\n    // If the number of characters before the cursor increased, need to push a\n    // few NULs onto the replace stack.\n    if (REPLACE_NORMAL(State) && start_col >= 0)\n    {\n\twhile (start_col > (int)curwin->w_cursor.col)\n\t{\n\t    replace_join(0);\t    // remove a NUL from the replace stack\n\t    --start_col;\n\t}\n\twhile (start_col < (int)curwin->w_cursor.col || replaced)\n\t{\n\t    replace_push(NUL);\n\t    if (replaced)\n\t    {\n\t\treplace_push(replaced);\n\t\treplaced = NUL;\n\t    }\n\t    ++start_col;\n\t}\n    }\n\n    // For VREPLACE mode, we also have to fix the replace stack.  In this case\n    // it is always possible because we backspace over the whole line and then\n    // put it back again the way we wanted it.\n    if (State & VREPLACE_FLAG)\n    {\n\t// If orig_line didn't allocate, just return.  At least we did the job,\n\t// even if you can't backspace.\n\tif (orig_line == NULL)\n\t    return;\n\n\t// Save new line\n\tnew_line = vim_strsave(ml_get_curline());\n\tif (new_line == NULL)\n\t    return;\n\n\t// We only put back the new line up to the cursor\n\tnew_line[curwin->w_cursor.col] = NUL;\n\n\t// Put back original line\n\tml_replace(curwin->w_cursor.lnum, orig_line, FALSE);\n\tcurwin->w_cursor.col = orig_col;\n\n\t// Backspace from cursor to start of line\n\tbackspace_until_column(0);\n\n\t// Insert new stuff into line again\n\tins_bytes(new_line);\n\n\tvim_free(new_line);\n    }\n}", "func_hash": 104434622616430304167109103842435027722, "file_name": "indent.c", "file_hash": 225104819640164774379021828754456921804, "cwe": ["CWE-787"], "cve": "CVE-2022-0714", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.4436.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0714"}
{"idx": 452377, "project": "vim", "commit_id": "4e889f98e95ac05d7c8bd3ee933ab4d47820fdfa", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/4e889f98e95ac05d7c8bd3ee933ab4d47820fdfa", "commit_message": "patch 8.2.4436: crash with weird 'vartabstop' value\n\nProblem:    Crash with weird 'vartabstop' value.\nSolution:   Check for running into the end of the line.", "target": 0, "func": "change_indent(\n    int\t\ttype,\n    int\t\tamount,\n    int\t\tround,\n    int\t\treplaced,\t// replaced character, put on replace stack\n    int\t\tcall_changed_bytes)\t// call changed_bytes()\n{\n    int\t\tvcol;\n    int\t\tlast_vcol;\n    int\t\tinsstart_less;\t\t// reduction for Insstart.col\n    int\t\tnew_cursor_col;\n    int\t\ti;\n    char_u\t*ptr;\n    int\t\tsave_p_list;\n    int\t\tstart_col;\n    colnr_T\tvc;\n    colnr_T\torig_col = 0;\t\t// init for GCC\n    char_u\t*new_line, *orig_line = NULL;\t// init for GCC\n\n    // VREPLACE mode needs to know what the line was like before changing\n    if (State & VREPLACE_FLAG)\n    {\n\torig_line = vim_strsave(ml_get_curline());  // Deal with NULL below\n\torig_col = curwin->w_cursor.col;\n    }\n\n    // for the following tricks we don't want list mode\n    save_p_list = curwin->w_p_list;\n    curwin->w_p_list = FALSE;\n    vc = getvcol_nolist(&curwin->w_cursor);\n    vcol = vc;\n\n    // For Replace mode we need to fix the replace stack later, which is only\n    // possible when the cursor is in the indent.  Remember the number of\n    // characters before the cursor if it's possible.\n    start_col = curwin->w_cursor.col;\n\n    // determine offset from first non-blank\n    new_cursor_col = curwin->w_cursor.col;\n    beginline(BL_WHITE);\n    new_cursor_col -= curwin->w_cursor.col;\n\n    insstart_less = curwin->w_cursor.col;\n\n    // If the cursor is in the indent, compute how many screen columns the\n    // cursor is to the left of the first non-blank.\n    if (new_cursor_col < 0)\n\tvcol = get_indent() - vcol;\n\n    if (new_cursor_col > 0)\t    // can't fix replace stack\n\tstart_col = -1;\n\n    // Set the new indent.  The cursor will be put on the first non-blank.\n    if (type == INDENT_SET)\n\t(void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0);\n    else\n    {\n\tint\tsave_State = State;\n\n\t// Avoid being called recursively.\n\tif (State & VREPLACE_FLAG)\n\t    State = INSERT;\n\tshift_line(type == INDENT_DEC, round, 1, call_changed_bytes);\n\tState = save_State;\n    }\n    insstart_less -= curwin->w_cursor.col;\n\n    // Try to put cursor on same character.\n    // If the cursor is at or after the first non-blank in the line,\n    // compute the cursor column relative to the column of the first\n    // non-blank character.\n    // If we are not in insert mode, leave the cursor on the first non-blank.\n    // If the cursor is before the first non-blank, position it relative\n    // to the first non-blank, counted in screen columns.\n    if (new_cursor_col >= 0)\n    {\n\t// When changing the indent while the cursor is touching it, reset\n\t// Insstart_col to 0.\n\tif (new_cursor_col == 0)\n\t    insstart_less = MAXCOL;\n\tnew_cursor_col += curwin->w_cursor.col;\n    }\n    else if (!(State & INSERT))\n\tnew_cursor_col = curwin->w_cursor.col;\n    else\n    {\n\t// Compute the screen column where the cursor should be.\n\tvcol = get_indent() - vcol;\n\tcurwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol);\n\n\t// Advance the cursor until we reach the right screen column.\n\tvcol = last_vcol = 0;\n\tnew_cursor_col = -1;\n\tptr = ml_get_curline();\n\twhile (vcol <= (int)curwin->w_virtcol)\n\t{\n\t    last_vcol = vcol;\n\t    if (has_mbyte && new_cursor_col >= 0)\n\t\tnew_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col);\n\t    else\n\t\t++new_cursor_col;\n\t    if (ptr[new_cursor_col] == NUL)\n\t\tbreak;\n\t    vcol += lbr_chartabsize(ptr, ptr + new_cursor_col, (colnr_T)vcol);\n\t}\n\tvcol = last_vcol;\n\n\t// May need to insert spaces to be able to position the cursor on\n\t// the right screen column.\n\tif (vcol != (int)curwin->w_virtcol)\n\t{\n\t    curwin->w_cursor.col = (colnr_T)new_cursor_col;\n\t    i = (int)curwin->w_virtcol - vcol;\n\t    ptr = alloc(i + 1);\n\t    if (ptr != NULL)\n\t    {\n\t\tnew_cursor_col += i;\n\t\tptr[i] = NUL;\n\t\twhile (--i >= 0)\n\t\t    ptr[i] = ' ';\n\t\tins_str(ptr);\n\t\tvim_free(ptr);\n\t    }\n\t}\n\n\t// When changing the indent while the cursor is in it, reset\n\t// Insstart_col to 0.\n\tinsstart_less = MAXCOL;\n    }\n\n    curwin->w_p_list = save_p_list;\n\n    if (new_cursor_col <= 0)\n\tcurwin->w_cursor.col = 0;\n    else\n\tcurwin->w_cursor.col = (colnr_T)new_cursor_col;\n    curwin->w_set_curswant = TRUE;\n    changed_cline_bef_curs();\n\n    // May have to adjust the start of the insert.\n    if (State & INSERT)\n    {\n\tif (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0)\n\t{\n\t    if ((int)Insstart.col <= insstart_less)\n\t\tInsstart.col = 0;\n\t    else\n\t\tInsstart.col -= insstart_less;\n\t}\n\tif ((int)ai_col <= insstart_less)\n\t    ai_col = 0;\n\telse\n\t    ai_col -= insstart_less;\n    }\n\n    // For REPLACE mode, may have to fix the replace stack, if it's possible.\n    // If the number of characters before the cursor decreased, need to pop a\n    // few characters from the replace stack.\n    // If the number of characters before the cursor increased, need to push a\n    // few NULs onto the replace stack.\n    if (REPLACE_NORMAL(State) && start_col >= 0)\n    {\n\twhile (start_col > (int)curwin->w_cursor.col)\n\t{\n\t    replace_join(0);\t    // remove a NUL from the replace stack\n\t    --start_col;\n\t}\n\twhile (start_col < (int)curwin->w_cursor.col || replaced)\n\t{\n\t    replace_push(NUL);\n\t    if (replaced)\n\t    {\n\t\treplace_push(replaced);\n\t\treplaced = NUL;\n\t    }\n\t    ++start_col;\n\t}\n    }\n\n    // For VREPLACE mode, we also have to fix the replace stack.  In this case\n    // it is always possible because we backspace over the whole line and then\n    // put it back again the way we wanted it.\n    if (State & VREPLACE_FLAG)\n    {\n\t// If orig_line didn't allocate, just return.  At least we did the job,\n\t// even if you can't backspace.\n\tif (orig_line == NULL)\n\t    return;\n\n\t// Save new line\n\tnew_line = vim_strsave(ml_get_curline());\n\tif (new_line == NULL)\n\t    return;\n\n\t// We only put back the new line up to the cursor\n\tnew_line[curwin->w_cursor.col] = NUL;\n\n\t// Put back original line\n\tml_replace(curwin->w_cursor.lnum, orig_line, FALSE);\n\tcurwin->w_cursor.col = orig_col;\n\n\t// Backspace from cursor to start of line\n\tbackspace_until_column(0);\n\n\t// Insert new stuff into line again\n\tins_bytes(new_line);\n\n\tvim_free(new_line);\n    }\n}", "func_hash": 281315459122812097070130024816280546627, "file_name": "indent.c", "file_hash": 175343284041603087029849272826009468440, "cwe": ["CWE-787"], "cve": "CVE-2022-0714", "cve_desc": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.4436.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0714"}
{"idx": 211845, "project": "ImageMagick6", "commit_id": "1aea203eb36409ce6903b9e41fe7cb70030e8750", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/1aea203eb36409ce6903b9e41fe7cb70030e8750", "commit_message": "squash heap-buffer-overflow, PoC TIFF from Hardik", "target": 1, "func": "static Image *ReadTIFFImage(const ImageInfo *image_info,\n  ExceptionInfo *exception)\n{\n#define MaxPixelChannels  32\n#define ThrowTIFFException(severity,message) \\\n{ \\\n  if (pixel_info != (MemoryInfo *) NULL) \\\n    pixel_info=RelinquishVirtualMemory(pixel_info); \\\n  if (quantum_info != (QuantumInfo *) NULL) \\\n    quantum_info=DestroyQuantumInfo(quantum_info); \\\n  TIFFClose(tiff); \\\n  ThrowReaderException(severity,message); \\\n}\n\n  const char\n    *option;\n\n  float\n    *chromaticity = (float *) NULL,\n    x_position,\n    y_position,\n    x_resolution,\n    y_resolution;\n\n  Image\n    *image;\n\n  int\n    tiff_status = 0;\n\n  MagickBooleanType\n    more_frames;\n\n  MagickStatusType\n    status;\n\n  MemoryInfo\n    *pixel_info = (MemoryInfo *) NULL;\n\n  QuantumInfo\n    *quantum_info;\n\n  QuantumType\n    quantum_type;\n\n  size_t\n    number_pixels;\n\n  ssize_t\n    i,\n    scanline_size,\n    y;\n\n  TIFF\n    *tiff;\n\n  TIFFMethodType\n    method;\n\n  uint16\n    compress_tag = 0,\n    bits_per_sample = 0,\n    endian = 0,\n    extra_samples = 0,\n    interlace = 0,\n    max_sample_value = 0,\n    min_sample_value = 0,\n    orientation = 0,\n    pages = 0,\n    photometric = 0,\n    *sample_info = NULL,\n    sample_format = 0,\n    samples_per_pixel = 0,\n    units = 0,\n    value = 0;\n\n  uint32\n    height,\n    rows_per_strip,\n    width;\n\n  unsigned char\n    *pixels;\n\n  void\n    *sans[8] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };\n\n  /*\n    Open image.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  if (IsEventLogging() != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  image=AcquireImage(image_info);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  (void) SetMagickThreadValue(tiff_exception,exception);\n  tiff=TIFFClientOpen(image->filename,\"rb\",(thandle_t) image,TIFFReadBlob,\n    TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,\n    TIFFUnmapBlob);\n  if (tiff == (TIFF *) NULL)\n    {\n      if (exception->severity == UndefinedException)\n        ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  if (exception->severity > ErrorException)\n    {\n      TIFFClose(tiff);\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  if (image_info->number_scenes != 0)\n    {\n      /*\n        Generate blank images for subimage specification (e.g. image.tif[4].\n        We need to check the number of directores because it is possible that\n        the subimage(s) are stored in the photoshop profile.\n      */\n      if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff))\n        {\n          for (i=0; i < (ssize_t) image_info->scene; i++)\n          {\n            status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n            if (status == MagickFalse)\n              {\n                TIFFClose(tiff);\n                image=DestroyImageList(image);\n                return((Image *) NULL);\n              }\n            AcquireNextImage(image_info,image);\n            if (GetNextImageInList(image) == (Image *) NULL)\n              {\n                TIFFClose(tiff);\n                image=DestroyImageList(image);\n                return((Image *) NULL);\n              }\n            image=SyncNextImageInList(image);\n          }\n        }\n    }\n  more_frames=MagickTrue;\n  do\n  {\n    /* TIFFPrintDirectory(tiff,stdout,MagickFalse); */\n    photometric=PHOTOMETRIC_RGB;\n    if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||\n        (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1))\n      {\n        TIFFClose(tiff);\n        ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n    if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) &&\n        ((bits_per_sample <= 0) || (bits_per_sample > 32)))\n      {\n        TIFFClose(tiff);\n        ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\");\n      }\n    if (samples_per_pixel > MaxPixelChannels)\n      {\n        TIFFClose(tiff);\n        ThrowReaderException(CorruptImageError,\"MaximumChannelsExceeded\");\n      }\n    if (sample_format == SAMPLEFORMAT_IEEEFP)\n      (void) SetImageProperty(image,\"quantum:format\",\"floating-point\");\n    switch (photometric)\n    {\n      case PHOTOMETRIC_MINISBLACK:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-black\");\n        break;\n      }\n      case PHOTOMETRIC_MINISWHITE:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-white\");\n        break;\n      }\n      case PHOTOMETRIC_PALETTE:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"palette\");\n        break;\n      }\n      case PHOTOMETRIC_RGB:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"RGB\");\n        break;\n      }\n      case PHOTOMETRIC_CIELAB:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"CIELAB\");\n        break;\n      }\n      case PHOTOMETRIC_LOGL:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"CIE Log2(L)\");\n        break;\n      }\n      case PHOTOMETRIC_LOGLUV:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"LOGLUV\");\n        break;\n      }\n#if defined(PHOTOMETRIC_MASK)\n      case PHOTOMETRIC_MASK:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"MASK\");\n        break;\n      }\n#endif\n      case PHOTOMETRIC_SEPARATED:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"separated\");\n        break;\n      }\n      case PHOTOMETRIC_YCBCR:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"YCBCR\");\n        break;\n      }\n      default:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"unknown\");\n        break;\n      }\n    }\n    if (image->debug != MagickFalse)\n      {\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Geometry: %ux%u\",\n          (unsigned int) width,(unsigned int) height);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Interlace: %u\",\n          interlace);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"Bits per sample: %u\",bits_per_sample);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"Min sample value: %u\",min_sample_value);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"Max sample value: %u\",max_sample_value);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Photometric \"\n          \"interpretation: %s\",GetImageProperty(image,\"tiff:photometric\"));\n      }\n    image->columns=(size_t) width;\n    image->rows=(size_t) height;\n    image->depth=(size_t) bits_per_sample;\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Image depth: %.20g\",\n        (double) image->depth);\n    image->endian=MSBEndian;\n    if (endian == FILLORDER_LSB2MSB)\n      image->endian=LSBEndian;\n#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)\n    if (TIFFIsBigEndian(tiff) == 0)\n      {\n        (void) SetImageProperty(image,\"tiff:endian\",\"lsb\");\n        image->endian=LSBEndian;\n      }\n    else\n      {\n        (void) SetImageProperty(image,\"tiff:endian\",\"msb\");\n        image->endian=MSBEndian;\n      }\n#endif\n    if ((photometric == PHOTOMETRIC_MINISBLACK) ||\n        (photometric == PHOTOMETRIC_MINISWHITE))\n      image->colorspace=GRAYColorspace;\n    if (photometric == PHOTOMETRIC_SEPARATED)\n      image->colorspace=CMYKColorspace;\n    if (photometric == PHOTOMETRIC_CIELAB)\n      image->colorspace=LabColorspace;\n    if ((photometric == PHOTOMETRIC_YCBCR) &&\n        (compress_tag != COMPRESSION_OJPEG) &&\n        (compress_tag != COMPRESSION_JPEG))\n      image->colorspace=YCbCrColorspace;\n    status=TIFFGetProfiles(tiff,image);\n    if (status == MagickFalse)\n      {\n        TIFFClose(tiff);\n        InheritException(exception,&image->exception);\n        return(DestroyImageList(image));\n      }\n    status=TIFFGetProperties(tiff,image);\n    if (status == MagickFalse)\n      {\n        TIFFClose(tiff);\n        InheritException(exception,&image->exception);\n        return(DestroyImageList(image));\n      }\n    option=GetImageOption(image_info,\"tiff:exif-properties\");\n    if ((option == (const char *) NULL) ||\n        (IsMagickTrue(option) != MagickFalse))\n      (void) TIFFGetEXIFProperties(tiff,image);\n    option=GetImageOption(image_info,\"tiff:gps-properties\");\n    if ((option == (const char *) NULL) ||\n        (IsMagickTrue(option) != MagickFalse))\n      (void) TIFFGetGPSProperties(tiff,image);\n    if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution,sans) == 1) &&\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution,sans) == 1))\n      {\n        image->x_resolution=x_resolution;\n        image->y_resolution=y_resolution;\n      }\n    if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units,sans,sans) == 1)\n      {\n        if (units == RESUNIT_INCH)\n          image->units=PixelsPerInchResolution;\n        if (units == RESUNIT_CENTIMETER)\n          image->units=PixelsPerCentimeterResolution;\n      }\n    if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position,sans) == 1) &&\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position,sans) == 1))\n      {\n        image->page.x=CastDoubleToLong(ceil(x_position*\n          image->x_resolution-0.5));\n        image->page.y=CastDoubleToLong(ceil(y_position*\n          image->y_resolution-0.5));\n      }\n    if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation,sans) == 1)\n      image->orientation=(OrientationType) orientation;\n    if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)\n      {\n        if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0))\n          {\n            image->chromaticity.white_point.x=chromaticity[0];\n            image->chromaticity.white_point.y=chromaticity[1];\n          }\n      }\n    if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)\n      {\n        if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0))\n          {\n            image->chromaticity.red_primary.x=chromaticity[0];\n            image->chromaticity.red_primary.y=chromaticity[1];\n            image->chromaticity.green_primary.x=chromaticity[2];\n            image->chromaticity.green_primary.y=chromaticity[3];\n            image->chromaticity.blue_primary.x=chromaticity[4];\n            image->chromaticity.blue_primary.y=chromaticity[5];\n          }\n      }\n#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)\n    if ((compress_tag != COMPRESSION_NONE) &&\n        (TIFFIsCODECConfigured(compress_tag) == 0))\n      {\n        TIFFClose(tiff);\n        ThrowReaderException(CoderError,\"CompressNotSupported\");\n      }\n#endif\n    switch (compress_tag)\n    {\n      case COMPRESSION_NONE: image->compression=NoCompression; break;\n      case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;\n      case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;\n      case COMPRESSION_JPEG:\n      {\n         image->compression=JPEGCompression;\n#if defined(JPEG_SUPPORT)\n         {\n           char\n             sampling_factor[MaxTextExtent];\n\n           int\n             tiff_status;\n\n           uint16\n             horizontal,\n             vertical;\n\n           tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal,\n             &vertical);\n           if (tiff_status == 1)\n             {\n               (void) FormatLocaleString(sampling_factor,MaxTextExtent,\"%dx%d\",\n                 horizontal,vertical);\n               (void) SetImageProperty(image,\"jpeg:sampling-factor\",\n                 sampling_factor);\n               (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                 \"Sampling Factors: %s\",sampling_factor);\n             }\n         }\n#endif\n        break;\n      }\n      case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;\n#if defined(COMPRESSION_LZMA)\n      case COMPRESSION_LZMA: image->compression=LZMACompression; break;\n#endif\n      case COMPRESSION_LZW: image->compression=LZWCompression; break;\n      case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;\n      case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;\n#if defined(COMPRESSION_WEBP)\n      case COMPRESSION_WEBP: image->compression=WebPCompression; break;\n#endif\n#if defined(COMPRESSION_ZSTD)\n      case COMPRESSION_ZSTD: image->compression=ZstdCompression; break;\n#endif\n      default: image->compression=RLECompression; break;\n    }\n    quantum_info=(QuantumInfo *) NULL;\n    if ((photometric == PHOTOMETRIC_PALETTE) &&\n        (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))\n      {\n        size_t\n          colors;\n\n        colors=(size_t) GetQuantumRange(bits_per_sample)+1;\n        if (AcquireImageColormap(image,colors) == MagickFalse)\n          {\n            TIFFClose(tiff);\n            ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n          }\n      }\n    if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages,sans) == 1)\n      image->scene=value;\n    if (image->storage_class == PseudoClass)\n      {\n        int\n          tiff_status;\n\n        size_t\n          range;\n\n        uint16\n          *blue_colormap = (uint16 *) NULL,\n          *green_colormap = (uint16 *) NULL,\n          *red_colormap = (uint16 *) NULL;\n\n        /*\n          Initialize colormap.\n        */\n        tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,\n          &green_colormap,&blue_colormap);\n        if (tiff_status == 1)\n          {\n            if ((red_colormap != (uint16 *) NULL) &&\n                (green_colormap != (uint16 *) NULL) &&\n                (blue_colormap != (uint16 *) NULL))\n              {\n                range=255;  /* might be old style 8-bit colormap */\n                for (i=0; i < (ssize_t) image->colors; i++)\n                  if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||\n                      (blue_colormap[i] >= 256))\n                    {\n                      range=65535;\n                      break;\n                    }\n                for (i=0; i < (ssize_t) image->colors; i++)\n                {\n                  image->colormap[i].red=ClampToQuantum(((double)\n                    QuantumRange*red_colormap[i])/range);\n                  image->colormap[i].green=ClampToQuantum(((double)\n                    QuantumRange*green_colormap[i])/range);\n                  image->colormap[i].blue=ClampToQuantum(((double)\n                    QuantumRange*blue_colormap[i])/range);\n                }\n              }\n          }\n      }\n    if (image_info->ping != MagickFalse)\n      {\n        if (image_info->number_scenes != 0)\n          if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n            break;\n        goto next_tiff_frame;\n      }\n    status=SetImageExtent(image,image->columns,image->rows);\n    if (status == MagickFalse)\n      {\n        TIFFClose(tiff);\n        InheritException(exception,&image->exception);\n        return(DestroyImageList(image));\n      }\n    status=SetImageColorspace(image,image->colorspace);\n    status&=ResetImagePixels(image,exception);\n    if (status == MagickFalse)\n      {\n        TIFFClose(tiff);\n        InheritException(exception,&image->exception);\n        return(DestroyImageList(image));\n      }\n    /*\n      Allocate memory for the image and pixel buffer.\n    */\n    quantum_info=AcquireQuantumInfo(image_info,image);\n    if (quantum_info == (QuantumInfo *) NULL)\n      ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n    if (sample_format == SAMPLEFORMAT_UINT)\n      status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);\n    if (sample_format == SAMPLEFORMAT_INT)\n      status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);\n    if (sample_format == SAMPLEFORMAT_IEEEFP)\n      status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n    if (status == MagickFalse)\n      ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n    status=MagickTrue;\n    switch (photometric)\n    {\n      case PHOTOMETRIC_MINISBLACK:\n      {\n        quantum_info->min_is_white=MagickFalse;\n        break;\n      }\n      case PHOTOMETRIC_MINISWHITE:\n      {\n        quantum_info->min_is_white=MagickTrue;\n        break;\n      }\n      default:\n        break;\n    }\n    extra_samples=0;\n    tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,\n      &sample_info,sans);\n    if (tiff_status == 1)\n      {\n        (void) SetImageProperty(image,\"tiff:alpha\",\"unspecified\");\n        if (extra_samples == 0)\n          {\n            if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))\n              image->matte=MagickTrue;\n          }\n        else\n          for (i=0; i < extra_samples; i++)\n          {\n            image->matte=MagickTrue;\n            if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)\n              {\n                SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);\n                (void) SetImageProperty(image,\"tiff:alpha\",\"associated\");\n              }\n            else\n              if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)\n                {\n                  SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);\n                  (void) SetImageProperty(image,\"tiff:alpha\",\"unassociated\");\n                }\n          }\n      }\n    if (image->matte != MagickFalse)\n      (void) SetImageAlphaChannel(image,OpaqueAlphaChannel);\n    method=ReadGenericMethod;\n    rows_per_strip=(uint32) image->rows;\n    if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)\n      {\n        char\n          value[MaxTextExtent];\n\n        (void) FormatLocaleString(value,MaxTextExtent,\"%u\",(unsigned int)\n          rows_per_strip);\n        (void) SetImageProperty(image,\"tiff:rows-per-strip\",value);\n        method=ReadStripMethod;\n        if (rows_per_strip > (uint32) image->rows)\n          rows_per_strip=(uint32) image->rows;\n      }\n    if (TIFFIsTiled(tiff) != MagickFalse)\n      {\n        uint32\n          columns,\n          rows;\n\n        if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n            (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n          ThrowTIFFException(CoderError,\"ImageIsNotTiled\");\n        if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) ||\n            (AcquireMagickResource(HeightResource,rows) == MagickFalse))\n          ThrowTIFFException(ImageError,\"WidthOrHeightExceedsLimit\");\n        method=ReadTileMethod;\n      }\n    if ((photometric == PHOTOMETRIC_LOGLUV) ||\n        (compress_tag == COMPRESSION_CCITTFAX3))\n      method=ReadGenericMethod;\n    if (image->compression == JPEGCompression)\n      method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,\n        samples_per_pixel);\n    quantum_info->endian=LSBEndian;\n    scanline_size=TIFFScanlineSize(tiff);\n    if (scanline_size <= 0)\n      ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n    number_pixels=MagickMax((MagickSizeType) image->columns*samples_per_pixel*\n      pow(2.0,ceil(log(bits_per_sample)/log(2.0))),image->columns*\n      rows_per_strip);\n    if ((double) scanline_size > 1.5*number_pixels)\n      ThrowTIFFException(CorruptImageError,\"CorruptImage\");\n    number_pixels=MagickMax((MagickSizeType) scanline_size,number_pixels);\n    pixel_info=AcquireVirtualMemory(number_pixels,sizeof(uint32));\n    if (pixel_info == (MemoryInfo *) NULL)\n      ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n    pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n    (void) ResetMagickMemory(pixels,0,number_pixels*sizeof(uint32));\n    quantum_type=GrayQuantum;\n    if (image->storage_class == PseudoClass)\n      quantum_type=IndexQuantum;\n    if (interlace != PLANARCONFIG_SEPARATE)\n      {\n        size_t\n          pad;\n\n        pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);\n        if (image->matte != MagickFalse)\n          {\n            if (image->storage_class == PseudoClass)\n              quantum_type=IndexAlphaQuantum;\n            else\n              quantum_type=samples_per_pixel == 1 ? AlphaQuantum :\n                GrayAlphaQuantum;\n          }\n        if ((samples_per_pixel > 2) && (interlace != PLANARCONFIG_SEPARATE))\n          {\n            quantum_type=RGBQuantum;\n            pad=(size_t) MagickMax((ssize_t) samples_per_pixel+\n              extra_samples-3,0);\n            if (image->matte != MagickFalse)\n              {\n                quantum_type=RGBAQuantum;\n                pad=(size_t) MagickMax((ssize_t) samples_per_pixel+\n                  extra_samples-4,0);\n              }\n            if (image->colorspace == CMYKColorspace)\n              {\n                quantum_type=CMYKQuantum;\n                pad=(size_t) MagickMax((ssize_t) samples_per_pixel+\n                  extra_samples-4,0);\n                if (image->matte != MagickFalse)\n                  {\n                    quantum_type=CMYKAQuantum;\n                    pad=(size_t) MagickMax((ssize_t) samples_per_pixel+\n                      extra_samples-5,0);\n                  }\n              }\n            status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >>\n              3));\n            if (status == MagickFalse)\n              ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n          }\n      }\n    switch (method)\n    {\n      case ReadYCCKMethod:\n      {\n        /*\n          Convert YCC TIFF image.\n        */\n        for (y=0; y < (ssize_t) image->rows; y++)\n        {\n          int\n            status;\n\n          IndexPacket\n            *indexes;\n\n          PixelPacket\n            *magick_restrict q;\n\n          ssize_t\n            x;\n\n          unsigned char\n            *p;\n\n          status=TIFFReadPixels(tiff,0,y,(char *) pixels);\n          if (status == -1)\n            break;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          p=pixels;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+\n              (1.402*(double) *(p+2))-179.456)));\n            SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p-\n              (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+\n              135.45984)));\n            SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+\n              (1.772*(double) *(p+1))-226.816)));\n            SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3)));\n            q++;\n            p+=4;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n                image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      case ReadStripMethod:\n      {\n        unsigned char\n          *p;\n\n        size_t\n          extent;\n\n        ssize_t\n          stride,\n          strip_id;\n\n        tsize_t\n          strip_size;\n\n        unsigned char\n          *strip_pixels;\n\n        /*\n          Convert stripped TIFF image.\n        */\n        extent=4*(samples_per_pixel+1)*TIFFStripSize(tiff);\n        strip_pixels=(unsigned char *) AcquireQuantumMemory(extent,\n          sizeof(*strip_pixels));\n        if (strip_pixels == (unsigned char *) NULL)\n          ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n        (void) memset(strip_pixels,0,extent*sizeof(*strip_pixels));\n        stride=TIFFVStripSize(tiff,1);\n        strip_id=0;\n        p=strip_pixels;\n        for (i=0; i < (ssize_t) samples_per_pixel; i++)\n        {\n          size_t\n            rows_remaining;\n\n          switch (i)\n          {\n            case 0: break;\n            case 1: quantum_type=GreenQuantum; break;\n            case 2: quantum_type=BlueQuantum; break;\n            case 3:\n            {\n              quantum_type=AlphaQuantum;\n              if (image->colorspace == CMYKColorspace)\n                quantum_type=BlackQuantum;\n              break;\n            }\n            case 4: quantum_type=AlphaQuantum; break;\n            default: break;\n          }\n          rows_remaining=0;\n          for (y=0; y < (ssize_t) image->rows; y++)\n          {\n            PixelPacket\n              *magick_restrict q;\n\n            q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n            if (q == (PixelPacket *) NULL)\n              break;\n            if (rows_remaining == 0)\n              {\n                strip_size=TIFFReadEncodedStrip(tiff,strip_id,strip_pixels,\n                  TIFFStripSize(tiff));\n                if (strip_size == -1)\n                  break;\n                rows_remaining=rows_per_strip;\n                if ((y+rows_per_strip) > (ssize_t) image->rows)\n                  rows_remaining=(rows_per_strip-(y+rows_per_strip-\n                    image->rows));\n                p=strip_pixels;\n                strip_id++;\n              }\n            (void) ImportQuantumPixels(image,(CacheView *) NULL,\n              quantum_info,quantum_type,p,exception);\n            p+=stride;\n            rows_remaining--;\n            if (SyncAuthenticPixels(image,exception) == MagickFalse)\n              break;\n            if (image->previous == (Image *) NULL)\n              {\n                status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n                  image->rows);\n                if (status == MagickFalse)\n                  break;\n              }\n          }\n         if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE))\n            break;\n        }\n        strip_pixels=(unsigned char *) RelinquishMagickMemory(strip_pixels);\n        break;\n      }\n      case ReadTileMethod:\n      {\n        unsigned char\n          *p;\n\n        size_t\n          extent;\n\n        uint32\n          columns,\n          rows;\n\n        unsigned char\n          *tile_pixels;\n\n        /*\n          Convert tiled TIFF image.\n        */\n        if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n            (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n          ThrowTIFFException(CoderError,\"ImageIsNotTiled\");\n        number_pixels=(MagickSizeType) columns*rows;\n        if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)\n          ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n        extent=4*(samples_per_pixel+1)*MagickMax(rows*TIFFTileRowSize(tiff),\n          TIFFTileSize(tiff));\n        tile_pixels=(unsigned char *) AcquireQuantumMemory(extent,\n          sizeof(*tile_pixels));\n        if (tile_pixels == (unsigned char *) NULL)\n          ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n        (void) memset(tile_pixels,0,extent*sizeof(*tile_pixels));\n        for (i=0; i < (ssize_t) samples_per_pixel; i++)\n        {\n          switch (i)\n          {\n            case 0: break;\n            case 1: quantum_type=GreenQuantum; break;\n            case 2: quantum_type=BlueQuantum; break;\n            case 3:\n            {\n              quantum_type=AlphaQuantum;\n              if (image->colorspace == CMYKColorspace)\n                quantum_type=BlackQuantum;\n              break;\n            }\n            case 4: quantum_type=AlphaQuantum; break;\n            default: break;\n          }\n          for (y=0; y < (ssize_t) image->rows; y+=rows)\n          {\n            ssize_t\n              x;\n\n            size_t\n              rows_remaining;\n\n            rows_remaining=image->rows-y;\n            if ((ssize_t) (y+rows) < (ssize_t) image->rows)\n              rows_remaining=rows;\n            for (x=0; x < (ssize_t) image->columns; x+=columns)\n            {\n              size_t\n                columns_remaining,\n                row;\n\n              columns_remaining=image->columns-x;\n              if ((ssize_t) (x+columns) < (ssize_t) image->columns)\n                columns_remaining=columns;\n              tiff_status=TIFFReadTile(tiff,tile_pixels,(uint32) x,(uint32) y,\n                0,i);\n              if (tiff_status == -1)\n                break;\n              p=tile_pixels;\n              for (row=0; row < rows_remaining; row++)\n              {\n                PixelPacket\n                  *magick_restrict q;\n\n                q=GetAuthenticPixels(image,x,y+row,columns_remaining,1,\n                  exception);\n                if (q == (PixelPacket *) NULL)\n                  break;\n                (void) ImportQuantumPixels(image,(CacheView *) NULL,\n                  quantum_info,quantum_type,p,exception);\n                p+=TIFFTileRowSize(tiff);\n                if (SyncAuthenticPixels(image,exception) == MagickFalse)\n                  break;\n              }\n            }\n          }\n          if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE))\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) i,\n                samples_per_pixel);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        tile_pixels=(unsigned char *) RelinquishMagickMemory(tile_pixels);\n        break;\n      }\n      case ReadGenericMethod:\n      default:\n      {\n        MemoryInfo\n          *generic_info = (MemoryInfo *) NULL;\n\n        uint32\n          *p;\n\n        uint32\n          *pixels;\n\n        /*\n          Convert generic TIFF image.\n        */\n        if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)\n          ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n        number_pixels=(MagickSizeType) image->columns*image->rows;\n        generic_info=AcquireVirtualMemory(number_pixels,sizeof(*pixels));\n        if (generic_info == (MemoryInfo *) NULL)\n          ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n        pixels=(uint32 *) GetVirtualMemoryBlob(generic_info);\n        tiff_status=TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)\n          image->rows,(uint32 *) pixels,0);\n        if (tiff_status == -1)\n          {\n            generic_info=RelinquishVirtualMemory(generic_info);\n            break;\n          }\n        p=pixels+(image->columns*image->rows)-1;\n        for (y=0; y < (ssize_t) image->rows; y++)\n        {\n          ssize_t\n            x;\n\n          PixelPacket\n            *magick_restrict q;\n\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          q+=image->columns-1;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)));\n            SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)));\n            SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)));\n            if (image->matte == MagickFalse)\n              SetPixelOpacity(q,OpaqueOpacity);\n            else\n              SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)));\n            p--;\n            q--;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n                image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        generic_info=RelinquishVirtualMemory(generic_info);\n        break;\n      }\n    }\n    pixel_info=RelinquishVirtualMemory(pixel_info);\n    SetQuantumImageType(image,quantum_type);\n  next_tiff_frame:\n    if (quantum_info != (QuantumInfo *) NULL)\n      quantum_info=DestroyQuantumInfo(quantum_info);\n    if (tiff_status == -1)\n      {\n        status=MagickFalse;\n        break;\n      }\n    if (photometric == PHOTOMETRIC_CIELAB)\n      DecodeLabImage(image,exception);\n    if ((photometric == PHOTOMETRIC_LOGL) ||\n        (photometric == PHOTOMETRIC_MINISBLACK) ||\n        (photometric == PHOTOMETRIC_MINISWHITE))\n      {\n        image->type=GrayscaleType;\n        if (bits_per_sample == 1)\n          image->type=BilevelType;\n      }\n    /*\n      Proceed to next image.\n    */\n    if (image_info->number_scenes != 0)\n      if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n        break;\n    more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n    if (more_frames != MagickFalse)\n      {\n        /*\n          Allocate next image structure.\n        */\n        AcquireNextImage(image_info,image);\n        if (GetNextImageInList(image) == (Image *) NULL)\n          {\n            status=MagickFalse;\n            break;\n          }\n        image=SyncNextImageInList(image);\n        status=SetImageProgress(image,LoadImagesTag,image->scene-1,\n          image->scene);\n        if (status == MagickFalse)\n          break;\n      }\n  } while ((status != MagickFalse) && (more_frames != MagickFalse));\n  TIFFClose(tiff);\n  if ((image_info->number_scenes != 0) &&\n      (image_info->scene >= GetImageListLength(image)))\n    status=MagickFalse;\n  if (status == MagickFalse)\n    return(DestroyImageList(image));\n  TIFFReadPhotoshopLayers(image_info,image,exception);\n  return(GetFirstImageInList(image));\n}", "func_hash": 282124666378195634578988553119839535376, "file_name": "tiff.c", "file_hash": 94999311171482042296542443921541591860, "cwe": ["CWE-787"], "cve": "CVE-2022-3213", "cve_desc": "A heap buffer overflow issue was found in ImageMagick. When an application processes a malformed TIFF file, it could lead to undefined behavior or a crash causing a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3213"}
{"idx": 452391, "project": "ImageMagick6", "commit_id": "1aea203eb36409ce6903b9e41fe7cb70030e8750", "project_url": "https://github.com/ImageMagick/ImageMagick6", "commit_url": "https://github.com/ImageMagick/ImageMagick6/commit/1aea203eb36409ce6903b9e41fe7cb70030e8750", "commit_message": "squash heap-buffer-overflow, PoC TIFF from Hardik", "target": 0, "func": "static Image *ReadTIFFImage(const ImageInfo *image_info,\n  ExceptionInfo *exception)\n{\n#define MaxPixelChannels  32\n#define ThrowTIFFException(severity,message) \\\n{ \\\n  if (pixel_info != (MemoryInfo *) NULL) \\\n    pixel_info=RelinquishVirtualMemory(pixel_info); \\\n  if (quantum_info != (QuantumInfo *) NULL) \\\n    quantum_info=DestroyQuantumInfo(quantum_info); \\\n  TIFFClose(tiff); \\\n  ThrowReaderException(severity,message); \\\n}\n\n  const char\n    *option;\n\n  float\n    *chromaticity = (float *) NULL,\n    x_position,\n    y_position,\n    x_resolution,\n    y_resolution;\n\n  Image\n    *image;\n\n  int\n    tiff_status = 0;\n\n  MagickBooleanType\n    more_frames;\n\n  MagickStatusType\n    status;\n\n  MemoryInfo\n    *pixel_info = (MemoryInfo *) NULL;\n\n  QuantumInfo\n    *quantum_info;\n\n  QuantumType\n    quantum_type;\n\n  size_t\n    number_pixels;\n\n  ssize_t\n    i,\n    scanline_size,\n    y;\n\n  TIFF\n    *tiff;\n\n  TIFFMethodType\n    method;\n\n  uint16\n    compress_tag = 0,\n    bits_per_sample = 0,\n    endian = 0,\n    extra_samples = 0,\n    interlace = 0,\n    max_sample_value = 0,\n    min_sample_value = 0,\n    orientation = 0,\n    pages = 0,\n    photometric = 0,\n    *sample_info = NULL,\n    sample_format = 0,\n    samples_per_pixel = 0,\n    units = 0,\n    value = 0;\n\n  uint32\n    height,\n    rows_per_strip,\n    width;\n\n  unsigned char\n    *pixels;\n\n  void\n    *sans[8] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };\n\n  /*\n    Open image.\n  */\n  assert(image_info != (const ImageInfo *) NULL);\n  assert(image_info->signature == MagickCoreSignature);\n  assert(exception != (ExceptionInfo *) NULL);\n  assert(exception->signature == MagickCoreSignature);\n  if (IsEventLogging() != MagickFalse)\n    (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n      image_info->filename);\n  image=AcquireImage(image_info);\n  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n  if (status == MagickFalse)\n    {\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  (void) SetMagickThreadValue(tiff_exception,exception);\n  tiff=TIFFClientOpen(image->filename,\"rb\",(thandle_t) image,TIFFReadBlob,\n    TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,\n    TIFFUnmapBlob);\n  if (tiff == (TIFF *) NULL)\n    {\n      if (exception->severity == UndefinedException)\n        ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  if (exception->severity > ErrorException)\n    {\n      TIFFClose(tiff);\n      image=DestroyImageList(image);\n      return((Image *) NULL);\n    }\n  if (image_info->number_scenes != 0)\n    {\n      /*\n        Generate blank images for subimage specification (e.g. image.tif[4].\n        We need to check the number of directores because it is possible that\n        the subimage(s) are stored in the photoshop profile.\n      */\n      if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff))\n        {\n          for (i=0; i < (ssize_t) image_info->scene; i++)\n          {\n            status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n            if (status == MagickFalse)\n              {\n                TIFFClose(tiff);\n                image=DestroyImageList(image);\n                return((Image *) NULL);\n              }\n            AcquireNextImage(image_info,image);\n            if (GetNextImageInList(image) == (Image *) NULL)\n              {\n                TIFFClose(tiff);\n                image=DestroyImageList(image);\n                return((Image *) NULL);\n              }\n            image=SyncNextImageInList(image);\n          }\n        }\n    }\n  more_frames=MagickTrue;\n  do\n  {\n    /* TIFFPrintDirectory(tiff,stdout,MagickFalse); */\n    photometric=PHOTOMETRIC_RGB;\n    if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||\n        (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) ||\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1))\n      {\n        TIFFClose(tiff);\n        ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n      }\n    if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) &&\n        ((bits_per_sample <= 0) || (bits_per_sample > 32)))\n      {\n        TIFFClose(tiff);\n        ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\");\n      }\n    if (samples_per_pixel > MaxPixelChannels)\n      {\n        TIFFClose(tiff);\n        ThrowReaderException(CorruptImageError,\"MaximumChannelsExceeded\");\n      }\n    if (sample_format == SAMPLEFORMAT_IEEEFP)\n      (void) SetImageProperty(image,\"quantum:format\",\"floating-point\");\n    switch (photometric)\n    {\n      case PHOTOMETRIC_MINISBLACK:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-black\");\n        break;\n      }\n      case PHOTOMETRIC_MINISWHITE:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-white\");\n        break;\n      }\n      case PHOTOMETRIC_PALETTE:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"palette\");\n        break;\n      }\n      case PHOTOMETRIC_RGB:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"RGB\");\n        break;\n      }\n      case PHOTOMETRIC_CIELAB:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"CIELAB\");\n        break;\n      }\n      case PHOTOMETRIC_LOGL:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"CIE Log2(L)\");\n        break;\n      }\n      case PHOTOMETRIC_LOGLUV:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"LOGLUV\");\n        break;\n      }\n#if defined(PHOTOMETRIC_MASK)\n      case PHOTOMETRIC_MASK:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"MASK\");\n        break;\n      }\n#endif\n      case PHOTOMETRIC_SEPARATED:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"separated\");\n        break;\n      }\n      case PHOTOMETRIC_YCBCR:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"YCBCR\");\n        break;\n      }\n      default:\n      {\n        (void) SetImageProperty(image,\"tiff:photometric\",\"unknown\");\n        break;\n      }\n    }\n    if (image->debug != MagickFalse)\n      {\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Geometry: %ux%u\",\n          (unsigned int) width,(unsigned int) height);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Interlace: %u\",\n          interlace);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"Bits per sample: %u\",bits_per_sample);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"Min sample value: %u\",min_sample_value);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n          \"Max sample value: %u\",max_sample_value);\n        (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Photometric \"\n          \"interpretation: %s\",GetImageProperty(image,\"tiff:photometric\"));\n      }\n    image->columns=(size_t) width;\n    image->rows=(size_t) height;\n    image->depth=(size_t) bits_per_sample;\n    if (image->debug != MagickFalse)\n      (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Image depth: %.20g\",\n        (double) image->depth);\n    image->endian=MSBEndian;\n    if (endian == FILLORDER_LSB2MSB)\n      image->endian=LSBEndian;\n#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)\n    if (TIFFIsBigEndian(tiff) == 0)\n      {\n        (void) SetImageProperty(image,\"tiff:endian\",\"lsb\");\n        image->endian=LSBEndian;\n      }\n    else\n      {\n        (void) SetImageProperty(image,\"tiff:endian\",\"msb\");\n        image->endian=MSBEndian;\n      }\n#endif\n    if ((photometric == PHOTOMETRIC_MINISBLACK) ||\n        (photometric == PHOTOMETRIC_MINISWHITE))\n      image->colorspace=GRAYColorspace;\n    if (photometric == PHOTOMETRIC_SEPARATED)\n      image->colorspace=CMYKColorspace;\n    if (photometric == PHOTOMETRIC_CIELAB)\n      image->colorspace=LabColorspace;\n    if ((photometric == PHOTOMETRIC_YCBCR) &&\n        (compress_tag != COMPRESSION_OJPEG) &&\n        (compress_tag != COMPRESSION_JPEG))\n      image->colorspace=YCbCrColorspace;\n    status=TIFFGetProfiles(tiff,image);\n    if (status == MagickFalse)\n      {\n        TIFFClose(tiff);\n        InheritException(exception,&image->exception);\n        return(DestroyImageList(image));\n      }\n    status=TIFFGetProperties(tiff,image);\n    if (status == MagickFalse)\n      {\n        TIFFClose(tiff);\n        InheritException(exception,&image->exception);\n        return(DestroyImageList(image));\n      }\n    option=GetImageOption(image_info,\"tiff:exif-properties\");\n    if ((option == (const char *) NULL) ||\n        (IsMagickTrue(option) != MagickFalse))\n      (void) TIFFGetEXIFProperties(tiff,image);\n    option=GetImageOption(image_info,\"tiff:gps-properties\");\n    if ((option == (const char *) NULL) ||\n        (IsMagickTrue(option) != MagickFalse))\n      (void) TIFFGetGPSProperties(tiff,image);\n    if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution,sans) == 1) &&\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution,sans) == 1))\n      {\n        image->x_resolution=x_resolution;\n        image->y_resolution=y_resolution;\n      }\n    if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units,sans,sans) == 1)\n      {\n        if (units == RESUNIT_INCH)\n          image->units=PixelsPerInchResolution;\n        if (units == RESUNIT_CENTIMETER)\n          image->units=PixelsPerCentimeterResolution;\n      }\n    if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position,sans) == 1) &&\n        (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position,sans) == 1))\n      {\n        image->page.x=CastDoubleToLong(ceil(x_position*\n          image->x_resolution-0.5));\n        image->page.y=CastDoubleToLong(ceil(y_position*\n          image->y_resolution-0.5));\n      }\n    if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation,sans) == 1)\n      image->orientation=(OrientationType) orientation;\n    if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)\n      {\n        if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0))\n          {\n            image->chromaticity.white_point.x=chromaticity[0];\n            image->chromaticity.white_point.y=chromaticity[1];\n          }\n      }\n    if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)\n      {\n        if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0))\n          {\n            image->chromaticity.red_primary.x=chromaticity[0];\n            image->chromaticity.red_primary.y=chromaticity[1];\n            image->chromaticity.green_primary.x=chromaticity[2];\n            image->chromaticity.green_primary.y=chromaticity[3];\n            image->chromaticity.blue_primary.x=chromaticity[4];\n            image->chromaticity.blue_primary.y=chromaticity[5];\n          }\n      }\n#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)\n    if ((compress_tag != COMPRESSION_NONE) &&\n        (TIFFIsCODECConfigured(compress_tag) == 0))\n      {\n        TIFFClose(tiff);\n        ThrowReaderException(CoderError,\"CompressNotSupported\");\n      }\n#endif\n    switch (compress_tag)\n    {\n      case COMPRESSION_NONE: image->compression=NoCompression; break;\n      case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;\n      case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;\n      case COMPRESSION_JPEG:\n      {\n         image->compression=JPEGCompression;\n#if defined(JPEG_SUPPORT)\n         {\n           char\n             sampling_factor[MaxTextExtent];\n\n           int\n             tiff_status;\n\n           uint16\n             horizontal,\n             vertical;\n\n           tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal,\n             &vertical);\n           if (tiff_status == 1)\n             {\n               (void) FormatLocaleString(sampling_factor,MaxTextExtent,\"%dx%d\",\n                 horizontal,vertical);\n               (void) SetImageProperty(image,\"jpeg:sampling-factor\",\n                 sampling_factor);\n               (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n                 \"Sampling Factors: %s\",sampling_factor);\n             }\n         }\n#endif\n        break;\n      }\n      case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;\n#if defined(COMPRESSION_LZMA)\n      case COMPRESSION_LZMA: image->compression=LZMACompression; break;\n#endif\n      case COMPRESSION_LZW: image->compression=LZWCompression; break;\n      case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;\n      case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;\n#if defined(COMPRESSION_WEBP)\n      case COMPRESSION_WEBP: image->compression=WebPCompression; break;\n#endif\n#if defined(COMPRESSION_ZSTD)\n      case COMPRESSION_ZSTD: image->compression=ZstdCompression; break;\n#endif\n      default: image->compression=RLECompression; break;\n    }\n    quantum_info=(QuantumInfo *) NULL;\n    if ((photometric == PHOTOMETRIC_PALETTE) &&\n        (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))\n      {\n        size_t\n          colors;\n\n        colors=(size_t) GetQuantumRange(bits_per_sample)+1;\n        if (AcquireImageColormap(image,colors) == MagickFalse)\n          {\n            TIFFClose(tiff);\n            ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n          }\n      }\n    if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages,sans) == 1)\n      image->scene=value;\n    if (image->storage_class == PseudoClass)\n      {\n        int\n          tiff_status;\n\n        size_t\n          range;\n\n        uint16\n          *blue_colormap = (uint16 *) NULL,\n          *green_colormap = (uint16 *) NULL,\n          *red_colormap = (uint16 *) NULL;\n\n        /*\n          Initialize colormap.\n        */\n        tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,\n          &green_colormap,&blue_colormap);\n        if (tiff_status == 1)\n          {\n            if ((red_colormap != (uint16 *) NULL) &&\n                (green_colormap != (uint16 *) NULL) &&\n                (blue_colormap != (uint16 *) NULL))\n              {\n                range=255;  /* might be old style 8-bit colormap */\n                for (i=0; i < (ssize_t) image->colors; i++)\n                  if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||\n                      (blue_colormap[i] >= 256))\n                    {\n                      range=65535;\n                      break;\n                    }\n                for (i=0; i < (ssize_t) image->colors; i++)\n                {\n                  image->colormap[i].red=ClampToQuantum(((double)\n                    QuantumRange*red_colormap[i])/range);\n                  image->colormap[i].green=ClampToQuantum(((double)\n                    QuantumRange*green_colormap[i])/range);\n                  image->colormap[i].blue=ClampToQuantum(((double)\n                    QuantumRange*blue_colormap[i])/range);\n                }\n              }\n          }\n      }\n    if (image_info->ping != MagickFalse)\n      {\n        if (image_info->number_scenes != 0)\n          if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n            break;\n        goto next_tiff_frame;\n      }\n    status=SetImageExtent(image,image->columns,image->rows);\n    if (status == MagickFalse)\n      {\n        TIFFClose(tiff);\n        InheritException(exception,&image->exception);\n        return(DestroyImageList(image));\n      }\n    status=SetImageColorspace(image,image->colorspace);\n    status&=ResetImagePixels(image,exception);\n    if (status == MagickFalse)\n      {\n        TIFFClose(tiff);\n        InheritException(exception,&image->exception);\n        return(DestroyImageList(image));\n      }\n    /*\n      Allocate memory for the image and pixel buffer.\n    */\n    quantum_info=AcquireQuantumInfo(image_info,image);\n    if (quantum_info == (QuantumInfo *) NULL)\n      ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n    if (sample_format == SAMPLEFORMAT_UINT)\n      status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);\n    if (sample_format == SAMPLEFORMAT_INT)\n      status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);\n    if (sample_format == SAMPLEFORMAT_IEEEFP)\n      status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n    if (status == MagickFalse)\n      ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n    status=MagickTrue;\n    switch (photometric)\n    {\n      case PHOTOMETRIC_MINISBLACK:\n      {\n        quantum_info->min_is_white=MagickFalse;\n        break;\n      }\n      case PHOTOMETRIC_MINISWHITE:\n      {\n        quantum_info->min_is_white=MagickTrue;\n        break;\n      }\n      default:\n        break;\n    }\n    extra_samples=0;\n    tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,\n      &sample_info,sans);\n    if (tiff_status == 1)\n      {\n        (void) SetImageProperty(image,\"tiff:alpha\",\"unspecified\");\n        if (extra_samples == 0)\n          {\n            if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))\n              image->matte=MagickTrue;\n          }\n        else\n          for (i=0; i < extra_samples; i++)\n          {\n            image->matte=MagickTrue;\n            if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)\n              {\n                SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);\n                (void) SetImageProperty(image,\"tiff:alpha\",\"associated\");\n              }\n            else\n              if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)\n                {\n                  SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);\n                  (void) SetImageProperty(image,\"tiff:alpha\",\"unassociated\");\n                }\n          }\n      }\n    if (image->matte != MagickFalse)\n      (void) SetImageAlphaChannel(image,OpaqueAlphaChannel);\n    method=ReadGenericMethod;\n    rows_per_strip=(uint32) image->rows;\n    if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)\n      {\n        char\n          value[MaxTextExtent];\n\n        (void) FormatLocaleString(value,MaxTextExtent,\"%u\",(unsigned int)\n          rows_per_strip);\n        (void) SetImageProperty(image,\"tiff:rows-per-strip\",value);\n        method=ReadStripMethod;\n        if (rows_per_strip > (uint32) image->rows)\n          rows_per_strip=(uint32) image->rows;\n      }\n    if (TIFFIsTiled(tiff) != MagickFalse)\n      {\n        uint32\n          columns,\n          rows;\n\n        if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n            (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n          ThrowTIFFException(CoderError,\"ImageIsNotTiled\");\n        if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) ||\n            (AcquireMagickResource(HeightResource,rows) == MagickFalse))\n          ThrowTIFFException(ImageError,\"WidthOrHeightExceedsLimit\");\n        method=ReadTileMethod;\n      }\n    if ((photometric == PHOTOMETRIC_LOGLUV) ||\n        (compress_tag == COMPRESSION_CCITTFAX3))\n      method=ReadGenericMethod;\n    if (image->compression == JPEGCompression)\n      method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,\n        samples_per_pixel);\n    quantum_info->endian=LSBEndian;\n    scanline_size=TIFFScanlineSize(tiff);\n    if (scanline_size <= 0)\n      ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n    number_pixels=MagickMax((MagickSizeType) image->columns*samples_per_pixel*\n      pow(2.0,ceil(log(bits_per_sample)/log(2.0))),image->columns*\n      rows_per_strip);\n    if ((double) scanline_size > 1.5*number_pixels)\n      ThrowTIFFException(CorruptImageError,\"CorruptImage\");\n    number_pixels=MagickMax((MagickSizeType) scanline_size,number_pixels);\n    pixel_info=AcquireVirtualMemory(number_pixels,sizeof(uint32));\n    if (pixel_info == (MemoryInfo *) NULL)\n      ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n    pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n    (void) ResetMagickMemory(pixels,0,number_pixels*sizeof(uint32));\n    quantum_type=GrayQuantum;\n    if (image->storage_class == PseudoClass)\n      quantum_type=IndexQuantum;\n    if (interlace != PLANARCONFIG_SEPARATE)\n      {\n        size_t\n          pad;\n\n        pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);\n        if (image->matte != MagickFalse)\n          {\n            if (image->storage_class == PseudoClass)\n              quantum_type=IndexAlphaQuantum;\n            else\n              quantum_type=samples_per_pixel == 1 ? AlphaQuantum :\n                GrayAlphaQuantum;\n          }\n        if ((samples_per_pixel > 2) && (interlace != PLANARCONFIG_SEPARATE))\n          {\n            quantum_type=RGBQuantum;\n            pad=(size_t) MagickMax((ssize_t) samples_per_pixel+\n              extra_samples-3,0);\n            if (image->matte != MagickFalse)\n              {\n                quantum_type=RGBAQuantum;\n                pad=(size_t) MagickMax((ssize_t) samples_per_pixel+\n                  extra_samples-4,0);\n              }\n            if (image->colorspace == CMYKColorspace)\n              {\n                quantum_type=CMYKQuantum;\n                pad=(size_t) MagickMax((ssize_t) samples_per_pixel+\n                  extra_samples-4,0);\n                if (image->matte != MagickFalse)\n                  {\n                    quantum_type=CMYKAQuantum;\n                    pad=(size_t) MagickMax((ssize_t) samples_per_pixel+\n                      extra_samples-5,0);\n                  }\n              }\n            status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >>\n              3));\n            if (status == MagickFalse)\n              ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n          }\n      }\n    switch (method)\n    {\n      case ReadYCCKMethod:\n      {\n        /*\n          Convert YCC TIFF image.\n        */\n        for (y=0; y < (ssize_t) image->rows; y++)\n        {\n          int\n            status;\n\n          IndexPacket\n            *indexes;\n\n          PixelPacket\n            *magick_restrict q;\n\n          ssize_t\n            x;\n\n          unsigned char\n            *p;\n\n          status=TIFFReadPixels(tiff,0,y,(char *) pixels);\n          if (status == -1)\n            break;\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          indexes=GetAuthenticIndexQueue(image);\n          p=pixels;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+\n              (1.402*(double) *(p+2))-179.456)));\n            SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p-\n              (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+\n              135.45984)));\n            SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+\n              (1.772*(double) *(p+1))-226.816)));\n            SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3)));\n            q++;\n            p+=4;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n                image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        break;\n      }\n      case ReadStripMethod:\n      {\n        unsigned char\n          *p;\n\n        size_t\n          extent;\n\n        ssize_t\n          stride,\n          strip_id;\n\n        tsize_t\n          strip_size;\n\n        unsigned char\n          *strip_pixels;\n\n        /*\n          Convert stripped TIFF image.\n        */\n        extent=4*((image->depth+7)/8)*(samples_per_pixel+1)*TIFFStripSize(tiff);\n        strip_pixels=(unsigned char *) AcquireQuantumMemory(extent,\n          sizeof(*strip_pixels));\n        if (strip_pixels == (unsigned char *) NULL)\n          ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n        (void) memset(strip_pixels,0,extent*sizeof(*strip_pixels));\n        stride=TIFFVStripSize(tiff,1);\n        strip_id=0;\n        p=strip_pixels;\n        for (i=0; i < (ssize_t) samples_per_pixel; i++)\n        {\n          size_t\n            rows_remaining;\n\n          switch (i)\n          {\n            case 0: break;\n            case 1: quantum_type=GreenQuantum; break;\n            case 2: quantum_type=BlueQuantum; break;\n            case 3:\n            {\n              quantum_type=AlphaQuantum;\n              if (image->colorspace == CMYKColorspace)\n                quantum_type=BlackQuantum;\n              break;\n            }\n            case 4: quantum_type=AlphaQuantum; break;\n            default: break;\n          }\n          rows_remaining=0;\n          for (y=0; y < (ssize_t) image->rows; y++)\n          {\n            PixelPacket\n              *magick_restrict q;\n\n            q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n            if (q == (PixelPacket *) NULL)\n              break;\n            if (rows_remaining == 0)\n              {\n                strip_size=TIFFReadEncodedStrip(tiff,strip_id,strip_pixels,\n                  TIFFStripSize(tiff));\n                if (strip_size == -1)\n                  break;\n                rows_remaining=rows_per_strip;\n                if ((y+rows_per_strip) > (ssize_t) image->rows)\n                  rows_remaining=(rows_per_strip-(y+rows_per_strip-\n                    image->rows));\n                p=strip_pixels;\n                strip_id++;\n              }\n            (void) ImportQuantumPixels(image,(CacheView *) NULL,\n              quantum_info,quantum_type,p,exception);\n            p+=stride;\n            rows_remaining--;\n            if (SyncAuthenticPixels(image,exception) == MagickFalse)\n              break;\n            if (image->previous == (Image *) NULL)\n              {\n                status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n                  image->rows);\n                if (status == MagickFalse)\n                  break;\n              }\n          }\n         if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE))\n            break;\n        }\n        strip_pixels=(unsigned char *) RelinquishMagickMemory(strip_pixels);\n        break;\n      }\n      case ReadTileMethod:\n      {\n        unsigned char\n          *p;\n\n        size_t\n          extent;\n\n        uint32\n          columns,\n          rows;\n\n        unsigned char\n          *tile_pixels;\n\n        /*\n          Convert tiled TIFF image.\n        */\n        if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n            (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n          ThrowTIFFException(CoderError,\"ImageIsNotTiled\");\n        number_pixels=(MagickSizeType) columns*rows;\n        if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)\n          ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n        extent=4*(samples_per_pixel+1)*MagickMax(rows*TIFFTileRowSize(tiff),\n          TIFFTileSize(tiff));\n        tile_pixels=(unsigned char *) AcquireQuantumMemory(extent,\n          sizeof(*tile_pixels));\n        if (tile_pixels == (unsigned char *) NULL)\n          ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n        (void) memset(tile_pixels,0,extent*sizeof(*tile_pixels));\n        for (i=0; i < (ssize_t) samples_per_pixel; i++)\n        {\n          switch (i)\n          {\n            case 0: break;\n            case 1: quantum_type=GreenQuantum; break;\n            case 2: quantum_type=BlueQuantum; break;\n            case 3:\n            {\n              quantum_type=AlphaQuantum;\n              if (image->colorspace == CMYKColorspace)\n                quantum_type=BlackQuantum;\n              break;\n            }\n            case 4: quantum_type=AlphaQuantum; break;\n            default: break;\n          }\n          for (y=0; y < (ssize_t) image->rows; y+=rows)\n          {\n            ssize_t\n              x;\n\n            size_t\n              rows_remaining;\n\n            rows_remaining=image->rows-y;\n            if ((ssize_t) (y+rows) < (ssize_t) image->rows)\n              rows_remaining=rows;\n            for (x=0; x < (ssize_t) image->columns; x+=columns)\n            {\n              size_t\n                columns_remaining,\n                row;\n\n              columns_remaining=image->columns-x;\n              if ((ssize_t) (x+columns) < (ssize_t) image->columns)\n                columns_remaining=columns;\n              tiff_status=TIFFReadTile(tiff,tile_pixels,(uint32) x,(uint32) y,\n                0,i);\n              if (tiff_status == -1)\n                break;\n              p=tile_pixels;\n              for (row=0; row < rows_remaining; row++)\n              {\n                PixelPacket\n                  *magick_restrict q;\n\n                q=GetAuthenticPixels(image,x,y+row,columns_remaining,1,\n                  exception);\n                if (q == (PixelPacket *) NULL)\n                  break;\n                (void) ImportQuantumPixels(image,(CacheView *) NULL,\n                  quantum_info,quantum_type,p,exception);\n                p+=TIFFTileRowSize(tiff);\n                if (SyncAuthenticPixels(image,exception) == MagickFalse)\n                  break;\n              }\n            }\n          }\n          if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE))\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) i,\n                samples_per_pixel);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        tile_pixels=(unsigned char *) RelinquishMagickMemory(tile_pixels);\n        break;\n      }\n      case ReadGenericMethod:\n      default:\n      {\n        MemoryInfo\n          *generic_info = (MemoryInfo *) NULL;\n\n        uint32\n          *p;\n\n        uint32\n          *pixels;\n\n        /*\n          Convert generic TIFF image.\n        */\n        if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)\n          ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n        number_pixels=(MagickSizeType) image->columns*image->rows;\n        generic_info=AcquireVirtualMemory(number_pixels,sizeof(*pixels));\n        if (generic_info == (MemoryInfo *) NULL)\n          ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n        pixels=(uint32 *) GetVirtualMemoryBlob(generic_info);\n        tiff_status=TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)\n          image->rows,(uint32 *) pixels,0);\n        if (tiff_status == -1)\n          {\n            generic_info=RelinquishVirtualMemory(generic_info);\n            break;\n          }\n        p=pixels+(image->columns*image->rows)-1;\n        for (y=0; y < (ssize_t) image->rows; y++)\n        {\n          ssize_t\n            x;\n\n          PixelPacket\n            *magick_restrict q;\n\n          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n          if (q == (PixelPacket *) NULL)\n            break;\n          q+=image->columns-1;\n          for (x=0; x < (ssize_t) image->columns; x++)\n          {\n            SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)));\n            SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)));\n            SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)));\n            if (image->matte == MagickFalse)\n              SetPixelOpacity(q,OpaqueOpacity);\n            else\n              SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)));\n            p--;\n            q--;\n          }\n          if (SyncAuthenticPixels(image,exception) == MagickFalse)\n            break;\n          if (image->previous == (Image *) NULL)\n            {\n              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n                image->rows);\n              if (status == MagickFalse)\n                break;\n            }\n        }\n        generic_info=RelinquishVirtualMemory(generic_info);\n        break;\n      }\n    }\n    pixel_info=RelinquishVirtualMemory(pixel_info);\n    SetQuantumImageType(image,quantum_type);\n  next_tiff_frame:\n    if (quantum_info != (QuantumInfo *) NULL)\n      quantum_info=DestroyQuantumInfo(quantum_info);\n    if (tiff_status == -1)\n      {\n        status=MagickFalse;\n        break;\n      }\n    if (photometric == PHOTOMETRIC_CIELAB)\n      DecodeLabImage(image,exception);\n    if ((photometric == PHOTOMETRIC_LOGL) ||\n        (photometric == PHOTOMETRIC_MINISBLACK) ||\n        (photometric == PHOTOMETRIC_MINISWHITE))\n      {\n        image->type=GrayscaleType;\n        if (bits_per_sample == 1)\n          image->type=BilevelType;\n      }\n    /*\n      Proceed to next image.\n    */\n    if (image_info->number_scenes != 0)\n      if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n        break;\n    more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n    if (more_frames != MagickFalse)\n      {\n        /*\n          Allocate next image structure.\n        */\n        AcquireNextImage(image_info,image);\n        if (GetNextImageInList(image) == (Image *) NULL)\n          {\n            status=MagickFalse;\n            break;\n          }\n        image=SyncNextImageInList(image);\n        status=SetImageProgress(image,LoadImagesTag,image->scene-1,\n          image->scene);\n        if (status == MagickFalse)\n          break;\n      }\n  } while ((status != MagickFalse) && (more_frames != MagickFalse));\n  TIFFClose(tiff);\n  if ((image_info->number_scenes != 0) &&\n      (image_info->scene >= GetImageListLength(image)))\n    status=MagickFalse;\n  if (status == MagickFalse)\n    return(DestroyImageList(image));\n  TIFFReadPhotoshopLayers(image_info,image,exception);\n  return(GetFirstImageInList(image));\n}", "func_hash": 299907120858996373991818547886083873911, "file_name": "tiff.c", "file_hash": 106627250122948436089504190965714390547, "cwe": ["CWE-787"], "cve": "CVE-2022-3213", "cve_desc": "A heap buffer overflow issue was found in ImageMagick. When an application processes a malformed TIFF file, it could lead to undefined behavior or a crash causing a denial of service.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3213"}
{"idx": 211868, "project": "nf", "commit_id": "b1a5983f56e371046dcf164f90bfaf704d2b89f6", "project_url": "http://git.kernel.org/cgit/linux/kernel/git/pablo/nf", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/netfilter/nf.git/commit/?id=b1a5983f56e371046dcf164f90bfaf704d2b89f6", "commit_message": "netfilter: nf_tables_offload: incorrect flow offload action array size\n\nimmediate verdict expression needs to allocate one slot in the flow offload\naction array, however, immediate data expression does not need to do so.\n\nfwd and dup expression need to allocate one slot, this is missing.\n\nAdd a new offload_action interface to report if this expression needs to\nallocate one slot in the flow offload action array.\n\nFixes: be2861dc36d7 (\"netfilter: nft_{fwd,dup}_netdev: add offload support\")\nReported-and-tested-by: Nick Gregory \nSigned-off-by: Pablo Neira Ayuso ", "target": 1, "func": "struct nft_flow_rule *nft_flow_rule_create(struct net *net,\n\t\t\t\t\t   const struct nft_rule *rule)\n{\n\tstruct nft_offload_ctx *ctx;\n\tstruct nft_flow_rule *flow;\n\tint num_actions = 0, err;\n\tstruct nft_expr *expr;\n\n\texpr = nft_expr_first(rule);\n\twhile (nft_expr_more(rule, expr)) {\n\t\tif (expr->ops->offload_flags & NFT_OFFLOAD_F_ACTION)\n\t\t\tnum_actions++;\n\n\t\texpr = nft_expr_next(expr);\n\t}\n\n\tif (num_actions == 0)\n\t\treturn ERR_PTR(-EOPNOTSUPP);\n\n\tflow = nft_flow_rule_alloc(num_actions);\n\tif (!flow)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\texpr = nft_expr_first(rule);\n\n\tctx = kzalloc(sizeof(struct nft_offload_ctx), GFP_KERNEL);\n\tif (!ctx) {\n\t\terr = -ENOMEM;\n\t\tgoto err_out;\n\t}\n\tctx->net = net;\n\tctx->dep.type = NFT_OFFLOAD_DEP_UNSPEC;\n\n\twhile (nft_expr_more(rule, expr)) {\n\t\tif (!expr->ops->offload) {\n\t\t\terr = -EOPNOTSUPP;\n\t\t\tgoto err_out;\n\t\t}\n\t\terr = expr->ops->offload(ctx, flow, expr);\n\t\tif (err < 0)\n\t\t\tgoto err_out;\n\n\t\texpr = nft_expr_next(expr);\n\t}\n\tnft_flow_rule_transfer_vlan(ctx, flow);\n\n\tflow->proto = ctx->dep.l3num;\n\tkfree(ctx);\n\n\treturn flow;\nerr_out:\n\tkfree(ctx);\n\tnft_flow_rule_destroy(flow);\n\n\treturn ERR_PTR(err);\n}", "func_hash": 135282973834013788624737629823587242676, "file_name": "nf_tables_offload.c", "file_hash": 26603376215652964964004794041493892983, "cwe": ["CWE-269"], "cve": "CVE-2022-25636", "cve_desc": "net/netfilter/nf_dup_netdev.c in the Linux kernel 5.4 through 5.6.10 allows local users to gain privileges because of a heap out-of-bounds write. This is related to nf_tables_offload.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-25636"}
{"idx": 452994, "project": "nf", "commit_id": "b1a5983f56e371046dcf164f90bfaf704d2b89f6", "project_url": "http://git.kernel.org/cgit/linux/kernel/git/pablo/nf", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/netfilter/nf.git/commit/?id=b1a5983f56e371046dcf164f90bfaf704d2b89f6", "commit_message": "netfilter: nf_tables_offload: incorrect flow offload action array size\n\nimmediate verdict expression needs to allocate one slot in the flow offload\naction array, however, immediate data expression does not need to do so.\n\nfwd and dup expression need to allocate one slot, this is missing.\n\nAdd a new offload_action interface to report if this expression needs to\nallocate one slot in the flow offload action array.\n\nFixes: be2861dc36d7 (\"netfilter: nft_{fwd,dup}_netdev: add offload support\")\nReported-and-tested-by: Nick Gregory \nSigned-off-by: Pablo Neira Ayuso ", "target": 0, "func": "struct nft_flow_rule *nft_flow_rule_create(struct net *net,\n\t\t\t\t\t   const struct nft_rule *rule)\n{\n\tstruct nft_offload_ctx *ctx;\n\tstruct nft_flow_rule *flow;\n\tint num_actions = 0, err;\n\tstruct nft_expr *expr;\n\n\texpr = nft_expr_first(rule);\n\twhile (nft_expr_more(rule, expr)) {\n\t\tif (expr->ops->offload_action &&\n\t\t    expr->ops->offload_action(expr))\n\t\t\tnum_actions++;\n\n\t\texpr = nft_expr_next(expr);\n\t}\n\n\tif (num_actions == 0)\n\t\treturn ERR_PTR(-EOPNOTSUPP);\n\n\tflow = nft_flow_rule_alloc(num_actions);\n\tif (!flow)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\texpr = nft_expr_first(rule);\n\n\tctx = kzalloc(sizeof(struct nft_offload_ctx), GFP_KERNEL);\n\tif (!ctx) {\n\t\terr = -ENOMEM;\n\t\tgoto err_out;\n\t}\n\tctx->net = net;\n\tctx->dep.type = NFT_OFFLOAD_DEP_UNSPEC;\n\n\twhile (nft_expr_more(rule, expr)) {\n\t\tif (!expr->ops->offload) {\n\t\t\terr = -EOPNOTSUPP;\n\t\t\tgoto err_out;\n\t\t}\n\t\terr = expr->ops->offload(ctx, flow, expr);\n\t\tif (err < 0)\n\t\t\tgoto err_out;\n\n\t\texpr = nft_expr_next(expr);\n\t}\n\tnft_flow_rule_transfer_vlan(ctx, flow);\n\n\tflow->proto = ctx->dep.l3num;\n\tkfree(ctx);\n\n\treturn flow;\nerr_out:\n\tkfree(ctx);\n\tnft_flow_rule_destroy(flow);\n\n\treturn ERR_PTR(err);\n}", "func_hash": 59444629723641299753508256533223671386, "file_name": "nf_tables_offload.c", "file_hash": 69217204877048087601961561157864546689, "cwe": ["CWE-269"], "cve": "CVE-2022-25636", "cve_desc": "net/netfilter/nf_dup_netdev.c in the Linux kernel 5.4 through 5.6.10 allows local users to gain privileges because of a heap out-of-bounds write. This is related to nf_tables_offload.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-25636"}
{"idx": 211877, "project": "libexpat", "commit_id": "a2fe525e660badd64b6c557c2b1ec26ddc07f6e4", "project_url": "https://github.com/libexpat/libexpat", "commit_url": "https://github.com/libexpat/libexpat/commit/a2fe525e660badd64b6c557c2b1ec26ddc07f6e4", "commit_message": "lib: Protect against malicious namespace declarations (CVE-2022-25236)", "target": 1, "func": "addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,\n           const XML_Char *uri, BINDING **bindingsPtr) {\n  static const XML_Char xmlNamespace[]\n      = {ASCII_h,      ASCII_t,     ASCII_t,     ASCII_p,      ASCII_COLON,\n         ASCII_SLASH,  ASCII_SLASH, ASCII_w,     ASCII_w,      ASCII_w,\n         ASCII_PERIOD, ASCII_w,     ASCII_3,     ASCII_PERIOD, ASCII_o,\n         ASCII_r,      ASCII_g,     ASCII_SLASH, ASCII_X,      ASCII_M,\n         ASCII_L,      ASCII_SLASH, ASCII_1,     ASCII_9,      ASCII_9,\n         ASCII_8,      ASCII_SLASH, ASCII_n,     ASCII_a,      ASCII_m,\n         ASCII_e,      ASCII_s,     ASCII_p,     ASCII_a,      ASCII_c,\n         ASCII_e,      '\\0'};\n  static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1;\n  static const XML_Char xmlnsNamespace[]\n      = {ASCII_h,     ASCII_t,      ASCII_t, ASCII_p, ASCII_COLON,  ASCII_SLASH,\n         ASCII_SLASH, ASCII_w,      ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w,\n         ASCII_3,     ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g,      ASCII_SLASH,\n         ASCII_2,     ASCII_0,      ASCII_0, ASCII_0, ASCII_SLASH,  ASCII_x,\n         ASCII_m,     ASCII_l,      ASCII_n, ASCII_s, ASCII_SLASH,  '\\0'};\n  static const int xmlnsLen\n      = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1;\n\n  XML_Bool mustBeXML = XML_FALSE;\n  XML_Bool isXML = XML_TRUE;\n  XML_Bool isXMLNS = XML_TRUE;\n\n  BINDING *b;\n  int len;\n\n  /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */\n  if (*uri == XML_T('\\0') && prefix->name)\n    return XML_ERROR_UNDECLARING_PREFIX;\n\n  if (prefix->name && prefix->name[0] == XML_T(ASCII_x)\n      && prefix->name[1] == XML_T(ASCII_m)\n      && prefix->name[2] == XML_T(ASCII_l)) {\n    /* Not allowed to bind xmlns */\n    if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s)\n        && prefix->name[5] == XML_T('\\0'))\n      return XML_ERROR_RESERVED_PREFIX_XMLNS;\n\n    if (prefix->name[3] == XML_T('\\0'))\n      mustBeXML = XML_TRUE;\n  }\n\n  for (len = 0; uri[len]; len++) {\n    if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))\n      isXML = XML_FALSE;\n\n    if (! mustBeXML && isXMLNS\n        && (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))\n      isXMLNS = XML_FALSE;\n  }\n  isXML = isXML && len == xmlLen;\n  isXMLNS = isXMLNS && len == xmlnsLen;\n\n  if (mustBeXML != isXML)\n    return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML\n                     : XML_ERROR_RESERVED_NAMESPACE_URI;\n\n  if (isXMLNS)\n    return XML_ERROR_RESERVED_NAMESPACE_URI;\n\n  if (parser->m_namespaceSeparator)\n    len++;\n  if (parser->m_freeBindingList) {\n    b = parser->m_freeBindingList;\n    if (len > b->uriAlloc) {\n      /* Detect and prevent integer overflow */\n      if (len > INT_MAX - EXPAND_SPARE) {\n        return XML_ERROR_NO_MEMORY;\n      }\n\n      /* Detect and prevent integer overflow.\n       * The preprocessor guard addresses the \"always false\" warning\n       * from -Wtype-limits on platforms where\n       * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n      if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {\n        return XML_ERROR_NO_MEMORY;\n      }\n#endif\n\n      XML_Char *temp = (XML_Char *)REALLOC(\n          parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE));\n      if (temp == NULL)\n        return XML_ERROR_NO_MEMORY;\n      b->uri = temp;\n      b->uriAlloc = len + EXPAND_SPARE;\n    }\n    parser->m_freeBindingList = b->nextTagBinding;\n  } else {\n    b = (BINDING *)MALLOC(parser, sizeof(BINDING));\n    if (! b)\n      return XML_ERROR_NO_MEMORY;\n\n    /* Detect and prevent integer overflow */\n    if (len > INT_MAX - EXPAND_SPARE) {\n      return XML_ERROR_NO_MEMORY;\n    }\n    /* Detect and prevent integer overflow.\n     * The preprocessor guard addresses the \"always false\" warning\n     * from -Wtype-limits on platforms where\n     * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n    if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {\n      return XML_ERROR_NO_MEMORY;\n    }\n#endif\n\n    b->uri\n        = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));\n    if (! b->uri) {\n      FREE(parser, b);\n      return XML_ERROR_NO_MEMORY;\n    }\n    b->uriAlloc = len + EXPAND_SPARE;\n  }\n  b->uriLen = len;\n  memcpy(b->uri, uri, len * sizeof(XML_Char));\n  if (parser->m_namespaceSeparator)\n    b->uri[len - 1] = parser->m_namespaceSeparator;\n  b->prefix = prefix;\n  b->attId = attId;\n  b->prevPrefixBinding = prefix->binding;\n  /* NULL binding when default namespace undeclared */\n  if (*uri == XML_T('\\0') && prefix == &parser->m_dtd->defaultPrefix)\n    prefix->binding = NULL;\n  else\n    prefix->binding = b;\n  b->nextTagBinding = *bindingsPtr;\n  *bindingsPtr = b;\n  /* if attId == NULL then we are not starting a namespace scope */\n  if (attId && parser->m_startNamespaceDeclHandler)\n    parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,\n                                        prefix->binding ? uri : 0);\n  return XML_ERROR_NONE;\n}", "func_hash": 22295362737021887331084829836677682659, "file_name": "xmlparse.c", "file_hash": 64970761866861782031621044957132437337, "cwe": ["CWE-668"], "cve": "CVE-2022-25236", "cve_desc": "xmlparse.c in Expat (aka libexpat) before 2.4.5 allows attackers to insert namespace-separator characters into namespace URIs.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-25236"}
{"idx": 453109, "project": "libexpat", "commit_id": "a2fe525e660badd64b6c557c2b1ec26ddc07f6e4", "project_url": "https://github.com/libexpat/libexpat", "commit_url": "https://github.com/libexpat/libexpat/commit/a2fe525e660badd64b6c557c2b1ec26ddc07f6e4", "commit_message": "lib: Protect against malicious namespace declarations (CVE-2022-25236)", "target": 0, "func": "addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,\n           const XML_Char *uri, BINDING **bindingsPtr) {\n  static const XML_Char xmlNamespace[]\n      = {ASCII_h,      ASCII_t,     ASCII_t,     ASCII_p,      ASCII_COLON,\n         ASCII_SLASH,  ASCII_SLASH, ASCII_w,     ASCII_w,      ASCII_w,\n         ASCII_PERIOD, ASCII_w,     ASCII_3,     ASCII_PERIOD, ASCII_o,\n         ASCII_r,      ASCII_g,     ASCII_SLASH, ASCII_X,      ASCII_M,\n         ASCII_L,      ASCII_SLASH, ASCII_1,     ASCII_9,      ASCII_9,\n         ASCII_8,      ASCII_SLASH, ASCII_n,     ASCII_a,      ASCII_m,\n         ASCII_e,      ASCII_s,     ASCII_p,     ASCII_a,      ASCII_c,\n         ASCII_e,      '\\0'};\n  static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1;\n  static const XML_Char xmlnsNamespace[]\n      = {ASCII_h,     ASCII_t,      ASCII_t, ASCII_p, ASCII_COLON,  ASCII_SLASH,\n         ASCII_SLASH, ASCII_w,      ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w,\n         ASCII_3,     ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g,      ASCII_SLASH,\n         ASCII_2,     ASCII_0,      ASCII_0, ASCII_0, ASCII_SLASH,  ASCII_x,\n         ASCII_m,     ASCII_l,      ASCII_n, ASCII_s, ASCII_SLASH,  '\\0'};\n  static const int xmlnsLen\n      = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1;\n\n  XML_Bool mustBeXML = XML_FALSE;\n  XML_Bool isXML = XML_TRUE;\n  XML_Bool isXMLNS = XML_TRUE;\n\n  BINDING *b;\n  int len;\n\n  /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */\n  if (*uri == XML_T('\\0') && prefix->name)\n    return XML_ERROR_UNDECLARING_PREFIX;\n\n  if (prefix->name && prefix->name[0] == XML_T(ASCII_x)\n      && prefix->name[1] == XML_T(ASCII_m)\n      && prefix->name[2] == XML_T(ASCII_l)) {\n    /* Not allowed to bind xmlns */\n    if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s)\n        && prefix->name[5] == XML_T('\\0'))\n      return XML_ERROR_RESERVED_PREFIX_XMLNS;\n\n    if (prefix->name[3] == XML_T('\\0'))\n      mustBeXML = XML_TRUE;\n  }\n\n  for (len = 0; uri[len]; len++) {\n    if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))\n      isXML = XML_FALSE;\n\n    if (! mustBeXML && isXMLNS\n        && (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))\n      isXMLNS = XML_FALSE;\n\n    // NOTE: While Expat does not validate namespace URIs against RFC 3986,\n    //       we have to at least make sure that the XML processor on top of\n    //       Expat (that is splitting tag names by namespace separator into\n    //       2- or 3-tuples (uri-local or uri-local-prefix)) cannot be confused\n    //       by an attacker putting additional namespace separator characters\n    //       into namespace declarations.  That would be ambiguous and not to\n    //       be expected.\n    if (parser->m_ns && (uri[len] == parser->m_namespaceSeparator)) {\n      return XML_ERROR_SYNTAX;\n    }\n  }\n  isXML = isXML && len == xmlLen;\n  isXMLNS = isXMLNS && len == xmlnsLen;\n\n  if (mustBeXML != isXML)\n    return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML\n                     : XML_ERROR_RESERVED_NAMESPACE_URI;\n\n  if (isXMLNS)\n    return XML_ERROR_RESERVED_NAMESPACE_URI;\n\n  if (parser->m_namespaceSeparator)\n    len++;\n  if (parser->m_freeBindingList) {\n    b = parser->m_freeBindingList;\n    if (len > b->uriAlloc) {\n      /* Detect and prevent integer overflow */\n      if (len > INT_MAX - EXPAND_SPARE) {\n        return XML_ERROR_NO_MEMORY;\n      }\n\n      /* Detect and prevent integer overflow.\n       * The preprocessor guard addresses the \"always false\" warning\n       * from -Wtype-limits on platforms where\n       * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n      if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {\n        return XML_ERROR_NO_MEMORY;\n      }\n#endif\n\n      XML_Char *temp = (XML_Char *)REALLOC(\n          parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE));\n      if (temp == NULL)\n        return XML_ERROR_NO_MEMORY;\n      b->uri = temp;\n      b->uriAlloc = len + EXPAND_SPARE;\n    }\n    parser->m_freeBindingList = b->nextTagBinding;\n  } else {\n    b = (BINDING *)MALLOC(parser, sizeof(BINDING));\n    if (! b)\n      return XML_ERROR_NO_MEMORY;\n\n    /* Detect and prevent integer overflow */\n    if (len > INT_MAX - EXPAND_SPARE) {\n      return XML_ERROR_NO_MEMORY;\n    }\n    /* Detect and prevent integer overflow.\n     * The preprocessor guard addresses the \"always false\" warning\n     * from -Wtype-limits on platforms where\n     * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n    if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {\n      return XML_ERROR_NO_MEMORY;\n    }\n#endif\n\n    b->uri\n        = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));\n    if (! b->uri) {\n      FREE(parser, b);\n      return XML_ERROR_NO_MEMORY;\n    }\n    b->uriAlloc = len + EXPAND_SPARE;\n  }\n  b->uriLen = len;\n  memcpy(b->uri, uri, len * sizeof(XML_Char));\n  if (parser->m_namespaceSeparator)\n    b->uri[len - 1] = parser->m_namespaceSeparator;\n  b->prefix = prefix;\n  b->attId = attId;\n  b->prevPrefixBinding = prefix->binding;\n  /* NULL binding when default namespace undeclared */\n  if (*uri == XML_T('\\0') && prefix == &parser->m_dtd->defaultPrefix)\n    prefix->binding = NULL;\n  else\n    prefix->binding = b;\n  b->nextTagBinding = *bindingsPtr;\n  *bindingsPtr = b;\n  /* if attId == NULL then we are not starting a namespace scope */\n  if (attId && parser->m_startNamespaceDeclHandler)\n    parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,\n                                        prefix->binding ? uri : 0);\n  return XML_ERROR_NONE;\n}", "func_hash": 180909609780994811991308792390157424153, "file_name": "xmlparse.c", "file_hash": 39872007825496999526918942248087494728, "cwe": ["CWE-668"], "cve": "CVE-2022-25236", "cve_desc": "xmlparse.c in Expat (aka libexpat) before 2.4.5 allows attackers to insert namespace-separator characters into namespace URIs.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-25236"}
{"idx": 211915, "project": "jasper", "commit_id": "839b1bcf0450ff036c28e8db40a7abf886e02891", "project_url": "https://github.com/mdadams/jasper", "commit_url": "https://github.com/jasper-software/jasper/commit/839b1bcf0450ff036c28e8db40a7abf886e02891", "commit_message": "jp2_dec: fix `numchans` mixup\n\nWhen iterating over `dec->cdef->data.cdef.ents`, we need to use its\n`numchans` variable, not the one in `jp2_dec_t`.\n\nFixes CVE-2018-19543\nFixes CVE-2017-9782\n\nCloses https://github.com/jasper-maint/jasper/issues/13\nCloses https://github.com/jasper-maint/jasper/issues/18\nCloses https://github.com/mdadams/jasper/issues/140\nCloses https://github.com/mdadams/jasper/issues/182", "target": 1, "func": "jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr)\n{\n\tjp2_box_t *box;\n\tint found;\n\tjas_image_t *image;\n\tjp2_dec_t *dec;\n\tbool samedtype;\n\tint dtype;\n\tunsigned int i;\n\tjp2_cmap_t *cmapd;\n\tjp2_pclr_t *pclrd;\n\tjp2_cdef_t *cdefd;\n\tunsigned int channo;\n\tint newcmptno;\n\tint_fast32_t *lutents;\n#if 0\n\tjp2_cdefchan_t *cdefent;\n\tint cmptno;\n#endif\n\tjp2_cmapent_t *cmapent;\n\tjas_icchdr_t icchdr;\n\tjas_iccprof_t *iccprof;\n\n\tdec = 0;\n\tbox = 0;\n\timage = 0;\n\n\tJAS_DBGLOG(100, (\"jp2_decode(%p, \\\"%s\\\")\\n\", in, optstr));\n\n\tif (!(dec = jp2_dec_create())) {\n\t\tgoto error;\n\t}\n\n\t/* Get the first box.  This should be a JP box. */\n\tif (!(box = jp2_box_get(in))) {\n\t\tjas_eprintf(\"error: cannot get box\\n\");\n\t\tgoto error;\n\t}\n\tif (box->type != JP2_BOX_JP) {\n\t\tjas_eprintf(\"error: expecting signature box\\n\");\n\t\tgoto error;\n\t}\n\tif (box->data.jp.magic != JP2_JP_MAGIC) {\n\t\tjas_eprintf(\"incorrect magic number\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/* Get the second box.  This should be a FTYP box. */\n\tif (!(box = jp2_box_get(in))) {\n\t\tgoto error;\n\t}\n\tif (box->type != JP2_BOX_FTYP) {\n\t\tjas_eprintf(\"expecting file type box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/* Get more boxes... */\n\tfound = 0;\n\twhile ((box = jp2_box_get(in))) {\n\t\tif (jas_getdbglevel() >= 1) {\n\t\t\tjas_eprintf(\"got box type %s\\n\", box->info->name);\n\t\t}\n\t\tswitch (box->type) {\n\t\tcase JP2_BOX_JP2C:\n\t\t\tfound = 1;\n\t\t\tbreak;\n\t\tcase JP2_BOX_IHDR:\n\t\t\tif (!dec->ihdr) {\n\t\t\t\tdec->ihdr = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_BPCC:\n\t\t\tif (!dec->bpcc) {\n\t\t\t\tdec->bpcc = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_CDEF:\n\t\t\tif (!dec->cdef) {\n\t\t\t\tdec->cdef = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_PCLR:\n\t\t\tif (!dec->pclr) {\n\t\t\t\tdec->pclr = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_CMAP:\n\t\t\tif (!dec->cmap) {\n\t\t\t\tdec->cmap = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_COLR:\n\t\t\tif (!dec->colr) {\n\t\t\t\tdec->colr = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (box) {\n\t\t\tjp2_box_destroy(box);\n\t\t\tbox = 0;\n\t\t}\n\t\tif (found) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!found) {\n\t\tjas_eprintf(\"error: no code stream found\\n\");\n\t\tgoto error;\n\t}\n\n\tif (!(dec->image = jpc_decode(in, optstr))) {\n\t\tjas_eprintf(\"error: cannot decode code stream\\n\");\n\t\tgoto error;\n\t}\n\n\t/* An IHDR box must be present. */\n\tif (!dec->ihdr) {\n\t\tjas_eprintf(\"error: missing IHDR box\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Does the number of components indicated in the IHDR box match\n\t  the value specified in the code stream? */\n\tif (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint,\n\t  jas_image_numcmpts(dec->image))) {\n\t\tjas_eprintf(\"warning: number of components mismatch\\n\");\n\t}\n\n\t/* At least one component must be present. */\n\tif (!jas_image_numcmpts(dec->image)) {\n\t\tjas_eprintf(\"error: no components\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Determine if all components have the same data type. */\n\tsamedtype = true;\n\tdtype = jas_image_cmptdtype(dec->image, 0);\n\tfor (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {\n\t\tif (jas_image_cmptdtype(dec->image, i) != dtype) {\n\t\t\tsamedtype = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* Is the component data type indicated in the IHDR box consistent\n\t  with the data in the code stream? */\n\tif ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||\n\t  (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {\n\t\tjas_eprintf(\"warning: component data type mismatch\\n\");\n\t}\n\n\t/* Is the compression type supported? */\n\tif (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {\n\t\tjas_eprintf(\"error: unsupported compression type\\n\");\n\t\tgoto error;\n\t}\n\n\tif (dec->bpcc) {\n\t\t/* Is the number of components indicated in the BPCC box\n\t\t  consistent with the code stream data? */\n\t\tif (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts(\n\t\t  dec->image))) {\n\t\t\tjas_eprintf(\"warning: number of components mismatch\\n\");\n\t\t}\n\t\t/* Is the component data type information indicated in the BPCC\n\t\t  box consistent with the code stream data? */\n\t\tif (!samedtype) {\n\t\t\tfor (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));\n\t\t\t  ++i) {\n\t\t\t\tif (jas_image_cmptdtype(dec->image, i) !=\n\t\t\t\t  JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {\n\t\t\t\t\tjas_eprintf(\"warning: component data type mismatch\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tjas_eprintf(\"warning: superfluous BPCC box\\n\");\n\t\t}\n\t}\n\n\t/* A COLR box must be present. */\n\tif (!dec->colr) {\n\t\tjas_eprintf(\"error: no COLR box\\n\");\n\t\tgoto error;\n\t}\n\n\tswitch (dec->colr->data.colr.method) {\n\tcase JP2_COLR_ENUM:\n\t\tjas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));\n\t\tbreak;\n\tcase JP2_COLR_ICC:\n\t\ticcprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,\n\t\t  dec->colr->data.colr.iccplen);\n\t\tif (!iccprof) {\n\t\t\tjas_eprintf(\"error: failed to parse ICC profile\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tjas_iccprof_gethdr(iccprof, &icchdr);\n\t\tjas_eprintf(\"ICC Profile CS %08x\\n\", icchdr.colorspc);\n\t\tjas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));\n\t\tdec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);\n\t\tassert(dec->image->cmprof_);\n\t\tjas_iccprof_destroy(iccprof);\n\t\tbreak;\n\t}\n\n\t/* If a CMAP box is present, a PCLR box must also be present. */\n\tif (dec->cmap && !dec->pclr) {\n\t\tjas_eprintf(\"warning: missing PCLR box or superfluous CMAP box\\n\");\n\t\tjp2_box_destroy(dec->cmap);\n\t\tdec->cmap = 0;\n\t}\n\n\t/* If a CMAP box is not present, a PCLR box must not be present. */\n\tif (!dec->cmap && dec->pclr) {\n\t\tjas_eprintf(\"warning: missing CMAP box or superfluous PCLR box\\n\");\n\t\tjp2_box_destroy(dec->pclr);\n\t\tdec->pclr = 0;\n\t}\n\n\t/* Determine the number of channels (which is essentially the number\n\t  of components after any palette mappings have been applied). */\n\tdec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans :\n\t  JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));\n\n\t/* Perform a basic sanity check on the CMAP box if present. */\n\tif (dec->cmap) {\n\t\tfor (i = 0; i < dec->numchans; ++i) {\n\t\t\t/* Is the component number reasonable? */\n\t\t\tif (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint,\n\t\t\t  jas_image_numcmpts(dec->image))) {\n\t\t\t\tjas_eprintf(\"error: invalid component number in CMAP box\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\t/* Is the LUT index reasonable? */\n\t\t\tif (dec->cmap->data.cmap.ents[i].pcol >=\n\t\t\t  dec->pclr->data.pclr.numchans) {\n\t\t\t\tjas_eprintf(\"error: invalid CMAP LUT index\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Allocate space for the channel-number to component-number LUT. */\n\tif (!(dec->chantocmptlut = jas_alloc2(dec->numchans,\n\t  sizeof(uint_fast16_t)))) {\n\t\tjas_eprintf(\"error: no memory\\n\");\n\t\tgoto error;\n\t}\n\n\tif (!dec->cmap) {\n\t\tfor (i = 0; i < dec->numchans; ++i) {\n\t\t\tdec->chantocmptlut[i] = i;\n\t\t}\n\t} else {\n\t\tcmapd = &dec->cmap->data.cmap;\n\t\tpclrd = &dec->pclr->data.pclr;\n\t\tcdefd = &dec->cdef->data.cdef;\n\t\tfor (channo = 0; channo < cmapd->numchans; ++channo) {\n\t\t\tcmapent = &cmapd->ents[channo];\n\t\t\tif (cmapent->map == JP2_CMAP_DIRECT) {\n\t\t\t\tdec->chantocmptlut[channo] = channo;\n\t\t\t} else if (cmapent->map == JP2_CMAP_PALETTE) {\n\t\t\t\tlutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t));\n\t\t\t\tfor (i = 0; i < pclrd->numlutents; ++i) {\n\t\t\t\t\tlutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];\n\t\t\t\t}\n\t\t\t\tnewcmptno = jas_image_numcmpts(dec->image);\n\t\t\t\tjas_image_depalettize(dec->image, cmapent->cmptno,\n\t\t\t\t  pclrd->numlutents, lutents,\n\t\t\t\t  JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);\n\t\t\t\tdec->chantocmptlut[channo] = newcmptno;\n\t\t\t\tjas_free(lutents);\n#if 0\n\t\t\t\tif (dec->cdef) {\n\t\t\t\t\tcdefent = jp2_cdef_lookup(cdefd, channo);\n\t\t\t\t\tif (!cdefent) {\n\t\t\t\t\t\tabort();\n\t\t\t\t\t}\n\t\t\t\tjas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));\n\t\t\t\t} else {\n\t\t\t\tjas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));\n\t\t\t\t}\n#endif\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Mark all components as being of unknown type. */\n\n\tfor (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {\n\t\tjas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);\n\t}\n\n\t/* Determine the type of each component. */\n\tif (dec->cdef) {\n\t\tfor (i = 0; i < dec->numchans; ++i) {\n\t\t\t/* Is the channel number reasonable? */\n\t\t\tif (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) {\n\t\t\t\tjas_eprintf(\"error: invalid channel number in CDEF box\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\tjas_image_setcmpttype(dec->image,\n\t\t\t  dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo],\n\t\t\t  jp2_getct(jas_image_clrspc(dec->image),\n\t\t\t  dec->cdef->data.cdef.ents[i].type,\n\t\t\t  dec->cdef->data.cdef.ents[i].assoc));\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < dec->numchans; ++i) {\n\t\t\tjas_image_setcmpttype(dec->image, dec->chantocmptlut[i],\n\t\t\t  jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));\n\t\t}\n\t}\n\n\t/* Delete any components that are not of interest. */\n\tfor (i = jas_image_numcmpts(dec->image); i > 0; --i) {\n\t\tif (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {\n\t\t\tjas_image_delcmpt(dec->image, i - 1);\n\t\t}\n\t}\n\n\t/* Ensure that some components survived. */\n\tif (!jas_image_numcmpts(dec->image)) {\n\t\tjas_eprintf(\"error: no components\\n\");\n\t\tgoto error;\n\t}\n#if 0\njas_eprintf(\"no of components is %d\\n\", jas_image_numcmpts(dec->image));\n#endif\n\n\t/* Prevent the image from being destroyed later. */\n\timage = dec->image;\n\tdec->image = 0;\n\n\tjp2_dec_destroy(dec);\n\n\treturn image;\n\nerror:\n\tif (box) {\n\t\tjp2_box_destroy(box);\n\t}\n\tif (dec) {\n\t\tjp2_dec_destroy(dec);\n\t}\n\treturn 0;\n}", "func_hash": 59868521314205020877993173661951509362, "file_name": "jp2_dec.c", "file_hash": 93955147082917127962057718477708272955, "cwe": ["CWE-125"], "cve": "CVE-2017-9782", "cve_desc": "JasPer 2.0.12 allows remote attackers to cause a denial of service (heap-based buffer over-read and application crash) via a crafted image, related to the jp2_decode function in libjasper/jp2/jp2_dec.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-9782"}
{"idx": 453265, "project": "jasper", "commit_id": "839b1bcf0450ff036c28e8db40a7abf886e02891", "project_url": "https://github.com/mdadams/jasper", "commit_url": "https://github.com/jasper-software/jasper/commit/839b1bcf0450ff036c28e8db40a7abf886e02891", "commit_message": "jp2_dec: fix `numchans` mixup\n\nWhen iterating over `dec->cdef->data.cdef.ents`, we need to use its\n`numchans` variable, not the one in `jp2_dec_t`.\n\nFixes CVE-2018-19543\nFixes CVE-2017-9782\n\nCloses https://github.com/jasper-maint/jasper/issues/13\nCloses https://github.com/jasper-maint/jasper/issues/18\nCloses https://github.com/mdadams/jasper/issues/140\nCloses https://github.com/mdadams/jasper/issues/182", "target": 0, "func": "jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr)\n{\n\tjp2_box_t *box;\n\tint found;\n\tjas_image_t *image;\n\tjp2_dec_t *dec;\n\tbool samedtype;\n\tint dtype;\n\tunsigned int i;\n\tjp2_cmap_t *cmapd;\n\tjp2_pclr_t *pclrd;\n\tjp2_cdef_t *cdefd;\n\tunsigned int channo;\n\tint newcmptno;\n\tint_fast32_t *lutents;\n#if 0\n\tjp2_cdefchan_t *cdefent;\n\tint cmptno;\n#endif\n\tjp2_cmapent_t *cmapent;\n\tjas_icchdr_t icchdr;\n\tjas_iccprof_t *iccprof;\n\n\tdec = 0;\n\tbox = 0;\n\timage = 0;\n\n\tJAS_DBGLOG(100, (\"jp2_decode(%p, \\\"%s\\\")\\n\", in, optstr));\n\n\tif (!(dec = jp2_dec_create())) {\n\t\tgoto error;\n\t}\n\n\t/* Get the first box.  This should be a JP box. */\n\tif (!(box = jp2_box_get(in))) {\n\t\tjas_eprintf(\"error: cannot get box\\n\");\n\t\tgoto error;\n\t}\n\tif (box->type != JP2_BOX_JP) {\n\t\tjas_eprintf(\"error: expecting signature box\\n\");\n\t\tgoto error;\n\t}\n\tif (box->data.jp.magic != JP2_JP_MAGIC) {\n\t\tjas_eprintf(\"incorrect magic number\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/* Get the second box.  This should be a FTYP box. */\n\tif (!(box = jp2_box_get(in))) {\n\t\tgoto error;\n\t}\n\tif (box->type != JP2_BOX_FTYP) {\n\t\tjas_eprintf(\"expecting file type box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/* Get more boxes... */\n\tfound = 0;\n\twhile ((box = jp2_box_get(in))) {\n\t\tif (jas_getdbglevel() >= 1) {\n\t\t\tjas_eprintf(\"got box type %s\\n\", box->info->name);\n\t\t}\n\t\tswitch (box->type) {\n\t\tcase JP2_BOX_JP2C:\n\t\t\tfound = 1;\n\t\t\tbreak;\n\t\tcase JP2_BOX_IHDR:\n\t\t\tif (!dec->ihdr) {\n\t\t\t\tdec->ihdr = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_BPCC:\n\t\t\tif (!dec->bpcc) {\n\t\t\t\tdec->bpcc = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_CDEF:\n\t\t\tif (!dec->cdef) {\n\t\t\t\tdec->cdef = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_PCLR:\n\t\t\tif (!dec->pclr) {\n\t\t\t\tdec->pclr = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_CMAP:\n\t\t\tif (!dec->cmap) {\n\t\t\t\tdec->cmap = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase JP2_BOX_COLR:\n\t\t\tif (!dec->colr) {\n\t\t\t\tdec->colr = box;\n\t\t\t\tbox = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (box) {\n\t\t\tjp2_box_destroy(box);\n\t\t\tbox = 0;\n\t\t}\n\t\tif (found) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!found) {\n\t\tjas_eprintf(\"error: no code stream found\\n\");\n\t\tgoto error;\n\t}\n\n\tif (!(dec->image = jpc_decode(in, optstr))) {\n\t\tjas_eprintf(\"error: cannot decode code stream\\n\");\n\t\tgoto error;\n\t}\n\n\t/* An IHDR box must be present. */\n\tif (!dec->ihdr) {\n\t\tjas_eprintf(\"error: missing IHDR box\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Does the number of components indicated in the IHDR box match\n\t  the value specified in the code stream? */\n\tif (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint,\n\t  jas_image_numcmpts(dec->image))) {\n\t\tjas_eprintf(\"warning: number of components mismatch\\n\");\n\t}\n\n\t/* At least one component must be present. */\n\tif (!jas_image_numcmpts(dec->image)) {\n\t\tjas_eprintf(\"error: no components\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Determine if all components have the same data type. */\n\tsamedtype = true;\n\tdtype = jas_image_cmptdtype(dec->image, 0);\n\tfor (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {\n\t\tif (jas_image_cmptdtype(dec->image, i) != dtype) {\n\t\t\tsamedtype = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* Is the component data type indicated in the IHDR box consistent\n\t  with the data in the code stream? */\n\tif ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||\n\t  (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {\n\t\tjas_eprintf(\"warning: component data type mismatch\\n\");\n\t}\n\n\t/* Is the compression type supported? */\n\tif (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {\n\t\tjas_eprintf(\"error: unsupported compression type\\n\");\n\t\tgoto error;\n\t}\n\n\tif (dec->bpcc) {\n\t\t/* Is the number of components indicated in the BPCC box\n\t\t  consistent with the code stream data? */\n\t\tif (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts(\n\t\t  dec->image))) {\n\t\t\tjas_eprintf(\"warning: number of components mismatch\\n\");\n\t\t}\n\t\t/* Is the component data type information indicated in the BPCC\n\t\t  box consistent with the code stream data? */\n\t\tif (!samedtype) {\n\t\t\tfor (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));\n\t\t\t  ++i) {\n\t\t\t\tif (jas_image_cmptdtype(dec->image, i) !=\n\t\t\t\t  JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {\n\t\t\t\t\tjas_eprintf(\"warning: component data type mismatch\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tjas_eprintf(\"warning: superfluous BPCC box\\n\");\n\t\t}\n\t}\n\n\t/* A COLR box must be present. */\n\tif (!dec->colr) {\n\t\tjas_eprintf(\"error: no COLR box\\n\");\n\t\tgoto error;\n\t}\n\n\tswitch (dec->colr->data.colr.method) {\n\tcase JP2_COLR_ENUM:\n\t\tjas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));\n\t\tbreak;\n\tcase JP2_COLR_ICC:\n\t\ticcprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,\n\t\t  dec->colr->data.colr.iccplen);\n\t\tif (!iccprof) {\n\t\t\tjas_eprintf(\"error: failed to parse ICC profile\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tjas_iccprof_gethdr(iccprof, &icchdr);\n\t\tjas_eprintf(\"ICC Profile CS %08x\\n\", icchdr.colorspc);\n\t\tjas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));\n\t\tdec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);\n\t\tassert(dec->image->cmprof_);\n\t\tjas_iccprof_destroy(iccprof);\n\t\tbreak;\n\t}\n\n\t/* If a CMAP box is present, a PCLR box must also be present. */\n\tif (dec->cmap && !dec->pclr) {\n\t\tjas_eprintf(\"warning: missing PCLR box or superfluous CMAP box\\n\");\n\t\tjp2_box_destroy(dec->cmap);\n\t\tdec->cmap = 0;\n\t}\n\n\t/* If a CMAP box is not present, a PCLR box must not be present. */\n\tif (!dec->cmap && dec->pclr) {\n\t\tjas_eprintf(\"warning: missing CMAP box or superfluous PCLR box\\n\");\n\t\tjp2_box_destroy(dec->pclr);\n\t\tdec->pclr = 0;\n\t}\n\n\t/* Determine the number of channels (which is essentially the number\n\t  of components after any palette mappings have been applied). */\n\tdec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans :\n\t  JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));\n\n\t/* Perform a basic sanity check on the CMAP box if present. */\n\tif (dec->cmap) {\n\t\tfor (i = 0; i < dec->numchans; ++i) {\n\t\t\t/* Is the component number reasonable? */\n\t\t\tif (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint,\n\t\t\t  jas_image_numcmpts(dec->image))) {\n\t\t\t\tjas_eprintf(\"error: invalid component number in CMAP box\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\t/* Is the LUT index reasonable? */\n\t\t\tif (dec->cmap->data.cmap.ents[i].pcol >=\n\t\t\t  dec->pclr->data.pclr.numchans) {\n\t\t\t\tjas_eprintf(\"error: invalid CMAP LUT index\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Allocate space for the channel-number to component-number LUT. */\n\tif (!(dec->chantocmptlut = jas_alloc2(dec->numchans,\n\t  sizeof(uint_fast16_t)))) {\n\t\tjas_eprintf(\"error: no memory\\n\");\n\t\tgoto error;\n\t}\n\n\tif (!dec->cmap) {\n\t\tfor (i = 0; i < dec->numchans; ++i) {\n\t\t\tdec->chantocmptlut[i] = i;\n\t\t}\n\t} else {\n\t\tcmapd = &dec->cmap->data.cmap;\n\t\tpclrd = &dec->pclr->data.pclr;\n\t\tcdefd = &dec->cdef->data.cdef;\n\t\tfor (channo = 0; channo < cmapd->numchans; ++channo) {\n\t\t\tcmapent = &cmapd->ents[channo];\n\t\t\tif (cmapent->map == JP2_CMAP_DIRECT) {\n\t\t\t\tdec->chantocmptlut[channo] = channo;\n\t\t\t} else if (cmapent->map == JP2_CMAP_PALETTE) {\n\t\t\t\tlutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t));\n\t\t\t\tfor (i = 0; i < pclrd->numlutents; ++i) {\n\t\t\t\t\tlutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];\n\t\t\t\t}\n\t\t\t\tnewcmptno = jas_image_numcmpts(dec->image);\n\t\t\t\tjas_image_depalettize(dec->image, cmapent->cmptno,\n\t\t\t\t  pclrd->numlutents, lutents,\n\t\t\t\t  JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);\n\t\t\t\tdec->chantocmptlut[channo] = newcmptno;\n\t\t\t\tjas_free(lutents);\n#if 0\n\t\t\t\tif (dec->cdef) {\n\t\t\t\t\tcdefent = jp2_cdef_lookup(cdefd, channo);\n\t\t\t\t\tif (!cdefent) {\n\t\t\t\t\t\tabort();\n\t\t\t\t\t}\n\t\t\t\tjas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));\n\t\t\t\t} else {\n\t\t\t\tjas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));\n\t\t\t\t}\n#endif\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Mark all components as being of unknown type. */\n\n\tfor (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {\n\t\tjas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);\n\t}\n\n\t/* Determine the type of each component. */\n\tif (dec->cdef) {\n\t\tfor (i = 0; i < dec->cdef->data.cdef.numchans; ++i) {\n\t\t\t/* Is the channel number reasonable? */\n\t\t\tif (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) {\n\t\t\t\tjas_eprintf(\"error: invalid channel number in CDEF box\\n\");\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\tjas_image_setcmpttype(dec->image,\n\t\t\t  dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo],\n\t\t\t  jp2_getct(jas_image_clrspc(dec->image),\n\t\t\t  dec->cdef->data.cdef.ents[i].type,\n\t\t\t  dec->cdef->data.cdef.ents[i].assoc));\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < dec->numchans; ++i) {\n\t\t\tjas_image_setcmpttype(dec->image, dec->chantocmptlut[i],\n\t\t\t  jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));\n\t\t}\n\t}\n\n\t/* Delete any components that are not of interest. */\n\tfor (i = jas_image_numcmpts(dec->image); i > 0; --i) {\n\t\tif (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {\n\t\t\tjas_image_delcmpt(dec->image, i - 1);\n\t\t}\n\t}\n\n\t/* Ensure that some components survived. */\n\tif (!jas_image_numcmpts(dec->image)) {\n\t\tjas_eprintf(\"error: no components\\n\");\n\t\tgoto error;\n\t}\n#if 0\njas_eprintf(\"no of components is %d\\n\", jas_image_numcmpts(dec->image));\n#endif\n\n\t/* Prevent the image from being destroyed later. */\n\timage = dec->image;\n\tdec->image = 0;\n\n\tjp2_dec_destroy(dec);\n\n\treturn image;\n\nerror:\n\tif (box) {\n\t\tjp2_box_destroy(box);\n\t}\n\tif (dec) {\n\t\tjp2_dec_destroy(dec);\n\t}\n\treturn 0;\n}", "func_hash": 125813963803436339336182748178269813866, "file_name": "jp2_dec.c", "file_hash": 163023647028726236156493371179237582578, "cwe": ["CWE-125"], "cve": "CVE-2017-9782", "cve_desc": "JasPer 2.0.12 allows remote attackers to cause a denial of service (heap-based buffer over-read and application crash) via a crafted image, related to the jp2_decode function in libjasper/jp2/jp2_dec.c.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-9782"}
{"idx": 212083, "project": "linux", "commit_id": "690b2549b19563ec5ad53e5c82f6a944d910086e", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/690b2549b19563ec5ad53e5c82f6a944d910086e", "commit_message": "i2c: ismt: prevent memory corruption in ismt_access()\n\nThe \"data->block[0]\" variable comes from the user and is a number\nbetween 0-255.  It needs to be capped to prevent writing beyond the end\nof dma_buffer[].\n\nFixes: 5e9a97b1f449 (\"i2c: ismt: Adding support for I2C_SMBUS_BLOCK_PROC_CALL\")\nReported-and-tested-by: Zheyu Ma \nSigned-off-by: Dan Carpenter \nReviewed-by: Mika Westerberg \nSigned-off-by: Linus Torvalds ", "target": 1, "func": "static int ismt_access(struct i2c_adapter *adap, u16 addr,\n\t\t       unsigned short flags, char read_write, u8 command,\n\t\t       int size, union i2c_smbus_data *data)\n{\n\tint ret;\n\tunsigned long time_left;\n\tdma_addr_t dma_addr = 0; /* address of the data buffer */\n\tu8 dma_size = 0;\n\tenum dma_data_direction dma_direction = 0;\n\tstruct ismt_desc *desc;\n\tstruct ismt_priv *priv = i2c_get_adapdata(adap);\n\tstruct device *dev = &priv->pci_dev->dev;\n\tu8 *dma_buffer = PTR_ALIGN(&priv->buffer[0], 16);\n\n\tdesc = &priv->hw[priv->head];\n\n\t/* Initialize the DMA buffer */\n\tmemset(priv->buffer, 0, sizeof(priv->buffer));\n\n\t/* Initialize the descriptor */\n\tmemset(desc, 0, sizeof(struct ismt_desc));\n\tdesc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, read_write);\n\n\t/* Always clear the log entries */\n\tmemset(priv->log, 0, ISMT_LOG_ENTRIES * sizeof(u32));\n\n\t/* Initialize common control bits */\n\tif (likely(pci_dev_msi_enabled(priv->pci_dev)))\n\t\tdesc->control = ISMT_DESC_INT | ISMT_DESC_FAIR;\n\telse\n\t\tdesc->control = ISMT_DESC_FAIR;\n\n\tif ((flags & I2C_CLIENT_PEC) && (size != I2C_SMBUS_QUICK)\n\t    && (size != I2C_SMBUS_I2C_BLOCK_DATA))\n\t\tdesc->control |= ISMT_DESC_PEC;\n\n\tswitch (size) {\n\tcase I2C_SMBUS_QUICK:\n\t\tdev_dbg(dev, \"I2C_SMBUS_QUICK\\n\");\n\t\tbreak;\n\n\tcase I2C_SMBUS_BYTE:\n\t\tif (read_write == I2C_SMBUS_WRITE) {\n\t\t\t/*\n\t\t\t * Send Byte\n\t\t\t * The command field contains the write data\n\t\t\t */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_BYTE:  WRITE\\n\");\n\t\t\tdesc->control |= ISMT_DESC_CWRL;\n\t\t\tdesc->wr_len_cmd = command;\n\t\t} else {\n\t\t\t/* Receive Byte */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_BYTE:  READ\\n\");\n\t\t\tdma_size = 1;\n\t\t\tdma_direction = DMA_FROM_DEVICE;\n\t\t\tdesc->rd_len = 1;\n\t\t}\n\t\tbreak;\n\n\tcase I2C_SMBUS_BYTE_DATA:\n\t\tif (read_write == I2C_SMBUS_WRITE) {\n\t\t\t/*\n\t\t\t * Write Byte\n\t\t\t * Command plus 1 data byte\n\t\t\t */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_BYTE_DATA:  WRITE\\n\");\n\t\t\tdesc->wr_len_cmd = 2;\n\t\t\tdma_size = 2;\n\t\t\tdma_direction = DMA_TO_DEVICE;\n\t\t\tdma_buffer[0] = command;\n\t\t\tdma_buffer[1] = data->byte;\n\t\t} else {\n\t\t\t/* Read Byte */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_BYTE_DATA:  READ\\n\");\n\t\t\tdesc->control |= ISMT_DESC_CWRL;\n\t\t\tdesc->wr_len_cmd = command;\n\t\t\tdesc->rd_len = 1;\n\t\t\tdma_size = 1;\n\t\t\tdma_direction = DMA_FROM_DEVICE;\n\t\t}\n\t\tbreak;\n\n\tcase I2C_SMBUS_WORD_DATA:\n\t\tif (read_write == I2C_SMBUS_WRITE) {\n\t\t\t/* Write Word */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_WORD_DATA:  WRITE\\n\");\n\t\t\tdesc->wr_len_cmd = 3;\n\t\t\tdma_size = 3;\n\t\t\tdma_direction = DMA_TO_DEVICE;\n\t\t\tdma_buffer[0] = command;\n\t\t\tdma_buffer[1] = data->word & 0xff;\n\t\t\tdma_buffer[2] = data->word >> 8;\n\t\t} else {\n\t\t\t/* Read Word */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_WORD_DATA:  READ\\n\");\n\t\t\tdesc->wr_len_cmd = command;\n\t\t\tdesc->control |= ISMT_DESC_CWRL;\n\t\t\tdesc->rd_len = 2;\n\t\t\tdma_size = 2;\n\t\t\tdma_direction = DMA_FROM_DEVICE;\n\t\t}\n\t\tbreak;\n\n\tcase I2C_SMBUS_PROC_CALL:\n\t\tdev_dbg(dev, \"I2C_SMBUS_PROC_CALL\\n\");\n\t\tdesc->wr_len_cmd = 3;\n\t\tdesc->rd_len = 2;\n\t\tdma_size = 3;\n\t\tdma_direction = DMA_BIDIRECTIONAL;\n\t\tdma_buffer[0] = command;\n\t\tdma_buffer[1] = data->word & 0xff;\n\t\tdma_buffer[2] = data->word >> 8;\n\t\tbreak;\n\n\tcase I2C_SMBUS_BLOCK_DATA:\n\t\tif (read_write == I2C_SMBUS_WRITE) {\n\t\t\t/* Block Write */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_BLOCK_DATA:  WRITE\\n\");\n\t\t\tdma_size = data->block[0] + 1;\n\t\t\tdma_direction = DMA_TO_DEVICE;\n\t\t\tdesc->wr_len_cmd = dma_size;\n\t\t\tdesc->control |= ISMT_DESC_BLK;\n\t\t\tdma_buffer[0] = command;\n\t\t\tmemcpy(&dma_buffer[1], &data->block[1], dma_size - 1);\n\t\t} else {\n\t\t\t/* Block Read */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_BLOCK_DATA:  READ\\n\");\n\t\t\tdma_size = I2C_SMBUS_BLOCK_MAX;\n\t\t\tdma_direction = DMA_FROM_DEVICE;\n\t\t\tdesc->rd_len = dma_size;\n\t\t\tdesc->wr_len_cmd = command;\n\t\t\tdesc->control |= (ISMT_DESC_BLK | ISMT_DESC_CWRL);\n\t\t}\n\t\tbreak;\n\n\tcase I2C_SMBUS_BLOCK_PROC_CALL:\n\t\tdev_dbg(dev, \"I2C_SMBUS_BLOCK_PROC_CALL\\n\");\n\t\tdma_size = I2C_SMBUS_BLOCK_MAX;\n\t\tdesc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 1);\n\t\tdesc->wr_len_cmd = data->block[0] + 1;\n\t\tdesc->rd_len = dma_size;\n\t\tdesc->control |= ISMT_DESC_BLK;\n\t\tdma_direction = DMA_BIDIRECTIONAL;\n\t\tdma_buffer[0] = command;\n\t\tmemcpy(&dma_buffer[1], &data->block[1], data->block[0]);\n\t\tbreak;\n\n\tcase I2C_SMBUS_I2C_BLOCK_DATA:\n\t\t/* Make sure the length is valid */\n\t\tif (data->block[0] < 1)\n\t\t\tdata->block[0] = 1;\n\n\t\tif (data->block[0] > I2C_SMBUS_BLOCK_MAX)\n\t\t\tdata->block[0] = I2C_SMBUS_BLOCK_MAX;\n\n\t\tif (read_write == I2C_SMBUS_WRITE) {\n\t\t\t/* i2c Block Write */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_I2C_BLOCK_DATA:  WRITE\\n\");\n\t\t\tdma_size = data->block[0] + 1;\n\t\t\tdma_direction = DMA_TO_DEVICE;\n\t\t\tdesc->wr_len_cmd = dma_size;\n\t\t\tdesc->control |= ISMT_DESC_I2C;\n\t\t\tdma_buffer[0] = command;\n\t\t\tmemcpy(&dma_buffer[1], &data->block[1], dma_size - 1);\n\t\t} else {\n\t\t\t/* i2c Block Read */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_I2C_BLOCK_DATA:  READ\\n\");\n\t\t\tdma_size = data->block[0];\n\t\t\tdma_direction = DMA_FROM_DEVICE;\n\t\t\tdesc->rd_len = dma_size;\n\t\t\tdesc->wr_len_cmd = command;\n\t\t\tdesc->control |= (ISMT_DESC_I2C | ISMT_DESC_CWRL);\n\t\t\t/*\n\t\t\t * Per the \"Table 15-15. I2C Commands\",\n\t\t\t * in the External Design Specification (EDS),\n\t\t\t * (Document Number: 508084, Revision: 2.0),\n\t\t\t * the _rw bit must be 0\n\t\t\t */\n\t\t\tdesc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 0);\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tdev_err(dev, \"Unsupported transaction %d\\n\",\n\t\t\tsize);\n\t\treturn -EOPNOTSUPP;\n\t}\n\n\t/* map the data buffer */\n\tif (dma_size != 0) {\n\t\tdev_dbg(dev, \" dev=%p\\n\", dev);\n\t\tdev_dbg(dev, \" data=%p\\n\", data);\n\t\tdev_dbg(dev, \" dma_buffer=%p\\n\", dma_buffer);\n\t\tdev_dbg(dev, \" dma_size=%d\\n\", dma_size);\n\t\tdev_dbg(dev, \" dma_direction=%d\\n\", dma_direction);\n\n\t\tdma_addr = dma_map_single(dev,\n\t\t\t\t      dma_buffer,\n\t\t\t\t      dma_size,\n\t\t\t\t      dma_direction);\n\n\t\tif (dma_mapping_error(dev, dma_addr)) {\n\t\t\tdev_err(dev, \"Error in mapping dma buffer %p\\n\",\n\t\t\t\tdma_buffer);\n\t\t\treturn -EIO;\n\t\t}\n\n\t\tdev_dbg(dev, \" dma_addr = %pad\\n\", &dma_addr);\n\n\t\tdesc->dptr_low = lower_32_bits(dma_addr);\n\t\tdesc->dptr_high = upper_32_bits(dma_addr);\n\t}\n\n\treinit_completion(&priv->cmp);\n\n\t/* Add the descriptor */\n\tismt_submit_desc(priv);\n\n\t/* Now we wait for interrupt completion, 1s */\n\ttime_left = wait_for_completion_timeout(&priv->cmp, HZ*1);\n\n\t/* unmap the data buffer */\n\tif (dma_size != 0)\n\t\tdma_unmap_single(dev, dma_addr, dma_size, dma_direction);\n\n\tif (unlikely(!time_left)) {\n\t\tdev_err(dev, \"completion wait timed out\\n\");\n\t\tret = -ETIMEDOUT;\n\t\tgoto out;\n\t}\n\n\t/* do any post processing of the descriptor here */\n\tret = ismt_process_desc(desc, data, priv, size, read_write);\n\nout:\n\t/* Update the ring pointer */\n\tpriv->head++;\n\tpriv->head %= ISMT_DESC_ENTRIES;\n\n\treturn ret;\n}", "func_hash": 91513236317351842038056466223233835211, "file_name": "i2c-ismt.c", "file_hash": 22364513944485151173045885792643538357, "cwe": ["CWE-703"], "cve": "CVE-2022-3077", "cve_desc": "A buffer overflow vulnerability was found in the Linux kernel Intel\u2019s iSMT SMBus host controller driver in the way it handled the I2C_SMBUS_BLOCK_PROC_CALL case (via the ioctl I2C_SMBUS) with malicious input data. This flaw could allow a local user to crash the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3077"}
{"idx": 454759, "project": "linux", "commit_id": "690b2549b19563ec5ad53e5c82f6a944d910086e", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/690b2549b19563ec5ad53e5c82f6a944d910086e", "commit_message": "i2c: ismt: prevent memory corruption in ismt_access()\n\nThe \"data->block[0]\" variable comes from the user and is a number\nbetween 0-255.  It needs to be capped to prevent writing beyond the end\nof dma_buffer[].\n\nFixes: 5e9a97b1f449 (\"i2c: ismt: Adding support for I2C_SMBUS_BLOCK_PROC_CALL\")\nReported-and-tested-by: Zheyu Ma \nSigned-off-by: Dan Carpenter \nReviewed-by: Mika Westerberg \nSigned-off-by: Linus Torvalds ", "target": 0, "func": "static int ismt_access(struct i2c_adapter *adap, u16 addr,\n\t\t       unsigned short flags, char read_write, u8 command,\n\t\t       int size, union i2c_smbus_data *data)\n{\n\tint ret;\n\tunsigned long time_left;\n\tdma_addr_t dma_addr = 0; /* address of the data buffer */\n\tu8 dma_size = 0;\n\tenum dma_data_direction dma_direction = 0;\n\tstruct ismt_desc *desc;\n\tstruct ismt_priv *priv = i2c_get_adapdata(adap);\n\tstruct device *dev = &priv->pci_dev->dev;\n\tu8 *dma_buffer = PTR_ALIGN(&priv->buffer[0], 16);\n\n\tdesc = &priv->hw[priv->head];\n\n\t/* Initialize the DMA buffer */\n\tmemset(priv->buffer, 0, sizeof(priv->buffer));\n\n\t/* Initialize the descriptor */\n\tmemset(desc, 0, sizeof(struct ismt_desc));\n\tdesc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, read_write);\n\n\t/* Always clear the log entries */\n\tmemset(priv->log, 0, ISMT_LOG_ENTRIES * sizeof(u32));\n\n\t/* Initialize common control bits */\n\tif (likely(pci_dev_msi_enabled(priv->pci_dev)))\n\t\tdesc->control = ISMT_DESC_INT | ISMT_DESC_FAIR;\n\telse\n\t\tdesc->control = ISMT_DESC_FAIR;\n\n\tif ((flags & I2C_CLIENT_PEC) && (size != I2C_SMBUS_QUICK)\n\t    && (size != I2C_SMBUS_I2C_BLOCK_DATA))\n\t\tdesc->control |= ISMT_DESC_PEC;\n\n\tswitch (size) {\n\tcase I2C_SMBUS_QUICK:\n\t\tdev_dbg(dev, \"I2C_SMBUS_QUICK\\n\");\n\t\tbreak;\n\n\tcase I2C_SMBUS_BYTE:\n\t\tif (read_write == I2C_SMBUS_WRITE) {\n\t\t\t/*\n\t\t\t * Send Byte\n\t\t\t * The command field contains the write data\n\t\t\t */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_BYTE:  WRITE\\n\");\n\t\t\tdesc->control |= ISMT_DESC_CWRL;\n\t\t\tdesc->wr_len_cmd = command;\n\t\t} else {\n\t\t\t/* Receive Byte */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_BYTE:  READ\\n\");\n\t\t\tdma_size = 1;\n\t\t\tdma_direction = DMA_FROM_DEVICE;\n\t\t\tdesc->rd_len = 1;\n\t\t}\n\t\tbreak;\n\n\tcase I2C_SMBUS_BYTE_DATA:\n\t\tif (read_write == I2C_SMBUS_WRITE) {\n\t\t\t/*\n\t\t\t * Write Byte\n\t\t\t * Command plus 1 data byte\n\t\t\t */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_BYTE_DATA:  WRITE\\n\");\n\t\t\tdesc->wr_len_cmd = 2;\n\t\t\tdma_size = 2;\n\t\t\tdma_direction = DMA_TO_DEVICE;\n\t\t\tdma_buffer[0] = command;\n\t\t\tdma_buffer[1] = data->byte;\n\t\t} else {\n\t\t\t/* Read Byte */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_BYTE_DATA:  READ\\n\");\n\t\t\tdesc->control |= ISMT_DESC_CWRL;\n\t\t\tdesc->wr_len_cmd = command;\n\t\t\tdesc->rd_len = 1;\n\t\t\tdma_size = 1;\n\t\t\tdma_direction = DMA_FROM_DEVICE;\n\t\t}\n\t\tbreak;\n\n\tcase I2C_SMBUS_WORD_DATA:\n\t\tif (read_write == I2C_SMBUS_WRITE) {\n\t\t\t/* Write Word */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_WORD_DATA:  WRITE\\n\");\n\t\t\tdesc->wr_len_cmd = 3;\n\t\t\tdma_size = 3;\n\t\t\tdma_direction = DMA_TO_DEVICE;\n\t\t\tdma_buffer[0] = command;\n\t\t\tdma_buffer[1] = data->word & 0xff;\n\t\t\tdma_buffer[2] = data->word >> 8;\n\t\t} else {\n\t\t\t/* Read Word */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_WORD_DATA:  READ\\n\");\n\t\t\tdesc->wr_len_cmd = command;\n\t\t\tdesc->control |= ISMT_DESC_CWRL;\n\t\t\tdesc->rd_len = 2;\n\t\t\tdma_size = 2;\n\t\t\tdma_direction = DMA_FROM_DEVICE;\n\t\t}\n\t\tbreak;\n\n\tcase I2C_SMBUS_PROC_CALL:\n\t\tdev_dbg(dev, \"I2C_SMBUS_PROC_CALL\\n\");\n\t\tdesc->wr_len_cmd = 3;\n\t\tdesc->rd_len = 2;\n\t\tdma_size = 3;\n\t\tdma_direction = DMA_BIDIRECTIONAL;\n\t\tdma_buffer[0] = command;\n\t\tdma_buffer[1] = data->word & 0xff;\n\t\tdma_buffer[2] = data->word >> 8;\n\t\tbreak;\n\n\tcase I2C_SMBUS_BLOCK_DATA:\n\t\tif (read_write == I2C_SMBUS_WRITE) {\n\t\t\t/* Block Write */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_BLOCK_DATA:  WRITE\\n\");\n\t\t\tdma_size = data->block[0] + 1;\n\t\t\tdma_direction = DMA_TO_DEVICE;\n\t\t\tdesc->wr_len_cmd = dma_size;\n\t\t\tdesc->control |= ISMT_DESC_BLK;\n\t\t\tdma_buffer[0] = command;\n\t\t\tmemcpy(&dma_buffer[1], &data->block[1], dma_size - 1);\n\t\t} else {\n\t\t\t/* Block Read */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_BLOCK_DATA:  READ\\n\");\n\t\t\tdma_size = I2C_SMBUS_BLOCK_MAX;\n\t\t\tdma_direction = DMA_FROM_DEVICE;\n\t\t\tdesc->rd_len = dma_size;\n\t\t\tdesc->wr_len_cmd = command;\n\t\t\tdesc->control |= (ISMT_DESC_BLK | ISMT_DESC_CWRL);\n\t\t}\n\t\tbreak;\n\n\tcase I2C_SMBUS_BLOCK_PROC_CALL:\n\t\tdev_dbg(dev, \"I2C_SMBUS_BLOCK_PROC_CALL\\n\");\n\t\tif (data->block[0] > I2C_SMBUS_BLOCK_MAX)\n\t\t\treturn -EINVAL;\n\n\t\tdma_size = I2C_SMBUS_BLOCK_MAX;\n\t\tdesc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 1);\n\t\tdesc->wr_len_cmd = data->block[0] + 1;\n\t\tdesc->rd_len = dma_size;\n\t\tdesc->control |= ISMT_DESC_BLK;\n\t\tdma_direction = DMA_BIDIRECTIONAL;\n\t\tdma_buffer[0] = command;\n\t\tmemcpy(&dma_buffer[1], &data->block[1], data->block[0]);\n\t\tbreak;\n\n\tcase I2C_SMBUS_I2C_BLOCK_DATA:\n\t\t/* Make sure the length is valid */\n\t\tif (data->block[0] < 1)\n\t\t\tdata->block[0] = 1;\n\n\t\tif (data->block[0] > I2C_SMBUS_BLOCK_MAX)\n\t\t\tdata->block[0] = I2C_SMBUS_BLOCK_MAX;\n\n\t\tif (read_write == I2C_SMBUS_WRITE) {\n\t\t\t/* i2c Block Write */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_I2C_BLOCK_DATA:  WRITE\\n\");\n\t\t\tdma_size = data->block[0] + 1;\n\t\t\tdma_direction = DMA_TO_DEVICE;\n\t\t\tdesc->wr_len_cmd = dma_size;\n\t\t\tdesc->control |= ISMT_DESC_I2C;\n\t\t\tdma_buffer[0] = command;\n\t\t\tmemcpy(&dma_buffer[1], &data->block[1], dma_size - 1);\n\t\t} else {\n\t\t\t/* i2c Block Read */\n\t\t\tdev_dbg(dev, \"I2C_SMBUS_I2C_BLOCK_DATA:  READ\\n\");\n\t\t\tdma_size = data->block[0];\n\t\t\tdma_direction = DMA_FROM_DEVICE;\n\t\t\tdesc->rd_len = dma_size;\n\t\t\tdesc->wr_len_cmd = command;\n\t\t\tdesc->control |= (ISMT_DESC_I2C | ISMT_DESC_CWRL);\n\t\t\t/*\n\t\t\t * Per the \"Table 15-15. I2C Commands\",\n\t\t\t * in the External Design Specification (EDS),\n\t\t\t * (Document Number: 508084, Revision: 2.0),\n\t\t\t * the _rw bit must be 0\n\t\t\t */\n\t\t\tdesc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 0);\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tdev_err(dev, \"Unsupported transaction %d\\n\",\n\t\t\tsize);\n\t\treturn -EOPNOTSUPP;\n\t}\n\n\t/* map the data buffer */\n\tif (dma_size != 0) {\n\t\tdev_dbg(dev, \" dev=%p\\n\", dev);\n\t\tdev_dbg(dev, \" data=%p\\n\", data);\n\t\tdev_dbg(dev, \" dma_buffer=%p\\n\", dma_buffer);\n\t\tdev_dbg(dev, \" dma_size=%d\\n\", dma_size);\n\t\tdev_dbg(dev, \" dma_direction=%d\\n\", dma_direction);\n\n\t\tdma_addr = dma_map_single(dev,\n\t\t\t\t      dma_buffer,\n\t\t\t\t      dma_size,\n\t\t\t\t      dma_direction);\n\n\t\tif (dma_mapping_error(dev, dma_addr)) {\n\t\t\tdev_err(dev, \"Error in mapping dma buffer %p\\n\",\n\t\t\t\tdma_buffer);\n\t\t\treturn -EIO;\n\t\t}\n\n\t\tdev_dbg(dev, \" dma_addr = %pad\\n\", &dma_addr);\n\n\t\tdesc->dptr_low = lower_32_bits(dma_addr);\n\t\tdesc->dptr_high = upper_32_bits(dma_addr);\n\t}\n\n\treinit_completion(&priv->cmp);\n\n\t/* Add the descriptor */\n\tismt_submit_desc(priv);\n\n\t/* Now we wait for interrupt completion, 1s */\n\ttime_left = wait_for_completion_timeout(&priv->cmp, HZ*1);\n\n\t/* unmap the data buffer */\n\tif (dma_size != 0)\n\t\tdma_unmap_single(dev, dma_addr, dma_size, dma_direction);\n\n\tif (unlikely(!time_left)) {\n\t\tdev_err(dev, \"completion wait timed out\\n\");\n\t\tret = -ETIMEDOUT;\n\t\tgoto out;\n\t}\n\n\t/* do any post processing of the descriptor here */\n\tret = ismt_process_desc(desc, data, priv, size, read_write);\n\nout:\n\t/* Update the ring pointer */\n\tpriv->head++;\n\tpriv->head %= ISMT_DESC_ENTRIES;\n\n\treturn ret;\n}", "func_hash": 337152422880524025166312472003442952073, "file_name": "i2c-ismt.c", "file_hash": 51244111268212170404918431081464078764, "cwe": ["CWE-703"], "cve": "CVE-2022-3077", "cve_desc": "A buffer overflow vulnerability was found in the Linux kernel Intel\u2019s iSMT SMBus host controller driver in the way it handled the I2C_SMBUS_BLOCK_PROC_CALL case (via the ioctl I2C_SMBUS) with malicious input data. This flaw could allow a local user to crash the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3077"}
{"idx": 212144, "project": "libmobi", "commit_id": "c78e186739b50d156cb3da5d08d70294f0490853", "project_url": "https://github.com/bfabiszewski/libmobi", "commit_url": "https://github.com/bfabiszewski/libmobi/commit/c78e186739b50d156cb3da5d08d70294f0490853", "commit_message": "Fix potential out-of-buffer read while parsing corrupt file, closes #38", "target": 1, "func": "MOBI_RET mobi_parse_huffdic(const MOBIData *m, MOBIHuffCdic *huffcdic) {\n    MOBI_RET ret;\n    const size_t offset = mobi_get_kf8offset(m);\n    if (m->mh == NULL || m->mh->huff_rec_index == NULL || m->mh->huff_rec_count == NULL) {\n        debug_print(\"%s\", \"HUFF/CDIC records metadata not found in MOBI header\\n\");\n        return MOBI_DATA_CORRUPT;\n    }\n    const size_t huff_rec_index = *m->mh->huff_rec_index + offset;\n    const size_t huff_rec_count = *m->mh->huff_rec_count;\n    if (huff_rec_count > HUFF_RECORD_MAXCNT) {\n        debug_print(\"Too many HUFF record (%zu)\\n\", huff_rec_count);\n        return MOBI_DATA_CORRUPT;\n    }\n    const MOBIPdbRecord *curr = mobi_get_record_by_seqnumber(m, huff_rec_index);\n    if (curr == NULL || huff_rec_count < 2) {\n        debug_print(\"%s\", \"HUFF/CDIC record not found\\n\");\n        return MOBI_DATA_CORRUPT;\n    }\n    if (curr->size < HUFF_RECORD_MINSIZE) {\n        debug_print(\"HUFF record too short (%zu b)\\n\", curr->size);\n        return MOBI_DATA_CORRUPT;\n    }\n    ret = mobi_parse_huff(huffcdic, curr);\n    if (ret != MOBI_SUCCESS) {\n        debug_print(\"%s\", \"HUFF parsing failed\\n\");\n        return ret;\n    }\n    curr = curr->next;\n    /* allocate memory for symbols data in each CDIC record */\n    huffcdic->symbols = malloc((huff_rec_count - 1) * sizeof(*huffcdic->symbols));\n    if (huffcdic->symbols == NULL) {\n        debug_print(\"%s\\n\", \"Memory allocation failed\");\n        return MOBI_MALLOC_FAILED;\n    }\n    /* get following CDIC records */\n    size_t i = 0;\n    while (i < huff_rec_count - 1) {\n        if (curr == NULL) {\n            debug_print(\"%s\\n\", \"CDIC record not found\");\n            return MOBI_DATA_CORRUPT;\n        }\n        ret = mobi_parse_cdic(huffcdic, curr, i++);\n        if (ret != MOBI_SUCCESS) {\n            debug_print(\"%s\", \"CDIC parsing failed\\n\");\n            return ret;\n        }\n        curr = curr->next;\n    }\n    return MOBI_SUCCESS;\n}", "func_hash": 272789865299199789225315738205107270064, "file_name": "read.c", "file_hash": 34500817876088764790813749563983010190, "cwe": ["CWE-119"], "cve": "CVE-2021-3888", "cve_desc": "libmobi is vulnerable to Use of Out-of-range Pointer Offset", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3888"}
{"idx": 455177, "project": "libmobi", "commit_id": "c78e186739b50d156cb3da5d08d70294f0490853", "project_url": "https://github.com/bfabiszewski/libmobi", "commit_url": "https://github.com/bfabiszewski/libmobi/commit/c78e186739b50d156cb3da5d08d70294f0490853", "commit_message": "Fix potential out-of-buffer read while parsing corrupt file, closes #38", "target": 0, "func": "MOBI_RET mobi_parse_huffdic(const MOBIData *m, MOBIHuffCdic *huffcdic) {\n    MOBI_RET ret;\n    const size_t offset = mobi_get_kf8offset(m);\n    if (m->mh == NULL || m->mh->huff_rec_index == NULL || m->mh->huff_rec_count == NULL) {\n        debug_print(\"%s\", \"HUFF/CDIC records metadata not found in MOBI header\\n\");\n        return MOBI_DATA_CORRUPT;\n    }\n    const size_t huff_rec_index = *m->mh->huff_rec_index + offset;\n    const size_t huff_rec_count = *m->mh->huff_rec_count;\n    if (huff_rec_count > HUFF_RECORD_MAXCNT) {\n        debug_print(\"Too many HUFF record (%zu)\\n\", huff_rec_count);\n        return MOBI_DATA_CORRUPT;\n    }\n    const MOBIPdbRecord *curr = mobi_get_record_by_seqnumber(m, huff_rec_index);\n    if (curr == NULL || huff_rec_count < 2) {\n        debug_print(\"%s\", \"HUFF/CDIC record not found\\n\");\n        return MOBI_DATA_CORRUPT;\n    }\n    if (curr->size < HUFF_RECORD_MINSIZE) {\n        debug_print(\"HUFF record too short (%zu b)\\n\", curr->size);\n        return MOBI_DATA_CORRUPT;\n    }\n    ret = mobi_parse_huff(huffcdic, curr);\n    if (ret != MOBI_SUCCESS) {\n        debug_print(\"%s\", \"HUFF parsing failed\\n\");\n        return ret;\n    }\n    curr = curr->next;\n    /* allocate memory for symbols data in each CDIC record */\n    huffcdic->symbols = malloc((huff_rec_count - 1) * sizeof(*huffcdic->symbols));\n    if (huffcdic->symbols == NULL) {\n        debug_print(\"%s\\n\", \"Memory allocation failed\");\n        return MOBI_MALLOC_FAILED;\n    }\n    /* get following CDIC records */\n    size_t i = 0;\n    while (i < huff_rec_count - 1) {\n        if (curr == NULL) {\n            debug_print(\"%s\\n\", \"CDIC record not found\");\n            return MOBI_DATA_CORRUPT;\n        }\n        ret = mobi_parse_cdic(huffcdic, curr, i++);\n        if (ret != MOBI_SUCCESS) {\n            debug_print(\"%s\", \"CDIC parsing failed\\n\");\n            return ret;\n        }\n        curr = curr->next;\n    }\n    if (huffcdic->index_count != huffcdic->index_read) {\n        debug_print(\"CDIC: wrong read index count: %zu, total: %zu\\n\", huffcdic->index_read, huffcdic->index_count);\n        return MOBI_DATA_CORRUPT;\n    }\n    return MOBI_SUCCESS;\n}", "func_hash": 211530049158768490793426546245477731217, "file_name": "read.c", "file_hash": 228295168827515416887178420817040616622, "cwe": ["CWE-119"], "cve": "CVE-2021-3888", "cve_desc": "libmobi is vulnerable to Use of Out-of-range Pointer Offset", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3888"}
{"idx": 212152, "project": "bash", "commit_id": "951bdaad7a18cc0dc1036bba86b18b90874d39ff", "project_url": "https://github.com/bminor/bash", "commit_url": "https://github.com/bminor/bash/commit/951bdaad7a18cc0dc1036bba86b18b90874d39ff", "commit_message": "commit bash-20190628 snapshot", "target": 1, "func": "disable_priv_mode ()\n{\n  int e;\n\n  if (setuid (current_user.uid) < 0)\n    {\n      e = errno;\n      sys_error (_(\"cannot set uid to %d: effective uid %d\"), current_user.uid, current_user.euid);\n#if defined (EXIT_ON_SETUID_FAILURE)\n      if (e == EAGAIN)\n\texit (e);\n#endif\n    }\n  if (setgid (current_user.gid) < 0)\n    sys_error (_(\"cannot set gid to %d: effective gid %d\"), current_user.gid, current_user.egid);\n\n  current_user.euid = current_user.uid;\n  current_user.egid = current_user.gid;\n}", "func_hash": 247622822404411128670815043239926864688, "file_name": "shell.c", "file_hash": 63031401309370215256197051387367703039, "cwe": ["CWE-787"], "cve": "CVE-2019-18276", "cve_desc": "An issue was discovered in disable_priv_mode in shell.c in GNU Bash through 5.0 patch 11. By default, if Bash is run with its effective UID not equal to its real UID, it will drop privileges by setting its effective UID to its real UID. However, it does so incorrectly. On Linux and other systems that support \"saved UID\" functionality, the saved UID is not dropped. An attacker with command execution in the shell can use \"enable -f\" for runtime loading of a new builtin, which can be a shared object that calls setuid() and therefore regains privileges. However, binaries running with an effective UID of 0 are unaffected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-18276"}
{"idx": 455356, "project": "bash", "commit_id": "951bdaad7a18cc0dc1036bba86b18b90874d39ff", "project_url": "https://github.com/bminor/bash", "commit_url": "https://github.com/bminor/bash/commit/951bdaad7a18cc0dc1036bba86b18b90874d39ff", "commit_message": "commit bash-20190628 snapshot", "target": 0, "func": "disable_priv_mode ()\n{\n  int e;\n\n#if HAVE_DECL_SETRESUID\n  if (setresuid (current_user.uid, current_user.uid, current_user.uid) < 0)\n#else\n  if (setuid (current_user.uid) < 0)\n#endif\n    {\n      e = errno;\n      sys_error (_(\"cannot set uid to %d: effective uid %d\"), current_user.uid, current_user.euid);\n#if defined (EXIT_ON_SETUID_FAILURE)\n      if (e == EAGAIN)\n\texit (e);\n#endif\n    }\n#if HAVE_DECL_SETRESGID\n  if (setresgid (current_user.gid, current_user.gid, current_user.gid) < 0)\n#else\n  if (setgid (current_user.gid) < 0)\n#endif\n    sys_error (_(\"cannot set gid to %d: effective gid %d\"), current_user.gid, current_user.egid);\n\n  current_user.euid = current_user.uid;\n  current_user.egid = current_user.gid;\n}", "func_hash": 129442006485124574074853062128903057999, "file_name": "shell.c", "file_hash": 275188902865294694619472408620496076656, "cwe": ["CWE-787"], "cve": "CVE-2019-18276", "cve_desc": "An issue was discovered in disable_priv_mode in shell.c in GNU Bash through 5.0 patch 11. By default, if Bash is run with its effective UID not equal to its real UID, it will drop privileges by setting its effective UID to its real UID. However, it does so incorrectly. On Linux and other systems that support \"saved UID\" functionality, the saved UID is not dropped. An attacker with command execution in the shell can use \"enable -f\" for runtime loading of a new builtin, which can be a shared object that calls setuid() and therefore regains privileges. However, binaries running with an effective UID of 0 are unaffected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-18276"}
{"idx": 212339, "project": "icecast-server", "commit_id": "03ea74c04a5966114c2fe66e4e6892d11a68181e", "project_url": "https://gitlab.xiph.org/xiph/icecast-server", "commit_url": "https://gitlab.xiph.org/xiph/icecast-server/commit/03ea74c04a5966114c2fe66e4e6892d11a68181e", "commit_message": "Fix: Worked around buffer overflows in URL auth's cURL interface\n\nThis is only a workaround that keeps compatibility with 2.4.x mainline.\nA real fix has been implemented in 2.5.x (master).", "target": 1, "func": "static size_t handle_returned_header (void *ptr, size_t size, size_t nmemb, void *stream)\n{\n    auth_client *auth_user = stream;\n    size_t bytes = size * nmemb;\n    client_t *client = auth_user->client;\n\n    if (client)\n    {\n        auth_t *auth = client->auth;\n        auth_url *url = auth->state;\n        if (strncasecmp (ptr, url->auth_header, url->auth_header_len) == 0)\n            client->authenticated = 1;\n        if (strncasecmp (ptr, url->timelimit_header, url->timelimit_header_len) == 0)\n        {\n            unsigned int limit = 0;\n            sscanf ((char *)ptr+url->timelimit_header_len, \"%u\\r\\n\", &limit);\n            client->con->discon_time = time(NULL) + limit;\n        }\n        if (strncasecmp (ptr, \"icecast-auth-message: \", 22) == 0)\n        {\n            char *eol;\n            snprintf (url->errormsg, sizeof (url->errormsg), \"%s\", (char*)ptr+22);\n            eol = strchr (url->errormsg, '\\r');\n            if (eol == NULL)\n                eol = strchr (url->errormsg, '\\n');\n            if (eol)\n                *eol = '\\0';\n        }\n    }\n\n    return bytes;\n}", "func_hash": 172813813159602330520810310060333400473, "file_name": "auth_url.c", "file_hash": 1122861942142437056113331349516615132, "cwe": ["CWE-119"], "cve": "CVE-2018-18820", "cve_desc": "A buffer overflow was discovered in the URL-authentication backend of the Icecast before 2.4.4. If the backend is enabled, then any malicious HTTP client can send a request for that specific resource including a crafted header, leading to denial of service and potentially remote code execution.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-18820"}
{"idx": 457772, "project": "icecast-server", "commit_id": "03ea74c04a5966114c2fe66e4e6892d11a68181e", "project_url": "https://gitlab.xiph.org/xiph/icecast-server", "commit_url": "https://gitlab.xiph.org/xiph/icecast-server/commit/03ea74c04a5966114c2fe66e4e6892d11a68181e", "commit_message": "Fix: Worked around buffer overflows in URL auth's cURL interface\n\nThis is only a workaround that keeps compatibility with 2.4.x mainline.\nA real fix has been implemented in 2.5.x (master).", "target": 0, "func": "static size_t handle_returned_header (void *ptr, size_t size, size_t nmemb, void *stream)\n{\n    auth_client *auth_user = stream;\n    size_t len = size * nmemb;\n    client_t *client = auth_user->client;\n\n    if (client) {\n        auth_t *auth = client->auth;\n        auth_url *url = auth->state;\n\n        if (url->auth_header && len >= url->auth_header_len && strncasecmp(ptr, url->auth_header, url->auth_header_len) == 0)\n            client->authenticated = 1;\n\n        if (url->timelimit_header && len > url->timelimit_header_len && strncasecmp(ptr, url->timelimit_header, url->timelimit_header_len) == 0) {\n            const char *input = ptr;\n            unsigned int limit = 0;\n\n            if (len >= 2 && input[len - 2] == '\\r' && input[len - 1] == '\\n') {\n                input += url->timelimit_header_len;\n\n                if (sscanf(input, \"%u\\r\\n\", &limit) == 1) {\n                    client->con->discon_time = time(NULL) + limit;\n                } else {\n                    ICECAST_LOG_ERROR(\"Auth backend returned invalid timeline header: Can not parse limit\");\n                }\n            } else {\n                ICECAST_LOG_ERROR(\"Auth backend returned invalid timelimit header.\");\n            }\n        }\n\n        if (len > 24 && strncasecmp(ptr, \"icecast-auth-message: \", 22) == 0) {\n            const char *input = ptr;\n            size_t copy_len = len - 24 + 1; /* length of string plus \\0-termination */\n\n            if (copy_len > sizeof(url->errormsg)) {\n                copy_len = sizeof(url->errormsg);\n            }\n\n            if (len >= 2 && input[len - 2] == '\\r' && input[len - 1] == '\\n') {\n                input += 22;\n                memcpy(url->errormsg, input, copy_len);\n                url->errormsg[copy_len-1] = 0;\n            } else {\n                ICECAST_LOG_ERROR(\"Auth backend returned invalid message header.\");\n            }\n        }\n    }\n\n    return len;\n}", "func_hash": 325925920263284522777628774415448931953, "file_name": "auth_url.c", "file_hash": 331866999271559721275349792045163085611, "cwe": ["CWE-119"], "cve": "CVE-2018-18820", "cve_desc": "A buffer overflow was discovered in the URL-authentication backend of the Icecast before 2.4.4. If the backend is enabled, then any malicious HTTP client can send a request for that specific resource including a crafted header, leading to denial of service and potentially remote code execution.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-18820"}
{"idx": 212407, "project": "varnish-cache", "commit_id": "c5fd097e5cce8b461c6443af02b3448baef2491d", "project_url": "https://github.com/varnishcache/varnish-cache", "commit_url": "https://github.com/varnishcache/varnish-cache/commit/c5fd097e5cce8b461c6443af02b3448baef2491d", "commit_message": "Do not call http_hdr_flags() on pseudo-headers\n\nIn http_EstimateWS(), all headers are passed to the http_isfiltered()\nfunction to calculate how many bytes is needed to serialize the entire\nstruct http. http_isfiltered() will check the headers for whether they are\ngoing to be filtered out later and if so skip them.\n\nHowever http_isfiltered() would attempt to treat all elements of struct\nhttp as regular headers with an implicit structure. That does not hold for\nthe first three pseudo-header entries, which would lead to asserts in\nlater steps.\n\nThis patch skips the filter step for pseudo-headers.\n\nFixes: #3830", "target": 1, "func": "http_isfiltered(const struct http *fm, unsigned u, unsigned how)\n{\n\tconst char *e;\n\tconst struct http_hdrflg *f;\n\n\tif (fm->hdf[u] & HDF_FILTER)\n\t\treturn (1);\n\te = strchr(fm->hd[u].b, ':');\n\tif (e == NULL)\n\t\treturn (0);\n\tf = http_hdr_flags(fm->hd[u].b, e);\n\treturn (f != NULL && f->flag & how);\n}", "func_hash": 811300647438513744666233377828733318, "file_name": "cache_http.c", "file_hash": 145239057408586301398711991484884532857, "cwe": ["CWE-703"], "cve": "CVE-2022-38150", "cve_desc": "In Varnish Cache 7.0.0, 7.0.1, 7.0.2, and 7.1.0, it is possible to cause the Varnish Server to assert and automatically restart through forged HTTP/1 backend responses. An attack uses a crafted reason phrase of the backend response status line. This is fixed in 7.0.3 and 7.1.1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-38150"}
{"idx": 459029, "project": "varnish-cache", "commit_id": "c5fd097e5cce8b461c6443af02b3448baef2491d", "project_url": "https://github.com/varnishcache/varnish-cache", "commit_url": "https://github.com/varnishcache/varnish-cache/commit/c5fd097e5cce8b461c6443af02b3448baef2491d", "commit_message": "Do not call http_hdr_flags() on pseudo-headers\n\nIn http_EstimateWS(), all headers are passed to the http_isfiltered()\nfunction to calculate how many bytes is needed to serialize the entire\nstruct http. http_isfiltered() will check the headers for whether they are\ngoing to be filtered out later and if so skip them.\n\nHowever http_isfiltered() would attempt to treat all elements of struct\nhttp as regular headers with an implicit structure. That does not hold for\nthe first three pseudo-header entries, which would lead to asserts in\nlater steps.\n\nThis patch skips the filter step for pseudo-headers.\n\nFixes: #3830", "target": 0, "func": "http_isfiltered(const struct http *fm, unsigned u, unsigned how)\n{\n\tconst char *e;\n\tconst struct http_hdrflg *f;\n\n\tif (fm->hdf[u] & HDF_FILTER)\n\t\treturn (1);\n\tif (u < HTTP_HDR_FIRST)\n\t\treturn (0);\n\te = strchr(fm->hd[u].b, ':');\n\tif (e == NULL)\n\t\treturn (0);\n\tf = http_hdr_flags(fm->hd[u].b, e);\n\treturn (f != NULL && f->flag & how);\n}", "func_hash": 214500471714364858208416051205285025611, "file_name": "cache_http.c", "file_hash": 148461925742958572930249757440638720534, "cwe": ["CWE-703"], "cve": "CVE-2022-38150", "cve_desc": "In Varnish Cache 7.0.0, 7.0.1, 7.0.2, and 7.1.0, it is possible to cause the Varnish Server to assert and automatically restart through forged HTTP/1 backend responses. An attack uses a crafted reason phrase of the backend response status line. This is fixed in 7.0.3 and 7.1.1.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-38150"}
{"idx": 212414, "project": "linux", "commit_id": "04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5", "commit_message": "net: sched: fix use-after-free in tc_new_tfilter()\n\nWhenever tc_new_tfilter() jumps back to replay: label,\nwe need to make sure @q and @chain local variables are cleared again,\nor risk use-after-free as in [1]\n\nFor consistency, apply the same fix in tc_ctl_chain()\n\nBUG: KASAN: use-after-free in mini_qdisc_pair_swap+0x1b9/0x1f0 net/sched/sch_generic.c:1581\nWrite of size 8 at addr ffff8880985c4b08 by task syz-executor.4/1945\n\nCPU: 0 PID: 1945 Comm: syz-executor.4 Not tainted 5.17.0-rc1-syzkaller-00495-gff58831fa02d #0\nHardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011\nCall Trace:\n \n __dump_stack lib/dump_stack.c:88 [inline]\n dump_stack_lvl+0xcd/0x134 lib/dump_stack.c:106\n print_address_description.constprop.0.cold+0x8d/0x336 mm/kasan/report.c:255\n __kasan_report mm/kasan/report.c:442 [inline]\n kasan_report.cold+0x83/0xdf mm/kasan/report.c:459\n mini_qdisc_pair_swap+0x1b9/0x1f0 net/sched/sch_generic.c:1581\n tcf_chain_head_change_item net/sched/cls_api.c:372 [inline]\n tcf_chain0_head_change.isra.0+0xb9/0x120 net/sched/cls_api.c:386\n tcf_chain_tp_insert net/sched/cls_api.c:1657 [inline]\n tcf_chain_tp_insert_unique net/sched/cls_api.c:1707 [inline]\n tc_new_tfilter+0x1e67/0x2350 net/sched/cls_api.c:2086\n rtnetlink_rcv_msg+0x80d/0xb80 net/core/rtnetlink.c:5583\n netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494\n netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline]\n netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343\n netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919\n sock_sendmsg_nosec net/socket.c:705 [inline]\n sock_sendmsg+0xcf/0x120 net/socket.c:725\n ____sys_sendmsg+0x331/0x810 net/socket.c:2413\n ___sys_sendmsg+0xf3/0x170 net/socket.c:2467\n __sys_sendmmsg+0x195/0x470 net/socket.c:2553\n __do_sys_sendmmsg net/socket.c:2582 [inline]\n __se_sys_sendmmsg net/socket.c:2579 [inline]\n __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579\n do_syscall_x64 arch/x86/entry/common.c:50 [inline]\n do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80\n entry_SYSCALL_64_after_hwframe+0x44/0xae\nRIP: 0033:0x7f2647172059\nCode: ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 40 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 b8 ff ff ff f7 d8 64 89 01 48\nRSP: 002b:00007f2645aa5168 EFLAGS: 00000246 ORIG_RAX: 0000000000000133\nRAX: ffffffffffffffda RBX: 00007f2647285100 RCX: 00007f2647172059\nRDX: 040000000000009f RSI: 00000000200002c0 RDI: 0000000000000006\nRBP: 00007f26471cc08d R08: 0000000000000000 R09: 0000000000000000\nR10: 9e00000000000000 R11: 0000000000000246 R12: 0000000000000000\nR13: 00007fffb3f7f02f R14: 00007f2645aa5300 R15: 0000000000022000\n \n\nAllocated by task 1944:\n kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38\n kasan_set_track mm/kasan/common.c:45 [inline]\n set_alloc_info mm/kasan/common.c:436 [inline]\n ____kasan_kmalloc mm/kasan/common.c:515 [inline]\n ____kasan_kmalloc mm/kasan/common.c:474 [inline]\n __kasan_kmalloc+0xa9/0xd0 mm/kasan/common.c:524\n kmalloc_node include/linux/slab.h:604 [inline]\n kzalloc_node include/linux/slab.h:726 [inline]\n qdisc_alloc+0xac/0xa10 net/sched/sch_generic.c:941\n qdisc_create.constprop.0+0xce/0x10f0 net/sched/sch_api.c:1211\n tc_modify_qdisc+0x4c5/0x1980 net/sched/sch_api.c:1660\n rtnetlink_rcv_msg+0x413/0xb80 net/core/rtnetlink.c:5592\n netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494\n netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline]\n netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343\n netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919\n sock_sendmsg_nosec net/socket.c:705 [inline]\n sock_sendmsg+0xcf/0x120 net/socket.c:725\n ____sys_sendmsg+0x331/0x810 net/socket.c:2413\n ___sys_sendmsg+0xf3/0x170 net/socket.c:2467\n __sys_sendmmsg+0x195/0x470 net/socket.c:2553\n __do_sys_sendmmsg net/socket.c:2582 [inline]\n __se_sys_sendmmsg net/socket.c:2579 [inline]\n __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579\n do_syscall_x64 arch/x86/entry/common.c:50 [inline]\n do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nFreed by task 3609:\n kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38\n kasan_set_track+0x21/0x30 mm/kasan/common.c:45\n kasan_set_free_info+0x20/0x30 mm/kasan/generic.c:370\n ____kasan_slab_free mm/kasan/common.c:366 [inline]\n ____kasan_slab_free+0x130/0x160 mm/kasan/common.c:328\n kasan_slab_free include/linux/kasan.h:236 [inline]\n slab_free_hook mm/slub.c:1728 [inline]\n slab_free_freelist_hook+0x8b/0x1c0 mm/slub.c:1754\n slab_free mm/slub.c:3509 [inline]\n kfree+0xcb/0x280 mm/slub.c:4562\n rcu_do_batch kernel/rcu/tree.c:2527 [inline]\n rcu_core+0x7b8/0x1540 kernel/rcu/tree.c:2778\n __do_softirq+0x29b/0x9c2 kernel/softirq.c:558\n\nLast potentially related work creation:\n kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38\n __kasan_record_aux_stack+0xbe/0xd0 mm/kasan/generic.c:348\n __call_rcu kernel/rcu/tree.c:3026 [inline]\n call_rcu+0xb1/0x740 kernel/rcu/tree.c:3106\n qdisc_put_unlocked+0x6f/0x90 net/sched/sch_generic.c:1109\n tcf_block_release+0x86/0x90 net/sched/cls_api.c:1238\n tc_new_tfilter+0xc0d/0x2350 net/sched/cls_api.c:2148\n rtnetlink_rcv_msg+0x80d/0xb80 net/core/rtnetlink.c:5583\n netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494\n netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline]\n netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343\n netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919\n sock_sendmsg_nosec net/socket.c:705 [inline]\n sock_sendmsg+0xcf/0x120 net/socket.c:725\n ____sys_sendmsg+0x331/0x810 net/socket.c:2413\n ___sys_sendmsg+0xf3/0x170 net/socket.c:2467\n __sys_sendmmsg+0x195/0x470 net/socket.c:2553\n __do_sys_sendmmsg net/socket.c:2582 [inline]\n __se_sys_sendmmsg net/socket.c:2579 [inline]\n __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579\n do_syscall_x64 arch/x86/entry/common.c:50 [inline]\n do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nThe buggy address belongs to the object at ffff8880985c4800\n which belongs to the cache kmalloc-1k of size 1024\nThe buggy address is located 776 bytes inside of\n 1024-byte region [ffff8880985c4800, ffff8880985c4c00)\nThe buggy address belongs to the page:\npage:ffffea0002617000 refcount:1 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x985c0\nhead:ffffea0002617000 order:3 compound_mapcount:0 compound_pincount:0\nflags: 0xfff00000010200(slab|head|node=0|zone=1|lastcpupid=0x7ff)\nraw: 00fff00000010200 0000000000000000 dead000000000122 ffff888010c41dc0\nraw: 0000000000000000 0000000000100010 00000001ffffffff 0000000000000000\npage dumped because: kasan: bad access detected\npage_owner tracks the page as allocated\npage last allocated via order 3, migratetype Unmovable, gfp_mask 0x1d20c0(__GFP_IO|__GFP_FS|__GFP_NOWARN|__GFP_NORETRY|__GFP_COMP|__GFP_NOMEMALLOC|__GFP_HARDWALL), pid 1941, ts 1038999441284, free_ts 1033444432829\n prep_new_page mm/page_alloc.c:2434 [inline]\n get_page_from_freelist+0xa72/0x2f50 mm/page_alloc.c:4165\n __alloc_pages+0x1b2/0x500 mm/page_alloc.c:5389\n alloc_pages+0x1aa/0x310 mm/mempolicy.c:2271\n alloc_slab_page mm/slub.c:1799 [inline]\n allocate_slab mm/slub.c:1944 [inline]\n new_slab+0x28a/0x3b0 mm/slub.c:2004\n ___slab_alloc+0x87c/0xe90 mm/slub.c:3018\n __slab_alloc.constprop.0+0x4d/0xa0 mm/slub.c:3105\n slab_alloc_node mm/slub.c:3196 [inline]\n slab_alloc mm/slub.c:3238 [inline]\n __kmalloc+0x2fb/0x340 mm/slub.c:4420\n kmalloc include/linux/slab.h:586 [inline]\n kzalloc include/linux/slab.h:715 [inline]\n __register_sysctl_table+0x112/0x1090 fs/proc/proc_sysctl.c:1335\n neigh_sysctl_register+0x2c8/0x5e0 net/core/neighbour.c:3787\n devinet_sysctl_register+0xb1/0x230 net/ipv4/devinet.c:2618\n inetdev_init+0x286/0x580 net/ipv4/devinet.c:278\n inetdev_event+0xa8a/0x15d0 net/ipv4/devinet.c:1532\n notifier_call_chain+0xb5/0x200 kernel/notifier.c:84\n call_netdevice_notifiers_info+0xb5/0x130 net/core/dev.c:1919\n call_netdevice_notifiers_extack net/core/dev.c:1931 [inline]\n call_netdevice_notifiers net/core/dev.c:1945 [inline]\n register_netdevice+0x1073/0x1500 net/core/dev.c:9698\n veth_newlink+0x59c/0xa90 drivers/net/veth.c:1722\npage last free stack trace:\n reset_page_owner include/linux/page_owner.h:24 [inline]\n free_pages_prepare mm/page_alloc.c:1352 [inline]\n free_pcp_prepare+0x374/0x870 mm/page_alloc.c:1404\n free_unref_page_prepare mm/page_alloc.c:3325 [inline]\n free_unref_page+0x19/0x690 mm/page_alloc.c:3404\n release_pages+0x748/0x1220 mm/swap.c:956\n tlb_batch_pages_flush mm/mmu_gather.c:50 [inline]\n tlb_flush_mmu_free mm/mmu_gather.c:243 [inline]\n tlb_flush_mmu+0xe9/0x6b0 mm/mmu_gather.c:250\n zap_pte_range mm/memory.c:1441 [inline]\n zap_pmd_range mm/memory.c:1490 [inline]\n zap_pud_range mm/memory.c:1519 [inline]\n zap_p4d_range mm/memory.c:1540 [inline]\n unmap_page_range+0x1d1d/0x2a30 mm/memory.c:1561\n unmap_single_vma+0x198/0x310 mm/memory.c:1606\n unmap_vmas+0x16b/0x2f0 mm/memory.c:1638\n exit_mmap+0x201/0x670 mm/mmap.c:3178\n __mmput+0x122/0x4b0 kernel/fork.c:1114\n mmput+0x56/0x60 kernel/fork.c:1135\n exit_mm kernel/exit.c:507 [inline]\n do_exit+0xa3c/0x2a30 kernel/exit.c:793\n do_group_exit+0xd2/0x2f0 kernel/exit.c:935\n __do_sys_exit_group kernel/exit.c:946 [inline]\n __se_sys_exit_group kernel/exit.c:944 [inline]\n __x64_sys_exit_group+0x3a/0x50 kernel/exit.c:944\n do_syscall_x64 arch/x86/entry/common.c:50 [inline]\n do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nMemory state around the buggy address:\n ffff8880985c4a00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff8880985c4a80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n>ffff8880985c4b00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n                      ^\n ffff8880985c4b80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff8880985c4c00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n\nFixes: 470502de5bdb (\"net: sched: unlock rules update API\")\nSigned-off-by: Eric Dumazet \nCc: Vlad Buslov \nCc: Jiri Pirko \nCc: Cong Wang \nReported-by: syzbot \nLink: https://lore.kernel.org/r/20220131172018.3704490-1-eric.dumazet@gmail.com\nSigned-off-by: Jakub Kicinski ", "target": 1, "func": "static int tc_new_tfilter(struct sk_buff *skb, struct nlmsghdr *n,\n\t\t\t  struct netlink_ext_ack *extack)\n{\n\tstruct net *net = sock_net(skb->sk);\n\tstruct nlattr *tca[TCA_MAX + 1];\n\tchar name[IFNAMSIZ];\n\tstruct tcmsg *t;\n\tu32 protocol;\n\tu32 prio;\n\tbool prio_allocate;\n\tu32 parent;\n\tu32 chain_index;\n\tstruct Qdisc *q = NULL;\n\tstruct tcf_chain_info chain_info;\n\tstruct tcf_chain *chain = NULL;\n\tstruct tcf_block *block;\n\tstruct tcf_proto *tp;\n\tunsigned long cl;\n\tvoid *fh;\n\tint err;\n\tint tp_created;\n\tbool rtnl_held = false;\n\tu32 flags;\n\n\tif (!netlink_ns_capable(skb, net->user_ns, CAP_NET_ADMIN))\n\t\treturn -EPERM;\n\nreplay:\n\ttp_created = 0;\n\n\terr = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX,\n\t\t\t\t     rtm_tca_policy, extack);\n\tif (err < 0)\n\t\treturn err;\n\n\tt = nlmsg_data(n);\n\tprotocol = TC_H_MIN(t->tcm_info);\n\tprio = TC_H_MAJ(t->tcm_info);\n\tprio_allocate = false;\n\tparent = t->tcm_parent;\n\ttp = NULL;\n\tcl = 0;\n\tblock = NULL;\n\tflags = 0;\n\n\tif (prio == 0) {\n\t\t/* If no priority is provided by the user,\n\t\t * we allocate one.\n\t\t */\n\t\tif (n->nlmsg_flags & NLM_F_CREATE) {\n\t\t\tprio = TC_H_MAKE(0x80000000U, 0U);\n\t\t\tprio_allocate = true;\n\t\t} else {\n\t\t\tNL_SET_ERR_MSG(extack, \"Invalid filter command with priority of zero\");\n\t\t\treturn -ENOENT;\n\t\t}\n\t}\n\n\t/* Find head of filter chain. */\n\n\terr = __tcf_qdisc_find(net, &q, &parent, t->tcm_ifindex, false, extack);\n\tif (err)\n\t\treturn err;\n\n\tif (tcf_proto_check_kind(tca[TCA_KIND], name)) {\n\t\tNL_SET_ERR_MSG(extack, \"Specified TC filter name too long\");\n\t\terr = -EINVAL;\n\t\tgoto errout;\n\t}\n\n\t/* Take rtnl mutex if rtnl_held was set to true on previous iteration,\n\t * block is shared (no qdisc found), qdisc is not unlocked, classifier\n\t * type is not specified, classifier is not unlocked.\n\t */\n\tif (rtnl_held ||\n\t    (q && !(q->ops->cl_ops->flags & QDISC_CLASS_OPS_DOIT_UNLOCKED)) ||\n\t    !tcf_proto_is_unlocked(name)) {\n\t\trtnl_held = true;\n\t\trtnl_lock();\n\t}\n\n\terr = __tcf_qdisc_cl_find(q, parent, &cl, t->tcm_ifindex, extack);\n\tif (err)\n\t\tgoto errout;\n\n\tblock = __tcf_block_find(net, q, cl, t->tcm_ifindex, t->tcm_block_index,\n\t\t\t\t extack);\n\tif (IS_ERR(block)) {\n\t\terr = PTR_ERR(block);\n\t\tgoto errout;\n\t}\n\tblock->classid = parent;\n\n\tchain_index = tca[TCA_CHAIN] ? nla_get_u32(tca[TCA_CHAIN]) : 0;\n\tif (chain_index > TC_ACT_EXT_VAL_MASK) {\n\t\tNL_SET_ERR_MSG(extack, \"Specified chain index exceeds upper limit\");\n\t\terr = -EINVAL;\n\t\tgoto errout;\n\t}\n\tchain = tcf_chain_get(block, chain_index, true);\n\tif (!chain) {\n\t\tNL_SET_ERR_MSG(extack, \"Cannot create specified filter chain\");\n\t\terr = -ENOMEM;\n\t\tgoto errout;\n\t}\n\n\tmutex_lock(&chain->filter_chain_lock);\n\ttp = tcf_chain_tp_find(chain, &chain_info, protocol,\n\t\t\t       prio, prio_allocate);\n\tif (IS_ERR(tp)) {\n\t\tNL_SET_ERR_MSG(extack, \"Filter with specified priority/protocol not found\");\n\t\terr = PTR_ERR(tp);\n\t\tgoto errout_locked;\n\t}\n\n\tif (tp == NULL) {\n\t\tstruct tcf_proto *tp_new = NULL;\n\n\t\tif (chain->flushing) {\n\t\t\terr = -EAGAIN;\n\t\t\tgoto errout_locked;\n\t\t}\n\n\t\t/* Proto-tcf does not exist, create new one */\n\n\t\tif (tca[TCA_KIND] == NULL || !protocol) {\n\t\t\tNL_SET_ERR_MSG(extack, \"Filter kind and protocol must be specified\");\n\t\t\terr = -EINVAL;\n\t\t\tgoto errout_locked;\n\t\t}\n\n\t\tif (!(n->nlmsg_flags & NLM_F_CREATE)) {\n\t\t\tNL_SET_ERR_MSG(extack, \"Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter\");\n\t\t\terr = -ENOENT;\n\t\t\tgoto errout_locked;\n\t\t}\n\n\t\tif (prio_allocate)\n\t\t\tprio = tcf_auto_prio(tcf_chain_tp_prev(chain,\n\t\t\t\t\t\t\t       &chain_info));\n\n\t\tmutex_unlock(&chain->filter_chain_lock);\n\t\ttp_new = tcf_proto_create(name, protocol, prio, chain,\n\t\t\t\t\t  rtnl_held, extack);\n\t\tif (IS_ERR(tp_new)) {\n\t\t\terr = PTR_ERR(tp_new);\n\t\t\tgoto errout_tp;\n\t\t}\n\n\t\ttp_created = 1;\n\t\ttp = tcf_chain_tp_insert_unique(chain, tp_new, protocol, prio,\n\t\t\t\t\t\trtnl_held);\n\t\tif (IS_ERR(tp)) {\n\t\t\terr = PTR_ERR(tp);\n\t\t\tgoto errout_tp;\n\t\t}\n\t} else {\n\t\tmutex_unlock(&chain->filter_chain_lock);\n\t}\n\n\tif (tca[TCA_KIND] && nla_strcmp(tca[TCA_KIND], tp->ops->kind)) {\n\t\tNL_SET_ERR_MSG(extack, \"Specified filter kind does not match existing one\");\n\t\terr = -EINVAL;\n\t\tgoto errout;\n\t}\n\n\tfh = tp->ops->get(tp, t->tcm_handle);\n\n\tif (!fh) {\n\t\tif (!(n->nlmsg_flags & NLM_F_CREATE)) {\n\t\t\tNL_SET_ERR_MSG(extack, \"Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter\");\n\t\t\terr = -ENOENT;\n\t\t\tgoto errout;\n\t\t}\n\t} else if (n->nlmsg_flags & NLM_F_EXCL) {\n\t\ttfilter_put(tp, fh);\n\t\tNL_SET_ERR_MSG(extack, \"Filter already exists\");\n\t\terr = -EEXIST;\n\t\tgoto errout;\n\t}\n\n\tif (chain->tmplt_ops && chain->tmplt_ops != tp->ops) {\n\t\tNL_SET_ERR_MSG(extack, \"Chain template is set to a different filter kind\");\n\t\terr = -EINVAL;\n\t\tgoto errout;\n\t}\n\n\tif (!(n->nlmsg_flags & NLM_F_CREATE))\n\t\tflags |= TCA_ACT_FLAGS_REPLACE;\n\tif (!rtnl_held)\n\t\tflags |= TCA_ACT_FLAGS_NO_RTNL;\n\terr = tp->ops->change(net, skb, tp, cl, t->tcm_handle, tca, &fh,\n\t\t\t      flags, extack);\n\tif (err == 0) {\n\t\ttfilter_notify(net, skb, n, tp, block, q, parent, fh,\n\t\t\t       RTM_NEWTFILTER, false, rtnl_held);\n\t\ttfilter_put(tp, fh);\n\t\t/* q pointer is NULL for shared blocks */\n\t\tif (q)\n\t\t\tq->flags &= ~TCQ_F_CAN_BYPASS;\n\t}\n\nerrout:\n\tif (err && tp_created)\n\t\ttcf_chain_tp_delete_empty(chain, tp, rtnl_held, NULL);\nerrout_tp:\n\tif (chain) {\n\t\tif (tp && !IS_ERR(tp))\n\t\t\ttcf_proto_put(tp, rtnl_held, NULL);\n\t\tif (!tp_created)\n\t\t\ttcf_chain_put(chain);\n\t}\n\ttcf_block_release(q, block, rtnl_held);\n\n\tif (rtnl_held)\n\t\trtnl_unlock();\n\n\tif (err == -EAGAIN) {\n\t\t/* Take rtnl lock in case EAGAIN is caused by concurrent flush\n\t\t * of target chain.\n\t\t */\n\t\trtnl_held = true;\n\t\t/* Replay the request. */\n\t\tgoto replay;\n\t}\n\treturn err;\n\nerrout_locked:\n\tmutex_unlock(&chain->filter_chain_lock);\n\tgoto errout;\n}", "func_hash": 18151855959135734228627793679159459802, "file_name": "cls_api.c", "file_hash": 251903803472854915466369605008106287178, "cwe": ["CWE-416"], "cve": "CVE-2022-1055", "cve_desc": "A use-after-free exists in the Linux Kernel in tc_new_tfilter that could allow a local attacker to gain privilege escalation. The exploit requires unprivileged user namespaces. We recommend upgrading past commit 04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1055"}
{"idx": 459107, "project": "linux", "commit_id": "04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5", "commit_message": "net: sched: fix use-after-free in tc_new_tfilter()\n\nWhenever tc_new_tfilter() jumps back to replay: label,\nwe need to make sure @q and @chain local variables are cleared again,\nor risk use-after-free as in [1]\n\nFor consistency, apply the same fix in tc_ctl_chain()\n\nBUG: KASAN: use-after-free in mini_qdisc_pair_swap+0x1b9/0x1f0 net/sched/sch_generic.c:1581\nWrite of size 8 at addr ffff8880985c4b08 by task syz-executor.4/1945\n\nCPU: 0 PID: 1945 Comm: syz-executor.4 Not tainted 5.17.0-rc1-syzkaller-00495-gff58831fa02d #0\nHardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011\nCall Trace:\n \n __dump_stack lib/dump_stack.c:88 [inline]\n dump_stack_lvl+0xcd/0x134 lib/dump_stack.c:106\n print_address_description.constprop.0.cold+0x8d/0x336 mm/kasan/report.c:255\n __kasan_report mm/kasan/report.c:442 [inline]\n kasan_report.cold+0x83/0xdf mm/kasan/report.c:459\n mini_qdisc_pair_swap+0x1b9/0x1f0 net/sched/sch_generic.c:1581\n tcf_chain_head_change_item net/sched/cls_api.c:372 [inline]\n tcf_chain0_head_change.isra.0+0xb9/0x120 net/sched/cls_api.c:386\n tcf_chain_tp_insert net/sched/cls_api.c:1657 [inline]\n tcf_chain_tp_insert_unique net/sched/cls_api.c:1707 [inline]\n tc_new_tfilter+0x1e67/0x2350 net/sched/cls_api.c:2086\n rtnetlink_rcv_msg+0x80d/0xb80 net/core/rtnetlink.c:5583\n netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494\n netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline]\n netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343\n netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919\n sock_sendmsg_nosec net/socket.c:705 [inline]\n sock_sendmsg+0xcf/0x120 net/socket.c:725\n ____sys_sendmsg+0x331/0x810 net/socket.c:2413\n ___sys_sendmsg+0xf3/0x170 net/socket.c:2467\n __sys_sendmmsg+0x195/0x470 net/socket.c:2553\n __do_sys_sendmmsg net/socket.c:2582 [inline]\n __se_sys_sendmmsg net/socket.c:2579 [inline]\n __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579\n do_syscall_x64 arch/x86/entry/common.c:50 [inline]\n do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80\n entry_SYSCALL_64_after_hwframe+0x44/0xae\nRIP: 0033:0x7f2647172059\nCode: ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 40 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 b8 ff ff ff f7 d8 64 89 01 48\nRSP: 002b:00007f2645aa5168 EFLAGS: 00000246 ORIG_RAX: 0000000000000133\nRAX: ffffffffffffffda RBX: 00007f2647285100 RCX: 00007f2647172059\nRDX: 040000000000009f RSI: 00000000200002c0 RDI: 0000000000000006\nRBP: 00007f26471cc08d R08: 0000000000000000 R09: 0000000000000000\nR10: 9e00000000000000 R11: 0000000000000246 R12: 0000000000000000\nR13: 00007fffb3f7f02f R14: 00007f2645aa5300 R15: 0000000000022000\n \n\nAllocated by task 1944:\n kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38\n kasan_set_track mm/kasan/common.c:45 [inline]\n set_alloc_info mm/kasan/common.c:436 [inline]\n ____kasan_kmalloc mm/kasan/common.c:515 [inline]\n ____kasan_kmalloc mm/kasan/common.c:474 [inline]\n __kasan_kmalloc+0xa9/0xd0 mm/kasan/common.c:524\n kmalloc_node include/linux/slab.h:604 [inline]\n kzalloc_node include/linux/slab.h:726 [inline]\n qdisc_alloc+0xac/0xa10 net/sched/sch_generic.c:941\n qdisc_create.constprop.0+0xce/0x10f0 net/sched/sch_api.c:1211\n tc_modify_qdisc+0x4c5/0x1980 net/sched/sch_api.c:1660\n rtnetlink_rcv_msg+0x413/0xb80 net/core/rtnetlink.c:5592\n netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494\n netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline]\n netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343\n netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919\n sock_sendmsg_nosec net/socket.c:705 [inline]\n sock_sendmsg+0xcf/0x120 net/socket.c:725\n ____sys_sendmsg+0x331/0x810 net/socket.c:2413\n ___sys_sendmsg+0xf3/0x170 net/socket.c:2467\n __sys_sendmmsg+0x195/0x470 net/socket.c:2553\n __do_sys_sendmmsg net/socket.c:2582 [inline]\n __se_sys_sendmmsg net/socket.c:2579 [inline]\n __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579\n do_syscall_x64 arch/x86/entry/common.c:50 [inline]\n do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nFreed by task 3609:\n kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38\n kasan_set_track+0x21/0x30 mm/kasan/common.c:45\n kasan_set_free_info+0x20/0x30 mm/kasan/generic.c:370\n ____kasan_slab_free mm/kasan/common.c:366 [inline]\n ____kasan_slab_free+0x130/0x160 mm/kasan/common.c:328\n kasan_slab_free include/linux/kasan.h:236 [inline]\n slab_free_hook mm/slub.c:1728 [inline]\n slab_free_freelist_hook+0x8b/0x1c0 mm/slub.c:1754\n slab_free mm/slub.c:3509 [inline]\n kfree+0xcb/0x280 mm/slub.c:4562\n rcu_do_batch kernel/rcu/tree.c:2527 [inline]\n rcu_core+0x7b8/0x1540 kernel/rcu/tree.c:2778\n __do_softirq+0x29b/0x9c2 kernel/softirq.c:558\n\nLast potentially related work creation:\n kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38\n __kasan_record_aux_stack+0xbe/0xd0 mm/kasan/generic.c:348\n __call_rcu kernel/rcu/tree.c:3026 [inline]\n call_rcu+0xb1/0x740 kernel/rcu/tree.c:3106\n qdisc_put_unlocked+0x6f/0x90 net/sched/sch_generic.c:1109\n tcf_block_release+0x86/0x90 net/sched/cls_api.c:1238\n tc_new_tfilter+0xc0d/0x2350 net/sched/cls_api.c:2148\n rtnetlink_rcv_msg+0x80d/0xb80 net/core/rtnetlink.c:5583\n netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494\n netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline]\n netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343\n netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919\n sock_sendmsg_nosec net/socket.c:705 [inline]\n sock_sendmsg+0xcf/0x120 net/socket.c:725\n ____sys_sendmsg+0x331/0x810 net/socket.c:2413\n ___sys_sendmsg+0xf3/0x170 net/socket.c:2467\n __sys_sendmmsg+0x195/0x470 net/socket.c:2553\n __do_sys_sendmmsg net/socket.c:2582 [inline]\n __se_sys_sendmmsg net/socket.c:2579 [inline]\n __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579\n do_syscall_x64 arch/x86/entry/common.c:50 [inline]\n do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nThe buggy address belongs to the object at ffff8880985c4800\n which belongs to the cache kmalloc-1k of size 1024\nThe buggy address is located 776 bytes inside of\n 1024-byte region [ffff8880985c4800, ffff8880985c4c00)\nThe buggy address belongs to the page:\npage:ffffea0002617000 refcount:1 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x985c0\nhead:ffffea0002617000 order:3 compound_mapcount:0 compound_pincount:0\nflags: 0xfff00000010200(slab|head|node=0|zone=1|lastcpupid=0x7ff)\nraw: 00fff00000010200 0000000000000000 dead000000000122 ffff888010c41dc0\nraw: 0000000000000000 0000000000100010 00000001ffffffff 0000000000000000\npage dumped because: kasan: bad access detected\npage_owner tracks the page as allocated\npage last allocated via order 3, migratetype Unmovable, gfp_mask 0x1d20c0(__GFP_IO|__GFP_FS|__GFP_NOWARN|__GFP_NORETRY|__GFP_COMP|__GFP_NOMEMALLOC|__GFP_HARDWALL), pid 1941, ts 1038999441284, free_ts 1033444432829\n prep_new_page mm/page_alloc.c:2434 [inline]\n get_page_from_freelist+0xa72/0x2f50 mm/page_alloc.c:4165\n __alloc_pages+0x1b2/0x500 mm/page_alloc.c:5389\n alloc_pages+0x1aa/0x310 mm/mempolicy.c:2271\n alloc_slab_page mm/slub.c:1799 [inline]\n allocate_slab mm/slub.c:1944 [inline]\n new_slab+0x28a/0x3b0 mm/slub.c:2004\n ___slab_alloc+0x87c/0xe90 mm/slub.c:3018\n __slab_alloc.constprop.0+0x4d/0xa0 mm/slub.c:3105\n slab_alloc_node mm/slub.c:3196 [inline]\n slab_alloc mm/slub.c:3238 [inline]\n __kmalloc+0x2fb/0x340 mm/slub.c:4420\n kmalloc include/linux/slab.h:586 [inline]\n kzalloc include/linux/slab.h:715 [inline]\n __register_sysctl_table+0x112/0x1090 fs/proc/proc_sysctl.c:1335\n neigh_sysctl_register+0x2c8/0x5e0 net/core/neighbour.c:3787\n devinet_sysctl_register+0xb1/0x230 net/ipv4/devinet.c:2618\n inetdev_init+0x286/0x580 net/ipv4/devinet.c:278\n inetdev_event+0xa8a/0x15d0 net/ipv4/devinet.c:1532\n notifier_call_chain+0xb5/0x200 kernel/notifier.c:84\n call_netdevice_notifiers_info+0xb5/0x130 net/core/dev.c:1919\n call_netdevice_notifiers_extack net/core/dev.c:1931 [inline]\n call_netdevice_notifiers net/core/dev.c:1945 [inline]\n register_netdevice+0x1073/0x1500 net/core/dev.c:9698\n veth_newlink+0x59c/0xa90 drivers/net/veth.c:1722\npage last free stack trace:\n reset_page_owner include/linux/page_owner.h:24 [inline]\n free_pages_prepare mm/page_alloc.c:1352 [inline]\n free_pcp_prepare+0x374/0x870 mm/page_alloc.c:1404\n free_unref_page_prepare mm/page_alloc.c:3325 [inline]\n free_unref_page+0x19/0x690 mm/page_alloc.c:3404\n release_pages+0x748/0x1220 mm/swap.c:956\n tlb_batch_pages_flush mm/mmu_gather.c:50 [inline]\n tlb_flush_mmu_free mm/mmu_gather.c:243 [inline]\n tlb_flush_mmu+0xe9/0x6b0 mm/mmu_gather.c:250\n zap_pte_range mm/memory.c:1441 [inline]\n zap_pmd_range mm/memory.c:1490 [inline]\n zap_pud_range mm/memory.c:1519 [inline]\n zap_p4d_range mm/memory.c:1540 [inline]\n unmap_page_range+0x1d1d/0x2a30 mm/memory.c:1561\n unmap_single_vma+0x198/0x310 mm/memory.c:1606\n unmap_vmas+0x16b/0x2f0 mm/memory.c:1638\n exit_mmap+0x201/0x670 mm/mmap.c:3178\n __mmput+0x122/0x4b0 kernel/fork.c:1114\n mmput+0x56/0x60 kernel/fork.c:1135\n exit_mm kernel/exit.c:507 [inline]\n do_exit+0xa3c/0x2a30 kernel/exit.c:793\n do_group_exit+0xd2/0x2f0 kernel/exit.c:935\n __do_sys_exit_group kernel/exit.c:946 [inline]\n __se_sys_exit_group kernel/exit.c:944 [inline]\n __x64_sys_exit_group+0x3a/0x50 kernel/exit.c:944\n do_syscall_x64 arch/x86/entry/common.c:50 [inline]\n do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nMemory state around the buggy address:\n ffff8880985c4a00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff8880985c4a80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n>ffff8880985c4b00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n                      ^\n ffff8880985c4b80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff8880985c4c00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n\nFixes: 470502de5bdb (\"net: sched: unlock rules update API\")\nSigned-off-by: Eric Dumazet \nCc: Vlad Buslov \nCc: Jiri Pirko \nCc: Cong Wang \nReported-by: syzbot \nLink: https://lore.kernel.org/r/20220131172018.3704490-1-eric.dumazet@gmail.com\nSigned-off-by: Jakub Kicinski ", "target": 0, "func": "static int tc_new_tfilter(struct sk_buff *skb, struct nlmsghdr *n,\n\t\t\t  struct netlink_ext_ack *extack)\n{\n\tstruct net *net = sock_net(skb->sk);\n\tstruct nlattr *tca[TCA_MAX + 1];\n\tchar name[IFNAMSIZ];\n\tstruct tcmsg *t;\n\tu32 protocol;\n\tu32 prio;\n\tbool prio_allocate;\n\tu32 parent;\n\tu32 chain_index;\n\tstruct Qdisc *q;\n\tstruct tcf_chain_info chain_info;\n\tstruct tcf_chain *chain;\n\tstruct tcf_block *block;\n\tstruct tcf_proto *tp;\n\tunsigned long cl;\n\tvoid *fh;\n\tint err;\n\tint tp_created;\n\tbool rtnl_held = false;\n\tu32 flags;\n\n\tif (!netlink_ns_capable(skb, net->user_ns, CAP_NET_ADMIN))\n\t\treturn -EPERM;\n\nreplay:\n\ttp_created = 0;\n\n\terr = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX,\n\t\t\t\t     rtm_tca_policy, extack);\n\tif (err < 0)\n\t\treturn err;\n\n\tt = nlmsg_data(n);\n\tprotocol = TC_H_MIN(t->tcm_info);\n\tprio = TC_H_MAJ(t->tcm_info);\n\tprio_allocate = false;\n\tparent = t->tcm_parent;\n\ttp = NULL;\n\tcl = 0;\n\tblock = NULL;\n\tq = NULL;\n\tchain = NULL;\n\tflags = 0;\n\n\tif (prio == 0) {\n\t\t/* If no priority is provided by the user,\n\t\t * we allocate one.\n\t\t */\n\t\tif (n->nlmsg_flags & NLM_F_CREATE) {\n\t\t\tprio = TC_H_MAKE(0x80000000U, 0U);\n\t\t\tprio_allocate = true;\n\t\t} else {\n\t\t\tNL_SET_ERR_MSG(extack, \"Invalid filter command with priority of zero\");\n\t\t\treturn -ENOENT;\n\t\t}\n\t}\n\n\t/* Find head of filter chain. */\n\n\terr = __tcf_qdisc_find(net, &q, &parent, t->tcm_ifindex, false, extack);\n\tif (err)\n\t\treturn err;\n\n\tif (tcf_proto_check_kind(tca[TCA_KIND], name)) {\n\t\tNL_SET_ERR_MSG(extack, \"Specified TC filter name too long\");\n\t\terr = -EINVAL;\n\t\tgoto errout;\n\t}\n\n\t/* Take rtnl mutex if rtnl_held was set to true on previous iteration,\n\t * block is shared (no qdisc found), qdisc is not unlocked, classifier\n\t * type is not specified, classifier is not unlocked.\n\t */\n\tif (rtnl_held ||\n\t    (q && !(q->ops->cl_ops->flags & QDISC_CLASS_OPS_DOIT_UNLOCKED)) ||\n\t    !tcf_proto_is_unlocked(name)) {\n\t\trtnl_held = true;\n\t\trtnl_lock();\n\t}\n\n\terr = __tcf_qdisc_cl_find(q, parent, &cl, t->tcm_ifindex, extack);\n\tif (err)\n\t\tgoto errout;\n\n\tblock = __tcf_block_find(net, q, cl, t->tcm_ifindex, t->tcm_block_index,\n\t\t\t\t extack);\n\tif (IS_ERR(block)) {\n\t\terr = PTR_ERR(block);\n\t\tgoto errout;\n\t}\n\tblock->classid = parent;\n\n\tchain_index = tca[TCA_CHAIN] ? nla_get_u32(tca[TCA_CHAIN]) : 0;\n\tif (chain_index > TC_ACT_EXT_VAL_MASK) {\n\t\tNL_SET_ERR_MSG(extack, \"Specified chain index exceeds upper limit\");\n\t\terr = -EINVAL;\n\t\tgoto errout;\n\t}\n\tchain = tcf_chain_get(block, chain_index, true);\n\tif (!chain) {\n\t\tNL_SET_ERR_MSG(extack, \"Cannot create specified filter chain\");\n\t\terr = -ENOMEM;\n\t\tgoto errout;\n\t}\n\n\tmutex_lock(&chain->filter_chain_lock);\n\ttp = tcf_chain_tp_find(chain, &chain_info, protocol,\n\t\t\t       prio, prio_allocate);\n\tif (IS_ERR(tp)) {\n\t\tNL_SET_ERR_MSG(extack, \"Filter with specified priority/protocol not found\");\n\t\terr = PTR_ERR(tp);\n\t\tgoto errout_locked;\n\t}\n\n\tif (tp == NULL) {\n\t\tstruct tcf_proto *tp_new = NULL;\n\n\t\tif (chain->flushing) {\n\t\t\terr = -EAGAIN;\n\t\t\tgoto errout_locked;\n\t\t}\n\n\t\t/* Proto-tcf does not exist, create new one */\n\n\t\tif (tca[TCA_KIND] == NULL || !protocol) {\n\t\t\tNL_SET_ERR_MSG(extack, \"Filter kind and protocol must be specified\");\n\t\t\terr = -EINVAL;\n\t\t\tgoto errout_locked;\n\t\t}\n\n\t\tif (!(n->nlmsg_flags & NLM_F_CREATE)) {\n\t\t\tNL_SET_ERR_MSG(extack, \"Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter\");\n\t\t\terr = -ENOENT;\n\t\t\tgoto errout_locked;\n\t\t}\n\n\t\tif (prio_allocate)\n\t\t\tprio = tcf_auto_prio(tcf_chain_tp_prev(chain,\n\t\t\t\t\t\t\t       &chain_info));\n\n\t\tmutex_unlock(&chain->filter_chain_lock);\n\t\ttp_new = tcf_proto_create(name, protocol, prio, chain,\n\t\t\t\t\t  rtnl_held, extack);\n\t\tif (IS_ERR(tp_new)) {\n\t\t\terr = PTR_ERR(tp_new);\n\t\t\tgoto errout_tp;\n\t\t}\n\n\t\ttp_created = 1;\n\t\ttp = tcf_chain_tp_insert_unique(chain, tp_new, protocol, prio,\n\t\t\t\t\t\trtnl_held);\n\t\tif (IS_ERR(tp)) {\n\t\t\terr = PTR_ERR(tp);\n\t\t\tgoto errout_tp;\n\t\t}\n\t} else {\n\t\tmutex_unlock(&chain->filter_chain_lock);\n\t}\n\n\tif (tca[TCA_KIND] && nla_strcmp(tca[TCA_KIND], tp->ops->kind)) {\n\t\tNL_SET_ERR_MSG(extack, \"Specified filter kind does not match existing one\");\n\t\terr = -EINVAL;\n\t\tgoto errout;\n\t}\n\n\tfh = tp->ops->get(tp, t->tcm_handle);\n\n\tif (!fh) {\n\t\tif (!(n->nlmsg_flags & NLM_F_CREATE)) {\n\t\t\tNL_SET_ERR_MSG(extack, \"Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter\");\n\t\t\terr = -ENOENT;\n\t\t\tgoto errout;\n\t\t}\n\t} else if (n->nlmsg_flags & NLM_F_EXCL) {\n\t\ttfilter_put(tp, fh);\n\t\tNL_SET_ERR_MSG(extack, \"Filter already exists\");\n\t\terr = -EEXIST;\n\t\tgoto errout;\n\t}\n\n\tif (chain->tmplt_ops && chain->tmplt_ops != tp->ops) {\n\t\tNL_SET_ERR_MSG(extack, \"Chain template is set to a different filter kind\");\n\t\terr = -EINVAL;\n\t\tgoto errout;\n\t}\n\n\tif (!(n->nlmsg_flags & NLM_F_CREATE))\n\t\tflags |= TCA_ACT_FLAGS_REPLACE;\n\tif (!rtnl_held)\n\t\tflags |= TCA_ACT_FLAGS_NO_RTNL;\n\terr = tp->ops->change(net, skb, tp, cl, t->tcm_handle, tca, &fh,\n\t\t\t      flags, extack);\n\tif (err == 0) {\n\t\ttfilter_notify(net, skb, n, tp, block, q, parent, fh,\n\t\t\t       RTM_NEWTFILTER, false, rtnl_held);\n\t\ttfilter_put(tp, fh);\n\t\t/* q pointer is NULL for shared blocks */\n\t\tif (q)\n\t\t\tq->flags &= ~TCQ_F_CAN_BYPASS;\n\t}\n\nerrout:\n\tif (err && tp_created)\n\t\ttcf_chain_tp_delete_empty(chain, tp, rtnl_held, NULL);\nerrout_tp:\n\tif (chain) {\n\t\tif (tp && !IS_ERR(tp))\n\t\t\ttcf_proto_put(tp, rtnl_held, NULL);\n\t\tif (!tp_created)\n\t\t\ttcf_chain_put(chain);\n\t}\n\ttcf_block_release(q, block, rtnl_held);\n\n\tif (rtnl_held)\n\t\trtnl_unlock();\n\n\tif (err == -EAGAIN) {\n\t\t/* Take rtnl lock in case EAGAIN is caused by concurrent flush\n\t\t * of target chain.\n\t\t */\n\t\trtnl_held = true;\n\t\t/* Replay the request. */\n\t\tgoto replay;\n\t}\n\treturn err;\n\nerrout_locked:\n\tmutex_unlock(&chain->filter_chain_lock);\n\tgoto errout;\n}", "func_hash": 249400845678093962479611801234831545975, "file_name": "cls_api.c", "file_hash": 31293344430191637657447401884064089853, "cwe": ["CWE-416"], "cve": "CVE-2022-1055", "cve_desc": "A use-after-free exists in the Linux Kernel in tc_new_tfilter that could allow a local attacker to gain privilege escalation. The exploit requires unprivileged user namespaces. We recommend upgrading past commit 04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1055"}
{"idx": 212433, "project": "vim", "commit_id": "ccfde4d028e891a41e3548323c3d47b06fb0b83e", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/ccfde4d028e891a41e3548323c3d47b06fb0b83e", "commit_message": "patch 9.0.0389: crash when 'tagfunc' closes the window\n\nProblem:    Crash when 'tagfunc' closes the window.\nSolution:   Bail out when the window was closed.", "target": 1, "func": "do_tag(\n    char_u\t*tag,\t\t// tag (pattern) to jump to\n    int\t\ttype,\n    int\t\tcount,\n    int\t\tforceit,\t// :ta with !\n    int\t\tverbose)\t// print \"tag not found\" message\n{\n    taggy_T\t*tagstack = curwin->w_tagstack;\n    int\t\ttagstackidx = curwin->w_tagstackidx;\n    int\t\ttagstacklen = curwin->w_tagstacklen;\n    int\t\tcur_match = 0;\n    int\t\tcur_fnum = curbuf->b_fnum;\n    int\t\toldtagstackidx = tagstackidx;\n    int\t\tprevtagstackidx = tagstackidx;\n    int\t\tprev_num_matches;\n    int\t\tnew_tag = FALSE;\n    int\t\ti;\n    int\t\tic;\n    int\t\tno_regexp = FALSE;\n    int\t\terror_cur_match = 0;\n    int\t\tsave_pos = FALSE;\n    fmark_T\tsaved_fmark;\n#ifdef FEAT_CSCOPE\n    int\t\tjumped_to_tag = FALSE;\n#endif\n    int\t\tnew_num_matches;\n    char_u\t**new_matches;\n    int\t\tuse_tagstack;\n    int\t\tskip_msg = FALSE;\n    char_u\t*buf_ffname = curbuf->b_ffname;\t    // name to use for\n\t\t\t\t\t\t    // priority computation\n    int\t\tuse_tfu = 1;\n    char_u\t*tofree = NULL;\n\n    // remember the matches for the last used tag\n    static int\t\tnum_matches = 0;\n    static int\t\tmax_num_matches = 0;  // limit used for match search\n    static char_u\t**matches = NULL;\n    static int\t\tflags;\n\n#ifdef FEAT_EVAL\n    if (tfu_in_use)\n    {\n\temsg(_(e_cannot_modify_tag_stack_within_tagfunc));\n\treturn FALSE;\n    }\n#endif\n\n#ifdef EXITFREE\n    if (type == DT_FREE)\n    {\n\t// remove the list of matches\n\tFreeWild(num_matches, matches);\n# ifdef FEAT_CSCOPE\n\tcs_free_tags();\n# endif\n\tnum_matches = 0;\n\treturn FALSE;\n    }\n#endif\n\n    if (type == DT_HELP)\n    {\n\ttype = DT_TAG;\n\tno_regexp = TRUE;\n\tuse_tfu = 0;\n    }\n\n    prev_num_matches = num_matches;\n    free_string_option(nofile_fname);\n    nofile_fname = NULL;\n\n    CLEAR_POS(&saved_fmark.mark);\t// shutup gcc 4.0\n    saved_fmark.fnum = 0;\n\n    /*\n     * Don't add a tag to the tagstack if 'tagstack' has been reset.\n     */\n    if ((!p_tgst && *tag != NUL))\n    {\n\tuse_tagstack = FALSE;\n\tnew_tag = TRUE;\n#if defined(FEAT_QUICKFIX)\n\tif (g_do_tagpreview != 0)\n\t{\n\t    tagstack_clear_entry(&ptag_entry);\n\t    if ((ptag_entry.tagname = vim_strsave(tag)) == NULL)\n\t\tgoto end_do_tag;\n\t}\n#endif\n    }\n    else\n    {\n#if defined(FEAT_QUICKFIX)\n\tif (g_do_tagpreview != 0)\n\t    use_tagstack = FALSE;\n\telse\n#endif\n\t    use_tagstack = TRUE;\n\n\t// new pattern, add to the tag stack\n\tif (*tag != NUL\n\t\t&& (type == DT_TAG || type == DT_SELECT || type == DT_JUMP\n#ifdef FEAT_QUICKFIX\n\t\t    || type == DT_LTAG\n#endif\n#ifdef FEAT_CSCOPE\n\t\t    || type == DT_CSCOPE\n#endif\n\t\t    ))\n\t{\n#if defined(FEAT_QUICKFIX)\n\t    if (g_do_tagpreview != 0)\n\t    {\n\t\tif (ptag_entry.tagname != NULL\n\t\t\t&& STRCMP(ptag_entry.tagname, tag) == 0)\n\t\t{\n\t\t    // Jumping to same tag: keep the current match, so that\n\t\t    // the CursorHold autocommand example works.\n\t\t    cur_match = ptag_entry.cur_match;\n\t\t    cur_fnum = ptag_entry.cur_fnum;\n\t\t}\n\t\telse\n\t\t{\n\t\t    tagstack_clear_entry(&ptag_entry);\n\t\t    if ((ptag_entry.tagname = vim_strsave(tag)) == NULL)\n\t\t\tgoto end_do_tag;\n\t\t}\n\t    }\n\t    else\n#endif\n\t    {\n\t\t/*\n\t\t * If the last used entry is not at the top, delete all tag\n\t\t * stack entries above it.\n\t\t */\n\t\twhile (tagstackidx < tagstacklen)\n\t\t    tagstack_clear_entry(&tagstack[--tagstacklen]);\n\n\t\t// if the tagstack is full: remove oldest entry\n\t\tif (++tagstacklen > TAGSTACKSIZE)\n\t\t{\n\t\t    tagstacklen = TAGSTACKSIZE;\n\t\t    tagstack_clear_entry(&tagstack[0]);\n\t\t    for (i = 1; i < tagstacklen; ++i)\n\t\t\ttagstack[i - 1] = tagstack[i];\n\t\t    --tagstackidx;\n\t\t}\n\n\t\t/*\n\t\t * put the tag name in the tag stack\n\t\t */\n\t\tif ((tagstack[tagstackidx].tagname = vim_strsave(tag)) == NULL)\n\t\t{\n\t\t    curwin->w_tagstacklen = tagstacklen - 1;\n\t\t    goto end_do_tag;\n\t\t}\n\t\tcurwin->w_tagstacklen = tagstacklen;\n\n\t\tsave_pos = TRUE;\t// save the cursor position below\n\t    }\n\n\t    new_tag = TRUE;\n\t}\n\telse\n\t{\n\t    if (\n#if defined(FEAT_QUICKFIX)\n\t\t    g_do_tagpreview != 0 ? ptag_entry.tagname == NULL :\n#endif\n\t\t    tagstacklen == 0)\n\t    {\n\t\t// empty stack\n\t\temsg(_(e_tag_stack_empty));\n\t\tgoto end_do_tag;\n\t    }\n\n\t    if (type == DT_POP)\t\t// go to older position\n\t    {\n#ifdef FEAT_FOLDING\n\t\tint\told_KeyTyped = KeyTyped;\n#endif\n\t\tif ((tagstackidx -= count) < 0)\n\t\t{\n\t\t    emsg(_(e_at_bottom_of_tag_stack));\n\t\t    if (tagstackidx + count == 0)\n\t\t    {\n\t\t\t// We did [num]^T from the bottom of the stack\n\t\t\ttagstackidx = 0;\n\t\t\tgoto end_do_tag;\n\t\t    }\n\t\t    // We weren't at the bottom of the stack, so jump all the\n\t\t    // way to the bottom now.\n\t\t    tagstackidx = 0;\n\t\t}\n\t\telse if (tagstackidx >= tagstacklen)    // count == 0?\n\t\t{\n\t\t    emsg(_(e_at_top_of_tag_stack));\n\t\t    goto end_do_tag;\n\t\t}\n\n\t\t// Make a copy of the fmark, autocommands may invalidate the\n\t\t// tagstack before it's used.\n\t\tsaved_fmark = tagstack[tagstackidx].fmark;\n\t\tif (saved_fmark.fnum != curbuf->b_fnum)\n\t\t{\n\t\t    /*\n\t\t     * Jump to other file. If this fails (e.g. because the\n\t\t     * file was changed) keep original position in tag stack.\n\t\t     */\n\t\t    if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum,\n\t\t\t\t\t       GETF_SETMARK, forceit) == FAIL)\n\t\t    {\n\t\t\ttagstackidx = oldtagstackidx;  // back to old posn\n\t\t\tgoto end_do_tag;\n\t\t    }\n\t\t    // An BufReadPost autocommand may jump to the '\" mark, but\n\t\t    // we don't what that here.\n\t\t    curwin->w_cursor.lnum = saved_fmark.mark.lnum;\n\t\t}\n\t\telse\n\t\t{\n\t\t    setpcmark();\n\t\t    curwin->w_cursor.lnum = saved_fmark.mark.lnum;\n\t\t}\n\t\tcurwin->w_cursor.col = saved_fmark.mark.col;\n\t\tcurwin->w_set_curswant = TRUE;\n\t\tcheck_cursor();\n#ifdef FEAT_FOLDING\n\t\tif ((fdo_flags & FDO_TAG) && old_KeyTyped)\n\t\t    foldOpenCursor();\n#endif\n\n\t\t// remove the old list of matches\n\t\tFreeWild(num_matches, matches);\n#ifdef FEAT_CSCOPE\n\t\tcs_free_tags();\n#endif\n\t\tnum_matches = 0;\n\t\ttag_freematch();\n\t\tgoto end_do_tag;\n\t    }\n\n\t    if (type == DT_TAG\n#if defined(FEAT_QUICKFIX)\n\t\t    || type == DT_LTAG\n#endif\n\t       )\n\t    {\n#if defined(FEAT_QUICKFIX)\n\t\tif (g_do_tagpreview != 0)\n\t\t{\n\t\t    cur_match = ptag_entry.cur_match;\n\t\t    cur_fnum = ptag_entry.cur_fnum;\n\t\t}\n\t\telse\n#endif\n\t\t{\n\t\t    // \":tag\" (no argument): go to newer pattern\n\t\t    save_pos = TRUE;\t// save the cursor position below\n\t\t    if ((tagstackidx += count - 1) >= tagstacklen)\n\t\t    {\n\t\t\t/*\n\t\t\t * Beyond the last one, just give an error message and\n\t\t\t * go to the last one.  Don't store the cursor\n\t\t\t * position.\n\t\t\t */\n\t\t\ttagstackidx = tagstacklen - 1;\n\t\t\temsg(_(e_at_top_of_tag_stack));\n\t\t\tsave_pos = FALSE;\n\t\t    }\n\t\t    else if (tagstackidx < 0)\t// must have been count == 0\n\t\t    {\n\t\t\temsg(_(e_at_bottom_of_tag_stack));\n\t\t\ttagstackidx = 0;\n\t\t\tgoto end_do_tag;\n\t\t    }\n\t\t    cur_match = tagstack[tagstackidx].cur_match;\n\t\t    cur_fnum = tagstack[tagstackidx].cur_fnum;\n\t\t}\n\t\tnew_tag = TRUE;\n\t    }\n\t    else\t\t\t\t// go to other matching tag\n\t    {\n\t\t// Save index for when selection is cancelled.\n\t\tprevtagstackidx = tagstackidx;\n\n#if defined(FEAT_QUICKFIX)\n\t\tif (g_do_tagpreview != 0)\n\t\t{\n\t\t    cur_match = ptag_entry.cur_match;\n\t\t    cur_fnum = ptag_entry.cur_fnum;\n\t\t}\n\t\telse\n#endif\n\t\t{\n\t\t    if (--tagstackidx < 0)\n\t\t\ttagstackidx = 0;\n\t\t    cur_match = tagstack[tagstackidx].cur_match;\n\t\t    cur_fnum = tagstack[tagstackidx].cur_fnum;\n\t\t}\n\t\tswitch (type)\n\t\t{\n\t\t    case DT_FIRST: cur_match = count - 1; break;\n\t\t    case DT_SELECT:\n\t\t    case DT_JUMP:\n#ifdef FEAT_CSCOPE\n\t\t    case DT_CSCOPE:\n#endif\n\t\t    case DT_LAST:  cur_match = MAXCOL - 1; break;\n\t\t    case DT_NEXT:  cur_match += count; break;\n\t\t    case DT_PREV:  cur_match -= count; break;\n\t\t}\n\t\tif (cur_match >= MAXCOL)\n\t\t    cur_match = MAXCOL - 1;\n\t\telse if (cur_match < 0)\n\t\t{\n\t\t    emsg(_(e_cannot_go_before_first_matching_tag));\n\t\t    skip_msg = TRUE;\n\t\t    cur_match = 0;\n\t\t    cur_fnum = curbuf->b_fnum;\n\t\t}\n\t    }\n\t}\n\n#if defined(FEAT_QUICKFIX)\n\tif (g_do_tagpreview != 0)\n\t{\n\t    if (type != DT_SELECT && type != DT_JUMP)\n\t    {\n\t\tptag_entry.cur_match = cur_match;\n\t\tptag_entry.cur_fnum = cur_fnum;\n\t    }\n\t}\n\telse\n#endif\n\t{\n\t    /*\n\t     * For \":tag [arg]\" or \":tselect\" remember position before the jump.\n\t     */\n\t    saved_fmark = tagstack[tagstackidx].fmark;\n\t    if (save_pos)\n\t    {\n\t\ttagstack[tagstackidx].fmark.mark = curwin->w_cursor;\n\t\ttagstack[tagstackidx].fmark.fnum = curbuf->b_fnum;\n\t    }\n\n\t    // Curwin will change in the call to jumpto_tag() if \":stag\" was\n\t    // used or an autocommand jumps to another window; store value of\n\t    // tagstackidx now.\n\t    curwin->w_tagstackidx = tagstackidx;\n\t    if (type != DT_SELECT && type != DT_JUMP)\n\t    {\n\t\tcurwin->w_tagstack[tagstackidx].cur_match = cur_match;\n\t\tcurwin->w_tagstack[tagstackidx].cur_fnum = cur_fnum;\n\t    }\n\t}\n    }\n\n    // When not using the current buffer get the name of buffer \"cur_fnum\".\n    // Makes sure that the tag order doesn't change when using a remembered\n    // position for \"cur_match\".\n    if (cur_fnum != curbuf->b_fnum)\n    {\n\tbuf_T *buf = buflist_findnr(cur_fnum);\n\n\tif (buf != NULL)\n\t    buf_ffname = buf->b_ffname;\n    }\n\n    /*\n     * Repeat searching for tags, when a file has not been found.\n     */\n    for (;;)\n    {\n\tint\tother_name;\n\tchar_u\t*name;\n\n\t/*\n\t * When desired match not found yet, try to find it (and others).\n\t */\n\tif (use_tagstack)\n\t{\n\t    // make a copy, the tagstack may change in 'tagfunc'\n\t    name = vim_strsave(tagstack[tagstackidx].tagname);\n\t    vim_free(tofree);\n\t    tofree = name;\n\t}\n#if defined(FEAT_QUICKFIX)\n\telse if (g_do_tagpreview != 0)\n\t    name = ptag_entry.tagname;\n#endif\n\telse\n\t    name = tag;\n\tother_name = (tagmatchname == NULL || STRCMP(tagmatchname, name) != 0);\n\tif (new_tag\n\t\t|| (cur_match >= num_matches && max_num_matches != MAXCOL)\n\t\t|| other_name)\n\t{\n\t    if (other_name)\n\t    {\n\t\tvim_free(tagmatchname);\n\t\ttagmatchname = vim_strsave(name);\n\t    }\n\n\t    if (type == DT_SELECT || type == DT_JUMP\n#if defined(FEAT_QUICKFIX)\n\t\t|| type == DT_LTAG\n#endif\n\t\t)\n\t\tcur_match = MAXCOL - 1;\n\t    if (type == DT_TAG)\n\t\tmax_num_matches = MAXCOL;\n\t    else\n\t\tmax_num_matches = cur_match + 1;\n\n\t    // when the argument starts with '/', use it as a regexp\n\t    if (!no_regexp && *name == '/')\n\t    {\n\t\tflags = TAG_REGEXP;\n\t\t++name;\n\t    }\n\t    else\n\t\tflags = TAG_NOIC;\n\n#ifdef FEAT_CSCOPE\n\t    if (type == DT_CSCOPE)\n\t\tflags = TAG_CSCOPE;\n#endif\n\t    if (verbose)\n\t\tflags |= TAG_VERBOSE;\n\n\t    if (!use_tfu)\n\t\tflags |= TAG_NO_TAGFUNC;\n\n\t    if (find_tags(name, &new_num_matches, &new_matches, flags,\n\t\t\t\t\t    max_num_matches, buf_ffname) == OK\n\t\t    && new_num_matches < max_num_matches)\n\t\tmax_num_matches = MAXCOL; // If less than max_num_matches\n\t\t\t\t\t  // found: all matches found.\n\n\t    // If there already were some matches for the same name, move them\n\t    // to the start.  Avoids that the order changes when using\n\t    // \":tnext\" and jumping to another file.\n\t    if (!new_tag && !other_name)\n\t    {\n\t\tint\t    j, k;\n\t\tint\t    idx = 0;\n\t\ttagptrs_T   tagp, tagp2;\n\n\t\t// Find the position of each old match in the new list.  Need\n\t\t// to use parse_match() to find the tag line.\n\t\tfor (j = 0; j < num_matches; ++j)\n\t\t{\n\t\t    parse_match(matches[j], &tagp);\n\t\t    for (i = idx; i < new_num_matches; ++i)\n\t\t    {\n\t\t\tparse_match(new_matches[i], &tagp2);\n\t\t\tif (STRCMP(tagp.tagname, tagp2.tagname) == 0)\n\t\t\t{\n\t\t\t    char_u *p = new_matches[i];\n\t\t\t    for (k = i; k > idx; --k)\n\t\t\t\tnew_matches[k] = new_matches[k - 1];\n\t\t\t    new_matches[idx++] = p;\n\t\t\t    break;\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\t    FreeWild(num_matches, matches);\n\t    num_matches = new_num_matches;\n\t    matches = new_matches;\n\t}\n\n\tif (num_matches <= 0)\n\t{\n\t    if (verbose)\n\t\tsemsg(_(e_tag_not_found_str), name);\n#if defined(FEAT_QUICKFIX)\n\t    g_do_tagpreview = 0;\n#endif\n\t}\n\telse\n\t{\n\t    int ask_for_selection = FALSE;\n\n#ifdef FEAT_CSCOPE\n\t    if (type == DT_CSCOPE && num_matches > 1)\n\t    {\n\t\tcs_print_tags();\n\t\task_for_selection = TRUE;\n\t    }\n\t    else\n#endif\n\t    if (type == DT_TAG && *tag != NUL)\n\t\t// If a count is supplied to the \":tag \" command, then\n\t\t// jump to count'th matching tag.\n\t\tcur_match = count > 0 ? count - 1 : 0;\n\t    else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1))\n\t    {\n\t\tprint_tag_list(new_tag, use_tagstack, num_matches, matches);\n\t\task_for_selection = TRUE;\n\t    }\n#if defined(FEAT_QUICKFIX) && defined(FEAT_EVAL)\n\t    else if (type == DT_LTAG)\n\t    {\n\t\tif (add_llist_tags(tag, num_matches, matches) == FAIL)\n\t\t    goto end_do_tag;\n\t\tcur_match = 0;\t\t// Jump to the first tag\n\t    }\n#endif\n\n\t    if (ask_for_selection == TRUE)\n\t    {\n\t\t/*\n\t\t * Ask to select a tag from the list.\n\t\t */\n\t\ti = prompt_for_number(NULL);\n\t\tif (i <= 0 || i > num_matches || got_int)\n\t\t{\n\t\t    // no valid choice: don't change anything\n\t\t    if (use_tagstack)\n\t\t    {\n\t\t\ttagstack[tagstackidx].fmark = saved_fmark;\n\t\t\ttagstackidx = prevtagstackidx;\n\t\t    }\n#ifdef FEAT_CSCOPE\n\t\t    cs_free_tags();\n\t\t    jumped_to_tag = TRUE;\n#endif\n\t\t    break;\n\t\t}\n\t\tcur_match = i - 1;\n\t    }\n\n\t    if (cur_match >= num_matches)\n\t    {\n\t\t// Avoid giving this error when a file wasn't found and we're\n\t\t// looking for a match in another file, which wasn't found.\n\t\t// There will be an emsg(\"file doesn't exist\") below then.\n\t\tif ((type == DT_NEXT || type == DT_FIRST)\n\t\t\t\t\t\t      && nofile_fname == NULL)\n\t\t{\n\t\t    if (num_matches == 1)\n\t\t\temsg(_(e_there_is_only_one_matching_tag));\n\t\t    else\n\t\t\temsg(_(e_cannot_go_beyond_last_matching_tag));\n\t\t    skip_msg = TRUE;\n\t\t}\n\t\tcur_match = num_matches - 1;\n\t    }\n\t    if (use_tagstack)\n\t    {\n\t\ttagptrs_T   tagp;\n\n\t\ttagstack[tagstackidx].cur_match = cur_match;\n\t\ttagstack[tagstackidx].cur_fnum = cur_fnum;\n\n\t\t// store user-provided data originating from tagfunc\n\t\tif (use_tfu && parse_match(matches[cur_match], &tagp) == OK\n\t\t\t&& tagp.user_data)\n\t\t{\n\t\t    VIM_CLEAR(tagstack[tagstackidx].user_data);\n\t\t    tagstack[tagstackidx].user_data = vim_strnsave(\n\t\t\t  tagp.user_data, tagp.user_data_end - tagp.user_data);\n\t\t}\n\n\t\t++tagstackidx;\n\t    }\n#if defined(FEAT_QUICKFIX)\n\t    else if (g_do_tagpreview != 0)\n\t    {\n\t\tptag_entry.cur_match = cur_match;\n\t\tptag_entry.cur_fnum = cur_fnum;\n\t    }\n#endif\n\n\t    /*\n\t     * Only when going to try the next match, report that the previous\n\t     * file didn't exist.  Otherwise an emsg() is given below.\n\t     */\n\t    if (nofile_fname != NULL && error_cur_match != cur_match)\n\t\tsmsg(_(\"File \\\"%s\\\" does not exist\"), nofile_fname);\n\n\n\t    ic = (matches[cur_match][0] & MT_IC_OFF);\n\t    if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP\n#ifdef FEAT_CSCOPE\n\t\t&& type != DT_CSCOPE\n#endif\n\t\t&& (num_matches > 1 || ic)\n\t\t&& !skip_msg)\n\t    {\n\t\t// Give an indication of the number of matching tags\n\t\tsprintf((char *)IObuff, _(\"tag %d of %d%s\"),\n\t\t\t\tcur_match + 1,\n\t\t\t\tnum_matches,\n\t\t\t\tmax_num_matches != MAXCOL ? _(\" or more\") : \"\");\n\t\tif (ic)\n\t\t    STRCAT(IObuff, _(\"  Using tag with different case!\"));\n\t\tif ((num_matches > prev_num_matches || new_tag)\n\t\t\t\t\t\t\t   && num_matches > 1)\n\t\t{\n\t\t    if (ic)\n\t\t\tmsg_attr((char *)IObuff, HL_ATTR(HLF_W));\n\t\t    else\n\t\t\tmsg((char *)IObuff);\n\t\t    msg_scroll = TRUE;\t// don't overwrite this message\n\t\t}\n\t\telse\n\t\t    give_warning(IObuff, ic);\n\t\tif (ic && !msg_scrolled && msg_silent == 0)\n\t\t{\n\t\t    out_flush();\n\t\t    ui_delay(1007L, TRUE);\n\t\t}\n\t    }\n\n#if defined(FEAT_EVAL)\n\t    // Let the SwapExists event know what tag we are jumping to.\n\t    vim_snprintf((char *)IObuff, IOSIZE, \":ta %s\\r\", name);\n\t    set_vim_var_string(VV_SWAPCOMMAND, IObuff, -1);\n#endif\n\n\t    /*\n\t     * Jump to the desired match.\n\t     */\n\t    i = jumpto_tag(matches[cur_match], forceit, type != DT_CSCOPE);\n\n#if defined(FEAT_EVAL)\n\t    set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);\n#endif\n\n\t    if (i == NOTAGFILE)\n\t    {\n\t\t// File not found: try again with another matching tag\n\t\tif ((type == DT_PREV && cur_match > 0)\n\t\t\t|| ((type == DT_TAG || type == DT_NEXT\n\t\t\t\t\t\t\t  || type == DT_FIRST)\n\t\t\t    && (max_num_matches != MAXCOL\n\t\t\t\t\t     || cur_match < num_matches - 1)))\n\t\t{\n\t\t    error_cur_match = cur_match;\n\t\t    if (use_tagstack)\n\t\t\t--tagstackidx;\n\t\t    if (type == DT_PREV)\n\t\t\t--cur_match;\n\t\t    else\n\t\t    {\n\t\t\ttype = DT_NEXT;\n\t\t\t++cur_match;\n\t\t    }\n\t\t    continue;\n\t\t}\n\t\tsemsg(_(e_file_str_does_not_exist), nofile_fname);\n\t    }\n\t    else\n\t    {\n\t\t// We may have jumped to another window, check that\n\t\t// tagstackidx is still valid.\n\t\tif (use_tagstack && tagstackidx > curwin->w_tagstacklen)\n\t\t    tagstackidx = curwin->w_tagstackidx;\n#ifdef FEAT_CSCOPE\n\t\tjumped_to_tag = TRUE;\n#endif\n\t    }\n\t}\n\tbreak;\n    }\n\nend_do_tag:\n    // Only store the new index when using the tagstack and it's valid.\n    if (use_tagstack && tagstackidx <= curwin->w_tagstacklen)\n\tcurwin->w_tagstackidx = tagstackidx;\n    postponed_split = 0;\t// don't split next time\n# ifdef FEAT_QUICKFIX\n    g_do_tagpreview = 0;\t// don't do tag preview next time\n# endif\n\n    vim_free(tofree);\n#ifdef FEAT_CSCOPE\n    return jumped_to_tag;\n#else\n    return FALSE;\n#endif\n}", "func_hash": 163270354086098606424218695920397836600, "file_name": "tag.c", "file_hash": 256312624888395967188545141531528405807, "cwe": ["CWE-416"], "cve": "CVE-2022-3134", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 9.0.0389.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3134"}
{"idx": 459400, "project": "vim", "commit_id": "ccfde4d028e891a41e3548323c3d47b06fb0b83e", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/ccfde4d028e891a41e3548323c3d47b06fb0b83e", "commit_message": "patch 9.0.0389: crash when 'tagfunc' closes the window\n\nProblem:    Crash when 'tagfunc' closes the window.\nSolution:   Bail out when the window was closed.", "target": 0, "func": "do_tag(\n    char_u\t*tag,\t\t// tag (pattern) to jump to\n    int\t\ttype,\n    int\t\tcount,\n    int\t\tforceit,\t// :ta with !\n    int\t\tverbose)\t// print \"tag not found\" message\n{\n    taggy_T\t*tagstack = curwin->w_tagstack;\n    int\t\ttagstackidx = curwin->w_tagstackidx;\n    int\t\ttagstacklen = curwin->w_tagstacklen;\n    int\t\tcur_match = 0;\n    int\t\tcur_fnum = curbuf->b_fnum;\n    int\t\toldtagstackidx = tagstackidx;\n    int\t\tprevtagstackidx = tagstackidx;\n    int\t\tprev_num_matches;\n    int\t\tnew_tag = FALSE;\n    int\t\ti;\n    int\t\tic;\n    int\t\tno_regexp = FALSE;\n    int\t\terror_cur_match = 0;\n    int\t\tsave_pos = FALSE;\n    fmark_T\tsaved_fmark;\n#ifdef FEAT_CSCOPE\n    int\t\tjumped_to_tag = FALSE;\n#endif\n    int\t\tnew_num_matches;\n    char_u\t**new_matches;\n    int\t\tuse_tagstack;\n    int\t\tskip_msg = FALSE;\n    char_u\t*buf_ffname = curbuf->b_ffname;\t    // name to use for\n\t\t\t\t\t\t    // priority computation\n    int\t\tuse_tfu = 1;\n    char_u\t*tofree = NULL;\n\n    // remember the matches for the last used tag\n    static int\t\tnum_matches = 0;\n    static int\t\tmax_num_matches = 0;  // limit used for match search\n    static char_u\t**matches = NULL;\n    static int\t\tflags;\n\n#ifdef FEAT_EVAL\n    if (tfu_in_use)\n    {\n\temsg(_(e_cannot_modify_tag_stack_within_tagfunc));\n\treturn FALSE;\n    }\n#endif\n\n#ifdef EXITFREE\n    if (type == DT_FREE)\n    {\n\t// remove the list of matches\n\tFreeWild(num_matches, matches);\n# ifdef FEAT_CSCOPE\n\tcs_free_tags();\n# endif\n\tnum_matches = 0;\n\treturn FALSE;\n    }\n#endif\n\n    if (type == DT_HELP)\n    {\n\ttype = DT_TAG;\n\tno_regexp = TRUE;\n\tuse_tfu = 0;\n    }\n\n    prev_num_matches = num_matches;\n    free_string_option(nofile_fname);\n    nofile_fname = NULL;\n\n    CLEAR_POS(&saved_fmark.mark);\t// shutup gcc 4.0\n    saved_fmark.fnum = 0;\n\n    /*\n     * Don't add a tag to the tagstack if 'tagstack' has been reset.\n     */\n    if ((!p_tgst && *tag != NUL))\n    {\n\tuse_tagstack = FALSE;\n\tnew_tag = TRUE;\n#if defined(FEAT_QUICKFIX)\n\tif (g_do_tagpreview != 0)\n\t{\n\t    tagstack_clear_entry(&ptag_entry);\n\t    if ((ptag_entry.tagname = vim_strsave(tag)) == NULL)\n\t\tgoto end_do_tag;\n\t}\n#endif\n    }\n    else\n    {\n#if defined(FEAT_QUICKFIX)\n\tif (g_do_tagpreview != 0)\n\t    use_tagstack = FALSE;\n\telse\n#endif\n\t    use_tagstack = TRUE;\n\n\t// new pattern, add to the tag stack\n\tif (*tag != NUL\n\t\t&& (type == DT_TAG || type == DT_SELECT || type == DT_JUMP\n#ifdef FEAT_QUICKFIX\n\t\t    || type == DT_LTAG\n#endif\n#ifdef FEAT_CSCOPE\n\t\t    || type == DT_CSCOPE\n#endif\n\t\t    ))\n\t{\n#if defined(FEAT_QUICKFIX)\n\t    if (g_do_tagpreview != 0)\n\t    {\n\t\tif (ptag_entry.tagname != NULL\n\t\t\t&& STRCMP(ptag_entry.tagname, tag) == 0)\n\t\t{\n\t\t    // Jumping to same tag: keep the current match, so that\n\t\t    // the CursorHold autocommand example works.\n\t\t    cur_match = ptag_entry.cur_match;\n\t\t    cur_fnum = ptag_entry.cur_fnum;\n\t\t}\n\t\telse\n\t\t{\n\t\t    tagstack_clear_entry(&ptag_entry);\n\t\t    if ((ptag_entry.tagname = vim_strsave(tag)) == NULL)\n\t\t\tgoto end_do_tag;\n\t\t}\n\t    }\n\t    else\n#endif\n\t    {\n\t\t/*\n\t\t * If the last used entry is not at the top, delete all tag\n\t\t * stack entries above it.\n\t\t */\n\t\twhile (tagstackidx < tagstacklen)\n\t\t    tagstack_clear_entry(&tagstack[--tagstacklen]);\n\n\t\t// if the tagstack is full: remove oldest entry\n\t\tif (++tagstacklen > TAGSTACKSIZE)\n\t\t{\n\t\t    tagstacklen = TAGSTACKSIZE;\n\t\t    tagstack_clear_entry(&tagstack[0]);\n\t\t    for (i = 1; i < tagstacklen; ++i)\n\t\t\ttagstack[i - 1] = tagstack[i];\n\t\t    --tagstackidx;\n\t\t}\n\n\t\t/*\n\t\t * put the tag name in the tag stack\n\t\t */\n\t\tif ((tagstack[tagstackidx].tagname = vim_strsave(tag)) == NULL)\n\t\t{\n\t\t    curwin->w_tagstacklen = tagstacklen - 1;\n\t\t    goto end_do_tag;\n\t\t}\n\t\tcurwin->w_tagstacklen = tagstacklen;\n\n\t\tsave_pos = TRUE;\t// save the cursor position below\n\t    }\n\n\t    new_tag = TRUE;\n\t}\n\telse\n\t{\n\t    if (\n#if defined(FEAT_QUICKFIX)\n\t\t    g_do_tagpreview != 0 ? ptag_entry.tagname == NULL :\n#endif\n\t\t    tagstacklen == 0)\n\t    {\n\t\t// empty stack\n\t\temsg(_(e_tag_stack_empty));\n\t\tgoto end_do_tag;\n\t    }\n\n\t    if (type == DT_POP)\t\t// go to older position\n\t    {\n#ifdef FEAT_FOLDING\n\t\tint\told_KeyTyped = KeyTyped;\n#endif\n\t\tif ((tagstackidx -= count) < 0)\n\t\t{\n\t\t    emsg(_(e_at_bottom_of_tag_stack));\n\t\t    if (tagstackidx + count == 0)\n\t\t    {\n\t\t\t// We did [num]^T from the bottom of the stack\n\t\t\ttagstackidx = 0;\n\t\t\tgoto end_do_tag;\n\t\t    }\n\t\t    // We weren't at the bottom of the stack, so jump all the\n\t\t    // way to the bottom now.\n\t\t    tagstackidx = 0;\n\t\t}\n\t\telse if (tagstackidx >= tagstacklen)    // count == 0?\n\t\t{\n\t\t    emsg(_(e_at_top_of_tag_stack));\n\t\t    goto end_do_tag;\n\t\t}\n\n\t\t// Make a copy of the fmark, autocommands may invalidate the\n\t\t// tagstack before it's used.\n\t\tsaved_fmark = tagstack[tagstackidx].fmark;\n\t\tif (saved_fmark.fnum != curbuf->b_fnum)\n\t\t{\n\t\t    /*\n\t\t     * Jump to other file. If this fails (e.g. because the\n\t\t     * file was changed) keep original position in tag stack.\n\t\t     */\n\t\t    if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum,\n\t\t\t\t\t       GETF_SETMARK, forceit) == FAIL)\n\t\t    {\n\t\t\ttagstackidx = oldtagstackidx;  // back to old posn\n\t\t\tgoto end_do_tag;\n\t\t    }\n\t\t    // An BufReadPost autocommand may jump to the '\" mark, but\n\t\t    // we don't what that here.\n\t\t    curwin->w_cursor.lnum = saved_fmark.mark.lnum;\n\t\t}\n\t\telse\n\t\t{\n\t\t    setpcmark();\n\t\t    curwin->w_cursor.lnum = saved_fmark.mark.lnum;\n\t\t}\n\t\tcurwin->w_cursor.col = saved_fmark.mark.col;\n\t\tcurwin->w_set_curswant = TRUE;\n\t\tcheck_cursor();\n#ifdef FEAT_FOLDING\n\t\tif ((fdo_flags & FDO_TAG) && old_KeyTyped)\n\t\t    foldOpenCursor();\n#endif\n\n\t\t// remove the old list of matches\n\t\tFreeWild(num_matches, matches);\n#ifdef FEAT_CSCOPE\n\t\tcs_free_tags();\n#endif\n\t\tnum_matches = 0;\n\t\ttag_freematch();\n\t\tgoto end_do_tag;\n\t    }\n\n\t    if (type == DT_TAG\n#if defined(FEAT_QUICKFIX)\n\t\t    || type == DT_LTAG\n#endif\n\t       )\n\t    {\n#if defined(FEAT_QUICKFIX)\n\t\tif (g_do_tagpreview != 0)\n\t\t{\n\t\t    cur_match = ptag_entry.cur_match;\n\t\t    cur_fnum = ptag_entry.cur_fnum;\n\t\t}\n\t\telse\n#endif\n\t\t{\n\t\t    // \":tag\" (no argument): go to newer pattern\n\t\t    save_pos = TRUE;\t// save the cursor position below\n\t\t    if ((tagstackidx += count - 1) >= tagstacklen)\n\t\t    {\n\t\t\t/*\n\t\t\t * Beyond the last one, just give an error message and\n\t\t\t * go to the last one.  Don't store the cursor\n\t\t\t * position.\n\t\t\t */\n\t\t\ttagstackidx = tagstacklen - 1;\n\t\t\temsg(_(e_at_top_of_tag_stack));\n\t\t\tsave_pos = FALSE;\n\t\t    }\n\t\t    else if (tagstackidx < 0)\t// must have been count == 0\n\t\t    {\n\t\t\temsg(_(e_at_bottom_of_tag_stack));\n\t\t\ttagstackidx = 0;\n\t\t\tgoto end_do_tag;\n\t\t    }\n\t\t    cur_match = tagstack[tagstackidx].cur_match;\n\t\t    cur_fnum = tagstack[tagstackidx].cur_fnum;\n\t\t}\n\t\tnew_tag = TRUE;\n\t    }\n\t    else\t\t\t\t// go to other matching tag\n\t    {\n\t\t// Save index for when selection is cancelled.\n\t\tprevtagstackidx = tagstackidx;\n\n#if defined(FEAT_QUICKFIX)\n\t\tif (g_do_tagpreview != 0)\n\t\t{\n\t\t    cur_match = ptag_entry.cur_match;\n\t\t    cur_fnum = ptag_entry.cur_fnum;\n\t\t}\n\t\telse\n#endif\n\t\t{\n\t\t    if (--tagstackidx < 0)\n\t\t\ttagstackidx = 0;\n\t\t    cur_match = tagstack[tagstackidx].cur_match;\n\t\t    cur_fnum = tagstack[tagstackidx].cur_fnum;\n\t\t}\n\t\tswitch (type)\n\t\t{\n\t\t    case DT_FIRST: cur_match = count - 1; break;\n\t\t    case DT_SELECT:\n\t\t    case DT_JUMP:\n#ifdef FEAT_CSCOPE\n\t\t    case DT_CSCOPE:\n#endif\n\t\t    case DT_LAST:  cur_match = MAXCOL - 1; break;\n\t\t    case DT_NEXT:  cur_match += count; break;\n\t\t    case DT_PREV:  cur_match -= count; break;\n\t\t}\n\t\tif (cur_match >= MAXCOL)\n\t\t    cur_match = MAXCOL - 1;\n\t\telse if (cur_match < 0)\n\t\t{\n\t\t    emsg(_(e_cannot_go_before_first_matching_tag));\n\t\t    skip_msg = TRUE;\n\t\t    cur_match = 0;\n\t\t    cur_fnum = curbuf->b_fnum;\n\t\t}\n\t    }\n\t}\n\n#if defined(FEAT_QUICKFIX)\n\tif (g_do_tagpreview != 0)\n\t{\n\t    if (type != DT_SELECT && type != DT_JUMP)\n\t    {\n\t\tptag_entry.cur_match = cur_match;\n\t\tptag_entry.cur_fnum = cur_fnum;\n\t    }\n\t}\n\telse\n#endif\n\t{\n\t    /*\n\t     * For \":tag [arg]\" or \":tselect\" remember position before the jump.\n\t     */\n\t    saved_fmark = tagstack[tagstackidx].fmark;\n\t    if (save_pos)\n\t    {\n\t\ttagstack[tagstackidx].fmark.mark = curwin->w_cursor;\n\t\ttagstack[tagstackidx].fmark.fnum = curbuf->b_fnum;\n\t    }\n\n\t    // Curwin will change in the call to jumpto_tag() if \":stag\" was\n\t    // used or an autocommand jumps to another window; store value of\n\t    // tagstackidx now.\n\t    curwin->w_tagstackidx = tagstackidx;\n\t    if (type != DT_SELECT && type != DT_JUMP)\n\t    {\n\t\tcurwin->w_tagstack[tagstackidx].cur_match = cur_match;\n\t\tcurwin->w_tagstack[tagstackidx].cur_fnum = cur_fnum;\n\t    }\n\t}\n    }\n\n    // When not using the current buffer get the name of buffer \"cur_fnum\".\n    // Makes sure that the tag order doesn't change when using a remembered\n    // position for \"cur_match\".\n    if (cur_fnum != curbuf->b_fnum)\n    {\n\tbuf_T *buf = buflist_findnr(cur_fnum);\n\n\tif (buf != NULL)\n\t    buf_ffname = buf->b_ffname;\n    }\n\n    /*\n     * Repeat searching for tags, when a file has not been found.\n     */\n    for (;;)\n    {\n\tint\tother_name;\n\tchar_u\t*name;\n\n\t/*\n\t * When desired match not found yet, try to find it (and others).\n\t */\n\tif (use_tagstack)\n\t{\n\t    // make a copy, the tagstack may change in 'tagfunc'\n\t    name = vim_strsave(tagstack[tagstackidx].tagname);\n\t    vim_free(tofree);\n\t    tofree = name;\n\t}\n#if defined(FEAT_QUICKFIX)\n\telse if (g_do_tagpreview != 0)\n\t    name = ptag_entry.tagname;\n#endif\n\telse\n\t    name = tag;\n\tother_name = (tagmatchname == NULL || STRCMP(tagmatchname, name) != 0);\n\tif (new_tag\n\t\t|| (cur_match >= num_matches && max_num_matches != MAXCOL)\n\t\t|| other_name)\n\t{\n\t    if (other_name)\n\t    {\n\t\tvim_free(tagmatchname);\n\t\ttagmatchname = vim_strsave(name);\n\t    }\n\n\t    if (type == DT_SELECT || type == DT_JUMP\n#if defined(FEAT_QUICKFIX)\n\t\t|| type == DT_LTAG\n#endif\n\t\t)\n\t\tcur_match = MAXCOL - 1;\n\t    if (type == DT_TAG)\n\t\tmax_num_matches = MAXCOL;\n\t    else\n\t\tmax_num_matches = cur_match + 1;\n\n\t    // when the argument starts with '/', use it as a regexp\n\t    if (!no_regexp && *name == '/')\n\t    {\n\t\tflags = TAG_REGEXP;\n\t\t++name;\n\t    }\n\t    else\n\t\tflags = TAG_NOIC;\n\n#ifdef FEAT_CSCOPE\n\t    if (type == DT_CSCOPE)\n\t\tflags = TAG_CSCOPE;\n#endif\n\t    if (verbose)\n\t\tflags |= TAG_VERBOSE;\n\n\t    if (!use_tfu)\n\t\tflags |= TAG_NO_TAGFUNC;\n\n\t    if (find_tags(name, &new_num_matches, &new_matches, flags,\n\t\t\t\t\t    max_num_matches, buf_ffname) == OK\n\t\t    && new_num_matches < max_num_matches)\n\t\tmax_num_matches = MAXCOL; // If less than max_num_matches\n\t\t\t\t\t  // found: all matches found.\n\n\t    // A tag function may do anything, which may cause various\n\t    // information to become invalid.  At least check for the tagstack\n\t    // to still be the same.\n\t    if (tagstack != curwin->w_tagstack)\n\t    {\n\t\temsg(_(e_window_unexpectedly_close_while_searching_for_tags));\n\t\tFreeWild(new_num_matches, new_matches);\n\t\tbreak;\n\t    }\n\n\t    // If there already were some matches for the same name, move them\n\t    // to the start.  Avoids that the order changes when using\n\t    // \":tnext\" and jumping to another file.\n\t    if (!new_tag && !other_name)\n\t    {\n\t\tint\t    j, k;\n\t\tint\t    idx = 0;\n\t\ttagptrs_T   tagp, tagp2;\n\n\t\t// Find the position of each old match in the new list.  Need\n\t\t// to use parse_match() to find the tag line.\n\t\tfor (j = 0; j < num_matches; ++j)\n\t\t{\n\t\t    parse_match(matches[j], &tagp);\n\t\t    for (i = idx; i < new_num_matches; ++i)\n\t\t    {\n\t\t\tparse_match(new_matches[i], &tagp2);\n\t\t\tif (STRCMP(tagp.tagname, tagp2.tagname) == 0)\n\t\t\t{\n\t\t\t    char_u *p = new_matches[i];\n\t\t\t    for (k = i; k > idx; --k)\n\t\t\t\tnew_matches[k] = new_matches[k - 1];\n\t\t\t    new_matches[idx++] = p;\n\t\t\t    break;\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\t    FreeWild(num_matches, matches);\n\t    num_matches = new_num_matches;\n\t    matches = new_matches;\n\t}\n\n\tif (num_matches <= 0)\n\t{\n\t    if (verbose)\n\t\tsemsg(_(e_tag_not_found_str), name);\n#if defined(FEAT_QUICKFIX)\n\t    g_do_tagpreview = 0;\n#endif\n\t}\n\telse\n\t{\n\t    int ask_for_selection = FALSE;\n\n#ifdef FEAT_CSCOPE\n\t    if (type == DT_CSCOPE && num_matches > 1)\n\t    {\n\t\tcs_print_tags();\n\t\task_for_selection = TRUE;\n\t    }\n\t    else\n#endif\n\t    if (type == DT_TAG && *tag != NUL)\n\t\t// If a count is supplied to the \":tag \" command, then\n\t\t// jump to count'th matching tag.\n\t\tcur_match = count > 0 ? count - 1 : 0;\n\t    else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1))\n\t    {\n\t\tprint_tag_list(new_tag, use_tagstack, num_matches, matches);\n\t\task_for_selection = TRUE;\n\t    }\n#if defined(FEAT_QUICKFIX) && defined(FEAT_EVAL)\n\t    else if (type == DT_LTAG)\n\t    {\n\t\tif (add_llist_tags(tag, num_matches, matches) == FAIL)\n\t\t    goto end_do_tag;\n\t\tcur_match = 0;\t\t// Jump to the first tag\n\t    }\n#endif\n\n\t    if (ask_for_selection == TRUE)\n\t    {\n\t\t/*\n\t\t * Ask to select a tag from the list.\n\t\t */\n\t\ti = prompt_for_number(NULL);\n\t\tif (i <= 0 || i > num_matches || got_int)\n\t\t{\n\t\t    // no valid choice: don't change anything\n\t\t    if (use_tagstack)\n\t\t    {\n\t\t\ttagstack[tagstackidx].fmark = saved_fmark;\n\t\t\ttagstackidx = prevtagstackidx;\n\t\t    }\n#ifdef FEAT_CSCOPE\n\t\t    cs_free_tags();\n\t\t    jumped_to_tag = TRUE;\n#endif\n\t\t    break;\n\t\t}\n\t\tcur_match = i - 1;\n\t    }\n\n\t    if (cur_match >= num_matches)\n\t    {\n\t\t// Avoid giving this error when a file wasn't found and we're\n\t\t// looking for a match in another file, which wasn't found.\n\t\t// There will be an emsg(\"file doesn't exist\") below then.\n\t\tif ((type == DT_NEXT || type == DT_FIRST)\n\t\t\t\t\t\t      && nofile_fname == NULL)\n\t\t{\n\t\t    if (num_matches == 1)\n\t\t\temsg(_(e_there_is_only_one_matching_tag));\n\t\t    else\n\t\t\temsg(_(e_cannot_go_beyond_last_matching_tag));\n\t\t    skip_msg = TRUE;\n\t\t}\n\t\tcur_match = num_matches - 1;\n\t    }\n\t    if (use_tagstack)\n\t    {\n\t\ttagptrs_T   tagp;\n\n\t\ttagstack[tagstackidx].cur_match = cur_match;\n\t\ttagstack[tagstackidx].cur_fnum = cur_fnum;\n\n\t\t// store user-provided data originating from tagfunc\n\t\tif (use_tfu && parse_match(matches[cur_match], &tagp) == OK\n\t\t\t&& tagp.user_data)\n\t\t{\n\t\t    VIM_CLEAR(tagstack[tagstackidx].user_data);\n\t\t    tagstack[tagstackidx].user_data = vim_strnsave(\n\t\t\t  tagp.user_data, tagp.user_data_end - tagp.user_data);\n\t\t}\n\n\t\t++tagstackidx;\n\t    }\n#if defined(FEAT_QUICKFIX)\n\t    else if (g_do_tagpreview != 0)\n\t    {\n\t\tptag_entry.cur_match = cur_match;\n\t\tptag_entry.cur_fnum = cur_fnum;\n\t    }\n#endif\n\n\t    /*\n\t     * Only when going to try the next match, report that the previous\n\t     * file didn't exist.  Otherwise an emsg() is given below.\n\t     */\n\t    if (nofile_fname != NULL && error_cur_match != cur_match)\n\t\tsmsg(_(\"File \\\"%s\\\" does not exist\"), nofile_fname);\n\n\n\t    ic = (matches[cur_match][0] & MT_IC_OFF);\n\t    if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP\n#ifdef FEAT_CSCOPE\n\t\t&& type != DT_CSCOPE\n#endif\n\t\t&& (num_matches > 1 || ic)\n\t\t&& !skip_msg)\n\t    {\n\t\t// Give an indication of the number of matching tags\n\t\tsprintf((char *)IObuff, _(\"tag %d of %d%s\"),\n\t\t\t\tcur_match + 1,\n\t\t\t\tnum_matches,\n\t\t\t\tmax_num_matches != MAXCOL ? _(\" or more\") : \"\");\n\t\tif (ic)\n\t\t    STRCAT(IObuff, _(\"  Using tag with different case!\"));\n\t\tif ((num_matches > prev_num_matches || new_tag)\n\t\t\t\t\t\t\t   && num_matches > 1)\n\t\t{\n\t\t    if (ic)\n\t\t\tmsg_attr((char *)IObuff, HL_ATTR(HLF_W));\n\t\t    else\n\t\t\tmsg((char *)IObuff);\n\t\t    msg_scroll = TRUE;\t// don't overwrite this message\n\t\t}\n\t\telse\n\t\t    give_warning(IObuff, ic);\n\t\tif (ic && !msg_scrolled && msg_silent == 0)\n\t\t{\n\t\t    out_flush();\n\t\t    ui_delay(1007L, TRUE);\n\t\t}\n\t    }\n\n#if defined(FEAT_EVAL)\n\t    // Let the SwapExists event know what tag we are jumping to.\n\t    vim_snprintf((char *)IObuff, IOSIZE, \":ta %s\\r\", name);\n\t    set_vim_var_string(VV_SWAPCOMMAND, IObuff, -1);\n#endif\n\n\t    /*\n\t     * Jump to the desired match.\n\t     */\n\t    i = jumpto_tag(matches[cur_match], forceit, type != DT_CSCOPE);\n\n#if defined(FEAT_EVAL)\n\t    set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);\n#endif\n\n\t    if (i == NOTAGFILE)\n\t    {\n\t\t// File not found: try again with another matching tag\n\t\tif ((type == DT_PREV && cur_match > 0)\n\t\t\t|| ((type == DT_TAG || type == DT_NEXT\n\t\t\t\t\t\t\t  || type == DT_FIRST)\n\t\t\t    && (max_num_matches != MAXCOL\n\t\t\t\t\t     || cur_match < num_matches - 1)))\n\t\t{\n\t\t    error_cur_match = cur_match;\n\t\t    if (use_tagstack)\n\t\t\t--tagstackidx;\n\t\t    if (type == DT_PREV)\n\t\t\t--cur_match;\n\t\t    else\n\t\t    {\n\t\t\ttype = DT_NEXT;\n\t\t\t++cur_match;\n\t\t    }\n\t\t    continue;\n\t\t}\n\t\tsemsg(_(e_file_str_does_not_exist), nofile_fname);\n\t    }\n\t    else\n\t    {\n\t\t// We may have jumped to another window, check that\n\t\t// tagstackidx is still valid.\n\t\tif (use_tagstack && tagstackidx > curwin->w_tagstacklen)\n\t\t    tagstackidx = curwin->w_tagstackidx;\n#ifdef FEAT_CSCOPE\n\t\tjumped_to_tag = TRUE;\n#endif\n\t    }\n\t}\n\tbreak;\n    }\n\nend_do_tag:\n    // Only store the new index when using the tagstack and it's valid.\n    if (use_tagstack && tagstackidx <= curwin->w_tagstacklen)\n\tcurwin->w_tagstackidx = tagstackidx;\n    postponed_split = 0;\t// don't split next time\n# ifdef FEAT_QUICKFIX\n    g_do_tagpreview = 0;\t// don't do tag preview next time\n# endif\n\n    vim_free(tofree);\n#ifdef FEAT_CSCOPE\n    return jumped_to_tag;\n#else\n    return FALSE;\n#endif\n}", "func_hash": 294928399408778524511468577192657953231, "file_name": "None", "file_hash": null, "cwe": ["CWE-416"], "cve": "CVE-2022-3134", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 9.0.0389.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3134"}
{"idx": 212436, "project": "linux", "commit_id": "30e29a9a2bc6a4888335a6ede968b75cd329657a", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/30e29a9a2bc6a4888335a6ede968b75cd329657a", "commit_message": "bpf: Fix integer overflow in prealloc_elems_and_freelist()\n\nIn prealloc_elems_and_freelist(), the multiplication to calculate the\nsize passed to bpf_map_area_alloc() could lead to an integer overflow.\nAs a result, out-of-bounds write could occur in pcpu_freelist_populate()\nas reported by KASAN:\n\n[...]\n[   16.968613] BUG: KASAN: slab-out-of-bounds in pcpu_freelist_populate+0xd9/0x100\n[   16.969408] Write of size 8 at addr ffff888104fc6ea0 by task crash/78\n[   16.970038]\n[   16.970195] CPU: 0 PID: 78 Comm: crash Not tainted 5.15.0-rc2+ #1\n[   16.970878] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1ubuntu1.1 04/01/2014\n[   16.972026] Call Trace:\n[   16.972306]  dump_stack_lvl+0x34/0x44\n[   16.972687]  print_address_description.constprop.0+0x21/0x140\n[   16.973297]  ? pcpu_freelist_populate+0xd9/0x100\n[   16.973777]  ? pcpu_freelist_populate+0xd9/0x100\n[   16.974257]  kasan_report.cold+0x7f/0x11b\n[   16.974681]  ? pcpu_freelist_populate+0xd9/0x100\n[   16.975190]  pcpu_freelist_populate+0xd9/0x100\n[   16.975669]  stack_map_alloc+0x209/0x2a0\n[   16.976106]  __sys_bpf+0xd83/0x2ce0\n[...]\n\nThe possibility of this overflow was originally discussed in [0], but\nwas overlooked.\n\nFix the integer overflow by changing elem_size to u64 from u32.\n\n  [0] https://lore.kernel.org/bpf/728b238e-a481-eb50-98e9-b0f430ab01e7@gmail.com/\n\nFixes: 557c0c6e7df8 (\"bpf: convert stackmap to pre-allocation\")\nSigned-off-by: Tatsuhiko Yasumatsu \nSigned-off-by: Daniel Borkmann \nLink: https://lore.kernel.org/bpf/20210930135545.173698-1-th.yasumatsu@gmail.com", "target": 1, "func": "static int prealloc_elems_and_freelist(struct bpf_stack_map *smap)\n{\n\tu32 elem_size = sizeof(struct stack_map_bucket) + smap->map.value_size;\n\tint err;\n\n\tsmap->elems = bpf_map_area_alloc(elem_size * smap->map.max_entries,\n\t\t\t\t\t smap->map.numa_node);\n\tif (!smap->elems)\n\t\treturn -ENOMEM;\n\n\terr = pcpu_freelist_init(&smap->freelist);\n\tif (err)\n\t\tgoto free_elems;\n\n\tpcpu_freelist_populate(&smap->freelist, smap->elems, elem_size,\n\t\t\t       smap->map.max_entries);\n\treturn 0;\n\nfree_elems:\n\tbpf_map_area_free(smap->elems);\n\treturn err;\n}", "func_hash": 178134261771669129761013963339102987528, "file_name": "stackmap.c", "file_hash": 212947868785159241816012605096544782433, "cwe": ["CWE-787"], "cve": "CVE-2021-41864", "cve_desc": "prealloc_elems_and_freelist in kernel/bpf/stackmap.c in the Linux kernel before 5.14.12 allows unprivileged users to trigger an eBPF multiplication integer overflow with a resultant out-of-bounds write.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41864"}
{"idx": 459524, "project": "linux", "commit_id": "30e29a9a2bc6a4888335a6ede968b75cd329657a", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/30e29a9a2bc6a4888335a6ede968b75cd329657a", "commit_message": "bpf: Fix integer overflow in prealloc_elems_and_freelist()\n\nIn prealloc_elems_and_freelist(), the multiplication to calculate the\nsize passed to bpf_map_area_alloc() could lead to an integer overflow.\nAs a result, out-of-bounds write could occur in pcpu_freelist_populate()\nas reported by KASAN:\n\n[...]\n[   16.968613] BUG: KASAN: slab-out-of-bounds in pcpu_freelist_populate+0xd9/0x100\n[   16.969408] Write of size 8 at addr ffff888104fc6ea0 by task crash/78\n[   16.970038]\n[   16.970195] CPU: 0 PID: 78 Comm: crash Not tainted 5.15.0-rc2+ #1\n[   16.970878] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1ubuntu1.1 04/01/2014\n[   16.972026] Call Trace:\n[   16.972306]  dump_stack_lvl+0x34/0x44\n[   16.972687]  print_address_description.constprop.0+0x21/0x140\n[   16.973297]  ? pcpu_freelist_populate+0xd9/0x100\n[   16.973777]  ? pcpu_freelist_populate+0xd9/0x100\n[   16.974257]  kasan_report.cold+0x7f/0x11b\n[   16.974681]  ? pcpu_freelist_populate+0xd9/0x100\n[   16.975190]  pcpu_freelist_populate+0xd9/0x100\n[   16.975669]  stack_map_alloc+0x209/0x2a0\n[   16.976106]  __sys_bpf+0xd83/0x2ce0\n[...]\n\nThe possibility of this overflow was originally discussed in [0], but\nwas overlooked.\n\nFix the integer overflow by changing elem_size to u64 from u32.\n\n  [0] https://lore.kernel.org/bpf/728b238e-a481-eb50-98e9-b0f430ab01e7@gmail.com/\n\nFixes: 557c0c6e7df8 (\"bpf: convert stackmap to pre-allocation\")\nSigned-off-by: Tatsuhiko Yasumatsu \nSigned-off-by: Daniel Borkmann \nLink: https://lore.kernel.org/bpf/20210930135545.173698-1-th.yasumatsu@gmail.com", "target": 0, "func": "static int prealloc_elems_and_freelist(struct bpf_stack_map *smap)\n{\n\tu64 elem_size = sizeof(struct stack_map_bucket) +\n\t\t\t(u64)smap->map.value_size;\n\tint err;\n\n\tsmap->elems = bpf_map_area_alloc(elem_size * smap->map.max_entries,\n\t\t\t\t\t smap->map.numa_node);\n\tif (!smap->elems)\n\t\treturn -ENOMEM;\n\n\terr = pcpu_freelist_init(&smap->freelist);\n\tif (err)\n\t\tgoto free_elems;\n\n\tpcpu_freelist_populate(&smap->freelist, smap->elems, elem_size,\n\t\t\t       smap->map.max_entries);\n\treturn 0;\n\nfree_elems:\n\tbpf_map_area_free(smap->elems);\n\treturn err;\n}", "func_hash": 247842121005492107026661682297731302199, "file_name": "stackmap.c", "file_hash": 198452357082465344097055898312719400384, "cwe": ["CWE-787"], "cve": "CVE-2021-41864", "cve_desc": "prealloc_elems_and_freelist in kernel/bpf/stackmap.c in the Linux kernel before 5.14.12 allows unprivileged users to trigger an eBPF multiplication integer overflow with a resultant out-of-bounds write.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41864"}
{"idx": 212818, "project": "pjproject", "commit_id": "15663e3f37091069b8c98a7fce680dc04bc8e865", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/15663e3f37091069b8c98a7fce680dc04bc8e865", "commit_message": "Merge pull request from GHSA-2qpg-f6wf-w984", "target": 1, "func": "static pj_status_t decode_errcode_attr(pj_pool_t *pool, \n\t\t\t\t       const pj_uint8_t *buf,\n\t\t\t\t       const pj_stun_msg_hdr *msghdr, \n\t\t\t\t       void **p_attr)\n{\n    pj_stun_errcode_attr *attr;\n    pj_str_t value;\n\n    PJ_UNUSED_ARG(msghdr);\n\n    /* Create the attribute */\n    attr = PJ_POOL_ZALLOC_T(pool, pj_stun_errcode_attr);\n    GETATTRHDR(buf, &attr->hdr);\n\n    attr->err_code = buf[6] * 100 + buf[7];\n\n    /* Get pointer to the string in the message */\n    value.ptr = ((char*)buf + ATTR_HDR_LEN + 4);\n    value.slen = attr->hdr.length - 4;\n\n    /* Copy the string to the attribute */\n    pj_strdup(pool, &attr->reason, &value);\n\n    /* Done */\n    *p_attr = attr;\n\n    return PJ_SUCCESS;\n}", "func_hash": 82181264062889236862873379634797479013, "file_name": "None", "file_hash": null, "cwe": ["CWE-191"], "cve": "CVE-2021-37706", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In affected versions if the incoming STUN message contains an ERROR-CODE attribute, the header length is not checked before performing a subtraction operation, potentially resulting in an integer underflow scenario. This issue affects all users that use STUN. A malicious actor located within the victim\u2019s network may forge and send a specially crafted UDP (STUN) message that could remotely execute arbitrary code on the victim\u2019s machine. Users are advised to upgrade as soon as possible. There are no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37706"}
{"idx": 462278, "project": "pjproject", "commit_id": "15663e3f37091069b8c98a7fce680dc04bc8e865", "project_url": "https://github.com/pjsip/pjproject", "commit_url": "https://github.com/pjsip/pjproject/commit/15663e3f37091069b8c98a7fce680dc04bc8e865", "commit_message": "Merge pull request from GHSA-2qpg-f6wf-w984", "target": 0, "func": "static pj_status_t decode_errcode_attr(pj_pool_t *pool, \n\t\t\t\t       const pj_uint8_t *buf,\n\t\t\t\t       const pj_stun_msg_hdr *msghdr, \n\t\t\t\t       void **p_attr)\n{\n    pj_stun_errcode_attr *attr;\n    pj_str_t value;\n\n    PJ_UNUSED_ARG(msghdr);\n\n    /* Create the attribute */\n    attr = PJ_POOL_ZALLOC_T(pool, pj_stun_errcode_attr);\n    GETATTRHDR(buf, &attr->hdr);\n\n    attr->err_code = buf[6] * 100 + buf[7];\n\n    /* Get pointer to the string in the message */\n    value.ptr = ((char*)buf + ATTR_HDR_LEN + 4);\n    value.slen = attr->hdr.length - 4;\n    /* Make sure the length is never negative */\n    if (value.slen < 0)\n    \tvalue.slen = 0;\n\n    /* Copy the string to the attribute */\n    pj_strdup(pool, &attr->reason, &value);\n\n    /* Done */\n    *p_attr = attr;\n\n    return PJ_SUCCESS;\n}", "func_hash": 288158129212060678092169077807436012711, "file_name": "None", "file_hash": null, "cwe": ["CWE-191"], "cve": "CVE-2021-37706", "cve_desc": "PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In affected versions if the incoming STUN message contains an ERROR-CODE attribute, the header length is not checked before performing a subtraction operation, potentially resulting in an integer underflow scenario. This issue affects all users that use STUN. A malicious actor located within the victim\u2019s network may forge and send a specially crafted UDP (STUN) message that could remotely execute arbitrary code on the victim\u2019s machine. Users are advised to upgrade as soon as possible. There are no known workarounds.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37706"}
{"idx": 212822, "project": "ghostpdl", "commit_id": "e1134d375e2ca176068e19a2aa9b040baffe1c22", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=e1134d375e2ca176068e19a2aa9b040baffe1c22", "commit_message": "Bug 705156(1): Avoid double free of PCL error buffer", "target": 1, "func": "pcl_status_read(byte * data, uint max_data, pcl_state_t * pcs)\n{\n    uint count = min(max_data,\n                     pcs->status.write_pos - pcs->status.read_pos);\n\n    if (count)\n        memcpy(data, pcs->status.buffer + pcs->status.read_pos, count);\n    pcs->status.read_pos += count;\n    if (pcs->status.read_pos == pcs->status.write_pos) {\n        gs_free_object(pcs->memory, pcs->status.buffer, \"status buffer\");\n        pcs->status.write_pos = pcs->status.read_pos = 0;\n    }\n    return count;\n}", "func_hash": 16750323744555373538118400797572057026, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-1350", "cve_desc": "A vulnerability classified as problematic was found in GhostPCL 9.55.0. This vulnerability affects the function chunk_free_object of the file gsmchunk.c. The manipulation with a malicious file leads to a memory corruption. The attack can be initiated remotely but requires user interaction. The exploit has been disclosed to the public as a POC and may be used. It is recommended to apply the patches to fix this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1350"}
{"idx": 462316, "project": "ghostpdl", "commit_id": "e1134d375e2ca176068e19a2aa9b040baffe1c22", "project_url": "https://github.com/ArtifexSoftware/ghostpdl", "commit_url": "http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=e1134d375e2ca176068e19a2aa9b040baffe1c22", "commit_message": "Bug 705156(1): Avoid double free of PCL error buffer", "target": 0, "func": "pcl_status_read(byte * data, uint max_data, pcl_state_t * pcs)\n{\n    uint count = min(max_data,\n                     pcs->status.write_pos - pcs->status.read_pos);\n\n    if (count)\n        memcpy(data, pcs->status.buffer + pcs->status.read_pos, count);\n    pcs->status.read_pos += count;\n    if (pcs->status.read_pos == pcs->status.write_pos) {\n        gs_free_object(pcs->memory, pcs->status.buffer, \"status buffer\");\n        pcs->status.buffer = NULL;\n        pcs->status.write_pos = pcs->status.read_pos = 0;\n    }\n    return count;\n}", "func_hash": 64666065290032911431051417469693013930, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-1350", "cve_desc": "A vulnerability classified as problematic was found in GhostPCL 9.55.0. This vulnerability affects the function chunk_free_object of the file gsmchunk.c. The manipulation with a malicious file leads to a memory corruption. The attack can be initiated remotely but requires user interaction. The exploit has been disclosed to the public as a POC and may be used. It is recommended to apply the patches to fix this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1350"}
{"idx": 212829, "project": "php-src", "commit_id": "698a691724c0a949295991e5df091ce16f899e02", "project_url": "https://github.com/php/php-src", "commit_url": "https://github.com/php/php-src/commit/698a691724c0a949295991e5df091ce16f899e02?w=1", "commit_message": "Fix bug #72750: wddx_deserialize null dereference", "target": 1, "func": " */\nstatic void php_wddx_pop_element(void *user_data, const XML_Char *name)\n{\n\tst_entry \t\t\t*ent1, *ent2;\n\twddx_stack \t\t\t*stack = (wddx_stack *)user_data;\n\tHashTable \t\t\t*target_hash;\n\tzend_class_entry \t**pce;\n\tzval\t\t\t\t*obj;\n\tzval\t\t\t\t*tmp;\n\tTSRMLS_FETCH();\n\n/* OBJECTS_FIXME */\n\tif (stack->top == 0) {\n\t\treturn;\n\t}\n\n\tif (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||\n\t\t!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||\n\t  \t!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||\n\t\t!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||\n\t\t!strcmp(name, EL_DATETIME)) {\n\t\twddx_stack_top(stack, (void**)&ent1);\n\n\t\tif (!ent1->data) {\n\t\t\tif (stack->top > 1) {\n\t\t\t\tstack->top--;\n\t\t\t} else {\n\t\t\t\tstack->done = 1;\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!strcmp(name, EL_BINARY)) {\n\t\t\tint new_len=0;\n\t\t\tunsigned char *new_str;\n\n\t\t\tnew_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);\n\t\t\tSTR_FREE(Z_STRVAL_P(ent1->data));\n\t\t\tZ_STRVAL_P(ent1->data) = new_str;\n\t\t\tZ_STRLEN_P(ent1->data) = new_len;\n\t\t}\n\n\t\t/* Call __wakeup() method on the object. */\n\t\tif (Z_TYPE_P(ent1->data) == IS_OBJECT) {\n\t\t\tzval *fname, *retval = NULL;\n\n\t\t\tMAKE_STD_ZVAL(fname);\n\t\t\tZVAL_STRING(fname, \"__wakeup\", 1);\n\n\t\t\tcall_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);\n\n\t\t\tzval_dtor(fname);\n\t\t\tFREE_ZVAL(fname);\n\t\t\tif (retval) {\n\t\t\t\tzval_ptr_dtor(&retval);\n\t\t\t}\n\t\t}\n\n\t\tif (stack->top > 1) {\n\t\t\tstack->top--;\n\t\t\twddx_stack_top(stack, (void**)&ent2);\n\n\t\t\t/* if non-existent field */\n\t\t\tif (ent2->type == ST_FIELD && ent2->data == NULL) {\n\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\tefree(ent1);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {\n\t\t\t\ttarget_hash = HASH_OF(ent2->data);\n\n\t\t\t\tif (ent1->varname) {\n\t\t\t\t\tif (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&\n\t\t\t\t\t\tZ_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&\n\t\t\t\t\t\tent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {\n\t\t\t\t\t\tzend_bool incomplete_class = 0;\n\n\t\t\t\t\t\tzend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n\t\t\t\t\t\tif (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),\n\t\t\t\t\t\t\t\t\t\t   Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {\n\t\t\t\t\t\t\tincomplete_class = 1;\n\t\t\t\t\t\t\tpce = &PHP_IC_ENTRY;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Initialize target object */\n\t\t\t\t\t\tMAKE_STD_ZVAL(obj);\n\t\t\t\t\t\tobject_init_ex(obj, *pce);\n\n\t\t\t\t\t\t/* Merge current hashtable with object's default properties */\n\t\t\t\t\t\tzend_hash_merge(Z_OBJPROP_P(obj),\n\t\t\t\t\t\t\t\t\t\tZ_ARRVAL_P(ent2->data),\n\t\t\t\t\t\t\t\t\t\t(void (*)(void *)) zval_add_ref,\n\t\t\t\t\t\t\t\t\t\t(void *) &tmp, sizeof(zval *), 0);\n\n\t\t\t\t\t\tif (incomplete_class) {\n\t\t\t\t\t\t\tphp_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Clean up old array entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent2->data);\n\n\t\t\t\t\t\t/* Set stack entry to point to the newly created object */\n\t\t\t\t\t\tent2->data = obj;\n\n\t\t\t\t\t\t/* Clean up class name var entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\t\t} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {\n\t\t\t\t\t\tzend_class_entry *old_scope = EG(scope);\n\n\t\t\t\t\t\tEG(scope) = Z_OBJCE_P(ent2->data);\n\t\t\t\t\t\tZ_DELREF_P(ent1->data);\n\t\t\t\t\t\tadd_property_zval(ent2->data, ent1->varname, ent1->data);\n\t\t\t\t\t\tEG(scope) = old_scope;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tzend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);\n\t\t\t\t\t}\n\t\t\t\t\tefree(ent1->varname);\n\t\t\t\t} else\t{\n\t\t\t\t\tzend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);\n\t\t\t\t}\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t} else {\n\t\t\tstack->done = 1;\n\t\t}\n\t} else if (!strcmp(name, EL_VAR) && stack->varname) {\n\t\tefree(stack->varname);\n\t\tstack->varname = NULL;\n\t} else if (!strcmp(name, EL_FIELD)) {\n\t\tst_entry *ent;\n\t\twddx_stack_top(stack, (void **)&ent);\n\t\tefree(ent);\n\t\tstack->top--;\n\t}", "func_hash": 256847714577175382991355330020307438516, "file_name": "wddx.c", "file_hash": 145600633466725124063532436200225083004, "cwe": ["CWE-476"], "cve": "CVE-2016-7130", "cve_desc": "The php_wddx_pop_element function in ext/wddx/wddx.c in PHP before 5.6.25 and 7.x before 7.0.10 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) or possibly have unspecified other impact via an invalid base64 binary value, as demonstrated by a wddx_deserialize call that mishandles a binary element in a wddxPacket XML document.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-7130"}
{"idx": 462395, "project": "php-src", "commit_id": "698a691724c0a949295991e5df091ce16f899e02", "project_url": "https://github.com/php/php-src", "commit_url": "https://github.com/php/php-src/commit/698a691724c0a949295991e5df091ce16f899e02?w=1", "commit_message": "Fix bug #72750: wddx_deserialize null dereference", "target": 0, "func": " */\nstatic void php_wddx_pop_element(void *user_data, const XML_Char *name)\n{\n\tst_entry \t\t\t*ent1, *ent2;\n\twddx_stack \t\t\t*stack = (wddx_stack *)user_data;\n\tHashTable \t\t\t*target_hash;\n\tzend_class_entry \t**pce;\n\tzval\t\t\t\t*obj;\n\tzval\t\t\t\t*tmp;\n\tTSRMLS_FETCH();\n\n/* OBJECTS_FIXME */\n\tif (stack->top == 0) {\n\t\treturn;\n\t}\n\n\tif (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||\n\t\t!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||\n\t  \t!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||\n\t\t!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||\n\t\t!strcmp(name, EL_DATETIME)) {\n\t\twddx_stack_top(stack, (void**)&ent1);\n\n\t\tif (!ent1->data) {\n\t\t\tif (stack->top > 1) {\n\t\t\t\tstack->top--;\n\t\t\t} else {\n\t\t\t\tstack->done = 1;\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!strcmp(name, EL_BINARY)) {\n\t\t\tint new_len=0;\n\t\t\tunsigned char *new_str;\n\n\t\t\tnew_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);\n\t\t\tSTR_FREE(Z_STRVAL_P(ent1->data));\n\t\t\tif (new_str) {\n\t\t\t\tZ_STRVAL_P(ent1->data) = new_str;\n\t\t\t\tZ_STRLEN_P(ent1->data) = new_len;\n\t\t\t} else {\n\t\t\t\tZVAL_EMPTY_STRING(ent1->data);\n\t\t\t}\n\t\t}\n\n\t\t/* Call __wakeup() method on the object. */\n\t\tif (Z_TYPE_P(ent1->data) == IS_OBJECT) {\n\t\t\tzval *fname, *retval = NULL;\n\n\t\t\tMAKE_STD_ZVAL(fname);\n\t\t\tZVAL_STRING(fname, \"__wakeup\", 1);\n\n\t\t\tcall_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);\n\n\t\t\tzval_dtor(fname);\n\t\t\tFREE_ZVAL(fname);\n\t\t\tif (retval) {\n\t\t\t\tzval_ptr_dtor(&retval);\n\t\t\t}\n\t\t}\n\n\t\tif (stack->top > 1) {\n\t\t\tstack->top--;\n\t\t\twddx_stack_top(stack, (void**)&ent2);\n\n\t\t\t/* if non-existent field */\n\t\t\tif (ent2->type == ST_FIELD && ent2->data == NULL) {\n\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\tefree(ent1);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {\n\t\t\t\ttarget_hash = HASH_OF(ent2->data);\n\n\t\t\t\tif (ent1->varname) {\n\t\t\t\t\tif (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&\n\t\t\t\t\t\tZ_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&\n\t\t\t\t\t\tent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {\n\t\t\t\t\t\tzend_bool incomplete_class = 0;\n\n\t\t\t\t\t\tzend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n\t\t\t\t\t\tif (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),\n\t\t\t\t\t\t\t\t\t\t   Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {\n\t\t\t\t\t\t\tincomplete_class = 1;\n\t\t\t\t\t\t\tpce = &PHP_IC_ENTRY;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Initialize target object */\n\t\t\t\t\t\tMAKE_STD_ZVAL(obj);\n\t\t\t\t\t\tobject_init_ex(obj, *pce);\n\n\t\t\t\t\t\t/* Merge current hashtable with object's default properties */\n\t\t\t\t\t\tzend_hash_merge(Z_OBJPROP_P(obj),\n\t\t\t\t\t\t\t\t\t\tZ_ARRVAL_P(ent2->data),\n\t\t\t\t\t\t\t\t\t\t(void (*)(void *)) zval_add_ref,\n\t\t\t\t\t\t\t\t\t\t(void *) &tmp, sizeof(zval *), 0);\n\n\t\t\t\t\t\tif (incomplete_class) {\n\t\t\t\t\t\t\tphp_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Clean up old array entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent2->data);\n\n\t\t\t\t\t\t/* Set stack entry to point to the newly created object */\n\t\t\t\t\t\tent2->data = obj;\n\n\t\t\t\t\t\t/* Clean up class name var entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\t\t} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {\n\t\t\t\t\t\tzend_class_entry *old_scope = EG(scope);\n\n\t\t\t\t\t\tEG(scope) = Z_OBJCE_P(ent2->data);\n\t\t\t\t\t\tZ_DELREF_P(ent1->data);\n\t\t\t\t\t\tadd_property_zval(ent2->data, ent1->varname, ent1->data);\n\t\t\t\t\t\tEG(scope) = old_scope;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tzend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);\n\t\t\t\t\t}\n\t\t\t\t\tefree(ent1->varname);\n\t\t\t\t} else\t{\n\t\t\t\t\tzend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);\n\t\t\t\t}\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t} else {\n\t\t\tstack->done = 1;\n\t\t}\n\t} else if (!strcmp(name, EL_VAR) && stack->varname) {\n\t\tefree(stack->varname);\n\t\tstack->varname = NULL;\n\t} else if (!strcmp(name, EL_FIELD)) {\n\t\tst_entry *ent;\n\t\twddx_stack_top(stack, (void **)&ent);\n\t\tefree(ent);\n\t\tstack->top--;\n\t}", "func_hash": 281846366232469448026733489364664016551, "file_name": "wddx.c", "file_hash": 180653157857930473406661829830823818897, "cwe": ["CWE-476"], "cve": "CVE-2016-7130", "cve_desc": "The php_wddx_pop_element function in ext/wddx/wddx.c in PHP before 5.6.25 and 7.x before 7.0.10 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) or possibly have unspecified other impact via an invalid base64 binary value, as demonstrated by a wddx_deserialize call that mishandles a binary element in a wddxPacket XML document.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-7130"}
{"idx": 212834, "project": "rsyslog", "commit_id": "0381a0de64a5a048c3d48b79055bd9848d0c7fc2", "project_url": "https://github.com/rsyslog/rsyslog", "commit_url": "https://github.com/rsyslog/rsyslog/commit/0381a0de64a5a048c3d48b79055bd9848d0c7fc2", "commit_message": "imptcp: fix Segmentation Fault when octet count is to high", "target": 1, "func": "processDataRcvd(ptcpsess_t *const __restrict__ pThis,\n\tchar **buff,\n\tconst int buffLen,\n\tstruct syslogTime *stTime,\n\tconst time_t ttGenTime,\n\tmulti_submit_t *pMultiSub,\n\tunsigned *const __restrict__ pnMsgs)\n{\n\tDEFiRet;\n\tchar c = **buff;\n\tint octatesToCopy, octatesToDiscard;\n\n\tif(pThis->inputState == eAtStrtFram) {\n\t\tif(pThis->bSuppOctetFram && isdigit((int) c)) {\n\t\t\tpThis->inputState = eInOctetCnt;\n\t\t\tpThis->iOctetsRemain = 0;\n\t\t\tpThis->eFraming = TCP_FRAMING_OCTET_COUNTING;\n\t\t} else if(pThis->bSPFramingFix && c == ' ') {\n\t\t\t/* Cisco very occasionally sends a SP after a LF, which\n\t\t\t * thrashes framing if not taken special care of. Here,\n\t\t\t * we permit space *in front of the next frame* and\n\t\t\t * ignore it.\n\t\t\t */\n\t\t\t FINALIZE;\n\t\t} else {\n\t\t\tpThis->inputState = eInMsg;\n\t\t\tpThis->eFraming = TCP_FRAMING_OCTET_STUFFING;\n\t\t}\n\t}\n\n\tif(pThis->inputState == eInOctetCnt) {\n\t\tif(isdigit(c)) {\n\t\t\tpThis->iOctetsRemain = pThis->iOctetsRemain * 10 + c - '0';\n\t\t} else { /* done with the octet count, so this must be the SP terminator */\n\t\t\tDBGPRINTF(\"TCP Message with octet-counter, size %d.\\n\", pThis->iOctetsRemain);\n\t\t\tif(c != ' ') {\n\t\t\t\terrmsg.LogError(0, NO_ERRCODE, \"Framing Error in received TCP message: \"\n\t\t\t\t\t    \"delimiter is not SP but has ASCII value %d.\", c);\n\t\t\t}\n\t\t\tif(pThis->iOctetsRemain < 1) {\n\t\t\t\t/* TODO: handle the case where the octet count is 0! */\n\t\t\t\tDBGPRINTF(\"Framing Error: invalid octet count\\n\");\n\t\t\t\terrmsg.LogError(0, NO_ERRCODE, \"Framing Error in received TCP message: \"\n\t\t\t\t\t    \"invalid octet count %d.\", pThis->iOctetsRemain);\n\t\t\t} else if(pThis->iOctetsRemain > iMaxLine) {\n\t\t\t\t/* while we can not do anything against it, we can at least log an indication\n\t\t\t\t * that something went wrong) -- rgerhards, 2008-03-14\n\t\t\t\t */\n\t\t\t\tDBGPRINTF(\"truncating message with %d octets - max msg size is %d\\n\",\n\t\t\t\t\t  pThis->iOctetsRemain, iMaxLine);\n\t\t\t\terrmsg.LogError(0, NO_ERRCODE, \"received oversize message: size is %d bytes, \"\n\t\t\t\t\t        \"max msg size is %d, truncating...\", pThis->iOctetsRemain, iMaxLine);\n\t\t\t}\n\t\t\tpThis->inputState = eInMsg;\n\t\t}\n\t} else {\n\t\tassert(pThis->inputState == eInMsg);\n\n\t\tif (pThis->eFraming == TCP_FRAMING_OCTET_STUFFING) {\n\t\t\tif(pThis->iMsg >= iMaxLine) {\n\t\t\t\t/* emergency, we now need to flush, no matter if we are at end of message or not... */\n\t\t\t\tint i = 1;\n\t\t\t\tchar currBuffChar;\n\t\t\t\twhile(i < buffLen && ((currBuffChar = (*buff)[i]) != '\\n'\n\t\t\t\t\t&& (pThis->pLstn->pSrv->iAddtlFrameDelim == TCPSRV_NO_ADDTL_DELIMITER\n\t\t\t\t\t\t|| currBuffChar != pThis->pLstn->pSrv->iAddtlFrameDelim))) {\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tLogError(0, NO_ERRCODE, \"error: message received is at least %d byte larger than max msg\"\n\t\t\t\t\t\" size; message will be split starting at: \\\"%.*s\\\"\\n\", i, (i < 32) ? i : 32, *buff);\n\t\t\t\tdoSubmitMsg(pThis, stTime, ttGenTime, pMultiSub);\n\t\t\t\t++(*pnMsgs);\n\t\t\t\t/* we might think if it is better to ignore the rest of the\n\t\t\t\t * message than to treat it as a new one. Maybe this is a good\n\t\t\t\t * candidate for a configuration parameter...\n\t\t\t\t * rgerhards, 2006-12-04\n\t\t\t\t */\n\t\t\t}\n\n\t\t\tif ((c == '\\n')\n\t\t\t\t   || ((pThis->pLstn->pSrv->iAddtlFrameDelim != TCPSRV_NO_ADDTL_DELIMITER)\n\t\t\t\t\t   && (c == pThis->pLstn->pSrv->iAddtlFrameDelim))\n\t\t\t\t   ) { /* record delimiter? */\n\t\t\t\tdoSubmitMsg(pThis, stTime, ttGenTime, pMultiSub);\n\t\t\t\t++(*pnMsgs);\n\t\t\t\tpThis->inputState = eAtStrtFram;\n\t\t\t} else {\n\t\t\t\t/* IMPORTANT: here we copy the actual frame content to the message - for BOTH framing modes!\n\t\t\t\t * If we have a message that is larger than the max msg size, we truncate it. This is the best\n\t\t\t\t * we can do in light of what the engine supports. -- rgerhards, 2008-03-14\n\t\t\t\t */\n\t\t\t\tif(pThis->iMsg < iMaxLine) {\n\t\t\t\t\t*(pThis->pMsg + pThis->iMsg++) = c;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tassert(pThis->eFraming == TCP_FRAMING_OCTET_COUNTING);\n\t\t\toctatesToCopy = pThis->iOctetsRemain;\n\t\t\toctatesToDiscard = 0;\n\t\t\tif (buffLen < octatesToCopy) {\n\t\t\t\toctatesToCopy = buffLen;\n\t\t\t}\n\t\t\tif (octatesToCopy + pThis->iMsg > iMaxLine) {\n\t\t\t\toctatesToDiscard = octatesToCopy - (iMaxLine - pThis->iMsg);\n\t\t\t\toctatesToCopy = iMaxLine - pThis->iMsg;\n\t\t\t}\n\n\t\t\tmemcpy(pThis->pMsg + pThis->iMsg, *buff, octatesToCopy);\n\t\t\tpThis->iMsg += octatesToCopy;\n\t\t\tpThis->iOctetsRemain -= (octatesToCopy + octatesToDiscard);\n\t\t\t*buff += (octatesToCopy + octatesToDiscard - 1);\n\t\t\tif (pThis->iOctetsRemain == 0) {\n\t\t\t\t/* we have end of frame! */\n\t\t\t\tdoSubmitMsg(pThis, stTime, ttGenTime, pMultiSub);\n\t\t\t\t++(*pnMsgs);\n\t\t\t\tpThis->inputState = eAtStrtFram;\n\t\t\t}\n\t\t}\n\n\t}\n\nfinalize_it:\n\tRETiRet;\n}", "func_hash": 175845780697344678841951403700990960175, "file_name": "imptcp.c", "file_hash": 66608949268386945207139768258979939814, "cwe": ["CWE-190"], "cve": "CVE-2018-16881", "cve_desc": "A denial of service vulnerability was found in rsyslog in the imptcp module. An attacker could send a specially crafted message to the imptcp socket, which would cause rsyslog to crash. Versions before 8.27.0 are vulnerable.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-16881"}
{"idx": 462409, "project": "rsyslog", "commit_id": "0381a0de64a5a048c3d48b79055bd9848d0c7fc2", "project_url": "https://github.com/rsyslog/rsyslog", "commit_url": "https://github.com/rsyslog/rsyslog/commit/0381a0de64a5a048c3d48b79055bd9848d0c7fc2", "commit_message": "imptcp: fix Segmentation Fault when octet count is to high", "target": 0, "func": "processDataRcvd(ptcpsess_t *const __restrict__ pThis,\n\tchar **buff,\n\tconst int buffLen,\n\tstruct syslogTime *stTime,\n\tconst time_t ttGenTime,\n\tmulti_submit_t *pMultiSub,\n\tunsigned *const __restrict__ pnMsgs)\n{\n\tDEFiRet;\n\tchar c = **buff;\n\tint octatesToCopy, octatesToDiscard;\n\n\tif(pThis->inputState == eAtStrtFram) {\n\t\tif(pThis->bSuppOctetFram && isdigit((int) c)) {\n\t\t\tpThis->inputState = eInOctetCnt;\n\t\t\tpThis->iOctetsRemain = 0;\n\t\t\tpThis->eFraming = TCP_FRAMING_OCTET_COUNTING;\n\t\t} else if(pThis->bSPFramingFix && c == ' ') {\n\t\t\t/* Cisco very occasionally sends a SP after a LF, which\n\t\t\t * thrashes framing if not taken special care of. Here,\n\t\t\t * we permit space *in front of the next frame* and\n\t\t\t * ignore it.\n\t\t\t */\n\t\t\t FINALIZE;\n\t\t} else {\n\t\t\tpThis->inputState = eInMsg;\n\t\t\tpThis->eFraming = TCP_FRAMING_OCTET_STUFFING;\n\t\t}\n\t}\n\n\tif(pThis->inputState == eInOctetCnt) {\n\t\tif(isdigit(c)) {\n\t\t\tif(pThis->iOctetsRemain <= 200000000) {\n\t\t\t\tpThis->iOctetsRemain = pThis->iOctetsRemain * 10 + c - '0';\n\t\t\t} else {\n\t\t\t\terrmsg.LogError(0, NO_ERRCODE, \"Framing Error in received TCP message: \"\n\t\t\t\t\t\t\"frame too large (at least %d%c), change to octet stuffing\",\n\t\t\t\t\t\tpThis->iOctetsRemain, c);\n\t\t\t\tpThis->eFraming = TCP_FRAMING_OCTET_STUFFING;\n\t\t\t\tpThis->inputState = eInMsg;\n\t\t\t}\n\t\t\t*(pThis->pMsg + pThis->iMsg++) = c;\n\t\t} else { /* done with the octet count, so this must be the SP terminator */\n\t\t\tDBGPRINTF(\"TCP Message with octet-counter, size %d.\\n\", pThis->iOctetsRemain);\n\t\t\tif(c != ' ') {\n\t\t\t\terrmsg.LogError(0, NO_ERRCODE, \"Framing Error in received TCP message: \"\n\t\t\t\t\t    \"delimiter is not SP but has ASCII value %d.\", c);\n\t\t\t}\n\t\t\tif(pThis->iOctetsRemain < 1) {\n\t\t\t\t/* TODO: handle the case where the octet count is 0! */\n\t\t\t\terrmsg.LogError(0, NO_ERRCODE, \"Framing Error in received TCP message: \"\n\t\t\t\t\t    \"invalid octet count %d.\", pThis->iOctetsRemain);\n\t\t\t\tpThis->eFraming = TCP_FRAMING_OCTET_STUFFING;\n\t\t\t} else if(pThis->iOctetsRemain > iMaxLine) {\n\t\t\t\t/* while we can not do anything against it, we can at least log an indication\n\t\t\t\t * that something went wrong) -- rgerhards, 2008-03-14\n\t\t\t\t */\n\t\t\t\tDBGPRINTF(\"truncating message with %d octets - max msg size is %d\\n\",\n\t\t\t\t\t  pThis->iOctetsRemain, iMaxLine);\n\t\t\t\terrmsg.LogError(0, NO_ERRCODE, \"received oversize message: size is %d bytes, \"\n\t\t\t\t\t        \"max msg size is %d, truncating...\", pThis->iOctetsRemain, iMaxLine);\n\t\t\t}\n\t\t\tpThis->inputState = eInMsg;\n\t\t\tpThis->iMsg = 0;\n\t\t}\n\t} else {\n\t\tassert(pThis->inputState == eInMsg);\n\n\t\tif (pThis->eFraming == TCP_FRAMING_OCTET_STUFFING) {\n\t\t\tif(pThis->iMsg >= iMaxLine) {\n\t\t\t\t/* emergency, we now need to flush, no matter if we are at end of message or not... */\n\t\t\t\tint i = 1;\n\t\t\t\tchar currBuffChar;\n\t\t\t\twhile(i < buffLen && ((currBuffChar = (*buff)[i]) != '\\n'\n\t\t\t\t\t&& (pThis->pLstn->pSrv->iAddtlFrameDelim == TCPSRV_NO_ADDTL_DELIMITER\n\t\t\t\t\t\t|| currBuffChar != pThis->pLstn->pSrv->iAddtlFrameDelim))) {\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tLogError(0, NO_ERRCODE, \"error: message received is at least %d byte larger than max msg\"\n\t\t\t\t\t\" size; message will be split starting at: \\\"%.*s\\\"\\n\", i, (i < 32) ? i : 32, *buff);\n\t\t\t\tdoSubmitMsg(pThis, stTime, ttGenTime, pMultiSub);\n\t\t\t\t++(*pnMsgs);\n\t\t\t\t/* we might think if it is better to ignore the rest of the\n\t\t\t\t * message than to treat it as a new one. Maybe this is a good\n\t\t\t\t * candidate for a configuration parameter...\n\t\t\t\t * rgerhards, 2006-12-04\n\t\t\t\t */\n\t\t\t}\n\n\t\t\tif ((c == '\\n')\n\t\t\t\t   || ((pThis->pLstn->pSrv->iAddtlFrameDelim != TCPSRV_NO_ADDTL_DELIMITER)\n\t\t\t\t\t   && (c == pThis->pLstn->pSrv->iAddtlFrameDelim))\n\t\t\t\t   ) { /* record delimiter? */\n\t\t\t\tdoSubmitMsg(pThis, stTime, ttGenTime, pMultiSub);\n\t\t\t\t++(*pnMsgs);\n\t\t\t\tpThis->inputState = eAtStrtFram;\n\t\t\t} else {\n\t\t\t\t/* IMPORTANT: here we copy the actual frame content to the message - for BOTH framing modes!\n\t\t\t\t * If we have a message that is larger than the max msg size, we truncate it. This is the best\n\t\t\t\t * we can do in light of what the engine supports. -- rgerhards, 2008-03-14\n\t\t\t\t */\n\t\t\t\tif(pThis->iMsg < iMaxLine) {\n\t\t\t\t\t*(pThis->pMsg + pThis->iMsg++) = c;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tassert(pThis->eFraming == TCP_FRAMING_OCTET_COUNTING);\n\t\t\toctatesToCopy = pThis->iOctetsRemain;\n\t\t\toctatesToDiscard = 0;\n\t\t\tif (buffLen < octatesToCopy) {\n\t\t\t\toctatesToCopy = buffLen;\n\t\t\t}\n\t\t\tif (octatesToCopy + pThis->iMsg > iMaxLine) {\n\t\t\t\toctatesToDiscard = octatesToCopy - (iMaxLine - pThis->iMsg);\n\t\t\t\toctatesToCopy = iMaxLine - pThis->iMsg;\n\t\t\t}\n\n\t\t\tmemcpy(pThis->pMsg + pThis->iMsg, *buff, octatesToCopy);\n\t\t\tpThis->iMsg += octatesToCopy;\n\t\t\tpThis->iOctetsRemain -= (octatesToCopy + octatesToDiscard);\n\t\t\t*buff += (octatesToCopy + octatesToDiscard - 1);\n\t\t\tif (pThis->iOctetsRemain == 0) {\n\t\t\t\t/* we have end of frame! */\n\t\t\t\tdoSubmitMsg(pThis, stTime, ttGenTime, pMultiSub);\n\t\t\t\t++(*pnMsgs);\n\t\t\t\tpThis->inputState = eAtStrtFram;\n\t\t\t}\n\t\t}\n\n\t}\n\nfinalize_it:\n\tRETiRet;\n}", "func_hash": 319180109338452321529530788318348241217, "file_name": "imptcp.c", "file_hash": 222511081390723120608536252618686301143, "cwe": ["CWE-190"], "cve": "CVE-2018-16881", "cve_desc": "A denial of service vulnerability was found in rsyslog in the imptcp module. An attacker could send a specially crafted message to the imptcp socket, which would cause rsyslog to crash. Versions before 8.27.0 are vulnerable.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-16881"}
{"idx": 212857, "project": "vim", "commit_id": "4f1b083be43f351bc107541e7b0c9655a5d2c0bb", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/4f1b083be43f351bc107541e7b0c9655a5d2c0bb", "commit_message": "patch 9.0.0322: crash when no errors and 'quickfixtextfunc' is set\n\nProblem:    Crash when no errors and 'quickfixtextfunc' is set.\nSolution:   Do not handle errors if there aren't any.", "target": 1, "func": "qf_fill_buffer(qf_list_T *qfl, buf_T *buf, qfline_T *old_last, int qf_winid)\n{\n    linenr_T\tlnum;\n    qfline_T\t*qfp;\n    int\t\told_KeyTyped = KeyTyped;\n    list_T\t*qftf_list = NULL;\n    listitem_T\t*qftf_li = NULL;\n\n    if (old_last == NULL)\n    {\n\tif (buf != curbuf)\n\t{\n\t    internal_error(\"qf_fill_buffer()\");\n\t    return;\n\t}\n\n\t// delete all existing lines\n\twhile ((curbuf->b_ml.ml_flags & ML_EMPTY) == 0)\n\t    (void)ml_delete((linenr_T)1);\n    }\n\n    // Check if there is anything to display\n    if (qfl != NULL)\n    {\n\tchar_u\t\tdirname[MAXPATHL];\n\tint\t\tinvalid_val = FALSE;\n\tint\t\tprev_bufnr = -1;\n\n\t*dirname = NUL;\n\n\t// Add one line for each error\n\tif (old_last == NULL)\n\t{\n\t    qfp = qfl->qf_start;\n\t    lnum = 0;\n\t}\n\telse\n\t{\n\t    if (old_last->qf_next != NULL)\n\t\tqfp = old_last->qf_next;\n\t    else\n\t\tqfp = old_last;\n\t    lnum = buf->b_ml.ml_line_count;\n\t}\n\n\tqftf_list = call_qftf_func(qfl, qf_winid, (long)(lnum + 1),\n\t\t\t\t\t\t\t(long)qfl->qf_count);\n\tif (qftf_list != NULL)\n\t    qftf_li = qftf_list->lv_first;\n\n\twhile (lnum < qfl->qf_count)\n\t{\n\t    char_u\t*qftf_str = NULL;\n\n\t    // Use the text supplied by the user defined function (if any).\n\t    // If the returned value is not string, then ignore the rest\n\t    // of the returned values and use the default.\n\t    if (qftf_li != NULL && !invalid_val)\n\t    {\n\t\tqftf_str = tv_get_string_chk(&qftf_li->li_tv);\n\t\tif (qftf_str == NULL)\n\t\t    invalid_val = TRUE;\n\t    }\n\n\t    if (qf_buf_add_line(buf, lnum, qfp, dirname,\n\t\t\tprev_bufnr != qfp->qf_fnum, qftf_str) == FAIL)\n\t\tbreak;\n\n\t    prev_bufnr = qfp->qf_fnum;\n\t    ++lnum;\n\t    qfp = qfp->qf_next;\n\t    if (qfp == NULL)\n\t\tbreak;\n\n\t    if (qftf_li != NULL)\n\t\tqftf_li = qftf_li->li_next;\n\t}\n\n\tif (old_last == NULL)\n\t    // Delete the empty line which is now at the end\n\t    (void)ml_delete(lnum + 1);\n    }\n\n    // correct cursor position\n    check_lnums(TRUE);\n\n    if (old_last == NULL)\n    {\n\t// Set the 'filetype' to \"qf\" each time after filling the buffer.\n\t// This resembles reading a file into a buffer, it's more logical when\n\t// using autocommands.\n\t++curbuf_lock;\n\tset_option_value_give_err((char_u *)\"ft\",\n\t\t\t\t\t\t0L, (char_u *)\"qf\", OPT_LOCAL);\n\tcurbuf->b_p_ma = FALSE;\n\n\tkeep_filetype = TRUE;\t\t// don't detect 'filetype'\n\tapply_autocmds(EVENT_BUFREADPOST, (char_u *)\"quickfix\", NULL,\n\t\t\t\t\t\t\t       FALSE, curbuf);\n\tapply_autocmds(EVENT_BUFWINENTER, (char_u *)\"quickfix\", NULL,\n\t\t\t\t\t\t\t       FALSE, curbuf);\n\tkeep_filetype = FALSE;\n\t--curbuf_lock;\n\n\t// make sure it will be redrawn\n\tredraw_curbuf_later(UPD_NOT_VALID);\n    }\n\n    // Restore KeyTyped, setting 'filetype' may reset it.\n    KeyTyped = old_KeyTyped;\n}", "func_hash": 19896236176049682773029755500370526703, "file_name": "quickfix.c", "file_hash": 67097038911895244025002740290880368768, "cwe": ["CWE-416"], "cve": "CVE-2022-3037", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 9.0.0322.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3037"}
{"idx": 462511, "project": "vim", "commit_id": "4f1b083be43f351bc107541e7b0c9655a5d2c0bb", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/4f1b083be43f351bc107541e7b0c9655a5d2c0bb", "commit_message": "patch 9.0.0322: crash when no errors and 'quickfixtextfunc' is set\n\nProblem:    Crash when no errors and 'quickfixtextfunc' is set.\nSolution:   Do not handle errors if there aren't any.", "target": 0, "func": "qf_fill_buffer(qf_list_T *qfl, buf_T *buf, qfline_T *old_last, int qf_winid)\n{\n    linenr_T\tlnum;\n    qfline_T\t*qfp;\n    int\t\told_KeyTyped = KeyTyped;\n    list_T\t*qftf_list = NULL;\n    listitem_T\t*qftf_li = NULL;\n\n    if (old_last == NULL)\n    {\n\tif (buf != curbuf)\n\t{\n\t    internal_error(\"qf_fill_buffer()\");\n\t    return;\n\t}\n\n\t// delete all existing lines\n\twhile ((curbuf->b_ml.ml_flags & ML_EMPTY) == 0)\n\t    (void)ml_delete((linenr_T)1);\n    }\n\n    // Check if there is anything to display\n    if (qfl != NULL && qfl->qf_start != NULL)\n    {\n\tchar_u\t\tdirname[MAXPATHL];\n\tint\t\tinvalid_val = FALSE;\n\tint\t\tprev_bufnr = -1;\n\n\t*dirname = NUL;\n\n\t// Add one line for each error\n\tif (old_last == NULL)\n\t{\n\t    qfp = qfl->qf_start;\n\t    lnum = 0;\n\t}\n\telse\n\t{\n\t    if (old_last->qf_next != NULL)\n\t\tqfp = old_last->qf_next;\n\t    else\n\t\tqfp = old_last;\n\t    lnum = buf->b_ml.ml_line_count;\n\t}\n\n\tqftf_list = call_qftf_func(qfl, qf_winid, (long)(lnum + 1),\n\t\t\t\t\t\t\t(long)qfl->qf_count);\n\tif (qftf_list != NULL)\n\t    qftf_li = qftf_list->lv_first;\n\n\twhile (lnum < qfl->qf_count)\n\t{\n\t    char_u\t*qftf_str = NULL;\n\n\t    // Use the text supplied by the user defined function (if any).\n\t    // If the returned value is not string, then ignore the rest\n\t    // of the returned values and use the default.\n\t    if (qftf_li != NULL && !invalid_val)\n\t    {\n\t\tqftf_str = tv_get_string_chk(&qftf_li->li_tv);\n\t\tif (qftf_str == NULL)\n\t\t    invalid_val = TRUE;\n\t    }\n\n\t    if (qf_buf_add_line(buf, lnum, qfp, dirname,\n\t\t\tprev_bufnr != qfp->qf_fnum, qftf_str) == FAIL)\n\t\tbreak;\n\n\t    prev_bufnr = qfp->qf_fnum;\n\t    ++lnum;\n\t    qfp = qfp->qf_next;\n\t    if (qfp == NULL)\n\t\tbreak;\n\n\t    if (qftf_li != NULL)\n\t\tqftf_li = qftf_li->li_next;\n\t}\n\n\tif (old_last == NULL)\n\t    // Delete the empty line which is now at the end\n\t    (void)ml_delete(lnum + 1);\n    }\n\n    // correct cursor position\n    check_lnums(TRUE);\n\n    if (old_last == NULL)\n    {\n\t// Set the 'filetype' to \"qf\" each time after filling the buffer.\n\t// This resembles reading a file into a buffer, it's more logical when\n\t// using autocommands.\n\t++curbuf_lock;\n\tset_option_value_give_err((char_u *)\"ft\",\n\t\t\t\t\t\t0L, (char_u *)\"qf\", OPT_LOCAL);\n\tcurbuf->b_p_ma = FALSE;\n\n\tkeep_filetype = TRUE;\t\t// don't detect 'filetype'\n\tapply_autocmds(EVENT_BUFREADPOST, (char_u *)\"quickfix\", NULL,\n\t\t\t\t\t\t\t       FALSE, curbuf);\n\tapply_autocmds(EVENT_BUFWINENTER, (char_u *)\"quickfix\", NULL,\n\t\t\t\t\t\t\t       FALSE, curbuf);\n\tkeep_filetype = FALSE;\n\t--curbuf_lock;\n\n\t// make sure it will be redrawn\n\tredraw_curbuf_later(UPD_NOT_VALID);\n    }\n\n    // Restore KeyTyped, setting 'filetype' may reset it.\n    KeyTyped = old_KeyTyped;\n}", "func_hash": 333242954823260199301291407740047378845, "file_name": "quickfix.c", "file_hash": 221790887990910120742119728344121157301, "cwe": ["CWE-416"], "cve": "CVE-2022-3037", "cve_desc": "Use After Free in GitHub repository vim/vim prior to 9.0.0322.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3037"}
{"idx": 212871, "project": "newsbeuter", "commit_id": "96e9506ae9e252c548665152d1b8968297128307", "project_url": "https://github.com/akrennmair/newsbeuter", "commit_url": "https://github.com/akrennmair/newsbeuter/commit/96e9506ae9e252c548665152d1b8968297128307", "commit_message": "Sanitize inputs to bookmark-cmd (#591)\n\nNewsbeuter didn't properly shell-escape the arguments passed to\nbookmarking command, which allows a remote attacker to perform remote\ncode execution by crafting an RSS item whose title and/or URL contain\nsomething interpretable by the shell (most notably subshell\ninvocations.)\n\nThis has been reported by Jeriko One , complete with\nPoC and a patch.\n\nThis vulnerability was assigned CVE-2017-12904.", "target": 1, "func": "std::string controller::bookmark(\n\t\tconst std::string& url,\n\t\tconst std::string& title,\n\t\tconst std::string& description,\n\t\tconst std::string& feed_title)\n{\n\tstd::string bookmark_cmd = cfg.get_configvalue(\"bookmark-cmd\");\n\tbool is_interactive = cfg.get_configvalue_as_bool(\"bookmark-interactive\");\n\tif (bookmark_cmd.length() > 0) {\n\t\tstd::string cmdline = strprintf::fmt(\"%s '%s' %s %s %s\",\n\t\t                                       bookmark_cmd,\n\t\t                                       utils::replace_all(url,\"'\", \"%27\"),\n\t\t                                       quote_empty(stfl::quote(title)),\n\t\t                                       quote_empty(stfl::quote(description)),\n\t\t                                       quote_empty(stfl::quote(feed_title)));\n\n\t\tLOG(level::DEBUG, \"controller::bookmark: cmd = %s\", cmdline);\n\n\t\tif (is_interactive) {\n\t\t\tv->push_empty_formaction();\n\t\t\tstfl::reset();\n\t\t\tutils::run_interactively(cmdline, \"controller::bookmark\");\n\t\t\tv->pop_current_formaction();\n\t\t\treturn \"\";\n\t\t} else {\n\t\t\tchar * my_argv[4];\n\t\t\tmy_argv[0] = const_cast(\"/bin/sh\");\n\t\t\tmy_argv[1] = const_cast(\"-c\");\n\t\t\tmy_argv[2] = const_cast(cmdline.c_str());\n\t\t\tmy_argv[3] = nullptr;\n\t\t\treturn utils::run_program(my_argv, \"\");\n\t\t}\n\t} else {\n\t\treturn _(\"bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly.\");\n\t}\n}", "func_hash": 264539000779301749255245601679907359223, "file_name": "controller.cpp", "file_hash": 304698252897756630266738619508328009845, "cwe": ["CWE-787"], "cve": "CVE-2017-12904", "cve_desc": "Improper Neutralization of Special Elements used in an OS Command in bookmarking function of Newsbeuter versions 0.7 through 2.9 allows remote attackers to perform user-assisted code execution by crafting an RSS item that includes shell code in its title and/or URL.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-12904"}
{"idx": 462566, "project": "newsbeuter", "commit_id": "96e9506ae9e252c548665152d1b8968297128307", "project_url": "https://github.com/akrennmair/newsbeuter", "commit_url": "https://github.com/akrennmair/newsbeuter/commit/96e9506ae9e252c548665152d1b8968297128307", "commit_message": "Sanitize inputs to bookmark-cmd (#591)\n\nNewsbeuter didn't properly shell-escape the arguments passed to\nbookmarking command, which allows a remote attacker to perform remote\ncode execution by crafting an RSS item whose title and/or URL contain\nsomething interpretable by the shell (most notably subshell\ninvocations.)\n\nThis has been reported by Jeriko One , complete with\nPoC and a patch.\n\nThis vulnerability was assigned CVE-2017-12904.", "target": 0, "func": "std::string controller::bookmark(\n\t\tconst std::string& url,\n\t\tconst std::string& title,\n\t\tconst std::string& description,\n\t\tconst std::string& feed_title)\n{\n\tstd::string bookmark_cmd = cfg.get_configvalue(\"bookmark-cmd\");\n\tbool is_interactive = cfg.get_configvalue_as_bool(\"bookmark-interactive\");\n\tif (bookmark_cmd.length() > 0) {\n\t\tstd::string cmdline = strprintf::fmt(\"%s '%s' '%s' '%s' '%s'\",\n\t\t                                       bookmark_cmd,\n\t\t                                       utils::replace_all(url,\"'\", \"%27\"),\n\t\t                                       utils::replace_all(title,\"'\", \"%27\"),\n\t\t                                       utils::replace_all(description,\"'\", \"%27\"),\n\t\t                                       utils::replace_all(feed_title,\"'\", \"%27\"));\n\n\t\tLOG(level::DEBUG, \"controller::bookmark: cmd = %s\", cmdline);\n\n\t\tif (is_interactive) {\n\t\t\tv->push_empty_formaction();\n\t\t\tstfl::reset();\n\t\t\tutils::run_interactively(cmdline, \"controller::bookmark\");\n\t\t\tv->pop_current_formaction();\n\t\t\treturn \"\";\n\t\t} else {\n\t\t\tchar * my_argv[4];\n\t\t\tmy_argv[0] = const_cast(\"/bin/sh\");\n\t\t\tmy_argv[1] = const_cast(\"-c\");\n\t\t\tmy_argv[2] = const_cast(cmdline.c_str());\n\t\t\tmy_argv[3] = nullptr;\n\t\t\treturn utils::run_program(my_argv, \"\");\n\t\t}\n\t} else {\n\t\treturn _(\"bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly.\");\n\t}\n}", "func_hash": 79271714330892808671163251460832419876, "file_name": "controller.cpp", "file_hash": 323926139485782731853395949715316223577, "cwe": ["CWE-787"], "cve": "CVE-2017-12904", "cve_desc": "Improper Neutralization of Special Elements used in an OS Command in bookmarking function of Newsbeuter versions 0.7 through 2.9 allows remote attackers to perform user-assisted code execution by crafting an RSS item that includes shell code in its title and/or URL.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-12904"}
{"idx": 212927, "project": "qemu", "commit_id": "8c92060d3c0248bd4d515719a35922cd2391b9b4", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://git.qemu.org/?p=qemu.git;a=commit;h=8c92060d3c0248bd4d515719a35922cd2391b9b4", "commit_message": "sungem: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Mark Cave-Ayland \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nReviewed-by: Alistair Francis \nSigned-off-by: Jason Wang ", "target": 1, "func": "static void sungem_send_packet(SunGEMState *s, const uint8_t *buf,\n                               int size)\n{\n    NetClientState *nc = qemu_get_queue(s->nic);\n\n    if (s->macregs[MAC_XIFCFG >> 2] & MAC_XIFCFG_LBCK) {\n        nc->info->receive(nc, buf, size);\n    } else {\n        qemu_send_packet(nc, buf, size);\n    }\n}", "func_hash": 112948077964204681005351426202657971698, "file_name": "sungem.c", "file_hash": 256783431250079747313896805247705613463, "cwe": ["CWE-835"], "cve": "CVE-2021-3416", "cve_desc": "A potential stack overflow via infinite loop issue was found in various NIC emulators of QEMU in versions up to and including 5.2.0. The issue occurs in loopback mode of a NIC wherein reentrant DMA checks get bypassed. A guest user/process may use this flaw to consume CPU cycles or crash the QEMU process on the host resulting in DoS scenario.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3416"}
{"idx": 463051, "project": "qemu", "commit_id": "8c92060d3c0248bd4d515719a35922cd2391b9b4", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://git.qemu.org/?p=qemu.git;a=commit;h=8c92060d3c0248bd4d515719a35922cd2391b9b4", "commit_message": "sungem: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Mark Cave-Ayland \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nReviewed-by: Alistair Francis \nSigned-off-by: Jason Wang ", "target": 0, "func": "static void sungem_send_packet(SunGEMState *s, const uint8_t *buf,\n                               int size)\n{\n    NetClientState *nc = qemu_get_queue(s->nic);\n\n    if (s->macregs[MAC_XIFCFG >> 2] & MAC_XIFCFG_LBCK) {\n        qemu_receive_packet(nc, buf, size);\n    } else {\n        qemu_send_packet(nc, buf, size);\n    }\n}", "func_hash": 84544313584680412999632571366119869555, "file_name": "sungem.c", "file_hash": 289260737548619033998236290754655826819, "cwe": ["CWE-835"], "cve": "CVE-2021-3416", "cve_desc": "A potential stack overflow via infinite loop issue was found in various NIC emulators of QEMU in versions up to and including 5.2.0. The issue occurs in loopback mode of a NIC wherein reentrant DMA checks get bypassed. A guest user/process may use this flaw to consume CPU cycles or crash the QEMU process on the host resulting in DoS scenario.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3416"}
{"idx": 212934, "project": "cyrus-imapd", "commit_id": "621f9e41465b521399f691c241181300fab55995", "project_url": "https://github.com/cyrusimap/cyrus-imapd", "commit_url": "https://github.com/cyrusimap/cyrus-imapd/commit/621f9e41465b521399f691c241181300fab55995", "commit_message": "annotate: don't allow everyone to write shared server entries", "target": 1, "func": "static int write_entry(struct mailbox *mailbox,\n                       unsigned int uid,\n                       const char *entry,\n                       const char *userid,\n                       const struct buf *value,\n                       int ignorequota,\n                       int silent,\n                       const struct annotate_metadata *mdata,\n                       int maywrite)\n\n{\n    char key[MAX_MAILBOX_PATH+1];\n    int keylen, r;\n    annotate_db_t *d = NULL;\n    struct buf oldval = BUF_INITIALIZER;\n    const char *mboxname = mailbox ? mailbox->name : \"\";\n    modseq_t modseq = mdata ? mdata->modseq : 0;\n\n    r = _annotate_getdb(mboxname, uid, CYRUSDB_CREATE, &d);\n    if (r)\n        return r;\n\n    /* must be in a transaction to modify the db */\n    annotate_begin(d);\n\n    keylen = make_key(mboxname, uid, entry, userid, key, sizeof(key));\n\n    if (mailbox) {\n        struct annotate_metadata oldmdata;\n        r = read_old_value(d, key, keylen, &oldval, &oldmdata);\n        if (r) goto out;\n\n        /* if the value is identical, don't touch the mailbox */\n        if (oldval.len == value->len && (!value->len || !memcmp(oldval.s, value->s, value->len)))\n            goto out;\n\n        if (!ignorequota) {\n            quota_t qdiffs[QUOTA_NUMRESOURCES] = QUOTA_DIFFS_DONTCARE_INITIALIZER;\n            qdiffs[QUOTA_ANNOTSTORAGE] = value->len - (quota_t)oldval.len;\n            r = mailbox_quota_check(mailbox, qdiffs);\n            if (r) goto out;\n        }\n\n        if (!maywrite) {\n            r = IMAP_PERMISSION_DENIED;\n            if (r) goto out;\n        }\n\n        /* do the annot-changed here before altering the DB */\n        mailbox_annot_changed(mailbox, uid, entry, userid, &oldval, value, silent);\n\n        /* grab the message annotation modseq, if not overridden */\n        if (uid && !mdata) {\n            modseq = mailbox->i.highestmodseq;\n        }\n    }\n\n    /* zero length annotation is deletion.\n     * keep tombstones for message annotations */\n    if (!value->len && !uid) {\n\n#if DEBUG\n        syslog(LOG_ERR, \"write_entry: deleting key %s from %s\",\n                key_as_string(d, key, keylen), d->filename);\n#endif\n\n        do {\n            r = cyrusdb_delete(d->db, key, keylen, tid(d), /*force*/1);\n        } while (r == CYRUSDB_AGAIN);\n    }\n    else {\n        struct buf data = BUF_INITIALIZER;\n        unsigned char flags = 0;\n        if (!value->len || value->s == NULL) {\n            flags |= ANNOTATE_FLAG_DELETED;\n        }\n        else {\n            // this is only here to allow cleanup of invalid values in the past...\n            // the calling of this API with a NULL \"userid\" is bogus, because that's\n            // supposed to be reserved for the make_key of prefixes - but there has\n            // been API abuse in the past, so some of these are in the wild.  *sigh*.\n            // Don't allow new ones to be written\n            if (!userid) goto out;\n        }\n        make_entry(&data, value, modseq, flags);\n\n#if DEBUG\n        syslog(LOG_ERR, \"write_entry: storing key %s (value: %s) to %s (modseq=\" MODSEQ_FMT \")\",\n                key_as_string(d, key, keylen), value->s, d->filename, modseq);\n#endif\n\n        do {\n            r = cyrusdb_store(d->db, key, keylen, data.s, data.len, tid(d));\n        } while (r == CYRUSDB_AGAIN);\n        buf_free(&data);\n    }\n\n    if (!mailbox)\n        sync_log_annotation(\"\");\n\nout:\n    annotate_putdb(&d);\n    buf_free(&oldval);\n\n    return r;\n}", "func_hash": 63211042070136121773849314849857565491, "file_name": "annotate.c", "file_hash": 152032054661376167383830098805318046193, "cwe": ["CWE-732"], "cve": "CVE-2021-32056", "cve_desc": "Cyrus IMAP before 3.2.7, and 3.3.x and 3.4.x before 3.4.1, allows remote authenticated users to bypass intended access restrictions on server annotations and consequently cause replication to stall.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32056"}
{"idx": 463134, "project": "cyrus-imapd", "commit_id": "621f9e41465b521399f691c241181300fab55995", "project_url": "https://github.com/cyrusimap/cyrus-imapd", "commit_url": "https://github.com/cyrusimap/cyrus-imapd/commit/621f9e41465b521399f691c241181300fab55995", "commit_message": "annotate: don't allow everyone to write shared server entries", "target": 0, "func": "static int write_entry(struct mailbox *mailbox,\n                       unsigned int uid,\n                       const char *entry,\n                       const char *userid,\n                       const struct buf *value,\n                       int ignorequota,\n                       int silent,\n                       const struct annotate_metadata *mdata,\n                       int maywrite)\n\n{\n    char key[MAX_MAILBOX_PATH+1];\n    int keylen, r;\n    annotate_db_t *d = NULL;\n    struct buf oldval = BUF_INITIALIZER;\n    const char *mboxname = mailbox ? mailbox->name : \"\";\n    modseq_t modseq = mdata ? mdata->modseq : 0;\n\n    r = _annotate_getdb(mboxname, uid, CYRUSDB_CREATE, &d);\n    if (r)\n        return r;\n\n    /* must be in a transaction to modify the db */\n    annotate_begin(d);\n\n    keylen = make_key(mboxname, uid, entry, userid, key, sizeof(key));\n\n    struct annotate_metadata oldmdata;\n    r = read_old_value(d, key, keylen, &oldval, &oldmdata);\n    if (r) goto out;\n\n    /* if the value is identical, don't touch the mailbox */\n    if (oldval.len == value->len && (!value->len || !memcmp(oldval.s, value->s, value->len)))\n        goto out;\n\n    if (!maywrite) {\n        r = IMAP_PERMISSION_DENIED;\n        if (r) goto out;\n    }\n\n    if (mailbox) {\n        if (!ignorequota) {\n            quota_t qdiffs[QUOTA_NUMRESOURCES] = QUOTA_DIFFS_DONTCARE_INITIALIZER;\n            qdiffs[QUOTA_ANNOTSTORAGE] = value->len - (quota_t)oldval.len;\n            r = mailbox_quota_check(mailbox, qdiffs);\n            if (r) goto out;\n        }\n\n        /* do the annot-changed here before altering the DB */\n        mailbox_annot_changed(mailbox, uid, entry, userid, &oldval, value, silent);\n\n        /* grab the message annotation modseq, if not overridden */\n        if (uid && !mdata) {\n            modseq = mailbox->i.highestmodseq;\n        }\n    }\n\n    /* zero length annotation is deletion.\n     * keep tombstones for message annotations */\n    if (!value->len && !uid) {\n\n#if DEBUG\n        syslog(LOG_ERR, \"write_entry: deleting key %s from %s\",\n                key_as_string(d, key, keylen), d->filename);\n#endif\n\n        do {\n            r = cyrusdb_delete(d->db, key, keylen, tid(d), /*force*/1);\n        } while (r == CYRUSDB_AGAIN);\n    }\n    else {\n        struct buf data = BUF_INITIALIZER;\n        unsigned char flags = 0;\n        if (!value->len || value->s == NULL) {\n            flags |= ANNOTATE_FLAG_DELETED;\n        }\n        else {\n            // this is only here to allow cleanup of invalid values in the past...\n            // the calling of this API with a NULL \"userid\" is bogus, because that's\n            // supposed to be reserved for the make_key of prefixes - but there has\n            // been API abuse in the past, so some of these are in the wild.  *sigh*.\n            // Don't allow new ones to be written\n            if (!userid) goto out;\n        }\n        make_entry(&data, value, modseq, flags);\n\n#if DEBUG\n        syslog(LOG_ERR, \"write_entry: storing key %s (value: %s) to %s (modseq=\" MODSEQ_FMT \")\",\n                key_as_string(d, key, keylen), value->s, d->filename, modseq);\n#endif\n\n        do {\n            r = cyrusdb_store(d->db, key, keylen, data.s, data.len, tid(d));\n        } while (r == CYRUSDB_AGAIN);\n        buf_free(&data);\n    }\n\n    if (!mailbox)\n        sync_log_annotation(\"\");\n\nout:\n    annotate_putdb(&d);\n    buf_free(&oldval);\n\n    return r;\n}", "func_hash": 337608514204534148463343228875212022606, "file_name": "annotate.c", "file_hash": 55084981439029014796527313329432397099, "cwe": ["CWE-732"], "cve": "CVE-2021-32056", "cve_desc": "Cyrus IMAP before 3.2.7, and 3.3.x and 3.4.x before 3.4.1, allows remote authenticated users to bypass intended access restrictions on server annotations and consequently cause replication to stall.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32056"}
{"idx": 212955, "project": "linux", "commit_id": "82e31755e55fbcea6a9dfaae5fe4860ade17cbc0", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/82e31755e55fbcea6a9dfaae5fe4860ade17cbc0", "commit_message": "ax25: Fix UAF bugs in ax25 timers\n\nThere are race conditions that may lead to UAF bugs in\nax25_heartbeat_expiry(), ax25_t1timer_expiry(), ax25_t2timer_expiry(),\nax25_t3timer_expiry() and ax25_idletimer_expiry(), when we call\nax25_release() to deallocate ax25_dev.\n\nOne of the UAF bugs caused by ax25_release() is shown below:\n\n      (Thread 1)                    |      (Thread 2)\nax25_dev_device_up() //(1)          |\n...                                 | ax25_kill_by_device()\nax25_bind()          //(2)          |\nax25_connect()                      | ...\n ax25_std_establish_data_link()     |\n  ax25_start_t1timer()              | ax25_dev_device_down() //(3)\n   mod_timer(&ax25->t1timer,..)     |\n                                    | ax25_release()\n   (wait a time)                    |  ...\n                                    |  ax25_dev_put(ax25_dev) //(4)FREE\n   ax25_t1timer_expiry()            |\n    ax25->ax25_dev->values[..] //USE|  ...\n     ...                            |\n\nWe increase the refcount of ax25_dev in position (1) and (2), and\ndecrease the refcount of ax25_dev in position (3) and (4).\nThe ax25_dev will be freed in position (4) and be used in\nax25_t1timer_expiry().\n\nThe fail log is shown below:\n==============================================================\n\n[  106.116942] BUG: KASAN: use-after-free in ax25_t1timer_expiry+0x1c/0x60\n[  106.116942] Read of size 8 at addr ffff88800bda9028 by task swapper/0/0\n[  106.116942] CPU: 0 PID: 0 Comm: swapper/0 Not tainted 5.17.0-06123-g0905eec574\n[  106.116942] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-14\n[  106.116942] Call Trace:\n...\n[  106.116942]  ax25_t1timer_expiry+0x1c/0x60\n[  106.116942]  call_timer_fn+0x122/0x3d0\n[  106.116942]  __run_timers.part.0+0x3f6/0x520\n[  106.116942]  run_timer_softirq+0x4f/0xb0\n[  106.116942]  __do_softirq+0x1c2/0x651\n...\n\nThis patch adds del_timer_sync() in ax25_release(), which could ensure\nthat all timers stop before we deallocate ax25_dev.\n\nSigned-off-by: Duoming Zhou \nSigned-off-by: Paolo Abeni ", "target": 1, "func": "static int ax25_release(struct socket *sock)\n{\n\tstruct sock *sk = sock->sk;\n\tax25_cb *ax25;\n\tax25_dev *ax25_dev;\n\n\tif (sk == NULL)\n\t\treturn 0;\n\n\tsock_hold(sk);\n\tlock_sock(sk);\n\tsock_orphan(sk);\n\tax25 = sk_to_ax25(sk);\n\tax25_dev = ax25->ax25_dev;\n\n\tif (sk->sk_type == SOCK_SEQPACKET) {\n\t\tswitch (ax25->state) {\n\t\tcase AX25_STATE_0:\n\t\t\trelease_sock(sk);\n\t\t\tax25_disconnect(ax25, 0);\n\t\t\tlock_sock(sk);\n\t\t\tax25_destroy_socket(ax25);\n\t\t\tbreak;\n\n\t\tcase AX25_STATE_1:\n\t\tcase AX25_STATE_2:\n\t\t\tax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);\n\t\t\trelease_sock(sk);\n\t\t\tax25_disconnect(ax25, 0);\n\t\t\tlock_sock(sk);\n\t\t\tif (!sock_flag(ax25->sk, SOCK_DESTROY))\n\t\t\t\tax25_destroy_socket(ax25);\n\t\t\tbreak;\n\n\t\tcase AX25_STATE_3:\n\t\tcase AX25_STATE_4:\n\t\t\tax25_clear_queues(ax25);\n\t\t\tax25->n2count = 0;\n\n\t\t\tswitch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) {\n\t\t\tcase AX25_PROTO_STD_SIMPLEX:\n\t\t\tcase AX25_PROTO_STD_DUPLEX:\n\t\t\t\tax25_send_control(ax25,\n\t\t\t\t\t\t  AX25_DISC,\n\t\t\t\t\t\t  AX25_POLLON,\n\t\t\t\t\t\t  AX25_COMMAND);\n\t\t\t\tax25_stop_t2timer(ax25);\n\t\t\t\tax25_stop_t3timer(ax25);\n\t\t\t\tax25_stop_idletimer(ax25);\n\t\t\t\tbreak;\n#ifdef CONFIG_AX25_DAMA_SLAVE\n\t\t\tcase AX25_PROTO_DAMA_SLAVE:\n\t\t\t\tax25_stop_t3timer(ax25);\n\t\t\t\tax25_stop_idletimer(ax25);\n\t\t\t\tbreak;\n#endif\n\t\t\t}\n\t\t\tax25_calculate_t1(ax25);\n\t\t\tax25_start_t1timer(ax25);\n\t\t\tax25->state = AX25_STATE_2;\n\t\t\tsk->sk_state                = TCP_CLOSE;\n\t\t\tsk->sk_shutdown            |= SEND_SHUTDOWN;\n\t\t\tsk->sk_state_change(sk);\n\t\t\tsock_set_flag(sk, SOCK_DESTROY);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t} else {\n\t\tsk->sk_state     = TCP_CLOSE;\n\t\tsk->sk_shutdown |= SEND_SHUTDOWN;\n\t\tsk->sk_state_change(sk);\n\t\tax25_destroy_socket(ax25);\n\t}\n\tif (ax25_dev) {\n\t\tdev_put_track(ax25_dev->dev, &ax25_dev->dev_tracker);\n\t\tax25_dev_put(ax25_dev);\n\t}\n\n\tsock->sk   = NULL;\n\trelease_sock(sk);\n\tsock_put(sk);\n\n\treturn 0;\n}", "func_hash": 322863638930156349228190868934879958122, "file_name": "af_ax25.c", "file_hash": 161595370162210735322175103800372569534, "cwe": ["CWE-476"], "cve": "CVE-2022-1205", "cve_desc": "A NULL pointer dereference flaw was found in the Linux kernel\u2019s Amateur Radio AX.25 protocol functionality in the way a user connects with the protocol. This flaw allows a local user to crash the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1205"}
{"idx": 463476, "project": "linux", "commit_id": "82e31755e55fbcea6a9dfaae5fe4860ade17cbc0", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/82e31755e55fbcea6a9dfaae5fe4860ade17cbc0", "commit_message": "ax25: Fix UAF bugs in ax25 timers\n\nThere are race conditions that may lead to UAF bugs in\nax25_heartbeat_expiry(), ax25_t1timer_expiry(), ax25_t2timer_expiry(),\nax25_t3timer_expiry() and ax25_idletimer_expiry(), when we call\nax25_release() to deallocate ax25_dev.\n\nOne of the UAF bugs caused by ax25_release() is shown below:\n\n      (Thread 1)                    |      (Thread 2)\nax25_dev_device_up() //(1)          |\n...                                 | ax25_kill_by_device()\nax25_bind()          //(2)          |\nax25_connect()                      | ...\n ax25_std_establish_data_link()     |\n  ax25_start_t1timer()              | ax25_dev_device_down() //(3)\n   mod_timer(&ax25->t1timer,..)     |\n                                    | ax25_release()\n   (wait a time)                    |  ...\n                                    |  ax25_dev_put(ax25_dev) //(4)FREE\n   ax25_t1timer_expiry()            |\n    ax25->ax25_dev->values[..] //USE|  ...\n     ...                            |\n\nWe increase the refcount of ax25_dev in position (1) and (2), and\ndecrease the refcount of ax25_dev in position (3) and (4).\nThe ax25_dev will be freed in position (4) and be used in\nax25_t1timer_expiry().\n\nThe fail log is shown below:\n==============================================================\n\n[  106.116942] BUG: KASAN: use-after-free in ax25_t1timer_expiry+0x1c/0x60\n[  106.116942] Read of size 8 at addr ffff88800bda9028 by task swapper/0/0\n[  106.116942] CPU: 0 PID: 0 Comm: swapper/0 Not tainted 5.17.0-06123-g0905eec574\n[  106.116942] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-14\n[  106.116942] Call Trace:\n...\n[  106.116942]  ax25_t1timer_expiry+0x1c/0x60\n[  106.116942]  call_timer_fn+0x122/0x3d0\n[  106.116942]  __run_timers.part.0+0x3f6/0x520\n[  106.116942]  run_timer_softirq+0x4f/0xb0\n[  106.116942]  __do_softirq+0x1c2/0x651\n...\n\nThis patch adds del_timer_sync() in ax25_release(), which could ensure\nthat all timers stop before we deallocate ax25_dev.\n\nSigned-off-by: Duoming Zhou \nSigned-off-by: Paolo Abeni ", "target": 0, "func": "static int ax25_release(struct socket *sock)\n{\n\tstruct sock *sk = sock->sk;\n\tax25_cb *ax25;\n\tax25_dev *ax25_dev;\n\n\tif (sk == NULL)\n\t\treturn 0;\n\n\tsock_hold(sk);\n\tlock_sock(sk);\n\tsock_orphan(sk);\n\tax25 = sk_to_ax25(sk);\n\tax25_dev = ax25->ax25_dev;\n\n\tif (sk->sk_type == SOCK_SEQPACKET) {\n\t\tswitch (ax25->state) {\n\t\tcase AX25_STATE_0:\n\t\t\trelease_sock(sk);\n\t\t\tax25_disconnect(ax25, 0);\n\t\t\tlock_sock(sk);\n\t\t\tax25_destroy_socket(ax25);\n\t\t\tbreak;\n\n\t\tcase AX25_STATE_1:\n\t\tcase AX25_STATE_2:\n\t\t\tax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);\n\t\t\trelease_sock(sk);\n\t\t\tax25_disconnect(ax25, 0);\n\t\t\tlock_sock(sk);\n\t\t\tif (!sock_flag(ax25->sk, SOCK_DESTROY))\n\t\t\t\tax25_destroy_socket(ax25);\n\t\t\tbreak;\n\n\t\tcase AX25_STATE_3:\n\t\tcase AX25_STATE_4:\n\t\t\tax25_clear_queues(ax25);\n\t\t\tax25->n2count = 0;\n\n\t\t\tswitch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) {\n\t\t\tcase AX25_PROTO_STD_SIMPLEX:\n\t\t\tcase AX25_PROTO_STD_DUPLEX:\n\t\t\t\tax25_send_control(ax25,\n\t\t\t\t\t\t  AX25_DISC,\n\t\t\t\t\t\t  AX25_POLLON,\n\t\t\t\t\t\t  AX25_COMMAND);\n\t\t\t\tax25_stop_t2timer(ax25);\n\t\t\t\tax25_stop_t3timer(ax25);\n\t\t\t\tax25_stop_idletimer(ax25);\n\t\t\t\tbreak;\n#ifdef CONFIG_AX25_DAMA_SLAVE\n\t\t\tcase AX25_PROTO_DAMA_SLAVE:\n\t\t\t\tax25_stop_t3timer(ax25);\n\t\t\t\tax25_stop_idletimer(ax25);\n\t\t\t\tbreak;\n#endif\n\t\t\t}\n\t\t\tax25_calculate_t1(ax25);\n\t\t\tax25_start_t1timer(ax25);\n\t\t\tax25->state = AX25_STATE_2;\n\t\t\tsk->sk_state                = TCP_CLOSE;\n\t\t\tsk->sk_shutdown            |= SEND_SHUTDOWN;\n\t\t\tsk->sk_state_change(sk);\n\t\t\tsock_set_flag(sk, SOCK_DESTROY);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t} else {\n\t\tsk->sk_state     = TCP_CLOSE;\n\t\tsk->sk_shutdown |= SEND_SHUTDOWN;\n\t\tsk->sk_state_change(sk);\n\t\tax25_destroy_socket(ax25);\n\t}\n\tif (ax25_dev) {\n\t\tdel_timer_sync(&ax25->timer);\n\t\tdel_timer_sync(&ax25->t1timer);\n\t\tdel_timer_sync(&ax25->t2timer);\n\t\tdel_timer_sync(&ax25->t3timer);\n\t\tdel_timer_sync(&ax25->idletimer);\n\t\tdev_put_track(ax25_dev->dev, &ax25_dev->dev_tracker);\n\t\tax25_dev_put(ax25_dev);\n\t}\n\n\tsock->sk   = NULL;\n\trelease_sock(sk);\n\tsock_put(sk);\n\n\treturn 0;\n}", "func_hash": 148812270576683691154381215671514833423, "file_name": "af_ax25.c", "file_hash": 305687071181329049431144170214324654974, "cwe": ["CWE-476"], "cve": "CVE-2022-1205", "cve_desc": "A NULL pointer dereference flaw was found in the Linux kernel\u2019s Amateur Radio AX.25 protocol functionality in the way a user connects with the protocol. This flaw allows a local user to crash the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1205"}
{"idx": 213037, "project": "php-src", "commit_id": "2bcbc95f033c31b00595ed39f79c3a99b4ed0501", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=2bcbc95f033c31b00595ed39f79c3a99b4ed0501", "commit_message": "Fix bug #79037 (global buffer-overflow in `mbfl_filt_conv_big5_wchar`)", "target": 1, "func": "mbfl_filt_conv_big5_wchar(int c, mbfl_convert_filter *filter)\n{\n\tint k;\n\tint c1, w, c2;\n\n\tswitch (filter->status) {\n\tcase 0:\n\t\tif (filter->from->no_encoding == mbfl_no_encoding_cp950) {\n\t\t\tc1 = 0x80;\n\t\t} else {\n\t\t\tc1 = 0xa0;\n\t\t}\n\n\t\tif (c >= 0 && c <= 0x80) {\t/* latin */\n\t\t\tCK((*filter->output_function)(c, filter->data));\n\t\t} else if (c == 0xff) {\n\t\t\tCK((*filter->output_function)(0xf8f8, filter->data));\n\t\t} else if (c > c1 && c < 0xff) {\t/* dbcs lead byte */\n\t\t\tfilter->status = 1;\n\t\t\tfilter->cache = c;\n\t\t} else {\n\t\t\tw = c & MBFL_WCSGROUP_MASK;\n\t\t\tw |= MBFL_WCSGROUP_THROUGH;\n\t\t\tCK((*filter->output_function)(w, filter->data));\n\t\t}\n\t\tbreak;\n\n\tcase 1:\t\t/* dbcs second byte */\n\t\tfilter->status = 0;\n\t\tc1 = filter->cache;\n\t\tif ((c > 0x39 && c < 0x7f) | (c > 0xa0 && c < 0xff)) {\n\t\t\tif (c < 0x7f){\n\t\t\t\tw = (c1 - 0xa1)*157 + (c - 0x40);\n\t\t\t} else {\n\t\t\t\tw = (c1 - 0xa1)*157 + (c - 0xa1) + 0x3f;\n\t\t\t}\n\t\t\tif (w >= 0 && w < big5_ucs_table_size) {\n\t\t\t\tw = big5_ucs_table[w];\n\t\t\t} else {\n\t\t\t\tw = 0;\n\t\t\t}\n\n\t\t\tif (filter->from->no_encoding == mbfl_no_encoding_cp950) {\n\t\t\t\t/* PUA for CP950 */\n\t\t\t\tif (w <= 0 &&\n\t\t\t\t\t(((c1 >= 0xfa && c1 <= 0xfe) || (c1 >= 0x8e && c1 <= 0xa0) ||\n\t\t\t\t\t  (c1 >= 0x81 && c1 <= 0x8d) ||(c1 >= 0xc7 && c1 <= 0xc8))\n\t\t\t\t\t && ((c > 0x39 && c < 0x7f) || (c > 0xa0 && c < 0xff))) ||\n\t\t\t\t\t((c1 == 0xc6) && (c > 0xa0 && c < 0xff))) {\n\t\t\t\t\tc2 = c1 << 8 | c;\n\t\t\t\t\tfor (k = 0; k < sizeof(cp950_pua_tbl)/(sizeof(unsigned short)*4); k++) {\n\t\t\t\t\t\tif (c2 >= cp950_pua_tbl[k][2] && c2 <= cp950_pua_tbl[k][3]) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif ((cp950_pua_tbl[k][2] & 0xff) == 0x40) {\n\t\t\t\t\t\tw = 157*(c1 - (cp950_pua_tbl[k][2]>>8)) + c - (c >= 0xa1 ? 0x62 : 0x40)\n\t\t\t\t\t\t\t+ cp950_pua_tbl[k][0];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tw = c2 - cp950_pua_tbl[k][2] + cp950_pua_tbl[k][0];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (w <= 0) {\n\t\t\t\tw = (c1 << 8) | c;\n\t\t\t\tw &= MBFL_WCSPLANE_MASK;\n\t\t\t\tw |= MBFL_WCSPLANE_BIG5;\n\t\t\t}\n\t\t\tCK((*filter->output_function)(w, filter->data));\n\t\t} else if ((c >= 0 && c < 0x21) || c == 0x7f) {\t\t/* CTLs */\n\t\t\tCK((*filter->output_function)(c, filter->data));\n\t\t} else {\n\t\t\tw = (c1 << 8) | c;\n\t\t\tw &= MBFL_WCSGROUP_MASK;\n\t\t\tw |= MBFL_WCSGROUP_THROUGH;\n\t\t\tCK((*filter->output_function)(w, filter->data));\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tfilter->status = 0;\n\t\tbreak;\n\t}\n\n\treturn c;\n}", "func_hash": 8283586201644887300915898295948875795, "file_name": "mbfilter_big5.c", "file_hash": 67113767760618335945735132719612525083, "cwe": ["CWE-125"], "cve": "CVE-2020-7060", "cve_desc": "When using certain mbstring functions to convert multibyte encodings, in PHP versions 7.2.x below 7.2.27, 7.3.x below 7.3.14 and 7.4.x below 7.4.2 it is possible to supply data that will cause function mbfl_filt_conv_big5_wchar to read past the allocated buffer. This may lead to information disclosure or crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-7060"}
{"idx": 464942, "project": "php-src", "commit_id": "2bcbc95f033c31b00595ed39f79c3a99b4ed0501", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=2bcbc95f033c31b00595ed39f79c3a99b4ed0501", "commit_message": "Fix bug #79037 (global buffer-overflow in `mbfl_filt_conv_big5_wchar`)", "target": 0, "func": "mbfl_filt_conv_big5_wchar(int c, mbfl_convert_filter *filter)\n{\n\tint k;\n\tint c1, w, c2;\n\n\tswitch (filter->status) {\n\tcase 0:\n\t\tif (filter->from->no_encoding == mbfl_no_encoding_cp950) {\n\t\t\tc1 = 0x80;\n\t\t} else {\n\t\t\tc1 = 0xa0;\n\t\t}\n\n\t\tif (c >= 0 && c <= 0x80) {\t/* latin */\n\t\t\tCK((*filter->output_function)(c, filter->data));\n\t\t} else if (c == 0xff) {\n\t\t\tCK((*filter->output_function)(0xf8f8, filter->data));\n\t\t} else if (c > c1 && c < 0xff) {\t/* dbcs lead byte */\n\t\t\tfilter->status = 1;\n\t\t\tfilter->cache = c;\n\t\t} else {\n\t\t\tw = c & MBFL_WCSGROUP_MASK;\n\t\t\tw |= MBFL_WCSGROUP_THROUGH;\n\t\t\tCK((*filter->output_function)(w, filter->data));\n\t\t}\n\t\tbreak;\n\n\tcase 1:\t\t/* dbcs second byte */\n\t\tfilter->status = 0;\n\t\tc1 = filter->cache;\n\t\tif ((c > 0x39 && c < 0x7f) | (c > 0xa0 && c < 0xff)) {\n\t\t\tif (c < 0x7f){\n\t\t\t\tw = (c1 - 0xa1)*157 + (c - 0x40);\n\t\t\t} else {\n\t\t\t\tw = (c1 - 0xa1)*157 + (c - 0xa1) + 0x3f;\n\t\t\t}\n\t\t\tif (w >= 0 && w < big5_ucs_table_size) {\n\t\t\t\tw = big5_ucs_table[w];\n\t\t\t} else {\n\t\t\t\tw = 0;\n\t\t\t}\n\n\t\t\tif (filter->from->no_encoding == mbfl_no_encoding_cp950) {\n\t\t\t\t/* PUA for CP950 */\n\t\t\t\tif (w <= 0 && is_in_cp950_pua(c1, c)) {\n\t\t\t\t\tc2 = c1 << 8 | c;\n\t\t\t\t\tfor (k = 0; k < sizeof(cp950_pua_tbl)/(sizeof(unsigned short)*4); k++) {\n\t\t\t\t\t\tif (c2 >= cp950_pua_tbl[k][2] && c2 <= cp950_pua_tbl[k][3]) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif ((cp950_pua_tbl[k][2] & 0xff) == 0x40) {\n\t\t\t\t\t\tw = 157*(c1 - (cp950_pua_tbl[k][2]>>8)) + c - (c >= 0xa1 ? 0x62 : 0x40)\n\t\t\t\t\t\t\t+ cp950_pua_tbl[k][0];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tw = c2 - cp950_pua_tbl[k][2] + cp950_pua_tbl[k][0];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (w <= 0) {\n\t\t\t\tw = (c1 << 8) | c;\n\t\t\t\tw &= MBFL_WCSPLANE_MASK;\n\t\t\t\tw |= MBFL_WCSPLANE_BIG5;\n\t\t\t}\n\t\t\tCK((*filter->output_function)(w, filter->data));\n\t\t} else if ((c >= 0 && c < 0x21) || c == 0x7f) {\t\t/* CTLs */\n\t\t\tCK((*filter->output_function)(c, filter->data));\n\t\t} else {\n\t\t\tw = (c1 << 8) | c;\n\t\t\tw &= MBFL_WCSGROUP_MASK;\n\t\t\tw |= MBFL_WCSGROUP_THROUGH;\n\t\t\tCK((*filter->output_function)(w, filter->data));\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tfilter->status = 0;\n\t\tbreak;\n\t}\n\n\treturn c;\n}", "func_hash": 324298547167958214830404594575086371894, "file_name": "mbfilter_big5.c", "file_hash": 135358838595920427772392870415942108469, "cwe": ["CWE-125"], "cve": "CVE-2020-7060", "cve_desc": "When using certain mbstring functions to convert multibyte encodings, in PHP versions 7.2.x below 7.2.27, 7.3.x below 7.3.14 and 7.4.x below 7.4.2 it is possible to supply data that will cause function mbfl_filt_conv_big5_wchar to read past the allocated buffer. This may lead to information disclosure or crash.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-7060"}
{"idx": 213075, "project": "linux", "commit_id": "d270453a0d9ec10bb8a802a142fb1b3601a83098", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/d270453a0d9ec10bb8a802a142fb1b3601a83098", "commit_message": "nfc: nfcmrvl: main: reorder destructive operations in nfcmrvl_nci_unregister_dev to avoid bugs\n\nThere are destructive operations such as nfcmrvl_fw_dnld_abort and\ngpio_free in nfcmrvl_nci_unregister_dev. The resources such as firmware,\ngpio and so on could be destructed while the upper layer functions such as\nnfcmrvl_fw_dnld_start and nfcmrvl_nci_recv_frame is executing, which leads\nto double-free, use-after-free and null-ptr-deref bugs.\n\nThere are three situations that could lead to double-free bugs.\n\nThe first situation is shown below:\n\n   (Thread 1)                 |      (Thread 2)\nnfcmrvl_fw_dnld_start         |\n ...                          |  nfcmrvl_nci_unregister_dev\n release_firmware()           |   nfcmrvl_fw_dnld_abort\n  kfree(fw) //(1)             |    fw_dnld_over\n                              |     release_firmware\n  ...                         |      kfree(fw) //(2)\n                              |     ...\n\nThe second situation is shown below:\n\n   (Thread 1)                 |      (Thread 2)\nnfcmrvl_fw_dnld_start         |\n ...                          |\n mod_timer                    |\n (wait a time)                |\n fw_dnld_timeout              |  nfcmrvl_nci_unregister_dev\n   fw_dnld_over               |   nfcmrvl_fw_dnld_abort\n    release_firmware          |    fw_dnld_over\n     kfree(fw) //(1)          |     release_firmware\n     ...                      |      kfree(fw) //(2)\n\nThe third situation is shown below:\n\n       (Thread 1)               |       (Thread 2)\nnfcmrvl_nci_recv_frame          |\n if(..->fw_download_in_progress)|\n  nfcmrvl_fw_dnld_recv_frame    |\n   queue_work                   |\n                                |\nfw_dnld_rx_work                 | nfcmrvl_nci_unregister_dev\n fw_dnld_over                   |  nfcmrvl_fw_dnld_abort\n  release_firmware              |   fw_dnld_over\n   kfree(fw) //(1)              |    release_firmware\n                                |     kfree(fw) //(2)\n\nThe firmware struct is deallocated in position (1) and deallocated\nin position (2) again.\n\nThe crash trace triggered by POC is like below:\n\nBUG: KASAN: double-free or invalid-free in fw_dnld_over\nCall Trace:\n  kfree\n  fw_dnld_over\n  nfcmrvl_nci_unregister_dev\n  nci_uart_tty_close\n  tty_ldisc_kill\n  tty_ldisc_hangup\n  __tty_hangup.part.0\n  tty_release\n  ...\n\nWhat's more, there are also use-after-free and null-ptr-deref bugs\nin nfcmrvl_fw_dnld_start. If we deallocate firmware struct, gpio or\nset null to the members of priv->fw_dnld in nfcmrvl_nci_unregister_dev,\nthen, we dereference firmware, gpio or the members of priv->fw_dnld in\nnfcmrvl_fw_dnld_start, the UAF or NPD bugs will happen.\n\nThis patch reorders destructive operations after nci_unregister_device\nin order to synchronize between cleanup routine and firmware download\nroutine.\n\nThe nci_unregister_device is well synchronized. If the device is\ndetaching, the firmware download routine will goto error. If firmware\ndownload routine is executing, nci_unregister_device will wait until\nfirmware download routine is finished.\n\nFixes: 3194c6870158 (\"NFC: nfcmrvl: add firmware download support\")\nSigned-off-by: Duoming Zhou \nSigned-off-by: David S. Miller ", "target": 1, "func": "void nfcmrvl_nci_unregister_dev(struct nfcmrvl_private *priv)\n{\n\tstruct nci_dev *ndev = priv->ndev;\n\n\tif (priv->ndev->nfc_dev->fw_download_in_progress)\n\t\tnfcmrvl_fw_dnld_abort(priv);\n\n\tnfcmrvl_fw_dnld_deinit(priv);\n\n\tif (gpio_is_valid(priv->config.reset_n_io))\n\t\tgpio_free(priv->config.reset_n_io);\n\n\tnci_unregister_device(ndev);\n\tnci_free_device(ndev);\n\tkfree(priv);\n}", "func_hash": 80022393435189393698798858771068403226, "file_name": "main.c", "file_hash": 269589724165464795755961413543377431257, "cwe": ["CWE-416"], "cve": "CVE-2022-1734", "cve_desc": "A flaw in Linux Kernel found in nfcmrvl_nci_unregister_dev() in drivers/nfc/nfcmrvl/main.c can lead to use after free both read or write when non synchronized between cleanup routine and firmware download routine.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1734"}
{"idx": 465854, "project": "linux", "commit_id": "d270453a0d9ec10bb8a802a142fb1b3601a83098", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/d270453a0d9ec10bb8a802a142fb1b3601a83098", "commit_message": "nfc: nfcmrvl: main: reorder destructive operations in nfcmrvl_nci_unregister_dev to avoid bugs\n\nThere are destructive operations such as nfcmrvl_fw_dnld_abort and\ngpio_free in nfcmrvl_nci_unregister_dev. The resources such as firmware,\ngpio and so on could be destructed while the upper layer functions such as\nnfcmrvl_fw_dnld_start and nfcmrvl_nci_recv_frame is executing, which leads\nto double-free, use-after-free and null-ptr-deref bugs.\n\nThere are three situations that could lead to double-free bugs.\n\nThe first situation is shown below:\n\n   (Thread 1)                 |      (Thread 2)\nnfcmrvl_fw_dnld_start         |\n ...                          |  nfcmrvl_nci_unregister_dev\n release_firmware()           |   nfcmrvl_fw_dnld_abort\n  kfree(fw) //(1)             |    fw_dnld_over\n                              |     release_firmware\n  ...                         |      kfree(fw) //(2)\n                              |     ...\n\nThe second situation is shown below:\n\n   (Thread 1)                 |      (Thread 2)\nnfcmrvl_fw_dnld_start         |\n ...                          |\n mod_timer                    |\n (wait a time)                |\n fw_dnld_timeout              |  nfcmrvl_nci_unregister_dev\n   fw_dnld_over               |   nfcmrvl_fw_dnld_abort\n    release_firmware          |    fw_dnld_over\n     kfree(fw) //(1)          |     release_firmware\n     ...                      |      kfree(fw) //(2)\n\nThe third situation is shown below:\n\n       (Thread 1)               |       (Thread 2)\nnfcmrvl_nci_recv_frame          |\n if(..->fw_download_in_progress)|\n  nfcmrvl_fw_dnld_recv_frame    |\n   queue_work                   |\n                                |\nfw_dnld_rx_work                 | nfcmrvl_nci_unregister_dev\n fw_dnld_over                   |  nfcmrvl_fw_dnld_abort\n  release_firmware              |   fw_dnld_over\n   kfree(fw) //(1)              |    release_firmware\n                                |     kfree(fw) //(2)\n\nThe firmware struct is deallocated in position (1) and deallocated\nin position (2) again.\n\nThe crash trace triggered by POC is like below:\n\nBUG: KASAN: double-free or invalid-free in fw_dnld_over\nCall Trace:\n  kfree\n  fw_dnld_over\n  nfcmrvl_nci_unregister_dev\n  nci_uart_tty_close\n  tty_ldisc_kill\n  tty_ldisc_hangup\n  __tty_hangup.part.0\n  tty_release\n  ...\n\nWhat's more, there are also use-after-free and null-ptr-deref bugs\nin nfcmrvl_fw_dnld_start. If we deallocate firmware struct, gpio or\nset null to the members of priv->fw_dnld in nfcmrvl_nci_unregister_dev,\nthen, we dereference firmware, gpio or the members of priv->fw_dnld in\nnfcmrvl_fw_dnld_start, the UAF or NPD bugs will happen.\n\nThis patch reorders destructive operations after nci_unregister_device\nin order to synchronize between cleanup routine and firmware download\nroutine.\n\nThe nci_unregister_device is well synchronized. If the device is\ndetaching, the firmware download routine will goto error. If firmware\ndownload routine is executing, nci_unregister_device will wait until\nfirmware download routine is finished.\n\nFixes: 3194c6870158 (\"NFC: nfcmrvl: add firmware download support\")\nSigned-off-by: Duoming Zhou \nSigned-off-by: David S. Miller ", "target": 0, "func": "void nfcmrvl_nci_unregister_dev(struct nfcmrvl_private *priv)\n{\n\tstruct nci_dev *ndev = priv->ndev;\n\n\tnci_unregister_device(ndev);\n\tif (priv->ndev->nfc_dev->fw_download_in_progress)\n\t\tnfcmrvl_fw_dnld_abort(priv);\n\n\tnfcmrvl_fw_dnld_deinit(priv);\n\n\tif (gpio_is_valid(priv->config.reset_n_io))\n\t\tgpio_free(priv->config.reset_n_io);\n\n\tnci_free_device(ndev);\n\tkfree(priv);\n}", "func_hash": 316889922482617255369760811895973398042, "file_name": "main.c", "file_hash": 72783035661229533043408251312926412443, "cwe": ["CWE-416"], "cve": "CVE-2022-1734", "cve_desc": "A flaw in Linux Kernel found in nfcmrvl_nci_unregister_dev() in drivers/nfc/nfcmrvl/main.c can lead to use after free both read or write when non synchronized between cleanup routine and firmware download routine.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1734"}
{"idx": 213370, "project": "glib", "commit_id": "d553d92d6e9f53cbe5a34166fcb919ba652c6a8e", "project_url": "https://gitlab.gnome.org/GNOME/glib", "commit_url": "https://gitlab.gnome.org/GNOME/glib/commit/d553d92d6e9f53cbe5a34166fcb919ba652c6a8e", "commit_message": "gsocketclient: Fix criticals\n\nThis ensures the parent GTask is kept alive as long as an enumeration\nis running and trying to connect.\n\nCloses #1646\nCloses #1649", "target": 1, "func": "g_socket_client_connected_callback (GObject      *source,\n\t\t\t\t    GAsyncResult *result,\n\t\t\t\t    gpointer      user_data)\n{\n  ConnectionAttempt *attempt = user_data;\n  GSocketClientAsyncConnectData *data = attempt->data;\n  GSList *l;\n  GError *error = NULL;\n  GProxy *proxy;\n  const gchar *protocol;\n\n  /* data is NULL once the task is completed */\n  if (data && g_task_return_error_if_cancelled (data->task))\n    {\n      g_object_unref (data->task);\n      connection_attempt_unref (attempt);\n      return;\n    }\n\n  if (attempt->timeout_source)\n    {\n      g_source_destroy (attempt->timeout_source);\n      g_clear_pointer (&attempt->timeout_source, g_source_unref);\n    }\n\n  if (!g_socket_connection_connect_finish (G_SOCKET_CONNECTION (source),\n\t\t\t\t\t   result, &error))\n    {\n      if (!g_cancellable_is_cancelled (attempt->cancellable))\n        {\n          clarify_connect_error (error, data->connectable, attempt->address);\n          set_last_error (data, error);\n        }\n      else\n        g_clear_error (&error);\n\n      if (data)\n        {\n          connection_attempt_remove (attempt);\n          enumerator_next_async (data);\n        }\n      else\n        connection_attempt_unref (attempt);\n\n      return;\n    }\n\n  data->socket = g_steal_pointer (&attempt->socket);\n  data->connection = g_steal_pointer (&attempt->connection);\n\n  for (l = data->connection_attempts; l; l = g_slist_next (l))\n    {\n      ConnectionAttempt *attempt_entry = l->data;\n      g_cancellable_cancel (attempt_entry->cancellable);\n      attempt_entry->data = NULL;\n      connection_attempt_unref (attempt_entry);\n    }\n  g_slist_free (data->connection_attempts);\n  data->connection_attempts = NULL;\n  connection_attempt_unref (attempt);\n\n  g_socket_connection_set_cached_remote_address ((GSocketConnection*)data->connection, NULL);\n  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTED, data->connectable, data->connection);\n\n  /* wrong, but backward compatible */\n  g_socket_set_blocking (data->socket, TRUE);\n\n  if (!data->proxy_addr)\n    {\n      g_socket_client_tls_handshake (data);\n      return;\n    }\n\n  protocol = g_proxy_address_get_protocol (data->proxy_addr);\n\n  /* The connection should not be anything other than TCP,\n   * but let's put a safety guard in case\n   */\n  if (!G_IS_TCP_CONNECTION (data->connection))\n    {\n      g_critical (\"Trying to proxy over non-TCP connection, this is \"\n          \"most likely a bug in GLib IO library.\");\n\n      g_set_error_literal (&data->last_error,\n          G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,\n          _(\"Proxying over a non-TCP connection is not supported.\"));\n\n      enumerator_next_async (data);\n    }\n  else if (g_hash_table_contains (data->client->priv->app_proxies, protocol))\n    {\n      /* Simply complete the connection, we don't want to do TLS handshake\n       * as the application proxy handling may need proxy handshake first */\n      g_socket_client_async_connect_complete (data);\n    }\n  else if ((proxy = g_proxy_get_default_for_protocol (protocol)))\n    {\n      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, data->connectable, data->connection);\n      g_proxy_connect_async (proxy,\n                             data->connection,\n                             data->proxy_addr,\n                             g_task_get_cancellable (data->task),\n                             g_socket_client_proxy_connect_callback,\n                             data);\n      g_object_unref (proxy);\n    }\n  else\n    {\n      g_clear_error (&data->last_error);\n\n      g_set_error (&data->last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,\n          _(\"Proxy protocol \u201c%s\u201d is not supported.\"),\n          protocol);\n\n      enumerator_next_async (data);\n    }\n}", "func_hash": 303931634452049999477477859565079753152, "file_name": "gsocketclient.c", "file_hash": 112189477762116433441013263383719019263, "cwe": ["CWE-754"], "cve": "CVE-2019-9633", "cve_desc": "gio/gsocketclient.c in GNOME GLib 2.59.2 does not ensure that a parent GTask remains alive during the execution of a connection-attempting enumeration, which allows remote attackers to cause a denial of service (g_socket_client_connected_callback mishandling and application crash) via a crafted web site, as demonstrated by GNOME Web (aka Epiphany).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-9633"}
{"idx": 468349, "project": "glib", "commit_id": "d553d92d6e9f53cbe5a34166fcb919ba652c6a8e", "project_url": "https://gitlab.gnome.org/GNOME/glib", "commit_url": "https://gitlab.gnome.org/GNOME/glib/commit/d553d92d6e9f53cbe5a34166fcb919ba652c6a8e", "commit_message": "gsocketclient: Fix criticals\n\nThis ensures the parent GTask is kept alive as long as an enumeration\nis running and trying to connect.\n\nCloses #1646\nCloses #1649", "target": 0, "func": "g_socket_client_connected_callback (GObject      *source,\n\t\t\t\t    GAsyncResult *result,\n\t\t\t\t    gpointer      user_data)\n{\n  ConnectionAttempt *attempt = user_data;\n  GSocketClientAsyncConnectData *data = attempt->data;\n  GSList *l;\n  GError *error = NULL;\n  GProxy *proxy;\n  const gchar *protocol;\n\n  if (g_cancellable_is_cancelled (attempt->cancellable) || task_completed_or_cancelled (data->task))\n    {\n      g_object_unref (data->task);\n      connection_attempt_unref (attempt);\n      return;\n    }\n\n  if (attempt->timeout_source)\n    {\n      g_source_destroy (attempt->timeout_source);\n      g_clear_pointer (&attempt->timeout_source, g_source_unref);\n    }\n\n  if (!g_socket_connection_connect_finish (G_SOCKET_CONNECTION (source),\n\t\t\t\t\t   result, &error))\n    {\n      if (!g_cancellable_is_cancelled (attempt->cancellable))\n        {\n          clarify_connect_error (error, data->connectable, attempt->address);\n          set_last_error (data, error);\n          connection_attempt_remove (attempt);\n          enumerator_next_async (data, FALSE);\n        }\n      else\n        {\n          g_clear_error (&error);\n          g_object_unref (data->task);\n          connection_attempt_unref (attempt);\n        }\n\n      return;\n    }\n\n  data->socket = g_steal_pointer (&attempt->socket);\n  data->connection = g_steal_pointer (&attempt->connection);\n\n  for (l = data->connection_attempts; l; l = g_slist_next (l))\n    {\n      ConnectionAttempt *attempt_entry = l->data;\n      g_cancellable_cancel (attempt_entry->cancellable);\n      connection_attempt_unref (attempt_entry);\n    }\n  g_slist_free (data->connection_attempts);\n  data->connection_attempts = NULL;\n  connection_attempt_unref (attempt);\n\n  g_socket_connection_set_cached_remote_address ((GSocketConnection*)data->connection, NULL);\n  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTED, data->connectable, data->connection);\n\n  /* wrong, but backward compatible */\n  g_socket_set_blocking (data->socket, TRUE);\n\n  if (!data->proxy_addr)\n    {\n      g_socket_client_tls_handshake (data);\n      return;\n    }\n\n  protocol = g_proxy_address_get_protocol (data->proxy_addr);\n\n  /* The connection should not be anything other than TCP,\n   * but let's put a safety guard in case\n   */\n  if (!G_IS_TCP_CONNECTION (data->connection))\n    {\n      g_critical (\"Trying to proxy over non-TCP connection, this is \"\n          \"most likely a bug in GLib IO library.\");\n\n      g_set_error_literal (&data->last_error,\n          G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,\n          _(\"Proxying over a non-TCP connection is not supported.\"));\n\n      enumerator_next_async (data, FALSE);\n    }\n  else if (g_hash_table_contains (data->client->priv->app_proxies, protocol))\n    {\n      /* Simply complete the connection, we don't want to do TLS handshake\n       * as the application proxy handling may need proxy handshake first */\n      g_socket_client_async_connect_complete (data);\n    }\n  else if ((proxy = g_proxy_get_default_for_protocol (protocol)))\n    {\n      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, data->connectable, data->connection);\n      g_proxy_connect_async (proxy,\n                             data->connection,\n                             data->proxy_addr,\n                             g_task_get_cancellable (data->task),\n                             g_socket_client_proxy_connect_callback,\n                             data);\n      g_object_unref (proxy);\n    }\n  else\n    {\n      g_clear_error (&data->last_error);\n\n      g_set_error (&data->last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,\n          _(\"Proxy protocol \u201c%s\u201d is not supported.\"),\n          protocol);\n\n      enumerator_next_async (data, FALSE);\n    }\n}", "func_hash": 284257451684326472377624066772232784907, "file_name": "gsocketclient.c", "file_hash": 157905572963596557383512485968044873989, "cwe": ["CWE-754"], "cve": "CVE-2019-9633", "cve_desc": "gio/gsocketclient.c in GNOME GLib 2.59.2 does not ensure that a parent GTask remains alive during the execution of a connection-attempting enumeration, which allows remote attackers to cause a denial of service (g_socket_client_connected_callback mishandling and application crash) via a crafted web site, as demonstrated by GNOME Web (aka Epiphany).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-9633"}
{"idx": 213515, "project": "vim", "commit_id": "5c68617d395f9d7b824f68475b24ce3e38d653a3", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/5c68617d395f9d7b824f68475b24ce3e38d653a3", "commit_message": "patch 8.2.4563: \"z=\" in Visual mode may go beyond the end of the line\n\nProblem:    \"z=\" in Visual mode may go beyond the end of the line.\nSolution:   Adjust \"badlen\".", "target": 1, "func": "spell_suggest(int count)\n{\n    char_u\t*line;\n    pos_T\tprev_cursor = curwin->w_cursor;\n    char_u\twcopy[MAXWLEN + 2];\n    char_u\t*p;\n    int\t\ti;\n    int\t\tc;\n    suginfo_T\tsug;\n    suggest_T\t*stp;\n    int\t\tmouse_used;\n    int\t\tneed_cap;\n    int\t\tlimit;\n    int\t\tselected = count;\n    int\t\tbadlen = 0;\n    int\t\tmsg_scroll_save = msg_scroll;\n    int\t\two_spell_save = curwin->w_p_spell;\n\n    if (!curwin->w_p_spell)\n    {\n\tdid_set_spelllang(curwin);\n\tcurwin->w_p_spell = TRUE;\n    }\n\n    if (*curwin->w_s->b_p_spl == NUL)\n    {\n\temsg(_(e_spell_checking_is_not_possible));\n\treturn;\n    }\n\n    if (VIsual_active)\n    {\n\t// Use the Visually selected text as the bad word.  But reject\n\t// a multi-line selection.\n\tif (curwin->w_cursor.lnum != VIsual.lnum)\n\t{\n\t    vim_beep(BO_SPELL);\n\t    return;\n\t}\n\tbadlen = (int)curwin->w_cursor.col - (int)VIsual.col;\n\tif (badlen < 0)\n\t    badlen = -badlen;\n\telse\n\t    curwin->w_cursor.col = VIsual.col;\n\t++badlen;\n\tend_visual_mode();\n    }\n    // Find the start of the badly spelled word.\n    else if (spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL) == 0\n\t    || curwin->w_cursor.col > prev_cursor.col)\n    {\n\t// No bad word or it starts after the cursor: use the word under the\n\t// cursor.\n\tcurwin->w_cursor = prev_cursor;\n\tline = ml_get_curline();\n\tp = line + curwin->w_cursor.col;\n\t// Backup to before start of word.\n\twhile (p > line && spell_iswordp_nmw(p, curwin))\n\t    MB_PTR_BACK(line, p);\n\t// Forward to start of word.\n\twhile (*p != NUL && !spell_iswordp_nmw(p, curwin))\n\t    MB_PTR_ADV(p);\n\n\tif (!spell_iswordp_nmw(p, curwin))\t\t// No word found.\n\t{\n\t    beep_flush();\n\t    return;\n\t}\n\tcurwin->w_cursor.col = (colnr_T)(p - line);\n    }\n\n    // Get the word and its length.\n\n    // Figure out if the word should be capitalised.\n    need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col);\n\n    // Make a copy of current line since autocommands may free the line.\n    line = vim_strsave(ml_get_curline());\n    if (line == NULL)\n\tgoto skip;\n\n    // Get the list of suggestions.  Limit to 'lines' - 2 or the number in\n    // 'spellsuggest', whatever is smaller.\n    if (sps_limit > (int)Rows - 2)\n\tlimit = (int)Rows - 2;\n    else\n\tlimit = sps_limit;\n    spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit,\n\t\t\t\t\t\t\tTRUE, need_cap, TRUE);\n\n    if (sug.su_ga.ga_len == 0)\n\tmsg(_(\"Sorry, no suggestions\"));\n    else if (count > 0)\n    {\n\tif (count > sug.su_ga.ga_len)\n\t    smsg(_(\"Sorry, only %ld suggestions\"), (long)sug.su_ga.ga_len);\n    }\n    else\n    {\n#ifdef FEAT_RIGHTLEFT\n\t// When 'rightleft' is set the list is drawn right-left.\n\tcmdmsg_rl = curwin->w_p_rl;\n\tif (cmdmsg_rl)\n\t    msg_col = Columns - 1;\n#endif\n\n\t// List the suggestions.\n\tmsg_start();\n\tmsg_row = Rows - 1;\t// for when 'cmdheight' > 1\n\tlines_left = Rows;\t// avoid more prompt\n\tvim_snprintf((char *)IObuff, IOSIZE, _(\"Change \\\"%.*s\\\" to:\"),\n\t\t\t\t\t\tsug.su_badlen, sug.su_badptr);\n#ifdef FEAT_RIGHTLEFT\n\tif (cmdmsg_rl && STRNCMP(IObuff, \"Change\", 6) == 0)\n\t{\n\t    // And now the rabbit from the high hat: Avoid showing the\n\t    // untranslated message rightleft.\n\t    vim_snprintf((char *)IObuff, IOSIZE, \":ot \\\"%.*s\\\" egnahC\",\n\t\t\t\t\t\tsug.su_badlen, sug.su_badptr);\n\t}\n#endif\n\tmsg_puts((char *)IObuff);\n\tmsg_clr_eos();\n\tmsg_putchar('\\n');\n\n\tmsg_scroll = TRUE;\n\tfor (i = 0; i < sug.su_ga.ga_len; ++i)\n\t{\n\t    stp = &SUG(sug.su_ga, i);\n\n\t    // The suggested word may replace only part of the bad word, add\n\t    // the not replaced part.\n\t    vim_strncpy(wcopy, stp->st_word, MAXWLEN);\n\t    if (sug.su_badlen > stp->st_orglen)\n\t\tvim_strncpy(wcopy + stp->st_wordlen,\n\t\t\t\t\t       sug.su_badptr + stp->st_orglen,\n\t\t\t\t\t      sug.su_badlen - stp->st_orglen);\n\t    vim_snprintf((char *)IObuff, IOSIZE, \"%2d\", i + 1);\n#ifdef FEAT_RIGHTLEFT\n\t    if (cmdmsg_rl)\n\t\trl_mirror(IObuff);\n#endif\n\t    msg_puts((char *)IObuff);\n\n\t    vim_snprintf((char *)IObuff, IOSIZE, \" \\\"%s\\\"\", wcopy);\n\t    msg_puts((char *)IObuff);\n\n\t    // The word may replace more than \"su_badlen\".\n\t    if (sug.su_badlen < stp->st_orglen)\n\t    {\n\t\tvim_snprintf((char *)IObuff, IOSIZE, _(\" < \\\"%.*s\\\"\"),\n\t\t\t\t\t       stp->st_orglen, sug.su_badptr);\n\t\tmsg_puts((char *)IObuff);\n\t    }\n\n\t    if (p_verbose > 0)\n\t    {\n\t\t// Add the score.\n\t\tif (sps_flags & (SPS_DOUBLE | SPS_BEST))\n\t\t    vim_snprintf((char *)IObuff, IOSIZE, \" (%s%d - %d)\",\n\t\t\tstp->st_salscore ? \"s \" : \"\",\n\t\t\tstp->st_score, stp->st_altscore);\n\t\telse\n\t\t    vim_snprintf((char *)IObuff, IOSIZE, \" (%d)\",\n\t\t\t    stp->st_score);\n#ifdef FEAT_RIGHTLEFT\n\t\tif (cmdmsg_rl)\n\t\t    // Mirror the numbers, but keep the leading space.\n\t\t    rl_mirror(IObuff + 1);\n#endif\n\t\tmsg_advance(30);\n\t\tmsg_puts((char *)IObuff);\n\t    }\n\t    msg_putchar('\\n');\n\t}\n\n#ifdef FEAT_RIGHTLEFT\n\tcmdmsg_rl = FALSE;\n\tmsg_col = 0;\n#endif\n\t// Ask for choice.\n\tselected = prompt_for_number(&mouse_used);\n\tif (mouse_used)\n\t    selected -= lines_left;\n\tlines_left = Rows;\t\t// avoid more prompt\n\t// don't delay for 'smd' in normal_cmd()\n\tmsg_scroll = msg_scroll_save;\n    }\n\n    if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK)\n    {\n\t// Save the from and to text for :spellrepall.\n\tVIM_CLEAR(repl_from);\n\tVIM_CLEAR(repl_to);\n\n\tstp = &SUG(sug.su_ga, selected - 1);\n\tif (sug.su_badlen > stp->st_orglen)\n\t{\n\t    // Replacing less than \"su_badlen\", append the remainder to\n\t    // repl_to.\n\t    repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen);\n\t    vim_snprintf((char *)IObuff, IOSIZE, \"%s%.*s\", stp->st_word,\n\t\t    sug.su_badlen - stp->st_orglen,\n\t\t\t\t\t      sug.su_badptr + stp->st_orglen);\n\t    repl_to = vim_strsave(IObuff);\n\t}\n\telse\n\t{\n\t    // Replacing su_badlen or more, use the whole word.\n\t    repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen);\n\t    repl_to = vim_strsave(stp->st_word);\n\t}\n\n\t// Replace the word.\n\tp = alloc(STRLEN(line) - stp->st_orglen + stp->st_wordlen + 1);\n\tif (p != NULL)\n\t{\n\t    c = (int)(sug.su_badptr - line);\n\t    mch_memmove(p, line, c);\n\t    STRCPY(p + c, stp->st_word);\n\t    STRCAT(p, sug.su_badptr + stp->st_orglen);\n\n\t    // For redo we use a change-word command.\n\t    ResetRedobuff();\n\t    AppendToRedobuff((char_u *)\"ciw\");\n\t    AppendToRedobuffLit(p + c,\n\t\t\t    stp->st_wordlen + sug.su_badlen - stp->st_orglen);\n\t    AppendCharToRedobuff(ESC);\n\n\t    // \"p\" may be freed here\n\t    ml_replace(curwin->w_cursor.lnum, p, FALSE);\n\t    curwin->w_cursor.col = c;\n\n\t    changed_bytes(curwin->w_cursor.lnum, c);\n\t}\n    }\n    else\n\tcurwin->w_cursor = prev_cursor;\n\n    spell_find_cleanup(&sug);\nskip:\n    vim_free(line);\n    curwin->w_p_spell = wo_spell_save;\n}", "func_hash": 283321822802394416488141327214287342104, "file_name": "spellsuggest.c", "file_hash": 284064000006918275605147443263550733278, "cwe": ["CWE-787"], "cve": "CVE-2022-0943", "cve_desc": "Heap-based Buffer Overflow occurs in vim in GitHub repository vim/vim prior to 8.2.4563.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0943"}
{"idx": 471902, "project": "vim", "commit_id": "5c68617d395f9d7b824f68475b24ce3e38d653a3", "project_url": "https://github.com/vim/vim", "commit_url": "https://github.com/vim/vim/commit/5c68617d395f9d7b824f68475b24ce3e38d653a3", "commit_message": "patch 8.2.4563: \"z=\" in Visual mode may go beyond the end of the line\n\nProblem:    \"z=\" in Visual mode may go beyond the end of the line.\nSolution:   Adjust \"badlen\".", "target": 0, "func": "spell_suggest(int count)\n{\n    char_u\t*line;\n    pos_T\tprev_cursor = curwin->w_cursor;\n    char_u\twcopy[MAXWLEN + 2];\n    char_u\t*p;\n    int\t\ti;\n    int\t\tc;\n    suginfo_T\tsug;\n    suggest_T\t*stp;\n    int\t\tmouse_used;\n    int\t\tneed_cap;\n    int\t\tlimit;\n    int\t\tselected = count;\n    int\t\tbadlen = 0;\n    int\t\tmsg_scroll_save = msg_scroll;\n    int\t\two_spell_save = curwin->w_p_spell;\n\n    if (!curwin->w_p_spell)\n    {\n\tdid_set_spelllang(curwin);\n\tcurwin->w_p_spell = TRUE;\n    }\n\n    if (*curwin->w_s->b_p_spl == NUL)\n    {\n\temsg(_(e_spell_checking_is_not_possible));\n\treturn;\n    }\n\n    if (VIsual_active)\n    {\n\t// Use the Visually selected text as the bad word.  But reject\n\t// a multi-line selection.\n\tif (curwin->w_cursor.lnum != VIsual.lnum)\n\t{\n\t    vim_beep(BO_SPELL);\n\t    return;\n\t}\n\tbadlen = (int)curwin->w_cursor.col - (int)VIsual.col;\n\tif (badlen < 0)\n\t    badlen = -badlen;\n\telse\n\t    curwin->w_cursor.col = VIsual.col;\n\t++badlen;\n\tend_visual_mode();\n\t// make sure we don't include the NUL at the end of the line\n\tline = ml_get_curline();\n\tif (badlen > STRLEN(line) - curwin->w_cursor.col)\n\t    badlen = STRLEN(line) - curwin->w_cursor.col;\n    }\n    // Find the start of the badly spelled word.\n    else if (spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL) == 0\n\t    || curwin->w_cursor.col > prev_cursor.col)\n    {\n\t// No bad word or it starts after the cursor: use the word under the\n\t// cursor.\n\tcurwin->w_cursor = prev_cursor;\n\tline = ml_get_curline();\n\tp = line + curwin->w_cursor.col;\n\t// Backup to before start of word.\n\twhile (p > line && spell_iswordp_nmw(p, curwin))\n\t    MB_PTR_BACK(line, p);\n\t// Forward to start of word.\n\twhile (*p != NUL && !spell_iswordp_nmw(p, curwin))\n\t    MB_PTR_ADV(p);\n\n\tif (!spell_iswordp_nmw(p, curwin))\t\t// No word found.\n\t{\n\t    beep_flush();\n\t    return;\n\t}\n\tcurwin->w_cursor.col = (colnr_T)(p - line);\n    }\n\n    // Get the word and its length.\n\n    // Figure out if the word should be capitalised.\n    need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col);\n\n    // Make a copy of current line since autocommands may free the line.\n    line = vim_strsave(ml_get_curline());\n    if (line == NULL)\n\tgoto skip;\n\n    // Get the list of suggestions.  Limit to 'lines' - 2 or the number in\n    // 'spellsuggest', whatever is smaller.\n    if (sps_limit > (int)Rows - 2)\n\tlimit = (int)Rows - 2;\n    else\n\tlimit = sps_limit;\n    spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit,\n\t\t\t\t\t\t\tTRUE, need_cap, TRUE);\n\n    if (sug.su_ga.ga_len == 0)\n\tmsg(_(\"Sorry, no suggestions\"));\n    else if (count > 0)\n    {\n\tif (count > sug.su_ga.ga_len)\n\t    smsg(_(\"Sorry, only %ld suggestions\"), (long)sug.su_ga.ga_len);\n    }\n    else\n    {\n#ifdef FEAT_RIGHTLEFT\n\t// When 'rightleft' is set the list is drawn right-left.\n\tcmdmsg_rl = curwin->w_p_rl;\n\tif (cmdmsg_rl)\n\t    msg_col = Columns - 1;\n#endif\n\n\t// List the suggestions.\n\tmsg_start();\n\tmsg_row = Rows - 1;\t// for when 'cmdheight' > 1\n\tlines_left = Rows;\t// avoid more prompt\n\tvim_snprintf((char *)IObuff, IOSIZE, _(\"Change \\\"%.*s\\\" to:\"),\n\t\t\t\t\t\tsug.su_badlen, sug.su_badptr);\n#ifdef FEAT_RIGHTLEFT\n\tif (cmdmsg_rl && STRNCMP(IObuff, \"Change\", 6) == 0)\n\t{\n\t    // And now the rabbit from the high hat: Avoid showing the\n\t    // untranslated message rightleft.\n\t    vim_snprintf((char *)IObuff, IOSIZE, \":ot \\\"%.*s\\\" egnahC\",\n\t\t\t\t\t\tsug.su_badlen, sug.su_badptr);\n\t}\n#endif\n\tmsg_puts((char *)IObuff);\n\tmsg_clr_eos();\n\tmsg_putchar('\\n');\n\n\tmsg_scroll = TRUE;\n\tfor (i = 0; i < sug.su_ga.ga_len; ++i)\n\t{\n\t    stp = &SUG(sug.su_ga, i);\n\n\t    // The suggested word may replace only part of the bad word, add\n\t    // the not replaced part.\n\t    vim_strncpy(wcopy, stp->st_word, MAXWLEN);\n\t    if (sug.su_badlen > stp->st_orglen)\n\t\tvim_strncpy(wcopy + stp->st_wordlen,\n\t\t\t\t\t       sug.su_badptr + stp->st_orglen,\n\t\t\t\t\t      sug.su_badlen - stp->st_orglen);\n\t    vim_snprintf((char *)IObuff, IOSIZE, \"%2d\", i + 1);\n#ifdef FEAT_RIGHTLEFT\n\t    if (cmdmsg_rl)\n\t\trl_mirror(IObuff);\n#endif\n\t    msg_puts((char *)IObuff);\n\n\t    vim_snprintf((char *)IObuff, IOSIZE, \" \\\"%s\\\"\", wcopy);\n\t    msg_puts((char *)IObuff);\n\n\t    // The word may replace more than \"su_badlen\".\n\t    if (sug.su_badlen < stp->st_orglen)\n\t    {\n\t\tvim_snprintf((char *)IObuff, IOSIZE, _(\" < \\\"%.*s\\\"\"),\n\t\t\t\t\t       stp->st_orglen, sug.su_badptr);\n\t\tmsg_puts((char *)IObuff);\n\t    }\n\n\t    if (p_verbose > 0)\n\t    {\n\t\t// Add the score.\n\t\tif (sps_flags & (SPS_DOUBLE | SPS_BEST))\n\t\t    vim_snprintf((char *)IObuff, IOSIZE, \" (%s%d - %d)\",\n\t\t\tstp->st_salscore ? \"s \" : \"\",\n\t\t\tstp->st_score, stp->st_altscore);\n\t\telse\n\t\t    vim_snprintf((char *)IObuff, IOSIZE, \" (%d)\",\n\t\t\t    stp->st_score);\n#ifdef FEAT_RIGHTLEFT\n\t\tif (cmdmsg_rl)\n\t\t    // Mirror the numbers, but keep the leading space.\n\t\t    rl_mirror(IObuff + 1);\n#endif\n\t\tmsg_advance(30);\n\t\tmsg_puts((char *)IObuff);\n\t    }\n\t    msg_putchar('\\n');\n\t}\n\n#ifdef FEAT_RIGHTLEFT\n\tcmdmsg_rl = FALSE;\n\tmsg_col = 0;\n#endif\n\t// Ask for choice.\n\tselected = prompt_for_number(&mouse_used);\n\tif (mouse_used)\n\t    selected -= lines_left;\n\tlines_left = Rows;\t\t// avoid more prompt\n\t// don't delay for 'smd' in normal_cmd()\n\tmsg_scroll = msg_scroll_save;\n    }\n\n    if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK)\n    {\n\t// Save the from and to text for :spellrepall.\n\tVIM_CLEAR(repl_from);\n\tVIM_CLEAR(repl_to);\n\n\tstp = &SUG(sug.su_ga, selected - 1);\n\tif (sug.su_badlen > stp->st_orglen)\n\t{\n\t    // Replacing less than \"su_badlen\", append the remainder to\n\t    // repl_to.\n\t    repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen);\n\t    vim_snprintf((char *)IObuff, IOSIZE, \"%s%.*s\", stp->st_word,\n\t\t    sug.su_badlen - stp->st_orglen,\n\t\t\t\t\t      sug.su_badptr + stp->st_orglen);\n\t    repl_to = vim_strsave(IObuff);\n\t}\n\telse\n\t{\n\t    // Replacing su_badlen or more, use the whole word.\n\t    repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen);\n\t    repl_to = vim_strsave(stp->st_word);\n\t}\n\n\t// Replace the word.\n\tp = alloc(STRLEN(line) - stp->st_orglen + stp->st_wordlen + 1);\n\tif (p != NULL)\n\t{\n\t    c = (int)(sug.su_badptr - line);\n\t    mch_memmove(p, line, c);\n\t    STRCPY(p + c, stp->st_word);\n\t    STRCAT(p, sug.su_badptr + stp->st_orglen);\n\n\t    // For redo we use a change-word command.\n\t    ResetRedobuff();\n\t    AppendToRedobuff((char_u *)\"ciw\");\n\t    AppendToRedobuffLit(p + c,\n\t\t\t    stp->st_wordlen + sug.su_badlen - stp->st_orglen);\n\t    AppendCharToRedobuff(ESC);\n\n\t    // \"p\" may be freed here\n\t    ml_replace(curwin->w_cursor.lnum, p, FALSE);\n\t    curwin->w_cursor.col = c;\n\n\t    changed_bytes(curwin->w_cursor.lnum, c);\n\t}\n    }\n    else\n\tcurwin->w_cursor = prev_cursor;\n\n    spell_find_cleanup(&sug);\nskip:\n    vim_free(line);\n    curwin->w_p_spell = wo_spell_save;\n}", "func_hash": 210769611717793726730537343470434116318, "file_name": "spellsuggest.c", "file_hash": 285304759407649884654167568930599876914, "cwe": ["CWE-787"], "cve": "CVE-2022-0943", "cve_desc": "Heap-based Buffer Overflow occurs in vim in GitHub repository vim/vim prior to 8.2.4563.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0943"}
{"idx": 213528, "project": "linux", "commit_id": "3b0462726e7ef281c35a7a4ae33e93ee2bc9975b", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/3b0462726e7ef281c35a7a4ae33e93ee2bc9975b", "commit_message": "cgroup: verify that source is a string\n\nThe following sequence can be used to trigger a UAF:\n\n    int fscontext_fd = fsopen(\"cgroup\");\n    int fd_null = open(\"/dev/null, O_RDONLY);\n    int fsconfig(fscontext_fd, FSCONFIG_SET_FD, \"source\", fd_null);\n    close_range(3, ~0U, 0);\n\nThe cgroup v1 specific fs parser expects a string for the \"source\"\nparameter.  However, it is perfectly legitimate to e.g.  specify a file\ndescriptor for the \"source\" parameter.  The fs parser doesn't know what\na filesystem allows there.  So it's a bug to assume that \"source\" is\nalways of type fs_value_is_string when it can reasonably also be\nfs_value_is_file.\n\nThis assumption in the cgroup code causes a UAF because struct\nfs_parameter uses a union for the actual value.  Access to that union is\nguarded by the param->type member.  Since the cgroup paramter parser\ndidn't check param->type but unconditionally moved param->string into\nfc->source a close on the fscontext_fd would trigger a UAF during\nput_fs_context() which frees fc->source thereby freeing the file stashed\nin param->file causing a UAF during a close of the fd_null.\n\nFix this by verifying that param->type is actually a string and report\nan error if not.\n\nIn follow up patches I'll add a new generic helper that can be used here\nand by other filesystems instead of this error-prone copy-pasta fix.\nBut fixing it in here first makes backporting a it to stable a lot\neasier.\n\nFixes: 8d2451f4994f (\"cgroup1: switch to option-by-option parsing\")\nReported-by: syzbot+283ce5a46486d6acdbaf@syzkaller.appspotmail.com\nCc: Christoph Hellwig \nCc: Alexander Viro \nCc: Dmitry Vyukov \nCc: \nCc: syzkaller-bugs \nSigned-off-by: Christian Brauner \nSigned-off-by: Linus Torvalds ", "target": 1, "func": "int cgroup1_parse_param(struct fs_context *fc, struct fs_parameter *param)\n{\n\tstruct cgroup_fs_context *ctx = cgroup_fc2context(fc);\n\tstruct cgroup_subsys *ss;\n\tstruct fs_parse_result result;\n\tint opt, i;\n\n\topt = fs_parse(fc, cgroup1_fs_parameters, param, &result);\n\tif (opt == -ENOPARAM) {\n\t\tif (strcmp(param->key, \"source\") == 0) {\n\t\t\tif (fc->source)\n\t\t\t\treturn invalf(fc, \"Multiple sources not supported\");\n\t\t\tfc->source = param->string;\n\t\t\tparam->string = NULL;\n\t\t\treturn 0;\n\t\t}\n\t\tfor_each_subsys(ss, i) {\n\t\t\tif (strcmp(param->key, ss->legacy_name))\n\t\t\t\tcontinue;\n\t\t\tif (!cgroup_ssid_enabled(i) || cgroup1_ssid_disabled(i))\n\t\t\t\treturn invalfc(fc, \"Disabled controller '%s'\",\n\t\t\t\t\t       param->key);\n\t\t\tctx->subsys_mask |= (1 << i);\n\t\t\treturn 0;\n\t\t}\n\t\treturn invalfc(fc, \"Unknown subsys name '%s'\", param->key);\n\t}\n\tif (opt < 0)\n\t\treturn opt;\n\n\tswitch (opt) {\n\tcase Opt_none:\n\t\t/* Explicitly have no subsystems */\n\t\tctx->none = true;\n\t\tbreak;\n\tcase Opt_all:\n\t\tctx->all_ss = true;\n\t\tbreak;\n\tcase Opt_noprefix:\n\t\tctx->flags |= CGRP_ROOT_NOPREFIX;\n\t\tbreak;\n\tcase Opt_clone_children:\n\t\tctx->cpuset_clone_children = true;\n\t\tbreak;\n\tcase Opt_cpuset_v2_mode:\n\t\tctx->flags |= CGRP_ROOT_CPUSET_V2_MODE;\n\t\tbreak;\n\tcase Opt_xattr:\n\t\tctx->flags |= CGRP_ROOT_XATTR;\n\t\tbreak;\n\tcase Opt_release_agent:\n\t\t/* Specifying two release agents is forbidden */\n\t\tif (ctx->release_agent)\n\t\t\treturn invalfc(fc, \"release_agent respecified\");\n\t\tctx->release_agent = param->string;\n\t\tparam->string = NULL;\n\t\tbreak;\n\tcase Opt_name:\n\t\t/* blocked by boot param? */\n\t\tif (cgroup_no_v1_named)\n\t\t\treturn -ENOENT;\n\t\t/* Can't specify an empty name */\n\t\tif (!param->size)\n\t\t\treturn invalfc(fc, \"Empty name\");\n\t\tif (param->size > MAX_CGROUP_ROOT_NAMELEN - 1)\n\t\t\treturn invalfc(fc, \"Name too long\");\n\t\t/* Must match [\\w.-]+ */\n\t\tfor (i = 0; i < param->size; i++) {\n\t\t\tchar c = param->string[i];\n\t\t\tif (isalnum(c))\n\t\t\t\tcontinue;\n\t\t\tif ((c == '.') || (c == '-') || (c == '_'))\n\t\t\t\tcontinue;\n\t\t\treturn invalfc(fc, \"Invalid name\");\n\t\t}\n\t\t/* Specifying two names is forbidden */\n\t\tif (ctx->name)\n\t\t\treturn invalfc(fc, \"name respecified\");\n\t\tctx->name = param->string;\n\t\tparam->string = NULL;\n\t\tbreak;\n\t}\n\treturn 0;\n}", "func_hash": 2447930720327269598694221319559062155, "file_name": "cgroup-v1.c", "file_hash": 304027161926251240992448703175506915313, "cwe": ["CWE-416"], "cve": "CVE-2021-4154", "cve_desc": "A use-after-free flaw was found in cgroup1_parse_param in kernel/cgroup/cgroup-v1.c in the Linux kernel's cgroup v1 parser. A local attacker with a user privilege could cause a privilege escalation by exploiting the fsconfig syscall parameter leading to a container breakout and a denial of service on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-4154"}
{"idx": 472123, "project": "linux", "commit_id": "3b0462726e7ef281c35a7a4ae33e93ee2bc9975b", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/3b0462726e7ef281c35a7a4ae33e93ee2bc9975b", "commit_message": "cgroup: verify that source is a string\n\nThe following sequence can be used to trigger a UAF:\n\n    int fscontext_fd = fsopen(\"cgroup\");\n    int fd_null = open(\"/dev/null, O_RDONLY);\n    int fsconfig(fscontext_fd, FSCONFIG_SET_FD, \"source\", fd_null);\n    close_range(3, ~0U, 0);\n\nThe cgroup v1 specific fs parser expects a string for the \"source\"\nparameter.  However, it is perfectly legitimate to e.g.  specify a file\ndescriptor for the \"source\" parameter.  The fs parser doesn't know what\na filesystem allows there.  So it's a bug to assume that \"source\" is\nalways of type fs_value_is_string when it can reasonably also be\nfs_value_is_file.\n\nThis assumption in the cgroup code causes a UAF because struct\nfs_parameter uses a union for the actual value.  Access to that union is\nguarded by the param->type member.  Since the cgroup paramter parser\ndidn't check param->type but unconditionally moved param->string into\nfc->source a close on the fscontext_fd would trigger a UAF during\nput_fs_context() which frees fc->source thereby freeing the file stashed\nin param->file causing a UAF during a close of the fd_null.\n\nFix this by verifying that param->type is actually a string and report\nan error if not.\n\nIn follow up patches I'll add a new generic helper that can be used here\nand by other filesystems instead of this error-prone copy-pasta fix.\nBut fixing it in here first makes backporting a it to stable a lot\neasier.\n\nFixes: 8d2451f4994f (\"cgroup1: switch to option-by-option parsing\")\nReported-by: syzbot+283ce5a46486d6acdbaf@syzkaller.appspotmail.com\nCc: Christoph Hellwig \nCc: Alexander Viro \nCc: Dmitry Vyukov \nCc: \nCc: syzkaller-bugs \nSigned-off-by: Christian Brauner \nSigned-off-by: Linus Torvalds ", "target": 0, "func": "int cgroup1_parse_param(struct fs_context *fc, struct fs_parameter *param)\n{\n\tstruct cgroup_fs_context *ctx = cgroup_fc2context(fc);\n\tstruct cgroup_subsys *ss;\n\tstruct fs_parse_result result;\n\tint opt, i;\n\n\topt = fs_parse(fc, cgroup1_fs_parameters, param, &result);\n\tif (opt == -ENOPARAM) {\n\t\tif (strcmp(param->key, \"source\") == 0) {\n\t\t\tif (param->type != fs_value_is_string)\n\t\t\t\treturn invalf(fc, \"Non-string source\");\n\t\t\tif (fc->source)\n\t\t\t\treturn invalf(fc, \"Multiple sources not supported\");\n\t\t\tfc->source = param->string;\n\t\t\tparam->string = NULL;\n\t\t\treturn 0;\n\t\t}\n\t\tfor_each_subsys(ss, i) {\n\t\t\tif (strcmp(param->key, ss->legacy_name))\n\t\t\t\tcontinue;\n\t\t\tif (!cgroup_ssid_enabled(i) || cgroup1_ssid_disabled(i))\n\t\t\t\treturn invalfc(fc, \"Disabled controller '%s'\",\n\t\t\t\t\t       param->key);\n\t\t\tctx->subsys_mask |= (1 << i);\n\t\t\treturn 0;\n\t\t}\n\t\treturn invalfc(fc, \"Unknown subsys name '%s'\", param->key);\n\t}\n\tif (opt < 0)\n\t\treturn opt;\n\n\tswitch (opt) {\n\tcase Opt_none:\n\t\t/* Explicitly have no subsystems */\n\t\tctx->none = true;\n\t\tbreak;\n\tcase Opt_all:\n\t\tctx->all_ss = true;\n\t\tbreak;\n\tcase Opt_noprefix:\n\t\tctx->flags |= CGRP_ROOT_NOPREFIX;\n\t\tbreak;\n\tcase Opt_clone_children:\n\t\tctx->cpuset_clone_children = true;\n\t\tbreak;\n\tcase Opt_cpuset_v2_mode:\n\t\tctx->flags |= CGRP_ROOT_CPUSET_V2_MODE;\n\t\tbreak;\n\tcase Opt_xattr:\n\t\tctx->flags |= CGRP_ROOT_XATTR;\n\t\tbreak;\n\tcase Opt_release_agent:\n\t\t/* Specifying two release agents is forbidden */\n\t\tif (ctx->release_agent)\n\t\t\treturn invalfc(fc, \"release_agent respecified\");\n\t\tctx->release_agent = param->string;\n\t\tparam->string = NULL;\n\t\tbreak;\n\tcase Opt_name:\n\t\t/* blocked by boot param? */\n\t\tif (cgroup_no_v1_named)\n\t\t\treturn -ENOENT;\n\t\t/* Can't specify an empty name */\n\t\tif (!param->size)\n\t\t\treturn invalfc(fc, \"Empty name\");\n\t\tif (param->size > MAX_CGROUP_ROOT_NAMELEN - 1)\n\t\t\treturn invalfc(fc, \"Name too long\");\n\t\t/* Must match [\\w.-]+ */\n\t\tfor (i = 0; i < param->size; i++) {\n\t\t\tchar c = param->string[i];\n\t\t\tif (isalnum(c))\n\t\t\t\tcontinue;\n\t\t\tif ((c == '.') || (c == '-') || (c == '_'))\n\t\t\t\tcontinue;\n\t\t\treturn invalfc(fc, \"Invalid name\");\n\t\t}\n\t\t/* Specifying two names is forbidden */\n\t\tif (ctx->name)\n\t\t\treturn invalfc(fc, \"name respecified\");\n\t\tctx->name = param->string;\n\t\tparam->string = NULL;\n\t\tbreak;\n\t}\n\treturn 0;\n}", "func_hash": 334870785845210346899642963550735857549, "file_name": "cgroup-v1.c", "file_hash": 43168048456517404384153301721017353964, "cwe": ["CWE-416"], "cve": "CVE-2021-4154", "cve_desc": "A use-after-free flaw was found in cgroup1_parse_param in kernel/cgroup/cgroup-v1.c in the Linux kernel's cgroup v1 parser. A local attacker with a user privilege could cause a privilege escalation by exploiting the fsconfig syscall parameter leading to a container breakout and a denial of service on the system.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-4154"}
{"idx": 213998, "project": "libtpms", "commit_id": "ea62fd9679f8c6fc5e79471b33cfbd8227bfed72", "project_url": "https://github.com/stefanberger/libtpms", "commit_url": "https://github.com/stefanberger/libtpms/commit/ea62fd9679f8c6fc5e79471b33cfbd8227bfed72", "commit_message": "tpm2: Initialize a whole OBJECT before using it\n\nInitialize a whole OBJECT before using it. This is necessary since\nan OBJECT may also be used as a HASH_OBJECT via the ANY_OBJECT\nunion and that HASH_OBJECT can leave bad size inidicators in TPM2B\nbuffer in the OBJECT. To get rid of this problem we reset the whole\nOBJECT to 0 before using it. This is as if the memory for the\nOBJECT was just initialized.\n\nSigned-off-by: Stefan Berger ", "target": 1, "func": "FindEmptyObjectSlot(\n\t\t    TPMI_DH_OBJECT  *handle         // OUT: (optional)\n\t\t    )\n{\n    UINT32               i;\n    OBJECT              *object;\n    for(i = 0; i < MAX_LOADED_OBJECTS; i++)\n\t{\n\t    object = &s_objects[i];\n\t    if(object->attributes.occupied == CLEAR)\n\t\t{\n\t\t    if(handle)\n\t\t\t*handle = i + TRANSIENT_FIRST;\n\t\t    // Initialize the object attributes\n\t\t    MemorySet(&object->attributes, 0, sizeof(OBJECT_ATTRIBUTES));\n\t\t    return object;\n\t\t}\n\t}\n    return NULL;\n}", "func_hash": 267307307566893737550652048570735094605, "file_name": "Object.c", "file_hash": 21721239087984404174741324804041111077, "cwe": ["CWE-119"], "cve": "CVE-2021-3746", "cve_desc": "A flaw was found in the libtpms code that may cause access beyond the boundary of internal buffers. The vulnerability is triggered by specially-crafted TPM2 command packets that then trigger the issue when the state of the TPM2's volatile state is written. The highest threat from this vulnerability is to system availability. This issue affects libtpms versions before 0.8.5, before 0.7.9 and before 0.6.6.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3746"}
{"idx": 474434, "project": "libtpms", "commit_id": "ea62fd9679f8c6fc5e79471b33cfbd8227bfed72", "project_url": "https://github.com/stefanberger/libtpms", "commit_url": "https://github.com/stefanberger/libtpms/commit/ea62fd9679f8c6fc5e79471b33cfbd8227bfed72", "commit_message": "tpm2: Initialize a whole OBJECT before using it\n\nInitialize a whole OBJECT before using it. This is necessary since\nan OBJECT may also be used as a HASH_OBJECT via the ANY_OBJECT\nunion and that HASH_OBJECT can leave bad size inidicators in TPM2B\nbuffer in the OBJECT. To get rid of this problem we reset the whole\nOBJECT to 0 before using it. This is as if the memory for the\nOBJECT was just initialized.\n\nSigned-off-by: Stefan Berger ", "target": 0, "func": "FindEmptyObjectSlot(\n\t\t    TPMI_DH_OBJECT  *handle         // OUT: (optional)\n\t\t    )\n{\n    UINT32               i;\n    OBJECT              *object;\n    for(i = 0; i < MAX_LOADED_OBJECTS; i++)\n\t{\n\t    object = &s_objects[i];\n\t    if(object->attributes.occupied == CLEAR)\n\t\t{\n\t\t    if(handle)\n\t\t\t*handle = i + TRANSIENT_FIRST;\n\t\t    // Initialize the object attributes\n\t\t    // MemorySet(&object->attributes, 0, sizeof(OBJECT_ATTRIBUTES));\n\t\t    MemorySet(object, 0, sizeof(*object)); // libtpms added: Initialize the whole object\n\t\t    return object;\n\t\t}\n\t}\n    return NULL;\n}", "func_hash": 327698206124968939324347029407328822774, "file_name": "Object.c", "file_hash": 122617348389867631937316179213551374827, "cwe": ["CWE-119"], "cve": "CVE-2021-3746", "cve_desc": "A flaw was found in the libtpms code that may cause access beyond the boundary of internal buffers. The vulnerability is triggered by specially-crafted TPM2 command packets that then trigger the issue when the state of the TPM2's volatile state is written. The highest threat from this vulnerability is to system availability. This issue affects libtpms versions before 0.8.5, before 0.7.9 and before 0.6.6.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3746"}
{"idx": 214003, "project": "libvncserver", "commit_id": "7b1ef0ffc4815cab9a96c7278394152bdc89dc4d", "project_url": "https://github.com/LibVNC/libvncserver", "commit_url": "https://github.com/LibVNC/libvncserver/commit/7b1ef0ffc4815cab9a96c7278394152bdc89dc4d", "commit_message": "LibVNCClient: really fix #250", "target": 1, "func": "HandleCoRREBPP (rfbClient* client, int rx, int ry, int rw, int rh)\n{\n    rfbRREHeader hdr;\n    int i;\n    CARDBPP pix;\n    uint8_t *ptr;\n    int x, y, w, h;\n\n    if (!ReadFromRFBServer(client, (char *)&hdr, sz_rfbRREHeader))\n\treturn FALSE;\n\n    hdr.nSubrects = rfbClientSwap32IfLE(hdr.nSubrects);\n\n    if (!ReadFromRFBServer(client, (char *)&pix, sizeof(pix)))\n\treturn FALSE;\n\n    client->GotFillRect(client, rx, ry, rw, rh, pix);\n\n    if (hdr.nSubrects * (4 + (BPP / 8)) > RFB_BUFFER_SIZE || !ReadFromRFBServer(client, client->buffer, hdr.nSubrects * (4 + (BPP / 8))))\n\treturn FALSE;\n\n    ptr = (uint8_t *)client->buffer;\n\n    for (i = 0; i < hdr.nSubrects; i++) {\n\tpix = *(CARDBPP *)ptr;\n\tptr += BPP/8;\n\tx = *ptr++;\n\ty = *ptr++;\n\tw = *ptr++;\n\th = *ptr++;\n\n\tclient->GotFillRect(client, rx+x, ry+y, w, h, pix);\n    }\n\n    return TRUE;\n}", "func_hash": 237803274447948071871623859823888407579, "file_name": "corre.c", "file_hash": 261775603875912977761086457849276889433, "cwe": ["CWE-787"], "cve": "CVE-2018-20020", "cve_desc": "LibVNC before commit 7b1ef0ffc4815cab9a96c7278394152bdc89dc4d contains heap out-of-bound write vulnerability inside structure in VNC client code that can result remote code execution", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-20020"}
{"idx": 474462, "project": "libvncserver", "commit_id": "7b1ef0ffc4815cab9a96c7278394152bdc89dc4d", "project_url": "https://github.com/LibVNC/libvncserver", "commit_url": "https://github.com/LibVNC/libvncserver/commit/7b1ef0ffc4815cab9a96c7278394152bdc89dc4d", "commit_message": "LibVNCClient: really fix #250", "target": 0, "func": "HandleCoRREBPP (rfbClient* client, int rx, int ry, int rw, int rh)\n{\n    rfbRREHeader hdr;\n    int i;\n    CARDBPP pix;\n    uint8_t *ptr;\n    int x, y, w, h;\n\n    if (!ReadFromRFBServer(client, (char *)&hdr, sz_rfbRREHeader))\n\treturn FALSE;\n\n    hdr.nSubrects = rfbClientSwap32IfLE(hdr.nSubrects);\n\n    if (!ReadFromRFBServer(client, (char *)&pix, sizeof(pix)))\n\treturn FALSE;\n\n    client->GotFillRect(client, rx, ry, rw, rh, pix);\n\n    if (hdr.nSubrects > RFB_BUFFER_SIZE / (4 + (BPP / 8)) || !ReadFromRFBServer(client, client->buffer, hdr.nSubrects * (4 + (BPP / 8))))\n\treturn FALSE;\n\n    ptr = (uint8_t *)client->buffer;\n\n    for (i = 0; i < hdr.nSubrects; i++) {\n\tpix = *(CARDBPP *)ptr;\n\tptr += BPP/8;\n\tx = *ptr++;\n\ty = *ptr++;\n\tw = *ptr++;\n\th = *ptr++;\n\n\tclient->GotFillRect(client, rx+x, ry+y, w, h, pix);\n    }\n\n    return TRUE;\n}", "func_hash": 270120955611228778905999334086826608945, "file_name": "corre.c", "file_hash": 95538594092483864981062945399271614171, "cwe": ["CWE-787"], "cve": "CVE-2018-20020", "cve_desc": "LibVNC before commit 7b1ef0ffc4815cab9a96c7278394152bdc89dc4d contains heap out-of-bound write vulnerability inside structure in VNC client code that can result remote code execution", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-20020"}
{"idx": 214124, "project": "chafa", "commit_id": "e6ce3746cdcf0836b9dae659a5aed15d73a080d8", "project_url": "https://github.com/hpjansson/chafa", "commit_url": "https://github.com/hpjansson/chafa/commit/e6ce3746cdcf0836b9dae659a5aed15d73a080d8", "commit_message": "libnsgif: fix oob in lzw_decode", "target": 1, "func": "lzw_result lzw_decode(struct lzw_ctx *ctx,\n\t\tconst uint8_t ** const stack_pos_out)\n{\n\tlzw_result res;\n\tuint32_t code_new;\n\tuint32_t code_out;\n\tuint8_t last_value;\n\tuint8_t *stack_pos = ctx->stack_base;\n\tuint32_t clear_code = ctx->clear_code;\n\tuint32_t current_entry = ctx->current_entry;\n\tstruct lzw_dictionary_entry * const table = ctx->table;\n\n\t/* Get a new code from the input */\n\tres = lzw__next_code(&ctx->input, ctx->current_code_size, &code_new);\n\tif (res != LZW_OK) {\n\t\treturn res;\n\t}\n\n\t/* Handle the new code */\n\tif (code_new == clear_code) {\n\t\t/* Got Clear code */\n\t\treturn lzw__clear_codes(ctx, stack_pos_out);\n\n\t} else if (code_new == ctx->eoi_code) {\n\t\t/* Got End of Information code */\n\t\treturn LZW_EOI_CODE;\n\n\t} else if (code_new > current_entry) {\n\t\t/* Code is invalid */\n\t\treturn LZW_BAD_CODE;\n\n\t} else if (code_new < current_entry) {\n\t\t/* Code is in table */\n\t\tcode_out = code_new;\n\t\tlast_value = table[code_new].first_value;\n\t} else {\n\t\t/* Code not in table */\n\t\t*stack_pos++ = ctx->previous_code_first;\n\t\tcode_out = ctx->previous_code;\n\t\tlast_value = ctx->previous_code_first;\n\t}\n\n\t/* Add to the dictionary, only if there's space */\n\tif (current_entry < (1 << LZW_CODE_MAX)) {\n\t\tstruct lzw_dictionary_entry *entry = table + current_entry;\n\t\tentry->last_value     = last_value;\n\t\tentry->first_value    = ctx->previous_code_first;\n\t\tentry->previous_entry = ctx->previous_code;\n\t\tctx->current_entry++;\n\t}\n\n\t/* Ensure code size is increased, if needed. */\n\tif (current_entry == ctx->current_code_size_max) {\n\t\tif (ctx->current_code_size < LZW_CODE_MAX) {\n\t\t\tctx->current_code_size++;\n\t\t\tctx->current_code_size_max =\n\t\t\t\t\t(1 << ctx->current_code_size) - 1;\n\t\t}\n\t}\n\n\t/* Store details of this code as \"previous code\" to the context. */\n\tctx->previous_code_first = table[code_new].first_value;\n\tctx->previous_code = code_new;\n\n\t/* Put rest of data for this code on output stack.\n\t * Note, in the case of \"code not in table\", the last entry of the\n\t * current code has already been placed on the stack above. */\n\twhile (code_out > clear_code) {\n\t\tstruct lzw_dictionary_entry *entry = table + code_out;\n\t\t*stack_pos++ = entry->last_value;\n\t\tcode_out = entry->previous_entry;\n\t}\n\t*stack_pos++ = table[code_out].last_value;\n\n\t*stack_pos_out = stack_pos;\n\treturn LZW_OK;\n}", "func_hash": 197312030105469318680562726195282198881, "file_name": "lzw.c", "file_hash": 206609516216923718063023254663769273017, "cwe": ["CWE-125"], "cve": "CVE-2022-2061", "cve_desc": "Heap-based Buffer Overflow in GitHub repository hpjansson/chafa prior to 1.12.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2061"}
{"idx": 475987, "project": "chafa", "commit_id": "e6ce3746cdcf0836b9dae659a5aed15d73a080d8", "project_url": "https://github.com/hpjansson/chafa", "commit_url": "https://github.com/hpjansson/chafa/commit/e6ce3746cdcf0836b9dae659a5aed15d73a080d8", "commit_message": "libnsgif: fix oob in lzw_decode", "target": 0, "func": "lzw_result lzw_decode(struct lzw_ctx *ctx,\n\t\tconst uint8_t ** const stack_pos_out)\n{\n\tlzw_result res;\n\tuint32_t code_new;\n\tuint32_t code_out;\n\tuint8_t last_value;\n\tuint8_t *stack_pos = ctx->stack_base;\n\tuint32_t clear_code = ctx->clear_code;\n\tuint32_t current_entry = ctx->current_entry;\n\tstruct lzw_dictionary_entry * const table = ctx->table;\n\n\t/* Get a new code from the input */\n\tres = lzw__next_code(&ctx->input, ctx->current_code_size, &code_new);\n\tif (res != LZW_OK) {\n\t\treturn res;\n\t}\n\n\t/* Handle the new code */\n\tif (code_new == clear_code) {\n\t\t/* Got Clear code */\n\t\treturn lzw__clear_codes(ctx, stack_pos_out);\n\n\t} else if (code_new == ctx->eoi_code) {\n\t\t/* Got End of Information code */\n\t\treturn LZW_EOI_CODE;\n\n\t} else if (code_new > current_entry) {\n\t\t/* Code is invalid */\n\t\treturn LZW_BAD_CODE;\n\n\t} else if (code_new >= 1 << LZW_CODE_MAX) {\n\t\t/* Don't access out of bound */\n\t\treturn LZW_BAD_CODE;\n\n\t} else if (code_new < current_entry) {\n\t\t/* Code is in table */\n\t\tcode_out = code_new;\n\t\tlast_value = table[code_new].first_value;\n\t} else {\n\t\t/* Code not in table */\n\t\t*stack_pos++ = ctx->previous_code_first;\n\t\tcode_out = ctx->previous_code;\n\t\tlast_value = ctx->previous_code_first;\n\t}\n\n\t/* Add to the dictionary, only if there's space */\n\tif (current_entry < (1 << LZW_CODE_MAX)) {\n\t\tstruct lzw_dictionary_entry *entry = table + current_entry;\n\t\tentry->last_value     = last_value;\n\t\tentry->first_value    = ctx->previous_code_first;\n\t\tentry->previous_entry = ctx->previous_code;\n\t\tctx->current_entry++;\n\t}\n\n\t/* Ensure code size is increased, if needed. */\n\tif (current_entry == ctx->current_code_size_max) {\n\t\tif (ctx->current_code_size < LZW_CODE_MAX) {\n\t\t\tctx->current_code_size++;\n\t\t\tctx->current_code_size_max =\n\t\t\t\t\t(1 << ctx->current_code_size) - 1;\n\t\t}\n\t}\n\n\t/* Store details of this code as \"previous code\" to the context. */\n\tctx->previous_code_first = table[code_new].first_value;\n\tctx->previous_code = code_new;\n\n\t/* Put rest of data for this code on output stack.\n\t * Note, in the case of \"code not in table\", the last entry of the\n\t * current code has already been placed on the stack above. */\n\twhile (code_out > clear_code) {\n\t\tstruct lzw_dictionary_entry *entry = table + code_out;\n\t\t*stack_pos++ = entry->last_value;\n\t\tcode_out = entry->previous_entry;\n\t}\n\t*stack_pos++ = table[code_out].last_value;\n\n\t*stack_pos_out = stack_pos;\n\treturn LZW_OK;\n}", "func_hash": 232258018845507324994493987384082077230, "file_name": "lzw.c", "file_hash": 168965779407481929590316655829608211083, "cwe": ["CWE-125"], "cve": "CVE-2022-2061", "cve_desc": "Heap-based Buffer Overflow in GitHub repository hpjansson/chafa prior to 1.12.0.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-2061"}
{"idx": 214160, "project": "linux", "commit_id": "75e5b4849b81e19e9efe1654b30d7f3151c33c2c", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/75e5b4849b81e19e9efe1654b30d7f3151c33c2c", "commit_message": "USB: gadget: validate interface OS descriptor requests\n\nStall the control endpoint in case provided index exceeds array size of\nMAX_CONFIG_INTERFACES or when the retrieved function pointer is null.\n\nSigned-off-by: Szymon Heidrich \nCc: stable@kernel.org\nSigned-off-by: Greg Kroah-Hartman ", "target": 1, "func": "composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)\n{\n\tstruct usb_composite_dev\t*cdev = get_gadget_data(gadget);\n\tstruct usb_request\t\t*req = cdev->req;\n\tint\t\t\t\tvalue = -EOPNOTSUPP;\n\tint\t\t\t\tstatus = 0;\n\tu16\t\t\t\tw_index = le16_to_cpu(ctrl->wIndex);\n\tu8\t\t\t\tintf = w_index & 0xFF;\n\tu16\t\t\t\tw_value = le16_to_cpu(ctrl->wValue);\n\tu16\t\t\t\tw_length = le16_to_cpu(ctrl->wLength);\n\tstruct usb_function\t\t*f = NULL;\n\tu8\t\t\t\tendp;\n\n\tif (w_length > USB_COMP_EP0_BUFSIZ) {\n\t\tif (ctrl->bRequestType & USB_DIR_IN) {\n\t\t\t/* Cast away the const, we are going to overwrite on purpose. */\n\t\t\t__le16 *temp = (__le16 *)&ctrl->wLength;\n\n\t\t\t*temp = cpu_to_le16(USB_COMP_EP0_BUFSIZ);\n\t\t\tw_length = USB_COMP_EP0_BUFSIZ;\n\t\t} else {\n\t\t\tgoto done;\n\t\t}\n\t}\n\n\t/* partial re-init of the response message; the function or the\n\t * gadget might need to intercept e.g. a control-OUT completion\n\t * when we delegate to it.\n\t */\n\treq->zero = 0;\n\treq->context = cdev;\n\treq->complete = composite_setup_complete;\n\treq->length = 0;\n\tgadget->ep0->driver_data = cdev;\n\n\t/*\n\t * Don't let non-standard requests match any of the cases below\n\t * by accident.\n\t */\n\tif ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)\n\t\tgoto unknown;\n\n\tswitch (ctrl->bRequest) {\n\n\t/* we handle all standard USB descriptors */\n\tcase USB_REQ_GET_DESCRIPTOR:\n\t\tif (ctrl->bRequestType != USB_DIR_IN)\n\t\t\tgoto unknown;\n\t\tswitch (w_value >> 8) {\n\n\t\tcase USB_DT_DEVICE:\n\t\t\tcdev->desc.bNumConfigurations =\n\t\t\t\tcount_configs(cdev, USB_DT_DEVICE);\n\t\t\tcdev->desc.bMaxPacketSize0 =\n\t\t\t\tcdev->gadget->ep0->maxpacket;\n\t\t\tif (gadget_is_superspeed(gadget)) {\n\t\t\t\tif (gadget->speed >= USB_SPEED_SUPER) {\n\t\t\t\t\tcdev->desc.bcdUSB = cpu_to_le16(0x0320);\n\t\t\t\t\tcdev->desc.bMaxPacketSize0 = 9;\n\t\t\t\t} else {\n\t\t\t\t\tcdev->desc.bcdUSB = cpu_to_le16(0x0210);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (gadget->lpm_capable)\n\t\t\t\t\tcdev->desc.bcdUSB = cpu_to_le16(0x0201);\n\t\t\t\telse\n\t\t\t\t\tcdev->desc.bcdUSB = cpu_to_le16(0x0200);\n\t\t\t}\n\n\t\t\tvalue = min(w_length, (u16) sizeof cdev->desc);\n\t\t\tmemcpy(req->buf, &cdev->desc, value);\n\t\t\tbreak;\n\t\tcase USB_DT_DEVICE_QUALIFIER:\n\t\t\tif (!gadget_is_dualspeed(gadget) ||\n\t\t\t    gadget->speed >= USB_SPEED_SUPER)\n\t\t\t\tbreak;\n\t\t\tdevice_qual(cdev);\n\t\t\tvalue = min_t(int, w_length,\n\t\t\t\tsizeof(struct usb_qualifier_descriptor));\n\t\t\tbreak;\n\t\tcase USB_DT_OTHER_SPEED_CONFIG:\n\t\t\tif (!gadget_is_dualspeed(gadget) ||\n\t\t\t    gadget->speed >= USB_SPEED_SUPER)\n\t\t\t\tbreak;\n\t\t\tfallthrough;\n\t\tcase USB_DT_CONFIG:\n\t\t\tvalue = config_desc(cdev, w_value);\n\t\t\tif (value >= 0)\n\t\t\t\tvalue = min(w_length, (u16) value);\n\t\t\tbreak;\n\t\tcase USB_DT_STRING:\n\t\t\tvalue = get_string(cdev, req->buf,\n\t\t\t\t\tw_index, w_value & 0xff);\n\t\t\tif (value >= 0)\n\t\t\t\tvalue = min(w_length, (u16) value);\n\t\t\tbreak;\n\t\tcase USB_DT_BOS:\n\t\t\tif (gadget_is_superspeed(gadget) ||\n\t\t\t    gadget->lpm_capable) {\n\t\t\t\tvalue = bos_desc(cdev);\n\t\t\t\tvalue = min(w_length, (u16) value);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase USB_DT_OTG:\n\t\t\tif (gadget_is_otg(gadget)) {\n\t\t\t\tstruct usb_configuration *config;\n\t\t\t\tint otg_desc_len = 0;\n\n\t\t\t\tif (cdev->config)\n\t\t\t\t\tconfig = cdev->config;\n\t\t\t\telse\n\t\t\t\t\tconfig = list_first_entry(\n\t\t\t\t\t\t\t&cdev->configs,\n\t\t\t\t\t\tstruct usb_configuration, list);\n\t\t\t\tif (!config)\n\t\t\t\t\tgoto done;\n\n\t\t\t\tif (gadget->otg_caps &&\n\t\t\t\t\t(gadget->otg_caps->otg_rev >= 0x0200))\n\t\t\t\t\totg_desc_len += sizeof(\n\t\t\t\t\t\tstruct usb_otg20_descriptor);\n\t\t\t\telse\n\t\t\t\t\totg_desc_len += sizeof(\n\t\t\t\t\t\tstruct usb_otg_descriptor);\n\n\t\t\t\tvalue = min_t(int, w_length, otg_desc_len);\n\t\t\t\tmemcpy(req->buf, config->descriptors[0], value);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\t/* any number of configs can work */\n\tcase USB_REQ_SET_CONFIGURATION:\n\t\tif (ctrl->bRequestType != 0)\n\t\t\tgoto unknown;\n\t\tif (gadget_is_otg(gadget)) {\n\t\t\tif (gadget->a_hnp_support)\n\t\t\t\tDBG(cdev, \"HNP available\\n\");\n\t\t\telse if (gadget->a_alt_hnp_support)\n\t\t\t\tDBG(cdev, \"HNP on another port\\n\");\n\t\t\telse\n\t\t\t\tVDBG(cdev, \"HNP inactive\\n\");\n\t\t}\n\t\tspin_lock(&cdev->lock);\n\t\tvalue = set_config(cdev, ctrl, w_value);\n\t\tspin_unlock(&cdev->lock);\n\t\tbreak;\n\tcase USB_REQ_GET_CONFIGURATION:\n\t\tif (ctrl->bRequestType != USB_DIR_IN)\n\t\t\tgoto unknown;\n\t\tif (cdev->config)\n\t\t\t*(u8 *)req->buf = cdev->config->bConfigurationValue;\n\t\telse\n\t\t\t*(u8 *)req->buf = 0;\n\t\tvalue = min(w_length, (u16) 1);\n\t\tbreak;\n\n\t/* function drivers must handle get/set altsetting */\n\tcase USB_REQ_SET_INTERFACE:\n\t\tif (ctrl->bRequestType != USB_RECIP_INTERFACE)\n\t\t\tgoto unknown;\n\t\tif (!cdev->config || intf >= MAX_CONFIG_INTERFACES)\n\t\t\tbreak;\n\t\tf = cdev->config->interface[intf];\n\t\tif (!f)\n\t\t\tbreak;\n\n\t\t/*\n\t\t * If there's no get_alt() method, we know only altsetting zero\n\t\t * works. There is no need to check if set_alt() is not NULL\n\t\t * as we check this in usb_add_function().\n\t\t */\n\t\tif (w_value && !f->get_alt)\n\t\t\tbreak;\n\n\t\tspin_lock(&cdev->lock);\n\t\tvalue = f->set_alt(f, w_index, w_value);\n\t\tif (value == USB_GADGET_DELAYED_STATUS) {\n\t\t\tDBG(cdev,\n\t\t\t \"%s: interface %d (%s) requested delayed status\\n\",\n\t\t\t\t\t__func__, intf, f->name);\n\t\t\tcdev->delayed_status++;\n\t\t\tDBG(cdev, \"delayed_status count %d\\n\",\n\t\t\t\t\tcdev->delayed_status);\n\t\t}\n\t\tspin_unlock(&cdev->lock);\n\t\tbreak;\n\tcase USB_REQ_GET_INTERFACE:\n\t\tif (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))\n\t\t\tgoto unknown;\n\t\tif (!cdev->config || intf >= MAX_CONFIG_INTERFACES)\n\t\t\tbreak;\n\t\tf = cdev->config->interface[intf];\n\t\tif (!f)\n\t\t\tbreak;\n\t\t/* lots of interfaces only need altsetting zero... */\n\t\tvalue = f->get_alt ? f->get_alt(f, w_index) : 0;\n\t\tif (value < 0)\n\t\t\tbreak;\n\t\t*((u8 *)req->buf) = value;\n\t\tvalue = min(w_length, (u16) 1);\n\t\tbreak;\n\tcase USB_REQ_GET_STATUS:\n\t\tif (gadget_is_otg(gadget) && gadget->hnp_polling_support &&\n\t\t\t\t\t\t(w_index == OTG_STS_SELECTOR)) {\n\t\t\tif (ctrl->bRequestType != (USB_DIR_IN |\n\t\t\t\t\t\t\tUSB_RECIP_DEVICE))\n\t\t\t\tgoto unknown;\n\t\t\t*((u8 *)req->buf) = gadget->host_request_flag;\n\t\t\tvalue = 1;\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * USB 3.0 additions:\n\t\t * Function driver should handle get_status request. If such cb\n\t\t * wasn't supplied we respond with default value = 0\n\t\t * Note: function driver should supply such cb only for the\n\t\t * first interface of the function\n\t\t */\n\t\tif (!gadget_is_superspeed(gadget))\n\t\t\tgoto unknown;\n\t\tif (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))\n\t\t\tgoto unknown;\n\t\tvalue = 2;\t/* This is the length of the get_status reply */\n\t\tput_unaligned_le16(0, req->buf);\n\t\tif (!cdev->config || intf >= MAX_CONFIG_INTERFACES)\n\t\t\tbreak;\n\t\tf = cdev->config->interface[intf];\n\t\tif (!f)\n\t\t\tbreak;\n\t\tstatus = f->get_status ? f->get_status(f) : 0;\n\t\tif (status < 0)\n\t\t\tbreak;\n\t\tput_unaligned_le16(status & 0x0000ffff, req->buf);\n\t\tbreak;\n\t/*\n\t * Function drivers should handle SetFeature/ClearFeature\n\t * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied\n\t * only for the first interface of the function\n\t */\n\tcase USB_REQ_CLEAR_FEATURE:\n\tcase USB_REQ_SET_FEATURE:\n\t\tif (!gadget_is_superspeed(gadget))\n\t\t\tgoto unknown;\n\t\tif (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))\n\t\t\tgoto unknown;\n\t\tswitch (w_value) {\n\t\tcase USB_INTRF_FUNC_SUSPEND:\n\t\t\tif (!cdev->config || intf >= MAX_CONFIG_INTERFACES)\n\t\t\t\tbreak;\n\t\t\tf = cdev->config->interface[intf];\n\t\t\tif (!f)\n\t\t\t\tbreak;\n\t\t\tvalue = 0;\n\t\t\tif (f->func_suspend)\n\t\t\t\tvalue = f->func_suspend(f, w_index >> 8);\n\t\t\tif (value < 0) {\n\t\t\t\tERROR(cdev,\n\t\t\t\t      \"func_suspend() returned error %d\\n\",\n\t\t\t\t      value);\n\t\t\t\tvalue = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\nunknown:\n\t\t/*\n\t\t * OS descriptors handling\n\t\t */\n\t\tif (cdev->use_os_string && cdev->os_desc_config &&\n\t\t    (ctrl->bRequestType & USB_TYPE_VENDOR) &&\n\t\t    ctrl->bRequest == cdev->b_vendor_code) {\n\t\t\tstruct usb_configuration\t*os_desc_cfg;\n\t\t\tu8\t\t\t\t*buf;\n\t\t\tint\t\t\t\tinterface;\n\t\t\tint\t\t\t\tcount = 0;\n\n\t\t\treq = cdev->os_desc_req;\n\t\t\treq->context = cdev;\n\t\t\treq->complete = composite_setup_complete;\n\t\t\tbuf = req->buf;\n\t\t\tos_desc_cfg = cdev->os_desc_config;\n\t\t\tw_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ);\n\t\t\tmemset(buf, 0, w_length);\n\t\t\tbuf[5] = 0x01;\n\t\t\tswitch (ctrl->bRequestType & USB_RECIP_MASK) {\n\t\t\tcase USB_RECIP_DEVICE:\n\t\t\t\tif (w_index != 0x4 || (w_value >> 8))\n\t\t\t\t\tbreak;\n\t\t\t\tbuf[6] = w_index;\n\t\t\t\t/* Number of ext compat interfaces */\n\t\t\t\tcount = count_ext_compat(os_desc_cfg);\n\t\t\t\tbuf[8] = count;\n\t\t\t\tcount *= 24; /* 24 B/ext compat desc */\n\t\t\t\tcount += 16; /* header */\n\t\t\t\tput_unaligned_le32(count, buf);\n\t\t\t\tvalue = w_length;\n\t\t\t\tif (w_length > 0x10) {\n\t\t\t\t\tvalue = fill_ext_compat(os_desc_cfg, buf);\n\t\t\t\t\tvalue = min_t(u16, w_length, value);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase USB_RECIP_INTERFACE:\n\t\t\t\tif (w_index != 0x5 || (w_value >> 8))\n\t\t\t\t\tbreak;\n\t\t\t\tinterface = w_value & 0xFF;\n\t\t\t\tbuf[6] = w_index;\n\t\t\t\tcount = count_ext_prop(os_desc_cfg,\n\t\t\t\t\tinterface);\n\t\t\t\tput_unaligned_le16(count, buf + 8);\n\t\t\t\tcount = len_ext_prop(os_desc_cfg,\n\t\t\t\t\tinterface);\n\t\t\t\tput_unaligned_le32(count, buf);\n\t\t\t\tvalue = w_length;\n\t\t\t\tif (w_length > 0x0A) {\n\t\t\t\t\tvalue = fill_ext_prop(os_desc_cfg,\n\t\t\t\t\t\t\t      interface, buf);\n\t\t\t\t\tif (value >= 0)\n\t\t\t\t\t\tvalue = min_t(u16, w_length, value);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tgoto check_value;\n\t\t}\n\n\t\tVDBG(cdev,\n\t\t\t\"non-core control req%02x.%02x v%04x i%04x l%d\\n\",\n\t\t\tctrl->bRequestType, ctrl->bRequest,\n\t\t\tw_value, w_index, w_length);\n\n\t\t/* functions always handle their interfaces and endpoints...\n\t\t * punt other recipients (other, WUSB, ...) to the current\n\t\t * configuration code.\n\t\t */\n\t\tif (cdev->config) {\n\t\t\tlist_for_each_entry(f, &cdev->config->functions, list)\n\t\t\t\tif (f->req_match &&\n\t\t\t\t    f->req_match(f, ctrl, false))\n\t\t\t\t\tgoto try_fun_setup;\n\t\t} else {\n\t\t\tstruct usb_configuration *c;\n\t\t\tlist_for_each_entry(c, &cdev->configs, list)\n\t\t\t\tlist_for_each_entry(f, &c->functions, list)\n\t\t\t\t\tif (f->req_match &&\n\t\t\t\t\t    f->req_match(f, ctrl, true))\n\t\t\t\t\t\tgoto try_fun_setup;\n\t\t}\n\t\tf = NULL;\n\n\t\tswitch (ctrl->bRequestType & USB_RECIP_MASK) {\n\t\tcase USB_RECIP_INTERFACE:\n\t\t\tif (!cdev->config || intf >= MAX_CONFIG_INTERFACES)\n\t\t\t\tbreak;\n\t\t\tf = cdev->config->interface[intf];\n\t\t\tbreak;\n\n\t\tcase USB_RECIP_ENDPOINT:\n\t\t\tif (!cdev->config)\n\t\t\t\tbreak;\n\t\t\tendp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);\n\t\t\tlist_for_each_entry(f, &cdev->config->functions, list) {\n\t\t\t\tif (test_bit(endp, f->endpoints))\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (&f->list == &cdev->config->functions)\n\t\t\t\tf = NULL;\n\t\t\tbreak;\n\t\t}\ntry_fun_setup:\n\t\tif (f && f->setup)\n\t\t\tvalue = f->setup(f, ctrl);\n\t\telse {\n\t\t\tstruct usb_configuration\t*c;\n\n\t\t\tc = cdev->config;\n\t\t\tif (!c)\n\t\t\t\tgoto done;\n\n\t\t\t/* try current config's setup */\n\t\t\tif (c->setup) {\n\t\t\t\tvalue = c->setup(c, ctrl);\n\t\t\t\tgoto done;\n\t\t\t}\n\n\t\t\t/* try the only function in the current config */\n\t\t\tif (!list_is_singular(&c->functions))\n\t\t\t\tgoto done;\n\t\t\tf = list_first_entry(&c->functions, struct usb_function,\n\t\t\t\t\t     list);\n\t\t\tif (f->setup)\n\t\t\t\tvalue = f->setup(f, ctrl);\n\t\t}\n\n\t\tgoto done;\n\t}\n\ncheck_value:\n\t/* respond with data transfer before status phase? */\n\tif (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {\n\t\treq->length = value;\n\t\treq->context = cdev;\n\t\treq->zero = value < w_length;\n\t\tvalue = composite_ep0_queue(cdev, req, GFP_ATOMIC);\n\t\tif (value < 0) {\n\t\t\tDBG(cdev, \"ep_queue --> %d\\n\", value);\n\t\t\treq->status = 0;\n\t\t\tcomposite_setup_complete(gadget->ep0, req);\n\t\t}\n\t} else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {\n\t\tWARN(cdev,\n\t\t\t\"%s: Delayed status not supported for w_length != 0\",\n\t\t\t__func__);\n\t}\n\ndone:\n\t/* device either stalls (value < 0) or reports success */\n\treturn value;\n}", "func_hash": 303126640832251617876878392273862526744, "file_name": "composite.c", "file_hash": 18887355761308803276229129312051135602, "cwe": ["CWE-476"], "cve": "CVE-2022-25258", "cve_desc": "An issue was discovered in drivers/usb/gadget/composite.c in the Linux kernel before 5.16.10. The USB Gadget subsystem lacks certain validation of interface OS descriptor requests (ones with a large array index and ones associated with NULL function pointer retrieval). Memory corruption might occur.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-25258"}
{"idx": 476103, "project": "linux", "commit_id": "75e5b4849b81e19e9efe1654b30d7f3151c33c2c", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/75e5b4849b81e19e9efe1654b30d7f3151c33c2c", "commit_message": "USB: gadget: validate interface OS descriptor requests\n\nStall the control endpoint in case provided index exceeds array size of\nMAX_CONFIG_INTERFACES or when the retrieved function pointer is null.\n\nSigned-off-by: Szymon Heidrich \nCc: stable@kernel.org\nSigned-off-by: Greg Kroah-Hartman ", "target": 0, "func": "composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)\n{\n\tstruct usb_composite_dev\t*cdev = get_gadget_data(gadget);\n\tstruct usb_request\t\t*req = cdev->req;\n\tint\t\t\t\tvalue = -EOPNOTSUPP;\n\tint\t\t\t\tstatus = 0;\n\tu16\t\t\t\tw_index = le16_to_cpu(ctrl->wIndex);\n\tu8\t\t\t\tintf = w_index & 0xFF;\n\tu16\t\t\t\tw_value = le16_to_cpu(ctrl->wValue);\n\tu16\t\t\t\tw_length = le16_to_cpu(ctrl->wLength);\n\tstruct usb_function\t\t*f = NULL;\n\tu8\t\t\t\tendp;\n\n\tif (w_length > USB_COMP_EP0_BUFSIZ) {\n\t\tif (ctrl->bRequestType & USB_DIR_IN) {\n\t\t\t/* Cast away the const, we are going to overwrite on purpose. */\n\t\t\t__le16 *temp = (__le16 *)&ctrl->wLength;\n\n\t\t\t*temp = cpu_to_le16(USB_COMP_EP0_BUFSIZ);\n\t\t\tw_length = USB_COMP_EP0_BUFSIZ;\n\t\t} else {\n\t\t\tgoto done;\n\t\t}\n\t}\n\n\t/* partial re-init of the response message; the function or the\n\t * gadget might need to intercept e.g. a control-OUT completion\n\t * when we delegate to it.\n\t */\n\treq->zero = 0;\n\treq->context = cdev;\n\treq->complete = composite_setup_complete;\n\treq->length = 0;\n\tgadget->ep0->driver_data = cdev;\n\n\t/*\n\t * Don't let non-standard requests match any of the cases below\n\t * by accident.\n\t */\n\tif ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)\n\t\tgoto unknown;\n\n\tswitch (ctrl->bRequest) {\n\n\t/* we handle all standard USB descriptors */\n\tcase USB_REQ_GET_DESCRIPTOR:\n\t\tif (ctrl->bRequestType != USB_DIR_IN)\n\t\t\tgoto unknown;\n\t\tswitch (w_value >> 8) {\n\n\t\tcase USB_DT_DEVICE:\n\t\t\tcdev->desc.bNumConfigurations =\n\t\t\t\tcount_configs(cdev, USB_DT_DEVICE);\n\t\t\tcdev->desc.bMaxPacketSize0 =\n\t\t\t\tcdev->gadget->ep0->maxpacket;\n\t\t\tif (gadget_is_superspeed(gadget)) {\n\t\t\t\tif (gadget->speed >= USB_SPEED_SUPER) {\n\t\t\t\t\tcdev->desc.bcdUSB = cpu_to_le16(0x0320);\n\t\t\t\t\tcdev->desc.bMaxPacketSize0 = 9;\n\t\t\t\t} else {\n\t\t\t\t\tcdev->desc.bcdUSB = cpu_to_le16(0x0210);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (gadget->lpm_capable)\n\t\t\t\t\tcdev->desc.bcdUSB = cpu_to_le16(0x0201);\n\t\t\t\telse\n\t\t\t\t\tcdev->desc.bcdUSB = cpu_to_le16(0x0200);\n\t\t\t}\n\n\t\t\tvalue = min(w_length, (u16) sizeof cdev->desc);\n\t\t\tmemcpy(req->buf, &cdev->desc, value);\n\t\t\tbreak;\n\t\tcase USB_DT_DEVICE_QUALIFIER:\n\t\t\tif (!gadget_is_dualspeed(gadget) ||\n\t\t\t    gadget->speed >= USB_SPEED_SUPER)\n\t\t\t\tbreak;\n\t\t\tdevice_qual(cdev);\n\t\t\tvalue = min_t(int, w_length,\n\t\t\t\tsizeof(struct usb_qualifier_descriptor));\n\t\t\tbreak;\n\t\tcase USB_DT_OTHER_SPEED_CONFIG:\n\t\t\tif (!gadget_is_dualspeed(gadget) ||\n\t\t\t    gadget->speed >= USB_SPEED_SUPER)\n\t\t\t\tbreak;\n\t\t\tfallthrough;\n\t\tcase USB_DT_CONFIG:\n\t\t\tvalue = config_desc(cdev, w_value);\n\t\t\tif (value >= 0)\n\t\t\t\tvalue = min(w_length, (u16) value);\n\t\t\tbreak;\n\t\tcase USB_DT_STRING:\n\t\t\tvalue = get_string(cdev, req->buf,\n\t\t\t\t\tw_index, w_value & 0xff);\n\t\t\tif (value >= 0)\n\t\t\t\tvalue = min(w_length, (u16) value);\n\t\t\tbreak;\n\t\tcase USB_DT_BOS:\n\t\t\tif (gadget_is_superspeed(gadget) ||\n\t\t\t    gadget->lpm_capable) {\n\t\t\t\tvalue = bos_desc(cdev);\n\t\t\t\tvalue = min(w_length, (u16) value);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase USB_DT_OTG:\n\t\t\tif (gadget_is_otg(gadget)) {\n\t\t\t\tstruct usb_configuration *config;\n\t\t\t\tint otg_desc_len = 0;\n\n\t\t\t\tif (cdev->config)\n\t\t\t\t\tconfig = cdev->config;\n\t\t\t\telse\n\t\t\t\t\tconfig = list_first_entry(\n\t\t\t\t\t\t\t&cdev->configs,\n\t\t\t\t\t\tstruct usb_configuration, list);\n\t\t\t\tif (!config)\n\t\t\t\t\tgoto done;\n\n\t\t\t\tif (gadget->otg_caps &&\n\t\t\t\t\t(gadget->otg_caps->otg_rev >= 0x0200))\n\t\t\t\t\totg_desc_len += sizeof(\n\t\t\t\t\t\tstruct usb_otg20_descriptor);\n\t\t\t\telse\n\t\t\t\t\totg_desc_len += sizeof(\n\t\t\t\t\t\tstruct usb_otg_descriptor);\n\n\t\t\t\tvalue = min_t(int, w_length, otg_desc_len);\n\t\t\t\tmemcpy(req->buf, config->descriptors[0], value);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\t/* any number of configs can work */\n\tcase USB_REQ_SET_CONFIGURATION:\n\t\tif (ctrl->bRequestType != 0)\n\t\t\tgoto unknown;\n\t\tif (gadget_is_otg(gadget)) {\n\t\t\tif (gadget->a_hnp_support)\n\t\t\t\tDBG(cdev, \"HNP available\\n\");\n\t\t\telse if (gadget->a_alt_hnp_support)\n\t\t\t\tDBG(cdev, \"HNP on another port\\n\");\n\t\t\telse\n\t\t\t\tVDBG(cdev, \"HNP inactive\\n\");\n\t\t}\n\t\tspin_lock(&cdev->lock);\n\t\tvalue = set_config(cdev, ctrl, w_value);\n\t\tspin_unlock(&cdev->lock);\n\t\tbreak;\n\tcase USB_REQ_GET_CONFIGURATION:\n\t\tif (ctrl->bRequestType != USB_DIR_IN)\n\t\t\tgoto unknown;\n\t\tif (cdev->config)\n\t\t\t*(u8 *)req->buf = cdev->config->bConfigurationValue;\n\t\telse\n\t\t\t*(u8 *)req->buf = 0;\n\t\tvalue = min(w_length, (u16) 1);\n\t\tbreak;\n\n\t/* function drivers must handle get/set altsetting */\n\tcase USB_REQ_SET_INTERFACE:\n\t\tif (ctrl->bRequestType != USB_RECIP_INTERFACE)\n\t\t\tgoto unknown;\n\t\tif (!cdev->config || intf >= MAX_CONFIG_INTERFACES)\n\t\t\tbreak;\n\t\tf = cdev->config->interface[intf];\n\t\tif (!f)\n\t\t\tbreak;\n\n\t\t/*\n\t\t * If there's no get_alt() method, we know only altsetting zero\n\t\t * works. There is no need to check if set_alt() is not NULL\n\t\t * as we check this in usb_add_function().\n\t\t */\n\t\tif (w_value && !f->get_alt)\n\t\t\tbreak;\n\n\t\tspin_lock(&cdev->lock);\n\t\tvalue = f->set_alt(f, w_index, w_value);\n\t\tif (value == USB_GADGET_DELAYED_STATUS) {\n\t\t\tDBG(cdev,\n\t\t\t \"%s: interface %d (%s) requested delayed status\\n\",\n\t\t\t\t\t__func__, intf, f->name);\n\t\t\tcdev->delayed_status++;\n\t\t\tDBG(cdev, \"delayed_status count %d\\n\",\n\t\t\t\t\tcdev->delayed_status);\n\t\t}\n\t\tspin_unlock(&cdev->lock);\n\t\tbreak;\n\tcase USB_REQ_GET_INTERFACE:\n\t\tif (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))\n\t\t\tgoto unknown;\n\t\tif (!cdev->config || intf >= MAX_CONFIG_INTERFACES)\n\t\t\tbreak;\n\t\tf = cdev->config->interface[intf];\n\t\tif (!f)\n\t\t\tbreak;\n\t\t/* lots of interfaces only need altsetting zero... */\n\t\tvalue = f->get_alt ? f->get_alt(f, w_index) : 0;\n\t\tif (value < 0)\n\t\t\tbreak;\n\t\t*((u8 *)req->buf) = value;\n\t\tvalue = min(w_length, (u16) 1);\n\t\tbreak;\n\tcase USB_REQ_GET_STATUS:\n\t\tif (gadget_is_otg(gadget) && gadget->hnp_polling_support &&\n\t\t\t\t\t\t(w_index == OTG_STS_SELECTOR)) {\n\t\t\tif (ctrl->bRequestType != (USB_DIR_IN |\n\t\t\t\t\t\t\tUSB_RECIP_DEVICE))\n\t\t\t\tgoto unknown;\n\t\t\t*((u8 *)req->buf) = gadget->host_request_flag;\n\t\t\tvalue = 1;\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * USB 3.0 additions:\n\t\t * Function driver should handle get_status request. If such cb\n\t\t * wasn't supplied we respond with default value = 0\n\t\t * Note: function driver should supply such cb only for the\n\t\t * first interface of the function\n\t\t */\n\t\tif (!gadget_is_superspeed(gadget))\n\t\t\tgoto unknown;\n\t\tif (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))\n\t\t\tgoto unknown;\n\t\tvalue = 2;\t/* This is the length of the get_status reply */\n\t\tput_unaligned_le16(0, req->buf);\n\t\tif (!cdev->config || intf >= MAX_CONFIG_INTERFACES)\n\t\t\tbreak;\n\t\tf = cdev->config->interface[intf];\n\t\tif (!f)\n\t\t\tbreak;\n\t\tstatus = f->get_status ? f->get_status(f) : 0;\n\t\tif (status < 0)\n\t\t\tbreak;\n\t\tput_unaligned_le16(status & 0x0000ffff, req->buf);\n\t\tbreak;\n\t/*\n\t * Function drivers should handle SetFeature/ClearFeature\n\t * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied\n\t * only for the first interface of the function\n\t */\n\tcase USB_REQ_CLEAR_FEATURE:\n\tcase USB_REQ_SET_FEATURE:\n\t\tif (!gadget_is_superspeed(gadget))\n\t\t\tgoto unknown;\n\t\tif (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))\n\t\t\tgoto unknown;\n\t\tswitch (w_value) {\n\t\tcase USB_INTRF_FUNC_SUSPEND:\n\t\t\tif (!cdev->config || intf >= MAX_CONFIG_INTERFACES)\n\t\t\t\tbreak;\n\t\t\tf = cdev->config->interface[intf];\n\t\t\tif (!f)\n\t\t\t\tbreak;\n\t\t\tvalue = 0;\n\t\t\tif (f->func_suspend)\n\t\t\t\tvalue = f->func_suspend(f, w_index >> 8);\n\t\t\tif (value < 0) {\n\t\t\t\tERROR(cdev,\n\t\t\t\t      \"func_suspend() returned error %d\\n\",\n\t\t\t\t      value);\n\t\t\t\tvalue = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\nunknown:\n\t\t/*\n\t\t * OS descriptors handling\n\t\t */\n\t\tif (cdev->use_os_string && cdev->os_desc_config &&\n\t\t    (ctrl->bRequestType & USB_TYPE_VENDOR) &&\n\t\t    ctrl->bRequest == cdev->b_vendor_code) {\n\t\t\tstruct usb_configuration\t*os_desc_cfg;\n\t\t\tu8\t\t\t\t*buf;\n\t\t\tint\t\t\t\tinterface;\n\t\t\tint\t\t\t\tcount = 0;\n\n\t\t\treq = cdev->os_desc_req;\n\t\t\treq->context = cdev;\n\t\t\treq->complete = composite_setup_complete;\n\t\t\tbuf = req->buf;\n\t\t\tos_desc_cfg = cdev->os_desc_config;\n\t\t\tw_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ);\n\t\t\tmemset(buf, 0, w_length);\n\t\t\tbuf[5] = 0x01;\n\t\t\tswitch (ctrl->bRequestType & USB_RECIP_MASK) {\n\t\t\tcase USB_RECIP_DEVICE:\n\t\t\t\tif (w_index != 0x4 || (w_value >> 8))\n\t\t\t\t\tbreak;\n\t\t\t\tbuf[6] = w_index;\n\t\t\t\t/* Number of ext compat interfaces */\n\t\t\t\tcount = count_ext_compat(os_desc_cfg);\n\t\t\t\tbuf[8] = count;\n\t\t\t\tcount *= 24; /* 24 B/ext compat desc */\n\t\t\t\tcount += 16; /* header */\n\t\t\t\tput_unaligned_le32(count, buf);\n\t\t\t\tvalue = w_length;\n\t\t\t\tif (w_length > 0x10) {\n\t\t\t\t\tvalue = fill_ext_compat(os_desc_cfg, buf);\n\t\t\t\t\tvalue = min_t(u16, w_length, value);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase USB_RECIP_INTERFACE:\n\t\t\t\tif (w_index != 0x5 || (w_value >> 8))\n\t\t\t\t\tbreak;\n\t\t\t\tinterface = w_value & 0xFF;\n\t\t\t\tif (interface >= MAX_CONFIG_INTERFACES ||\n\t\t\t\t    !os_desc_cfg->interface[interface])\n\t\t\t\t\tbreak;\n\t\t\t\tbuf[6] = w_index;\n\t\t\t\tcount = count_ext_prop(os_desc_cfg,\n\t\t\t\t\tinterface);\n\t\t\t\tput_unaligned_le16(count, buf + 8);\n\t\t\t\tcount = len_ext_prop(os_desc_cfg,\n\t\t\t\t\tinterface);\n\t\t\t\tput_unaligned_le32(count, buf);\n\t\t\t\tvalue = w_length;\n\t\t\t\tif (w_length > 0x0A) {\n\t\t\t\t\tvalue = fill_ext_prop(os_desc_cfg,\n\t\t\t\t\t\t\t      interface, buf);\n\t\t\t\t\tif (value >= 0)\n\t\t\t\t\t\tvalue = min_t(u16, w_length, value);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tgoto check_value;\n\t\t}\n\n\t\tVDBG(cdev,\n\t\t\t\"non-core control req%02x.%02x v%04x i%04x l%d\\n\",\n\t\t\tctrl->bRequestType, ctrl->bRequest,\n\t\t\tw_value, w_index, w_length);\n\n\t\t/* functions always handle their interfaces and endpoints...\n\t\t * punt other recipients (other, WUSB, ...) to the current\n\t\t * configuration code.\n\t\t */\n\t\tif (cdev->config) {\n\t\t\tlist_for_each_entry(f, &cdev->config->functions, list)\n\t\t\t\tif (f->req_match &&\n\t\t\t\t    f->req_match(f, ctrl, false))\n\t\t\t\t\tgoto try_fun_setup;\n\t\t} else {\n\t\t\tstruct usb_configuration *c;\n\t\t\tlist_for_each_entry(c, &cdev->configs, list)\n\t\t\t\tlist_for_each_entry(f, &c->functions, list)\n\t\t\t\t\tif (f->req_match &&\n\t\t\t\t\t    f->req_match(f, ctrl, true))\n\t\t\t\t\t\tgoto try_fun_setup;\n\t\t}\n\t\tf = NULL;\n\n\t\tswitch (ctrl->bRequestType & USB_RECIP_MASK) {\n\t\tcase USB_RECIP_INTERFACE:\n\t\t\tif (!cdev->config || intf >= MAX_CONFIG_INTERFACES)\n\t\t\t\tbreak;\n\t\t\tf = cdev->config->interface[intf];\n\t\t\tbreak;\n\n\t\tcase USB_RECIP_ENDPOINT:\n\t\t\tif (!cdev->config)\n\t\t\t\tbreak;\n\t\t\tendp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);\n\t\t\tlist_for_each_entry(f, &cdev->config->functions, list) {\n\t\t\t\tif (test_bit(endp, f->endpoints))\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (&f->list == &cdev->config->functions)\n\t\t\t\tf = NULL;\n\t\t\tbreak;\n\t\t}\ntry_fun_setup:\n\t\tif (f && f->setup)\n\t\t\tvalue = f->setup(f, ctrl);\n\t\telse {\n\t\t\tstruct usb_configuration\t*c;\n\n\t\t\tc = cdev->config;\n\t\t\tif (!c)\n\t\t\t\tgoto done;\n\n\t\t\t/* try current config's setup */\n\t\t\tif (c->setup) {\n\t\t\t\tvalue = c->setup(c, ctrl);\n\t\t\t\tgoto done;\n\t\t\t}\n\n\t\t\t/* try the only function in the current config */\n\t\t\tif (!list_is_singular(&c->functions))\n\t\t\t\tgoto done;\n\t\t\tf = list_first_entry(&c->functions, struct usb_function,\n\t\t\t\t\t     list);\n\t\t\tif (f->setup)\n\t\t\t\tvalue = f->setup(f, ctrl);\n\t\t}\n\n\t\tgoto done;\n\t}\n\ncheck_value:\n\t/* respond with data transfer before status phase? */\n\tif (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {\n\t\treq->length = value;\n\t\treq->context = cdev;\n\t\treq->zero = value < w_length;\n\t\tvalue = composite_ep0_queue(cdev, req, GFP_ATOMIC);\n\t\tif (value < 0) {\n\t\t\tDBG(cdev, \"ep_queue --> %d\\n\", value);\n\t\t\treq->status = 0;\n\t\t\tcomposite_setup_complete(gadget->ep0, req);\n\t\t}\n\t} else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {\n\t\tWARN(cdev,\n\t\t\t\"%s: Delayed status not supported for w_length != 0\",\n\t\t\t__func__);\n\t}\n\ndone:\n\t/* device either stalls (value < 0) or reports success */\n\treturn value;\n}", "func_hash": 150169819708721543824384188358095206836, "file_name": "composite.c", "file_hash": 106311505474453071070186160185104780414, "cwe": ["CWE-476"], "cve": "CVE-2022-25258", "cve_desc": "An issue was discovered in drivers/usb/gadget/composite.c in the Linux kernel before 5.16.10. The USB Gadget subsystem lacks certain validation of interface OS descriptor requests (ones with a large array index and ones associated with NULL function pointer retrieval). Memory corruption might occur.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-25258"}
{"idx": 214276, "project": "linux", "commit_id": "fa40d9734a57bcbfa79a280189799f76c88f7bb0", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/fa40d9734a57bcbfa79a280189799f76c88f7bb0", "commit_message": "tipc: fix size validations for the MSG_CRYPTO type\n\nThe function tipc_crypto_key_rcv is used to parse MSG_CRYPTO messages\nto receive keys from other nodes in the cluster in order to decrypt any\nfurther messages from them.\nThis patch verifies that any supplied sizes in the message body are\nvalid for the received message.\n\nFixes: 1ef6f7c9390f (\"tipc: add automatic session key exchange\")\nSigned-off-by: Max VA \nAcked-by: Ying Xue \nSigned-off-by: Greg Kroah-Hartman \nAcked-by: Jon Maloy \nSigned-off-by: David S. Miller ", "target": 1, "func": "static bool tipc_crypto_key_rcv(struct tipc_crypto *rx, struct tipc_msg *hdr)\n{\n\tstruct tipc_crypto *tx = tipc_net(rx->net)->crypto_tx;\n\tstruct tipc_aead_key *skey = NULL;\n\tu16 key_gen = msg_key_gen(hdr);\n\tu16 size = msg_data_sz(hdr);\n\tu8 *data = msg_data(hdr);\n\n\tspin_lock(&rx->lock);\n\tif (unlikely(rx->skey || (key_gen == rx->key_gen && rx->key.keys))) {\n\t\tpr_err(\"%s: key existed <%p>, gen %d vs %d\\n\", rx->name,\n\t\t       rx->skey, key_gen, rx->key_gen);\n\t\tgoto exit;\n\t}\n\n\t/* Allocate memory for the key */\n\tskey = kmalloc(size, GFP_ATOMIC);\n\tif (unlikely(!skey)) {\n\t\tpr_err(\"%s: unable to allocate memory for skey\\n\", rx->name);\n\t\tgoto exit;\n\t}\n\n\t/* Copy key from msg data */\n\tskey->keylen = ntohl(*((__be32 *)(data + TIPC_AEAD_ALG_NAME)));\n\tmemcpy(skey->alg_name, data, TIPC_AEAD_ALG_NAME);\n\tmemcpy(skey->key, data + TIPC_AEAD_ALG_NAME + sizeof(__be32),\n\t       skey->keylen);\n\n\t/* Sanity check */\n\tif (unlikely(size != tipc_aead_key_size(skey))) {\n\t\tkfree(skey);\n\t\tskey = NULL;\n\t\tgoto exit;\n\t}\n\n\trx->key_gen = key_gen;\n\trx->skey_mode = msg_key_mode(hdr);\n\trx->skey = skey;\n\trx->nokey = 0;\n\tmb(); /* for nokey flag */\n\nexit:\n\tspin_unlock(&rx->lock);\n\n\t/* Schedule the key attaching on this crypto */\n\tif (likely(skey && queue_delayed_work(tx->wq, &rx->work, 0)))\n\t\treturn true;\n\n\treturn false;\n}", "func_hash": 150450145750082729683403565650901445106, "file_name": "crypto.c", "file_hash": 58733917967082493268842355411939930161, "cwe": ["CWE-20"], "cve": "CVE-2021-43267", "cve_desc": "An issue was discovered in net/tipc/crypto.c in the Linux kernel before 5.14.16. The Transparent Inter-Process Communication (TIPC) functionality allows remote attackers to exploit insufficient validation of user-supplied sizes for the MSG_CRYPTO message type.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43267"}
{"idx": 477273, "project": "linux", "commit_id": "fa40d9734a57bcbfa79a280189799f76c88f7bb0", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/fa40d9734a57bcbfa79a280189799f76c88f7bb0", "commit_message": "tipc: fix size validations for the MSG_CRYPTO type\n\nThe function tipc_crypto_key_rcv is used to parse MSG_CRYPTO messages\nto receive keys from other nodes in the cluster in order to decrypt any\nfurther messages from them.\nThis patch verifies that any supplied sizes in the message body are\nvalid for the received message.\n\nFixes: 1ef6f7c9390f (\"tipc: add automatic session key exchange\")\nSigned-off-by: Max VA \nAcked-by: Ying Xue \nSigned-off-by: Greg Kroah-Hartman \nAcked-by: Jon Maloy \nSigned-off-by: David S. Miller ", "target": 0, "func": "static bool tipc_crypto_key_rcv(struct tipc_crypto *rx, struct tipc_msg *hdr)\n{\n\tstruct tipc_crypto *tx = tipc_net(rx->net)->crypto_tx;\n\tstruct tipc_aead_key *skey = NULL;\n\tu16 key_gen = msg_key_gen(hdr);\n\tu16 size = msg_data_sz(hdr);\n\tu8 *data = msg_data(hdr);\n\tunsigned int keylen;\n\n\t/* Verify whether the size can exist in the packet */\n\tif (unlikely(size < sizeof(struct tipc_aead_key) + TIPC_AEAD_KEYLEN_MIN)) {\n\t\tpr_debug(\"%s: message data size is too small\\n\", rx->name);\n\t\tgoto exit;\n\t}\n\n\tkeylen = ntohl(*((__be32 *)(data + TIPC_AEAD_ALG_NAME)));\n\n\t/* Verify the supplied size values */\n\tif (unlikely(size != keylen + sizeof(struct tipc_aead_key) ||\n\t\t     keylen > TIPC_AEAD_KEY_SIZE_MAX)) {\n\t\tpr_debug(\"%s: invalid MSG_CRYPTO key size\\n\", rx->name);\n\t\tgoto exit;\n\t}\n\n\tspin_lock(&rx->lock);\n\tif (unlikely(rx->skey || (key_gen == rx->key_gen && rx->key.keys))) {\n\t\tpr_err(\"%s: key existed <%p>, gen %d vs %d\\n\", rx->name,\n\t\t       rx->skey, key_gen, rx->key_gen);\n\t\tgoto exit_unlock;\n\t}\n\n\t/* Allocate memory for the key */\n\tskey = kmalloc(size, GFP_ATOMIC);\n\tif (unlikely(!skey)) {\n\t\tpr_err(\"%s: unable to allocate memory for skey\\n\", rx->name);\n\t\tgoto exit_unlock;\n\t}\n\n\t/* Copy key from msg data */\n\tskey->keylen = keylen;\n\tmemcpy(skey->alg_name, data, TIPC_AEAD_ALG_NAME);\n\tmemcpy(skey->key, data + TIPC_AEAD_ALG_NAME + sizeof(__be32),\n\t       skey->keylen);\n\n\trx->key_gen = key_gen;\n\trx->skey_mode = msg_key_mode(hdr);\n\trx->skey = skey;\n\trx->nokey = 0;\n\tmb(); /* for nokey flag */\n\nexit_unlock:\n\tspin_unlock(&rx->lock);\n\nexit:\n\t/* Schedule the key attaching on this crypto */\n\tif (likely(skey && queue_delayed_work(tx->wq, &rx->work, 0)))\n\t\treturn true;\n\n\treturn false;\n}", "func_hash": 21444025468428283247999063273803236471, "file_name": "crypto.c", "file_hash": 97644738698722030133364122587095840919, "cwe": ["CWE-20"], "cve": "CVE-2021-43267", "cve_desc": "An issue was discovered in net/tipc/crypto.c in the Linux kernel before 5.14.16. The Transparent Inter-Process Communication (TIPC) functionality allows remote attackers to exploit insufficient validation of user-supplied sizes for the MSG_CRYPTO message type.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43267"}
{"idx": 214282, "project": "radare2", "commit_id": "9650e3c352f675687bf6c6f65ff2c4a3d0e288fa", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/9650e3c352f675687bf6c6f65ff2c4a3d0e288fa", "commit_message": "Fix oobread segfault in java arith8.class ##crash\n\n* Reported by Cen Zhang via huntr.dev", "target": 1, "func": "R_API RBinJavaAttrInfo *r_bin_java_inner_classes_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tRBinJavaClassesAttribute *icattr;\n\tRBinJavaAttrInfo *attr = NULL;\n\tRBinJavaCPTypeObj *obj;\n\tut32 i = 0;\n\tut64 offset = 0, curpos;\n\tattr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (attr == NULL) {\n\t\t// TODO eprintf\n\t\treturn attr;\n\t}\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_INNER_CLASSES_ATTR;\n\tattr->info.inner_classes_attr.number_of_classes = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->info.inner_classes_attr.classes = r_list_newf (r_bin_java_inner_classes_attr_entry_free);\n\tfor (i = 0; i < attr->info.inner_classes_attr.number_of_classes; i++) {\n\t\tcurpos = buf_offset + offset;\n\t\tif (offset + 8 > sz) {\n\t\t\teprintf (\"Invalid amount of inner classes\\n\");\n\t\t\tbreak;\n\t\t}\n\t\ticattr = R_NEW0 (RBinJavaClassesAttribute);\n\t\tif (!icattr) {\n\t\t\tbreak;\n\t\t}\n\t\ticattr->inner_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\ticattr->outer_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\ticattr->inner_name_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\ticattr->inner_class_access_flags = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\ticattr->flags_str = retrieve_class_method_access_string (icattr->inner_class_access_flags);\n\t\ticattr->file_offset = curpos;\n\t\ticattr->size = 8;\n\n\t\tobj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_name_idx);\n\t\tif (obj == NULL) {\n\t\t\teprintf (\"BINCPLIS IS HULL %d\\n\", icattr->inner_name_idx);\n\t\t}\n\t\ticattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj);\n\t\tif (!icattr->name) {\n\t\t\tobj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_class_info_idx);\n\t\t\tif (!obj) {\n\t\t\t\teprintf (\"BINCPLIST IS NULL %d\\n\", icattr->inner_class_info_idx);\n\t\t\t}\n\t\t\ticattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj);\n\t\t\tif (!icattr->name) {\n\t\t\t\ticattr->name = r_str_dup (NULL, \"NULL\");\n\t\t\t\teprintf (\"r_bin_java_inner_classes_attr: Unable to find the name for %d index.\\n\", icattr->inner_name_idx);\n\t\t\t\tfree (icattr);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tIFDBG eprintf(\"r_bin_java_inner_classes_attr: Inner class name %d is %s.\\n\", icattr->inner_name_idx, icattr->name);\n\t\tr_list_append (attr->info.inner_classes_attr.classes, (void *) icattr);\n\t}\n\tattr->size = offset;\n\t// IFDBG r_bin_java_print_inner_classes_attr_summary(attr);\n\treturn attr;\n}", "func_hash": 64487889579921550880626488390413278294, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-0518", "cve_desc": "Heap-based Buffer Overflow in GitHub repository radareorg/radare2 prior to 5.6.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0518"}
{"idx": 477380, "project": "radare2", "commit_id": "9650e3c352f675687bf6c6f65ff2c4a3d0e288fa", "project_url": "https://github.com/radare/radare2", "commit_url": "https://github.com/radareorg/radare2/commit/9650e3c352f675687bf6c6f65ff2c4a3d0e288fa", "commit_message": "Fix oobread segfault in java arith8.class ##crash\n\n* Reported by Cen Zhang via huntr.dev", "target": 0, "func": "R_API RBinJavaAttrInfo *r_bin_java_inner_classes_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tRBinJavaClassesAttribute *icattr;\n\tRBinJavaAttrInfo *attr = NULL;\n\tRBinJavaCPTypeObj *obj;\n\tut32 i = 0;\n\tut64 offset = 0, curpos;\n\tattr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (buf_offset + offset + 8 > sz) {\n\t\teprintf (\"Invalid amount of inner classes\\n\");\n\t\treturn NULL;\n\t}\n\tif (attr == NULL) {\n\t\t// TODO eprintf\n\t\treturn attr;\n\t}\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_INNER_CLASSES_ATTR;\n\tattr->info.inner_classes_attr.number_of_classes = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->info.inner_classes_attr.classes = r_list_newf (r_bin_java_inner_classes_attr_entry_free);\n\tfor (i = 0; i < attr->info.inner_classes_attr.number_of_classes; i++) {\n\t\tcurpos = buf_offset + offset;\n\t\tif (buf_offset + offset + 8 > sz) {\n\t\t\teprintf (\"Invalid amount of inner classes\\n\");\n\t\t\tbreak;\n\t\t}\n\t\ticattr = R_NEW0 (RBinJavaClassesAttribute);\n\t\tif (!icattr) {\n\t\t\tbreak;\n\t\t}\n\t\ticattr->inner_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\ticattr->outer_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\ticattr->inner_name_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\ticattr->inner_class_access_flags = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\ticattr->flags_str = retrieve_class_method_access_string (icattr->inner_class_access_flags);\n\t\ticattr->file_offset = curpos;\n\t\ticattr->size = 8;\n\n\t\tobj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_name_idx);\n\t\tif (obj == NULL) {\n\t\t\teprintf (\"BINCPLIS IS HULL %d\\n\", icattr->inner_name_idx);\n\t\t}\n\t\ticattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj);\n\t\tif (!icattr->name) {\n\t\t\tobj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_class_info_idx);\n\t\t\tif (!obj) {\n\t\t\t\teprintf (\"BINCPLIST IS NULL %d\\n\", icattr->inner_class_info_idx);\n\t\t\t}\n\t\t\ticattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj);\n\t\t\tif (!icattr->name) {\n\t\t\t\ticattr->name = r_str_dup (NULL, \"NULL\");\n\t\t\t\teprintf (\"r_bin_java_inner_classes_attr: Unable to find the name for %d index.\\n\", icattr->inner_name_idx);\n\t\t\t\tfree (icattr);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tIFDBG eprintf(\"r_bin_java_inner_classes_attr: Inner class name %d is %s.\\n\", icattr->inner_name_idx, icattr->name);\n\t\tr_list_append (attr->info.inner_classes_attr.classes, (void *) icattr);\n\t}\n\tattr->size = offset;\n\t// IFDBG r_bin_java_print_inner_classes_attr_summary(attr);\n\treturn attr;\n}", "func_hash": 64877756474443733674480622739162380352, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2022-0518", "cve_desc": "Heap-based Buffer Overflow in GitHub repository radareorg/radare2 prior to 5.6.2.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0518"}
{"idx": 214335, "project": "ceph", "commit_id": "be7679007c3dfab3e19c22c38c36ccac91828e3b", "project_url": "https://github.com/ceph/ceph", "commit_url": "https://github.com/ceph/ceph/commit/be7679007c3dfab3e19c22c38c36ccac91828e3b", "commit_message": "rgw: reject control characters in response-header actions\n\nS3 GetObject permits overriding response header values, but those inputs\nneed to be validated to insure only characters that are valid in an HTTP\nheader value are present.\n\nCredit: Initial vulnerability discovery by William Bowling (@wcbowling)\nCredit: Further vulnerability discovery by Robin H. Johnson \nSigned-off-by: Robin H. Johnson ", "target": 1, "func": "int RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs,\n\t\t\t\t\t      off_t bl_len)\n{\n  const char *content_type = NULL;\n  string content_type_str;\n  map response_attrs;\n  map::iterator riter;\n  bufferlist metadata_bl;\n\n  string expires = get_s3_expiration_header(s, lastmod);\n\n  if (sent_header)\n    goto send_data;\n\n  if (custom_http_ret) {\n    set_req_state_err(s, 0);\n    dump_errno(s, custom_http_ret);\n  } else {\n    set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT\n                  : op_ret);\n    dump_errno(s);\n  }\n\n  if (op_ret)\n    goto done;\n\n  if (range_str)\n    dump_range(s, start, end, s->obj_size);\n\n  if (s->system_request &&\n      s->info.args.exists(RGW_SYS_PARAM_PREFIX \"prepend-metadata\")) {\n\n    dump_header(s, \"Rgwx-Object-Size\", (long long)total_len);\n\n    if (rgwx_stat) {\n      /*\n       * in this case, we're not returning the object's content, only the prepended\n       * extra metadata\n       */\n      total_len = 0;\n    }\n\n    /* JSON encode object metadata */\n    JSONFormatter jf;\n    jf.open_object_section(\"obj_metadata\");\n    encode_json(\"attrs\", attrs, &jf);\n    utime_t ut(lastmod);\n    encode_json(\"mtime\", ut, &jf);\n    jf.close_section();\n    stringstream ss;\n    jf.flush(ss);\n    metadata_bl.append(ss.str());\n    dump_header(s, \"Rgwx-Embedded-Metadata-Len\", metadata_bl.length());\n    total_len += metadata_bl.length();\n  }\n\n  if (s->system_request && !real_clock::is_zero(lastmod)) {\n    /* we end up dumping mtime in two different methods, a bit redundant */\n    dump_epoch_header(s, \"Rgwx-Mtime\", lastmod);\n    uint64_t pg_ver = 0;\n    int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0);\n    if (r < 0) {\n      ldpp_dout(this, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n    }\n    dump_header(s, \"Rgwx-Obj-PG-Ver\", pg_ver);\n\n    uint32_t source_zone_short_id = 0;\n    r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0);\n    if (r < 0) {\n      ldpp_dout(this, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n    }\n    if (source_zone_short_id != 0) {\n      dump_header(s, \"Rgwx-Source-Zone-Short-Id\", source_zone_short_id);\n    }\n  }\n\n  for (auto &it : crypt_http_responses)\n    dump_header(s, it.first, it.second);\n\n  dump_content_length(s, total_len);\n  dump_last_modified(s, lastmod);\n  dump_header_if_nonempty(s, \"x-amz-version-id\", version_id);\n  dump_header_if_nonempty(s, \"x-amz-expiration\", expires);\n\n  if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) {\n    dump_header(s, \"x-rgw-object-type\", \"Appendable\");\n    dump_header(s, \"x-rgw-next-append-position\", s->obj_size);\n  } else {\n    dump_header(s, \"x-rgw-object-type\", \"Normal\");\n  }\n\n  if (! op_ret) {\n    if (! lo_etag.empty()) {\n      /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly\n       * legit to perform GET on them through S3 API. In such situation,\n       * a client should receive the composited content with corresponding\n       * etag value. */\n      dump_etag(s, lo_etag);\n    } else {\n      auto iter = attrs.find(RGW_ATTR_ETAG);\n      if (iter != attrs.end()) {\n        dump_etag(s, iter->second.to_str());\n      }\n    }\n\n    for (struct response_attr_param *p = resp_attr_params; p->param; p++) {\n      bool exists;\n      string val = s->info.args.get(p->param, &exists);\n      if (exists) {\n\t/* reject unauthenticated response header manipulation, see\n\t * https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html */\n\tif (s->auth.identity->is_anonymous()) {\n\t  return -ERR_INVALID_REQUEST;\n\t}\n\tif (strcmp(p->param, \"response-content-type\") != 0) {\n\t  response_attrs[p->http_attr] = val;\n\t} else {\n\t  content_type_str = val;\n\t  content_type = content_type_str.c_str();\n\t}\n      }\n    }\n\n    for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) {\n      const char *name = iter->first.c_str();\n      map::iterator aiter = rgw_to_http_attrs.find(name);\n      if (aiter != rgw_to_http_attrs.end()) {\n        if (response_attrs.count(aiter->second) == 0) {\n          /* Was not already overridden by a response param. */\n\n          size_t len = iter->second.length();\n          string s(iter->second.c_str(), len);\n          while (len && !s[len - 1]) {\n            --len;\n            s.resize(len);\n          }\n          response_attrs[aiter->second] = s;\n        }\n      } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) {\n        /* Special handling for content_type. */\n        if (!content_type) {\n          content_type_str = rgw_bl_str(iter->second);\n          content_type = content_type_str.c_str();\n        }\n      } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) {\n        // this attr has an extra length prefix from encode() in prior versions\n        dump_header(s, \"X-Object-Meta-Static-Large-Object\", \"True\");\n      } else if (strncmp(name, RGW_ATTR_META_PREFIX,\n\t\t\t sizeof(RGW_ATTR_META_PREFIX)-1) == 0) {\n        /* User custom metadata. */\n        name += sizeof(RGW_ATTR_PREFIX) - 1;\n        dump_header(s, name, iter->second);\n      } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) {\n        RGWObjTags obj_tags;\n        try{\n          auto it = iter->second.cbegin();\n          obj_tags.decode(it);\n        } catch (buffer::error &err) {\n          ldpp_dout(this,0) << \"Error caught buffer::error couldn't decode TagSet \" << dendl;\n        }\n        dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count());\n      } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){\n        RGWObjectRetention retention;\n        try {\n          decode(retention, iter->second);\n          dump_header(s, \"x-amz-object-lock-mode\", retention.get_mode());\n          dump_time_header(s, \"x-amz-object-lock-retain-until-date\", retention.get_retain_until_date());\n        } catch (buffer::error& err) {\n          ldpp_dout(this, 0) << \"ERROR: failed to decode RGWObjectRetention\" << dendl;\n        }\n      } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) {\n        RGWObjectLegalHold legal_hold;\n        try {\n          decode(legal_hold, iter->second);\n          dump_header(s, \"x-amz-object-lock-legal-hold\",legal_hold.get_status());\n        } catch (buffer::error& err) {\n          ldpp_dout(this, 0) << \"ERROR: failed to decode RGWObjectLegalHold\" << dendl;\n        }\n      }\n    }\n  }\n\ndone:\n  for (riter = response_attrs.begin(); riter != response_attrs.end();\n       ++riter) {\n    dump_header(s, riter->first, riter->second);\n  }\n\n  if (op_ret == -ERR_NOT_MODIFIED) {\n      end_header(s, this);\n  } else {\n      if (!content_type)\n          content_type = \"binary/octet-stream\";\n\n      end_header(s, this, content_type);\n  }\n\n  if (metadata_bl.length()) {\n    dump_body(s, metadata_bl);\n  }\n  sent_header = true;\n\nsend_data:\n  if (get_data && !op_ret) {\n    int r = dump_body(s, bl.c_str() + bl_ofs, bl_len);\n    if (r < 0)\n      return r;\n  }\n\n  return 0;\n}", "func_hash": 252320959275346519647300715417843120718, "file_name": "rgw_rest_s3.cc", "file_hash": 121704064633287557349192949015382644860, "cwe": ["CWE-79"], "cve": "CVE-2020-1760", "cve_desc": "A flaw was found in the Ceph Object Gateway, where it supports request sent by an anonymous user in Amazon S3. This flaw could lead to potential XSS attacks due to the lack of proper neutralization of untrusted input.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1760"}
{"idx": 477800, "project": "ceph", "commit_id": "be7679007c3dfab3e19c22c38c36ccac91828e3b", "project_url": "https://github.com/ceph/ceph", "commit_url": "https://github.com/ceph/ceph/commit/be7679007c3dfab3e19c22c38c36ccac91828e3b", "commit_message": "rgw: reject control characters in response-header actions\n\nS3 GetObject permits overriding response header values, but those inputs\nneed to be validated to insure only characters that are valid in an HTTP\nheader value are present.\n\nCredit: Initial vulnerability discovery by William Bowling (@wcbowling)\nCredit: Further vulnerability discovery by Robin H. Johnson \nSigned-off-by: Robin H. Johnson ", "target": 0, "func": "int RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs,\n\t\t\t\t\t      off_t bl_len)\n{\n  const char *content_type = NULL;\n  string content_type_str;\n  map response_attrs;\n  map::iterator riter;\n  bufferlist metadata_bl;\n\n  string expires = get_s3_expiration_header(s, lastmod);\n\n  if (sent_header)\n    goto send_data;\n\n  if (custom_http_ret) {\n    set_req_state_err(s, 0);\n    dump_errno(s, custom_http_ret);\n  } else {\n    set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT\n                  : op_ret);\n    dump_errno(s);\n  }\n\n  if (op_ret)\n    goto done;\n\n  if (range_str)\n    dump_range(s, start, end, s->obj_size);\n\n  if (s->system_request &&\n      s->info.args.exists(RGW_SYS_PARAM_PREFIX \"prepend-metadata\")) {\n\n    dump_header(s, \"Rgwx-Object-Size\", (long long)total_len);\n\n    if (rgwx_stat) {\n      /*\n       * in this case, we're not returning the object's content, only the prepended\n       * extra metadata\n       */\n      total_len = 0;\n    }\n\n    /* JSON encode object metadata */\n    JSONFormatter jf;\n    jf.open_object_section(\"obj_metadata\");\n    encode_json(\"attrs\", attrs, &jf);\n    utime_t ut(lastmod);\n    encode_json(\"mtime\", ut, &jf);\n    jf.close_section();\n    stringstream ss;\n    jf.flush(ss);\n    metadata_bl.append(ss.str());\n    dump_header(s, \"Rgwx-Embedded-Metadata-Len\", metadata_bl.length());\n    total_len += metadata_bl.length();\n  }\n\n  if (s->system_request && !real_clock::is_zero(lastmod)) {\n    /* we end up dumping mtime in two different methods, a bit redundant */\n    dump_epoch_header(s, \"Rgwx-Mtime\", lastmod);\n    uint64_t pg_ver = 0;\n    int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0);\n    if (r < 0) {\n      ldpp_dout(this, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n    }\n    dump_header(s, \"Rgwx-Obj-PG-Ver\", pg_ver);\n\n    uint32_t source_zone_short_id = 0;\n    r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0);\n    if (r < 0) {\n      ldpp_dout(this, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n    }\n    if (source_zone_short_id != 0) {\n      dump_header(s, \"Rgwx-Source-Zone-Short-Id\", source_zone_short_id);\n    }\n  }\n\n  for (auto &it : crypt_http_responses)\n    dump_header(s, it.first, it.second);\n\n  dump_content_length(s, total_len);\n  dump_last_modified(s, lastmod);\n  dump_header_if_nonempty(s, \"x-amz-version-id\", version_id);\n  dump_header_if_nonempty(s, \"x-amz-expiration\", expires);\n\n  if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) {\n    dump_header(s, \"x-rgw-object-type\", \"Appendable\");\n    dump_header(s, \"x-rgw-next-append-position\", s->obj_size);\n  } else {\n    dump_header(s, \"x-rgw-object-type\", \"Normal\");\n  }\n\n  if (! op_ret) {\n    if (! lo_etag.empty()) {\n      /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly\n       * legit to perform GET on them through S3 API. In such situation,\n       * a client should receive the composited content with corresponding\n       * etag value. */\n      dump_etag(s, lo_etag);\n    } else {\n      auto iter = attrs.find(RGW_ATTR_ETAG);\n      if (iter != attrs.end()) {\n        dump_etag(s, iter->second.to_str());\n      }\n    }\n\n    for (struct response_attr_param *p = resp_attr_params; p->param; p++) {\n      bool exists;\n      string val = s->info.args.get(p->param, &exists);\n      if (exists) {\n\t/* reject unauthenticated response header manipulation, see\n\t * https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html */\n\tif (s->auth.identity->is_anonymous()) {\n\t  return -ERR_INVALID_REQUEST;\n\t}\n        /* HTTP specification says no control characters should be present in\n         * header values: https://tools.ietf.org/html/rfc7230#section-3.2\n         *      field-vchar    = VCHAR / obs-text\n         *\n         * Failure to validate this permits a CRLF injection in HTTP headers,\n         * whereas S3 GetObject only permits specific headers.\n         */\n        if(str_has_cntrl(val)) {\n          /* TODO: return a more distinct error in future;\n           * stating what the problem is */\n          return -ERR_INVALID_REQUEST;\n        }\n\n\tif (strcmp(p->param, \"response-content-type\") != 0) {\n\t  response_attrs[p->http_attr] = val;\n\t} else {\n\t  content_type_str = val;\n\t  content_type = content_type_str.c_str();\n\t}\n      }\n    }\n\n    for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) {\n      const char *name = iter->first.c_str();\n      map::iterator aiter = rgw_to_http_attrs.find(name);\n      if (aiter != rgw_to_http_attrs.end()) {\n        if (response_attrs.count(aiter->second) == 0) {\n          /* Was not already overridden by a response param. */\n\n          size_t len = iter->second.length();\n          string s(iter->second.c_str(), len);\n          while (len && !s[len - 1]) {\n            --len;\n            s.resize(len);\n          }\n          response_attrs[aiter->second] = s;\n        }\n      } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) {\n        /* Special handling for content_type. */\n        if (!content_type) {\n          content_type_str = rgw_bl_str(iter->second);\n          content_type = content_type_str.c_str();\n        }\n      } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) {\n        // this attr has an extra length prefix from encode() in prior versions\n        dump_header(s, \"X-Object-Meta-Static-Large-Object\", \"True\");\n      } else if (strncmp(name, RGW_ATTR_META_PREFIX,\n\t\t\t sizeof(RGW_ATTR_META_PREFIX)-1) == 0) {\n        /* User custom metadata. */\n        name += sizeof(RGW_ATTR_PREFIX) - 1;\n        dump_header(s, name, iter->second);\n      } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) {\n        RGWObjTags obj_tags;\n        try{\n          auto it = iter->second.cbegin();\n          obj_tags.decode(it);\n        } catch (buffer::error &err) {\n          ldpp_dout(this,0) << \"Error caught buffer::error couldn't decode TagSet \" << dendl;\n        }\n        dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count());\n      } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){\n        RGWObjectRetention retention;\n        try {\n          decode(retention, iter->second);\n          dump_header(s, \"x-amz-object-lock-mode\", retention.get_mode());\n          dump_time_header(s, \"x-amz-object-lock-retain-until-date\", retention.get_retain_until_date());\n        } catch (buffer::error& err) {\n          ldpp_dout(this, 0) << \"ERROR: failed to decode RGWObjectRetention\" << dendl;\n        }\n      } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) {\n        RGWObjectLegalHold legal_hold;\n        try {\n          decode(legal_hold, iter->second);\n          dump_header(s, \"x-amz-object-lock-legal-hold\",legal_hold.get_status());\n        } catch (buffer::error& err) {\n          ldpp_dout(this, 0) << \"ERROR: failed to decode RGWObjectLegalHold\" << dendl;\n        }\n      }\n    }\n  }\n\ndone:\n  for (riter = response_attrs.begin(); riter != response_attrs.end();\n       ++riter) {\n    dump_header(s, riter->first, riter->second);\n  }\n\n  if (op_ret == -ERR_NOT_MODIFIED) {\n      end_header(s, this);\n  } else {\n      if (!content_type)\n          content_type = \"binary/octet-stream\";\n\n      end_header(s, this, content_type);\n  }\n\n  if (metadata_bl.length()) {\n    dump_body(s, metadata_bl);\n  }\n  sent_header = true;\n\nsend_data:\n  if (get_data && !op_ret) {\n    int r = dump_body(s, bl.c_str() + bl_ofs, bl_len);\n    if (r < 0)\n      return r;\n  }\n\n  return 0;\n}", "func_hash": 262581748288231212684344001949485433363, "file_name": "rgw_rest_s3.cc", "file_hash": 18601801279536370570230302891439737230, "cwe": ["CWE-79"], "cve": "CVE-2020-1760", "cve_desc": "A flaw was found in the Ceph Object Gateway, where it supports request sent by an anonymous user in Amazon S3. This flaw could lead to potential XSS attacks due to the lack of proper neutralization of untrusted input.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1760"}
{"idx": 214336, "project": "linux", "commit_id": "ba953a9d89a00c078b85f4b190bc1dde66fe16b5", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/ba953a9d89a00c078b85f4b190bc1dde66fe16b5", "commit_message": "af_key: Do not call xfrm_probe_algs in parallel\n\nWhen namespace support was added to xfrm/afkey, it caused the\npreviously single-threaded call to xfrm_probe_algs to become\nmulti-threaded.  This is buggy and needs to be fixed with a mutex.\n\nReported-by: Abhishek Shah \nFixes: 283bc9f35bbb (\"xfrm: Namespacify xfrm state/policy locks\")\nSigned-off-by: Herbert Xu \nSigned-off-by: Steffen Klassert ", "target": 1, "func": "static int pfkey_register(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)\n{\n\tstruct pfkey_sock *pfk = pfkey_sk(sk);\n\tstruct sk_buff *supp_skb;\n\n\tif (hdr->sadb_msg_satype > SADB_SATYPE_MAX)\n\t\treturn -EINVAL;\n\n\tif (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) {\n\t\tif (pfk->registered&(1<sadb_msg_satype))\n\t\t\treturn -EEXIST;\n\t\tpfk->registered |= (1<sadb_msg_satype);\n\t}\n\n\txfrm_probe_algs();\n\n\tsupp_skb = compose_sadb_supported(hdr, GFP_KERNEL | __GFP_ZERO);\n\tif (!supp_skb) {\n\t\tif (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC)\n\t\t\tpfk->registered &= ~(1<sadb_msg_satype);\n\n\t\treturn -ENOBUFS;\n\t}\n\n\tpfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk,\n\t\t\tsock_net(sk));\n\treturn 0;\n}", "func_hash": 31330987608984194197058225349266288841, "file_name": "af_key.c", "file_hash": 41141499114881598479952301810943667867, "cwe": ["CWE-362"], "cve": "CVE-2022-3028", "cve_desc": "A race condition was found in the Linux kernel's IP framework for transforming packets (XFRM subsystem) when multiple calls to xfrm_probe_algs occurred simultaneously. This flaw could allow a local attacker to potentially trigger an out-of-bounds write or leak kernel heap memory by performing an out-of-bounds read and copying it into a socket.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3028"}
{"idx": 477803, "project": "linux", "commit_id": "ba953a9d89a00c078b85f4b190bc1dde66fe16b5", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/ba953a9d89a00c078b85f4b190bc1dde66fe16b5", "commit_message": "af_key: Do not call xfrm_probe_algs in parallel\n\nWhen namespace support was added to xfrm/afkey, it caused the\npreviously single-threaded call to xfrm_probe_algs to become\nmulti-threaded.  This is buggy and needs to be fixed with a mutex.\n\nReported-by: Abhishek Shah \nFixes: 283bc9f35bbb (\"xfrm: Namespacify xfrm state/policy locks\")\nSigned-off-by: Herbert Xu \nSigned-off-by: Steffen Klassert ", "target": 0, "func": "static int pfkey_register(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)\n{\n\tstruct pfkey_sock *pfk = pfkey_sk(sk);\n\tstruct sk_buff *supp_skb;\n\n\tif (hdr->sadb_msg_satype > SADB_SATYPE_MAX)\n\t\treturn -EINVAL;\n\n\tif (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) {\n\t\tif (pfk->registered&(1<sadb_msg_satype))\n\t\t\treturn -EEXIST;\n\t\tpfk->registered |= (1<sadb_msg_satype);\n\t}\n\n\tmutex_lock(&pfkey_mutex);\n\txfrm_probe_algs();\n\n\tsupp_skb = compose_sadb_supported(hdr, GFP_KERNEL | __GFP_ZERO);\n\tmutex_unlock(&pfkey_mutex);\n\n\tif (!supp_skb) {\n\t\tif (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC)\n\t\t\tpfk->registered &= ~(1<sadb_msg_satype);\n\n\t\treturn -ENOBUFS;\n\t}\n\n\tpfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk,\n\t\t\tsock_net(sk));\n\treturn 0;\n}", "func_hash": 267484480773860224509939208990668486476, "file_name": "af_key.c", "file_hash": 320308785060277331715018929148947306218, "cwe": ["CWE-362"], "cve": "CVE-2022-3028", "cve_desc": "A race condition was found in the Linux kernel's IP framework for transforming packets (XFRM subsystem) when multiple calls to xfrm_probe_algs occurred simultaneously. This flaw could allow a local attacker to potentially trigger an out-of-bounds write or leak kernel heap memory by performing an out-of-bounds read and copying it into a socket.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-3028"}
{"idx": 214339, "project": "linux", "commit_id": "f62f3c20647ebd5fb6ecb8f0b477b9281c44c10a", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f62f3c20647ebd5fb6ecb8f0b477b9281c44c10a", "commit_message": "KVM: PPC: Book3S: Fix H_RTAS rets buffer overflow\n\nThe kvmppc_rtas_hcall() sets the host rtas_args.rets pointer based on\nthe rtas_args.nargs that was provided by the guest. That guest nargs\nvalue is not range checked, so the guest can cause the host rets pointer\nto be pointed outside the args array. The individual rtas function\nhandlers check the nargs and nrets values to ensure they are correct,\nbut if they are not, the handlers store a -3 (0xfffffffd) failure\nindication in rets[0] which corrupts host memory.\n\nFix this by testing up front whether the guest supplied nargs and nret\nwould exceed the array size, and fail the hcall directly without storing\na failure indication to rets[0].\n\nAlso expand on a comment about why we kill the guest and try not to\nreturn errors directly if we have a valid rets[0] pointer.\n\nFixes: 8e591cb72047 (\"KVM: PPC: Book3S: Add infrastructure to implement kernel-side RTAS calls\")\nCc: stable@vger.kernel.org # v3.10+\nReported-by: Alexey Kardashevskiy \nSigned-off-by: Nicholas Piggin \nSigned-off-by: Michael Ellerman ", "target": 1, "func": "int kvmppc_rtas_hcall(struct kvm_vcpu *vcpu)\n{\n\tstruct rtas_token_definition *d;\n\tstruct rtas_args args;\n\trtas_arg_t *orig_rets;\n\tgpa_t args_phys;\n\tint rc;\n\n\t/*\n\t * r4 contains the guest physical address of the RTAS args\n\t * Mask off the top 4 bits since this is a guest real address\n\t */\n\targs_phys = kvmppc_get_gpr(vcpu, 4) & KVM_PAM;\n\n\tvcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);\n\trc = kvm_read_guest(vcpu->kvm, args_phys, &args, sizeof(args));\n\tsrcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);\n\tif (rc)\n\t\tgoto fail;\n\n\t/*\n\t * args->rets is a pointer into args->args. Now that we've\n\t * copied args we need to fix it up to point into our copy,\n\t * not the guest args. We also need to save the original\n\t * value so we can restore it on the way out.\n\t */\n\torig_rets = args.rets;\n\targs.rets = &args.args[be32_to_cpu(args.nargs)];\n\n\tmutex_lock(&vcpu->kvm->arch.rtas_token_lock);\n\n\trc = -ENOENT;\n\tlist_for_each_entry(d, &vcpu->kvm->arch.rtas_tokens, list) {\n\t\tif (d->token == be32_to_cpu(args.token)) {\n\t\t\td->handler->handler(vcpu, &args);\n\t\t\trc = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tmutex_unlock(&vcpu->kvm->arch.rtas_token_lock);\n\n\tif (rc == 0) {\n\t\targs.rets = orig_rets;\n\t\trc = kvm_write_guest(vcpu->kvm, args_phys, &args, sizeof(args));\n\t\tif (rc)\n\t\t\tgoto fail;\n\t}\n\n\treturn rc;\n\nfail:\n\t/*\n\t * We only get here if the guest has called RTAS with a bogus\n\t * args pointer. That means we can't get to the args, and so we\n\t * can't fail the RTAS call. So fail right out to userspace,\n\t * which should kill the guest.\n\t */\n\treturn rc;\n}", "func_hash": 66579788869283176691450230454774242085, "file_name": "book3s_rtas.c", "file_hash": 244969410022637408362665450874858593503, "cwe": ["CWE-787"], "cve": "CVE-2021-37576", "cve_desc": "arch/powerpc/kvm/book3s_rtas.c in the Linux kernel through 5.13.5 on the powerpc platform allows KVM guest OS users to cause host OS memory corruption via rtas_args.nargs, aka CID-f62f3c20647e.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37576"}
{"idx": 477811, "project": "linux", "commit_id": "f62f3c20647ebd5fb6ecb8f0b477b9281c44c10a", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f62f3c20647ebd5fb6ecb8f0b477b9281c44c10a", "commit_message": "KVM: PPC: Book3S: Fix H_RTAS rets buffer overflow\n\nThe kvmppc_rtas_hcall() sets the host rtas_args.rets pointer based on\nthe rtas_args.nargs that was provided by the guest. That guest nargs\nvalue is not range checked, so the guest can cause the host rets pointer\nto be pointed outside the args array. The individual rtas function\nhandlers check the nargs and nrets values to ensure they are correct,\nbut if they are not, the handlers store a -3 (0xfffffffd) failure\nindication in rets[0] which corrupts host memory.\n\nFix this by testing up front whether the guest supplied nargs and nret\nwould exceed the array size, and fail the hcall directly without storing\na failure indication to rets[0].\n\nAlso expand on a comment about why we kill the guest and try not to\nreturn errors directly if we have a valid rets[0] pointer.\n\nFixes: 8e591cb72047 (\"KVM: PPC: Book3S: Add infrastructure to implement kernel-side RTAS calls\")\nCc: stable@vger.kernel.org # v3.10+\nReported-by: Alexey Kardashevskiy \nSigned-off-by: Nicholas Piggin \nSigned-off-by: Michael Ellerman ", "target": 0, "func": "int kvmppc_rtas_hcall(struct kvm_vcpu *vcpu)\n{\n\tstruct rtas_token_definition *d;\n\tstruct rtas_args args;\n\trtas_arg_t *orig_rets;\n\tgpa_t args_phys;\n\tint rc;\n\n\t/*\n\t * r4 contains the guest physical address of the RTAS args\n\t * Mask off the top 4 bits since this is a guest real address\n\t */\n\targs_phys = kvmppc_get_gpr(vcpu, 4) & KVM_PAM;\n\n\tvcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);\n\trc = kvm_read_guest(vcpu->kvm, args_phys, &args, sizeof(args));\n\tsrcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);\n\tif (rc)\n\t\tgoto fail;\n\n\t/*\n\t * args->rets is a pointer into args->args. Now that we've\n\t * copied args we need to fix it up to point into our copy,\n\t * not the guest args. We also need to save the original\n\t * value so we can restore it on the way out.\n\t */\n\torig_rets = args.rets;\n\tif (be32_to_cpu(args.nargs) >= ARRAY_SIZE(args.args)) {\n\t\t/*\n\t\t * Don't overflow our args array: ensure there is room for\n\t\t * at least rets[0] (even if the call specifies 0 nret).\n\t\t *\n\t\t * Each handler must then check for the correct nargs and nret\n\t\t * values, but they may always return failure in rets[0].\n\t\t */\n\t\trc = -EINVAL;\n\t\tgoto fail;\n\t}\n\targs.rets = &args.args[be32_to_cpu(args.nargs)];\n\n\tmutex_lock(&vcpu->kvm->arch.rtas_token_lock);\n\n\trc = -ENOENT;\n\tlist_for_each_entry(d, &vcpu->kvm->arch.rtas_tokens, list) {\n\t\tif (d->token == be32_to_cpu(args.token)) {\n\t\t\td->handler->handler(vcpu, &args);\n\t\t\trc = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tmutex_unlock(&vcpu->kvm->arch.rtas_token_lock);\n\n\tif (rc == 0) {\n\t\targs.rets = orig_rets;\n\t\trc = kvm_write_guest(vcpu->kvm, args_phys, &args, sizeof(args));\n\t\tif (rc)\n\t\t\tgoto fail;\n\t}\n\n\treturn rc;\n\nfail:\n\t/*\n\t * We only get here if the guest has called RTAS with a bogus\n\t * args pointer or nargs/nret values that would overflow the\n\t * array. That means we can't get to the args, and so we can't\n\t * fail the RTAS call. So fail right out to userspace, which\n\t * should kill the guest.\n\t *\n\t * SLOF should actually pass the hcall return value from the\n\t * rtas handler call in r3, so enter_rtas could be modified to\n\t * return a failure indication in r3 and we could return such\n\t * errors to the guest rather than failing to host userspace.\n\t * However old guests that don't test for failure could then\n\t * continue silently after errors, so for now we won't do this.\n\t */\n\treturn rc;\n}", "func_hash": 270253933279643819807414798855847113264, "file_name": "book3s_rtas.c", "file_hash": 244634684304024017969354424959522055540, "cwe": ["CWE-787"], "cve": "CVE-2021-37576", "cve_desc": "arch/powerpc/kvm/book3s_rtas.c in the Linux kernel through 5.13.5 on the powerpc platform allows KVM guest OS users to cause host OS memory corruption via rtas_args.nargs, aka CID-f62f3c20647e.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37576"}
{"idx": 214358, "project": "clamav-devel", "commit_id": "224fee54dd6cd8933d7007331ec2bfca0398d4b4", "project_url": "https://github.com/vrtadmin/clamav-devel", "commit_url": "http://git.clamav.net/gitweb?p=clamav-devel.git;a=commit;h=224fee54dd6cd8933d7007331ec2bfca0398d4b4", "commit_message": "libclamav/mspack.c: fix Quantum decompressor (bb#1771)", "target": 1, "func": "int qtm_decompress(struct qtm_stream *qtm, off_t out_bytes) {\n  unsigned int frame_start, frame_end, window_posn, match_offset, range;\n  unsigned char *window, *i_ptr, *i_end, *runsrc, *rundest;\n  int i, j, selector, extra, sym, match_length, ret;\n  unsigned short H, L, C, symf;\n\n  register unsigned int bit_buffer;\n  register unsigned char bits_left;\n  unsigned char bits_needed, bit_run;\n\n  /* easy answers */\n  if (!qtm || (out_bytes < 0)) return CL_ENULLARG;\n  if (qtm->error) return qtm->error;\n\n  /* flush out any stored-up bytes before we begin */\n  i = qtm->o_end - qtm->o_ptr;\n  if ((off_t) i > out_bytes) i = (int) out_bytes;\n  if (i) {\n    if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) {\n      return qtm->error = ret;\n    }\n    qtm->o_ptr  += i;\n    out_bytes   -= i;\n  }\n  if (out_bytes == 0) return CL_SUCCESS;\n\n  /* restore local state */\n  QTM_RESTORE_BITS;\n  window = qtm->window;\n  window_posn = qtm->window_posn;\n  frame_start = qtm->frame_start;\n  H = qtm->H;\n  L = qtm->L;\n  C = qtm->C;\n\n  /* while we do not have enough decoded bytes in reserve: */\n  while ((qtm->o_end - qtm->o_ptr) < out_bytes) {\n\n    /* read header if necessary. Initialises H, L and C */\n    if (!qtm->header_read) {\n      H = 0xFFFF; L = 0; QTM_READ_BITS(C, 16);\n      qtm->header_read = 1;\n    }\n\n    /* decode more, at most up to to frame boundary */\n    frame_end = window_posn + (out_bytes - (qtm->o_end - qtm->o_ptr));\n    if ((frame_start + QTM_FRAME_SIZE) < frame_end) {\n      frame_end = frame_start + QTM_FRAME_SIZE;\n    }\n\n    while (window_posn < frame_end) {\n      QTM_GET_SYMBOL(qtm->model7, selector);\n      if (selector < 4) {\n\tstruct qtm_model *mdl = (selector == 0) ? &qtm->model0 :\n\t                        ((selector == 1) ? &qtm->model1 :\n\t\t\t\t((selector == 2) ? &qtm->model2 :\n                                                   &qtm->model3));\n\tQTM_GET_SYMBOL((*mdl), sym);\n\twindow[window_posn++] = sym;\n      }\n      else {\n\tswitch (selector) {\n\tcase 4: /* selector 4 = fixed length match (3 bytes) */\n\t  QTM_GET_SYMBOL(qtm->model4, sym);\n\t  QTM_READ_BITS(extra, qtm->extra_bits[sym]);\n\t  match_offset = qtm->position_base[sym] + extra + 1;\n\t  match_length = 3;\n\t  break;\n\n\tcase 5: /* selector 5 = fixed length match (4 bytes) */\n\t  QTM_GET_SYMBOL(qtm->model5, sym);\n\t  QTM_READ_BITS(extra, qtm->extra_bits[sym]);\n\t  match_offset = qtm->position_base[sym] + extra + 1;\n\t  match_length = 4;\n\t  break;\n\n\tcase 6: /* selector 6 = variable length match */\n\t  QTM_GET_SYMBOL(qtm->model6len, sym);\n\t  QTM_READ_BITS(extra, qtm->length_extra[sym]);\n\t  match_length = qtm->length_base[sym] + extra + 5;\n\n\t  QTM_GET_SYMBOL(qtm->model6, sym);\n\t  QTM_READ_BITS(extra, qtm->extra_bits[sym]);\n\t  match_offset = qtm->position_base[sym] + extra + 1;\n\t  break;\n\n\tdefault:\n\t  /* should be impossible, model7 can only return 0-6 */\n\t  return qtm->error = CL_EFORMAT;\n\t}\n\n\trundest = &window[window_posn];\n\ti = match_length;\n\t/* does match offset wrap the window? */\n\tif (match_offset > window_posn) {\n\t  /* j = length from match offset to end of window */\n\t  j = match_offset - window_posn;\n\t  if (j > (int) qtm->window_size) {\n\t    cli_dbgmsg(\"qtm_decompress: match offset beyond window boundaries\\n\");\n\t    return qtm->error = CL_EFORMAT;\n\t  }\n\t  runsrc = &window[qtm->window_size - j];\n\t  if (j < i) {\n\t    /* if match goes over the window edge, do two copy runs */\n\t    i -= j; while (j-- > 0) *rundest++ = *runsrc++;\n\t    runsrc = window;\n\t  }\n\t  while (i-- > 0) *rundest++ = *runsrc++;\n\t}\n\telse {\n\t  runsrc = rundest - match_offset;\n\t  if(i > (int) (qtm->window_size - window_posn))\n\t    i = qtm->window_size - window_posn;\n\t  while (i-- > 0) *rundest++ = *runsrc++;\n\t}\n\twindow_posn += match_length;\n      }\n    } /* while (window_posn < frame_end) */\n\n    qtm->o_end = &window[window_posn];\n\n    /* another frame completed? */\n    if ((window_posn - frame_start) >= QTM_FRAME_SIZE) {\n      if ((window_posn - frame_start) != QTM_FRAME_SIZE) {\n\tcli_dbgmsg(\"qtm_decompress: overshot frame alignment\\n\");\n\treturn qtm->error = CL_EFORMAT;\n      }\n\n      /* re-align input */\n      if (bits_left & 7) QTM_REMOVE_BITS(bits_left & 7);\n      do { QTM_READ_BITS(i, 8); } while (i != 0xFF);\n      qtm->header_read = 0;\n\n      /* window wrap? */\n      if (window_posn == qtm->window_size) {\n\t/* flush all currently stored data */\n\ti = (qtm->o_end - qtm->o_ptr);\n\tif (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) {\n\t  return qtm->error = ret;\n\t}\n\tout_bytes -= i;\n\tqtm->o_ptr = &window[0];\n\tqtm->o_end = &window[0];\n\twindow_posn = 0;\n      }\n\n      frame_start = window_posn;\n    }\n\n  } /* while (more bytes needed) */\n\n  if (out_bytes) {\n    i = (int) out_bytes;\n    if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) {\n      return qtm->error = ret;\n    }\n    qtm->o_ptr += i;\n  }\n\n  /* store local state */\n  QTM_STORE_BITS;\n  qtm->window_posn = window_posn;\n  qtm->frame_start = frame_start;\n  qtm->H = H;\n  qtm->L = L;\n  qtm->C = C;\n\n  return CL_SUCCESS;\n}", "func_hash": 291050376752284006088755347145639053650, "file_name": "mspack.c", "file_hash": 137114659534783781079186144852150621076, "cwe": ["CWE-20"], "cve": "CVE-2010-1311", "cve_desc": "The qtm_decompress function in libclamav/mspack.c in ClamAV before 0.96 allows remote attackers to cause a denial of service (memory corruption and application crash) via a crafted CAB archive that uses the Quantum (aka .Q) compression format.  NOTE: some of these details are obtained from third party information.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2010-1311"}
{"idx": 477946, "project": "clamav-devel", "commit_id": "224fee54dd6cd8933d7007331ec2bfca0398d4b4", "project_url": "https://github.com/vrtadmin/clamav-devel", "commit_url": "http://git.clamav.net/gitweb?p=clamav-devel.git;a=commit;h=224fee54dd6cd8933d7007331ec2bfca0398d4b4", "commit_message": "libclamav/mspack.c: fix Quantum decompressor (bb#1771)", "target": 0, "func": "int qtm_decompress(struct qtm_stream *qtm, off_t out_bytes) {\n  unsigned int frame_start, frame_end, window_posn, match_offset, range;\n  unsigned char *window, *i_ptr, *i_end, *runsrc, *rundest;\n  int i, j, selector, extra, sym, match_length, ret;\n  unsigned short H, L, C, symf;\n\n  register unsigned int bit_buffer;\n  register unsigned char bits_left;\n  unsigned char bits_needed, bit_run;\n\n  /* easy answers */\n  if (!qtm || (out_bytes < 0)) return CL_ENULLARG;\n  if (qtm->error) return qtm->error;\n\n  /* flush out any stored-up bytes before we begin */\n  i = qtm->o_end - qtm->o_ptr;\n  if ((off_t) i > out_bytes) i = (int) out_bytes;\n  if (i) {\n    if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) {\n      return qtm->error = ret;\n    }\n    qtm->o_ptr  += i;\n    out_bytes   -= i;\n  }\n  if (out_bytes == 0) return CL_SUCCESS;\n\n  /* restore local state */\n  QTM_RESTORE_BITS;\n  window = qtm->window;\n  window_posn = qtm->window_posn;\n  frame_start = qtm->frame_start;\n  H = qtm->H;\n  L = qtm->L;\n  C = qtm->C;\n\n  /* while we do not have enough decoded bytes in reserve: */\n  while ((qtm->o_end - qtm->o_ptr) < out_bytes) {\n\n    /* read header if necessary. Initialises H, L and C */\n    if (!qtm->header_read) {\n      H = 0xFFFF; L = 0; QTM_READ_BITS(C, 16);\n      qtm->header_read = 1;\n    }\n\n    /* decode more, at most up to to frame boundary */\n    frame_end = window_posn + (out_bytes - (qtm->o_end - qtm->o_ptr));\n    if ((frame_start + QTM_FRAME_SIZE) < frame_end) {\n      frame_end = frame_start + QTM_FRAME_SIZE;\n    }\n\n    while (window_posn < frame_end) {\n      QTM_GET_SYMBOL(qtm->model7, selector);\n      if (selector < 4) {\n\tstruct qtm_model *mdl = (selector == 0) ? &qtm->model0 :\n\t                        ((selector == 1) ? &qtm->model1 :\n\t\t\t\t((selector == 2) ? &qtm->model2 :\n                                                   &qtm->model3));\n\tQTM_GET_SYMBOL((*mdl), sym);\n\twindow[window_posn++] = sym;\n      }\n      else {\n\tswitch (selector) {\n\tcase 4: /* selector 4 = fixed length match (3 bytes) */\n\t  QTM_GET_SYMBOL(qtm->model4, sym);\n\t  QTM_READ_BITS(extra, qtm->extra_bits[sym]);\n\t  match_offset = qtm->position_base[sym] + extra + 1;\n\t  match_length = 3;\n\t  break;\n\n\tcase 5: /* selector 5 = fixed length match (4 bytes) */\n\t  QTM_GET_SYMBOL(qtm->model5, sym);\n\t  QTM_READ_BITS(extra, qtm->extra_bits[sym]);\n\t  match_offset = qtm->position_base[sym] + extra + 1;\n\t  match_length = 4;\n\t  break;\n\n\tcase 6: /* selector 6 = variable length match */\n\t  QTM_GET_SYMBOL(qtm->model6len, sym);\n\t  QTM_READ_BITS(extra, qtm->length_extra[sym]);\n\t  match_length = qtm->length_base[sym] + extra + 5;\n\n\t  QTM_GET_SYMBOL(qtm->model6, sym);\n\t  QTM_READ_BITS(extra, qtm->extra_bits[sym]);\n\t  match_offset = qtm->position_base[sym] + extra + 1;\n\t  break;\n\n\tdefault:\n\t  /* should be impossible, model7 can only return 0-6 */\n\t  return qtm->error = CL_EFORMAT;\n\t}\n\n\tif (window_posn + match_length > qtm->window_size) {\n\t  cli_dbgmsg(\"qtm_decompress: match ran over window wrap\\n\");\n\t  return qtm->error = CL_EFORMAT;\n\t}\n\n\trundest = &window[window_posn];\n\ti = match_length;\n\t/* does match offset wrap the window? */\n\tif (match_offset > window_posn) {\n\t  /* j = length from match offset to end of window */\n\t  j = match_offset - window_posn;\n\t  if (j > (int) qtm->window_size) {\n\t    cli_dbgmsg(\"qtm_decompress: match offset beyond window boundaries\\n\");\n\t    return qtm->error = CL_EFORMAT;\n\t  }\n\t  runsrc = &window[qtm->window_size - j];\n\t  if (j < i) {\n\t    /* if match goes over the window edge, do two copy runs */\n\t    i -= j; while (j-- > 0) *rundest++ = *runsrc++;\n\t    runsrc = window;\n\t  }\n\t  while (i-- > 0) *rundest++ = *runsrc++;\n\t}\n\telse {\n\t  runsrc = rundest - match_offset;\n\t  if(i > (int) (qtm->window_size - window_posn))\n\t    i = qtm->window_size - window_posn;\n\t  while (i-- > 0) *rundest++ = *runsrc++;\n\t}\n\twindow_posn += match_length;\n      }\n    } /* while (window_posn < frame_end) */\n\n    qtm->o_end = &window[window_posn];\n\n    /* another frame completed? */\n    if ((window_posn - frame_start) >= QTM_FRAME_SIZE) {\n      if ((window_posn - frame_start) != QTM_FRAME_SIZE) {\n\tcli_dbgmsg(\"qtm_decompress: overshot frame alignment\\n\");\n\treturn qtm->error = CL_EFORMAT;\n      }\n\n      /* re-align input */\n      if (bits_left & 7) QTM_REMOVE_BITS(bits_left & 7);\n      do { QTM_READ_BITS(i, 8); } while (i != 0xFF);\n      qtm->header_read = 0;\n\n      /* window wrap? */\n      if (window_posn == qtm->window_size) {\n\t/* flush all currently stored data */\n\ti = (qtm->o_end - qtm->o_ptr);\n\tif (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) {\n\t  return qtm->error = ret;\n\t}\n\tout_bytes -= i;\n\tqtm->o_ptr = &window[0];\n\tqtm->o_end = &window[0];\n\twindow_posn = 0;\n      }\n\n      frame_start = window_posn;\n    }\n\n  } /* while (more bytes needed) */\n\n  if (out_bytes) {\n    i = (int) out_bytes;\n    if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) {\n      return qtm->error = ret;\n    }\n    qtm->o_ptr += i;\n  }\n\n  /* store local state */\n  QTM_STORE_BITS;\n  qtm->window_posn = window_posn;\n  qtm->frame_start = frame_start;\n  qtm->H = H;\n  qtm->L = L;\n  qtm->C = C;\n\n  return CL_SUCCESS;\n}", "func_hash": 309561544522405112370599990059884786931, "file_name": "mspack.c", "file_hash": 294647704290965311324683497678599566631, "cwe": ["CWE-20"], "cve": "CVE-2010-1311", "cve_desc": "The qtm_decompress function in libclamav/mspack.c in ClamAV before 0.96 allows remote attackers to cause a denial of service (memory corruption and application crash) via a crafted CAB archive that uses the Quantum (aka .Q) compression format.  NOTE: some of these details are obtained from third party information.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2010-1311"}
{"idx": 214364, "project": "php-src", "commit_id": "e6c48213c22ed50b2b987b479fcc1ac709394caa", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=e6c48213c22ed50b2b987b479fcc1ac709394caa", "commit_message": "Fix bug #72606: heap-buffer-overflow (write) simplestring_addn simplestring.c", "target": 1, "func": "void simplestring_addn(simplestring* target, const char* source, int add_len) {\n   if(target && source) {\n      if(!target->str) {\n         simplestring_init_str(target);\n      }\n      if(target->len + add_len + 1 > target->size) {\n         /* newsize is current length + new length */\n         int newsize = target->len + add_len + 1;\n         int incr = target->size * 2;\n\n         /* align to SIMPLESTRING_INCR increments */\n         newsize = newsize - (newsize % incr) + incr;\n         target->str = (char*)realloc(target->str, newsize);\n\n         target->size = target->str ? newsize : 0;\n      }\n\n      if(target->str) {\n         if(add_len) {\n            memcpy(target->str + target->len, source, add_len);\n         }\n         target->len += add_len;\n         target->str[target->len] = 0; /* null terminate */\n      }\n   }\n}", "func_hash": 48339101902926135808878707654868204878, "file_name": "simplestring.c", "file_hash": 338610095237188637437183530843859723766, "cwe": ["CWE-119"], "cve": "CVE-2016-6296", "cve_desc": "Integer signedness error in the simplestring_addn function in simplestring.c in xmlrpc-epi through 0.54.2, as used in PHP before 5.5.38, 5.6.x before 5.6.24, and 7.x before 7.0.9, allows remote attackers to cause a denial of service (heap-based buffer overflow) or possibly have unspecified other impact via a long first argument to the PHP xmlrpc_encode_request function.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-6296"}
{"idx": 477975, "project": "php-src", "commit_id": "e6c48213c22ed50b2b987b479fcc1ac709394caa", "project_url": "https://github.com/php/php-src", "commit_url": "http://git.php.net/?p=php-src.git;a=commit;h=e6c48213c22ed50b2b987b479fcc1ac709394caa", "commit_message": "Fix bug #72606: heap-buffer-overflow (write) simplestring_addn simplestring.c", "target": 0, "func": "void simplestring_addn(simplestring* target, const char* source, size_t add_len) {\n   size_t newsize = target->size, incr = 0;\n   if(target && source) {\n      if(!target->str) {\n         simplestring_init_str(target);\n      }\n\n      if((SIZE_MAX - add_len) < target->len || (SIZE_MAX - add_len - 1) < target->len) {\n    \t  /* check for overflows, if there's a potential overflow do nothing */\n    \t  return;\n      }\n\n      if(target->len + add_len + 1 > target->size) {\n         /* newsize is current length + new length */\n         newsize = target->len + add_len + 1;\n         incr = target->size * 2;\n\n         /* align to SIMPLESTRING_INCR increments */\n         if (incr) {\n            newsize = newsize - (newsize % incr) + incr;\n         }\n         if(newsize < (target->len + add_len + 1)) {\n        \t /* some kind of overflow happened */\n        \t return;\n         }\n         target->str = (char*)realloc(target->str, newsize);\n\n         target->size = target->str ? newsize : 0;\n      }\n\n      if(target->str) {\n         if(add_len) {\n            memcpy(target->str + target->len, source, add_len);\n         }\n         target->len += add_len;\n         target->str[target->len] = 0; /* null terminate */\n      }\n   }\n}", "func_hash": 17303339734462956863208308798642286429, "file_name": "simplestring.c", "file_hash": 335043387623274482983135088926291395510, "cwe": ["CWE-119"], "cve": "CVE-2016-6296", "cve_desc": "Integer signedness error in the simplestring_addn function in simplestring.c in xmlrpc-epi through 0.54.2, as used in PHP before 5.5.38, 5.6.x before 5.6.24, and 7.x before 7.0.9, allows remote attackers to cause a denial of service (heap-based buffer overflow) or possibly have unspecified other impact via a long first argument to the PHP xmlrpc_encode_request function.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-6296"}
{"idx": 214909, "project": "linux", "commit_id": "c8c2a057fdc7de1cd16f4baa51425b932a42eb39", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/c8c2a057fdc7de1cd16f4baa51425b932a42eb39", "commit_message": "net/mlx5: prevent memory leak in mlx5_fpga_conn_create_cq\n\nIn mlx5_fpga_conn_create_cq if mlx5_vector2eqn fails the allocated\nmemory should be released.\n\nFixes: 537a50574175 (\"net/mlx5: FPGA, Add high-speed connection routines\")\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Saeed Mahameed ", "target": 1, "func": "static int mlx5_fpga_conn_create_cq(struct mlx5_fpga_conn *conn, int cq_size)\n{\n\tstruct mlx5_fpga_device *fdev = conn->fdev;\n\tstruct mlx5_core_dev *mdev = fdev->mdev;\n\tu32 temp_cqc[MLX5_ST_SZ_DW(cqc)] = {0};\n\tu32 out[MLX5_ST_SZ_DW(create_cq_out)];\n\tstruct mlx5_wq_param wqp;\n\tstruct mlx5_cqe64 *cqe;\n\tint inlen, err, eqn;\n\tunsigned int irqn;\n\tvoid *cqc, *in;\n\t__be64 *pas;\n\tu32 i;\n\n\tcq_size = roundup_pow_of_two(cq_size);\n\tMLX5_SET(cqc, temp_cqc, log_cq_size, ilog2(cq_size));\n\n\twqp.buf_numa_node = mdev->priv.numa_node;\n\twqp.db_numa_node  = mdev->priv.numa_node;\n\n\terr = mlx5_cqwq_create(mdev, &wqp, temp_cqc, &conn->cq.wq,\n\t\t\t       &conn->cq.wq_ctrl);\n\tif (err)\n\t\treturn err;\n\n\tfor (i = 0; i < mlx5_cqwq_get_size(&conn->cq.wq); i++) {\n\t\tcqe = mlx5_cqwq_get_wqe(&conn->cq.wq, i);\n\t\tcqe->op_own = MLX5_CQE_INVALID << 4 | MLX5_CQE_OWNER_MASK;\n\t}\n\n\tinlen = MLX5_ST_SZ_BYTES(create_cq_in) +\n\t\tsizeof(u64) * conn->cq.wq_ctrl.buf.npages;\n\tin = kvzalloc(inlen, GFP_KERNEL);\n\tif (!in) {\n\t\terr = -ENOMEM;\n\t\tgoto err_cqwq;\n\t}\n\n\terr = mlx5_vector2eqn(mdev, smp_processor_id(), &eqn, &irqn);\n\tif (err)\n\t\tgoto err_cqwq;\n\n\tcqc = MLX5_ADDR_OF(create_cq_in, in, cq_context);\n\tMLX5_SET(cqc, cqc, log_cq_size, ilog2(cq_size));\n\tMLX5_SET(cqc, cqc, c_eqn, eqn);\n\tMLX5_SET(cqc, cqc, uar_page, fdev->conn_res.uar->index);\n\tMLX5_SET(cqc, cqc, log_page_size, conn->cq.wq_ctrl.buf.page_shift -\n\t\t\t   MLX5_ADAPTER_PAGE_SHIFT);\n\tMLX5_SET64(cqc, cqc, dbr_addr, conn->cq.wq_ctrl.db.dma);\n\n\tpas = (__be64 *)MLX5_ADDR_OF(create_cq_in, in, pas);\n\tmlx5_fill_page_frag_array(&conn->cq.wq_ctrl.buf, pas);\n\n\terr = mlx5_core_create_cq(mdev, &conn->cq.mcq, in, inlen, out, sizeof(out));\n\tkvfree(in);\n\n\tif (err)\n\t\tgoto err_cqwq;\n\n\tconn->cq.mcq.cqe_sz     = 64;\n\tconn->cq.mcq.set_ci_db  = conn->cq.wq_ctrl.db.db;\n\tconn->cq.mcq.arm_db     = conn->cq.wq_ctrl.db.db + 1;\n\t*conn->cq.mcq.set_ci_db = 0;\n\t*conn->cq.mcq.arm_db    = 0;\n\tconn->cq.mcq.vector     = 0;\n\tconn->cq.mcq.comp       = mlx5_fpga_conn_cq_complete;\n\tconn->cq.mcq.event      = mlx5_fpga_conn_cq_event;\n\tconn->cq.mcq.irqn       = irqn;\n\tconn->cq.mcq.uar        = fdev->conn_res.uar;\n\ttasklet_init(&conn->cq.tasklet, mlx5_fpga_conn_cq_tasklet,\n\t\t     (unsigned long)conn);\n\n\tmlx5_fpga_dbg(fdev, \"Created CQ #0x%x\\n\", conn->cq.mcq.cqn);\n\n\tgoto out;\n\nerr_cqwq:\n\tmlx5_wq_destroy(&conn->cq.wq_ctrl);\nout:\n\treturn err;\n}", "func_hash": 49458891717982371333799410023640328338, "file_name": "conn.c", "file_hash": 180696471421094307893886411619232621599, "cwe": ["CWE-401"], "cve": "CVE-2019-19045", "cve_desc": "A memory leak in the mlx5_fpga_conn_create_cq() function in drivers/net/ethernet/mellanox/mlx5/core/fpga/conn.c in the Linux kernel before 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering mlx5_vector2eqn() failures, aka CID-c8c2a057fdc7.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19045"}
{"idx": 481267, "project": "linux", "commit_id": "c8c2a057fdc7de1cd16f4baa51425b932a42eb39", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/c8c2a057fdc7de1cd16f4baa51425b932a42eb39", "commit_message": "net/mlx5: prevent memory leak in mlx5_fpga_conn_create_cq\n\nIn mlx5_fpga_conn_create_cq if mlx5_vector2eqn fails the allocated\nmemory should be released.\n\nFixes: 537a50574175 (\"net/mlx5: FPGA, Add high-speed connection routines\")\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Saeed Mahameed ", "target": 0, "func": "static int mlx5_fpga_conn_create_cq(struct mlx5_fpga_conn *conn, int cq_size)\n{\n\tstruct mlx5_fpga_device *fdev = conn->fdev;\n\tstruct mlx5_core_dev *mdev = fdev->mdev;\n\tu32 temp_cqc[MLX5_ST_SZ_DW(cqc)] = {0};\n\tu32 out[MLX5_ST_SZ_DW(create_cq_out)];\n\tstruct mlx5_wq_param wqp;\n\tstruct mlx5_cqe64 *cqe;\n\tint inlen, err, eqn;\n\tunsigned int irqn;\n\tvoid *cqc, *in;\n\t__be64 *pas;\n\tu32 i;\n\n\tcq_size = roundup_pow_of_two(cq_size);\n\tMLX5_SET(cqc, temp_cqc, log_cq_size, ilog2(cq_size));\n\n\twqp.buf_numa_node = mdev->priv.numa_node;\n\twqp.db_numa_node  = mdev->priv.numa_node;\n\n\terr = mlx5_cqwq_create(mdev, &wqp, temp_cqc, &conn->cq.wq,\n\t\t\t       &conn->cq.wq_ctrl);\n\tif (err)\n\t\treturn err;\n\n\tfor (i = 0; i < mlx5_cqwq_get_size(&conn->cq.wq); i++) {\n\t\tcqe = mlx5_cqwq_get_wqe(&conn->cq.wq, i);\n\t\tcqe->op_own = MLX5_CQE_INVALID << 4 | MLX5_CQE_OWNER_MASK;\n\t}\n\n\tinlen = MLX5_ST_SZ_BYTES(create_cq_in) +\n\t\tsizeof(u64) * conn->cq.wq_ctrl.buf.npages;\n\tin = kvzalloc(inlen, GFP_KERNEL);\n\tif (!in) {\n\t\terr = -ENOMEM;\n\t\tgoto err_cqwq;\n\t}\n\n\terr = mlx5_vector2eqn(mdev, smp_processor_id(), &eqn, &irqn);\n\tif (err) {\n\t\tkvfree(in);\n\t\tgoto err_cqwq;\n\t}\n\n\tcqc = MLX5_ADDR_OF(create_cq_in, in, cq_context);\n\tMLX5_SET(cqc, cqc, log_cq_size, ilog2(cq_size));\n\tMLX5_SET(cqc, cqc, c_eqn, eqn);\n\tMLX5_SET(cqc, cqc, uar_page, fdev->conn_res.uar->index);\n\tMLX5_SET(cqc, cqc, log_page_size, conn->cq.wq_ctrl.buf.page_shift -\n\t\t\t   MLX5_ADAPTER_PAGE_SHIFT);\n\tMLX5_SET64(cqc, cqc, dbr_addr, conn->cq.wq_ctrl.db.dma);\n\n\tpas = (__be64 *)MLX5_ADDR_OF(create_cq_in, in, pas);\n\tmlx5_fill_page_frag_array(&conn->cq.wq_ctrl.buf, pas);\n\n\terr = mlx5_core_create_cq(mdev, &conn->cq.mcq, in, inlen, out, sizeof(out));\n\tkvfree(in);\n\n\tif (err)\n\t\tgoto err_cqwq;\n\n\tconn->cq.mcq.cqe_sz     = 64;\n\tconn->cq.mcq.set_ci_db  = conn->cq.wq_ctrl.db.db;\n\tconn->cq.mcq.arm_db     = conn->cq.wq_ctrl.db.db + 1;\n\t*conn->cq.mcq.set_ci_db = 0;\n\t*conn->cq.mcq.arm_db    = 0;\n\tconn->cq.mcq.vector     = 0;\n\tconn->cq.mcq.comp       = mlx5_fpga_conn_cq_complete;\n\tconn->cq.mcq.event      = mlx5_fpga_conn_cq_event;\n\tconn->cq.mcq.irqn       = irqn;\n\tconn->cq.mcq.uar        = fdev->conn_res.uar;\n\ttasklet_init(&conn->cq.tasklet, mlx5_fpga_conn_cq_tasklet,\n\t\t     (unsigned long)conn);\n\n\tmlx5_fpga_dbg(fdev, \"Created CQ #0x%x\\n\", conn->cq.mcq.cqn);\n\n\tgoto out;\n\nerr_cqwq:\n\tmlx5_wq_destroy(&conn->cq.wq_ctrl);\nout:\n\treturn err;\n}", "func_hash": 166786309951983227645990078525765970677, "file_name": "conn.c", "file_hash": 179201474190149214779616550859114985162, "cwe": ["CWE-401"], "cve": "CVE-2019-19045", "cve_desc": "A memory leak in the mlx5_fpga_conn_create_cq() function in drivers/net/ethernet/mellanox/mlx5/core/fpga/conn.c in the Linux kernel before 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering mlx5_vector2eqn() failures, aka CID-c8c2a057fdc7.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19045"}
{"idx": 214948, "project": "nagioscore", "commit_id": "b1a92a3b52d292ccb601e77a0b29cb1e67ac9d76", "project_url": "https://github.com/NagiosEnterprises/nagioscore", "commit_url": "https://github.com/NagiosEnterprises/nagioscore/commit/b1a92a3b52d292ccb601e77a0b29cb1e67ac9d76", "commit_message": "merge accidental master PR (#553) into maint and fix changelog\nmerge conflict", "target": 1, "func": "static int qh_help(int sd, char *buf, unsigned int len)\n{\n\tstruct query_handler *qh = NULL;\n\n\tif (!*buf || !strcmp(buf, \"help\")) {\n\t\tnsock_printf_nul(sd,\n\t\t\t\"  help    show help for handler \\n\"\n\t\t\t\"  help list     list registered handlers\\n\");\n\t\treturn 0;\n\t}\n\n\tif (!strcmp(buf, \"list\")) {\n\n\t\tfor (qh = qhandlers; qh != NULL; qh = qh->next_qh) {\n\t\t\tnsock_printf(sd, \"%-10s %s\\n\", qh->name, qh->description ? qh->description : \"(No description available)\");\n\t\t}\n\n\t\tnsock_printf(sd, \"%c\", 0);\n\t\treturn 0;\n\t}\n\n\tqh = qh_find_handler(buf);\n\tif (qh == NULL) {\n\n\t\tnsock_printf_nul(sd, \"No handler named '%s' is registered\\n\", buf);\n\n\t} else if (qh->handler(sd, \"help\", 4) > 200) {\n\n\t\tnsock_printf_nul(sd, \"The handler %s doesn't have any help yet.\", buf);\n\t}\n\n\treturn 0;\n}", "func_hash": 94205848469413247134990431510795041073, "file_name": "query-handler.c", "file_hash": 69411467652185615530893490033539842403, "cwe": ["CWE-476"], "cve": "CVE-2018-13441", "cve_desc": "qh_help in Nagios Core version 4.4.1 and earlier is prone to a NULL pointer dereference vulnerability, which allows attacker to cause a local denial-of-service condition by sending a crafted payload to the listening UNIX socket.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-13441"}
{"idx": 481787, "project": "nagioscore", "commit_id": "b1a92a3b52d292ccb601e77a0b29cb1e67ac9d76", "project_url": "https://github.com/NagiosEnterprises/nagioscore", "commit_url": "https://github.com/NagiosEnterprises/nagioscore/commit/b1a92a3b52d292ccb601e77a0b29cb1e67ac9d76", "commit_message": "merge accidental master PR (#553) into maint and fix changelog\nmerge conflict", "target": 0, "func": "static int qh_help(int sd, char *buf, unsigned int len)\n{\n\tstruct query_handler *qh = NULL;\n\n\tif (buf == NULL || !strcmp(buf, \"help\")) {\n\t\tnsock_printf_nul(sd,\n\t\t\t\"  help    show help for handler \\n\"\n\t\t\t\"  help list     list registered handlers\\n\");\n\t\treturn 0;\n\t}\n\n\tif (!strcmp(buf, \"list\")) {\n\n\t\tfor (qh = qhandlers; qh != NULL; qh = qh->next_qh) {\n\t\t\tnsock_printf(sd, \"%-10s %s\\n\", qh->name, qh->description ? qh->description : \"(No description available)\");\n\t\t}\n\n\t\tnsock_printf(sd, \"%c\", 0);\n\t\treturn 0;\n\t}\n\n\tqh = qh_find_handler(buf);\n\tif (qh == NULL) {\n\n\t\tnsock_printf_nul(sd, \"No handler named '%s' is registered\\n\", buf);\n\n\t} else if (qh->handler(sd, \"help\", 4) > 200) {\n\n\t\tnsock_printf_nul(sd, \"The handler %s doesn't have any help yet.\", buf);\n\t}\n\n\treturn 0;\n}", "func_hash": 205155132129673453942496407625358391443, "file_name": "query-handler.c", "file_hash": 275184931270866221094094086326042798019, "cwe": ["CWE-476"], "cve": "CVE-2018-13441", "cve_desc": "qh_help in Nagios Core version 4.4.1 and earlier is prone to a NULL pointer dereference vulnerability, which allows attacker to cause a local denial-of-service condition by sending a crafted payload to the listening UNIX socket.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2018-13441"}
{"idx": 214997, "project": "liblouis", "commit_id": "2e4772befb2b1c37cb4b9d6572945115ee28630a", "project_url": "https://github.com/liblouis/liblouis", "commit_url": "https://github.com/liblouis/liblouis/commit/2e4772befb2b1c37cb4b9d6572945115ee28630a", "commit_message": "Prevent an invalid memory writes in compileRule\n\nThanks to Han Zheng for reporting it\n\nFixes #1214", "target": 1, "func": "compileRule(FileInfo *file, TranslationTableHeader **table,\n\t\tDisplayTableHeader **displayTable, const MacroList **inScopeMacros) {\n\tCharsString token;\n\tTranslationTableOpcode opcode;\n\tCharsString ruleChars;\n\tCharsString ruleDots;\n\tCharsString cells;\n\tCharsString scratchPad;\n\tCharsString emphClass;\n\tTranslationTableCharacterAttributes after = 0;\n\tTranslationTableCharacterAttributes before = 0;\n\tint noback, nofor, nocross;\n\tnoback = nofor = nocross = 0;\ndoOpcode:\n\tif (!getToken(file, &token, NULL)) return 1;\t\t\t\t  /* blank line */\n\tif (token.chars[0] == '#' || token.chars[0] == '<') return 1; /* comment */\n\tif (file->lineNumber == 1 &&\n\t\t\t(eqasc2uni((unsigned char *)\"ISO\", token.chars, 3) ||\n\t\t\t\t\teqasc2uni((unsigned char *)\"UTF-8\", token.chars, 5))) {\n\t\tif (table)\n\t\t\tcompileHyphenation(file, &token, table);\n\t\telse\n\t\t\t/* ignore the whole file */\n\t\t\twhile (_lou_getALine(file))\n\t\t\t\t;\n\t\treturn 1;\n\t}\n\topcode = getOpcode(file, &token);\n\tswitch (opcode) {\n\tcase CTO_Macro: {\n\t\tconst Macro *macro;\n#ifdef ENABLE_MACROS\n\t\tif (!inScopeMacros) {\n\t\t\tcompileError(file, \"Defining macros only allowed in table files.\");\n\t\t\treturn 0;\n\t\t}\n\t\tif (compileMacro(file, ¯o)) {\n\t\t\t*inScopeMacros = cons_macro(macro, *inScopeMacros);\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n#else\n\t\tcompileError(file, \"Macro feature is disabled.\");\n\t\treturn 0;\n#endif\n\t}\n\tcase CTO_IncludeFile: {\n\t\tCharsString includedFile;\n\t\tif (!getToken(file, &token, \"include file name\")) return 0;\n\t\tif (!parseChars(file, &includedFile, &token)) return 0;\n\t\treturn includeFile(file, &includedFile, table, displayTable);\n\t}\n\tcase CTO_NoBack:\n\t\tif (nofor) {\n\t\t\tcompileError(file, \"%s already specified.\", _lou_findOpcodeName(CTO_NoFor));\n\t\t\treturn 0;\n\t\t}\n\t\tnoback = 1;\n\t\tgoto doOpcode;\n\tcase CTO_NoFor:\n\t\tif (noback) {\n\t\t\tcompileError(file, \"%s already specified.\", _lou_findOpcodeName(CTO_NoBack));\n\t\t\treturn 0;\n\t\t}\n\t\tnofor = 1;\n\t\tgoto doOpcode;\n\tcase CTO_Space:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_Space, noback, nofor, table, displayTable);\n\tcase CTO_Digit:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_Digit, noback, nofor, table, displayTable);\n\tcase CTO_LitDigit:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_LitDigit, noback, nofor, table, displayTable);\n\tcase CTO_Punctuation:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_Punctuation, noback, nofor, table, displayTable);\n\tcase CTO_Math:\n\t\treturn compileCharDef(file, opcode, CTC_Math, noback, nofor, table, displayTable);\n\tcase CTO_Sign:\n\t\treturn compileCharDef(file, opcode, CTC_Sign, noback, nofor, table, displayTable);\n\tcase CTO_Letter:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_Letter, noback, nofor, table, displayTable);\n\tcase CTO_UpperCase:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_UpperCase, noback, nofor, table, displayTable);\n\tcase CTO_LowerCase:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_LowerCase, noback, nofor, table, displayTable);\n\tcase CTO_Grouping:\n\t\treturn compileGrouping(file, noback, nofor, table, displayTable);\n\tcase CTO_Display:\n\t\tif (!displayTable) return 1;  // ignore\n\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\tif (!getRuleDotsPattern(file, &ruleDots)) return 0;\n\t\tif (ruleChars.length != 1 || ruleDots.length != 1) {\n\t\t\tcompileError(file, \"Exactly one character and one cell are required.\");\n\t\t\treturn 0;\n\t\t}\n\t\treturn putCharDotsMapping(\n\t\t\t\tfile, ruleChars.chars[0], ruleDots.chars[0], displayTable);\n\tcase CTO_UpLow:\n\tcase CTO_None: {\n\t\t// check if token is a macro name\n\t\tif (inScopeMacros) {\n\t\t\tconst MacroList *macros = *inScopeMacros;\n\t\t\twhile (macros) {\n\t\t\t\tconst Macro *m = macros->head;\n\t\t\t\tif (token.length == strlen(m->name) &&\n\t\t\t\t\t\teqasc2uni((unsigned char *)m->name, token.chars, token.length)) {\n\t\t\t\t\tif (!inScopeMacros) {\n\t\t\t\t\t\tcompileError(file, \"Calling macros only allowed in table files.\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\tFileInfo tmpFile;\n\t\t\t\t\tmemset(&tmpFile, 0, sizeof(tmpFile));\n\t\t\t\t\ttmpFile.fileName = file->fileName;\n\t\t\t\t\ttmpFile.sourceFile = file->sourceFile;\n\t\t\t\t\ttmpFile.lineNumber = file->lineNumber;\n\t\t\t\t\ttmpFile.encoding = noEncoding;\n\t\t\t\t\ttmpFile.status = 0;\n\t\t\t\t\ttmpFile.linepos = 0;\n\t\t\t\t\ttmpFile.linelen = 0;\n\t\t\t\t\tint argument_count = 0;\n\t\t\t\t\tCharsString *arguments =\n\t\t\t\t\t\t\tmalloc(m->argument_count * sizeof(CharsString));\n\t\t\t\t\twhile (argument_count < m->argument_count) {\n\t\t\t\t\t\tif (getToken(file, &token, \"macro argument\"))\n\t\t\t\t\t\t\targuments[argument_count++] = token;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (argument_count < m->argument_count) {\n\t\t\t\t\t\tcompileError(file, \"Expected %d arguments\", m->argument_count);\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\tint i = 0;\n\t\t\t\t\tint subst = 0;\n\t\t\t\t\tint next = subst < m->substitution_count ? m->substitutions[2 * subst]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t : m->definition_length;\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\twhile (i < next) {\n\t\t\t\t\t\t\twidechar c = m->definition[i++];\n\t\t\t\t\t\t\tif (c == '\\n') {\n\t\t\t\t\t\t\t\tif (!compileRule(&tmpFile, table, displayTable,\n\t\t\t\t\t\t\t\t\t\t\tinScopeMacros)) {\n\t\t\t\t\t\t\t\t\t_lou_logMessage(LOU_LOG_ERROR,\n\t\t\t\t\t\t\t\t\t\t\t\"result of macro expansion was: %s\",\n\t\t\t\t\t\t\t\t\t\t\t_lou_showString(\n\t\t\t\t\t\t\t\t\t\t\t\t\ttmpFile.line, tmpFile.linelen, 0));\n\t\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttmpFile.linepos = 0;\n\t\t\t\t\t\t\t\ttmpFile.linelen = 0;\n\t\t\t\t\t\t\t} else if (tmpFile.linelen >= MAXSTRING) {\n\t\t\t\t\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\t\t\t\t\"Line exceeds %d characters (post macro \"\n\t\t\t\t\t\t\t\t\t\t\"expansion)\",\n\t\t\t\t\t\t\t\t\t\tMAXSTRING);\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t} else\n\t\t\t\t\t\t\t\ttmpFile.line[tmpFile.linelen++] = c;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (subst < m->substitution_count) {\n\t\t\t\t\t\t\tCharsString arg =\n\t\t\t\t\t\t\t\t\targuments[m->substitutions[2 * subst + 1] - 1];\n\t\t\t\t\t\t\tfor (int j = 0; j < arg.length; j++)\n\t\t\t\t\t\t\t\ttmpFile.line[tmpFile.linelen++] = arg.chars[j];\n\t\t\t\t\t\t\tsubst++;\n\t\t\t\t\t\t\tnext = subst < m->substitution_count\n\t\t\t\t\t\t\t\t\t? m->substitutions[2 * subst]\n\t\t\t\t\t\t\t\t\t: m->definition_length;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (!compileRule(\n\t\t\t\t\t\t\t\t\t\t&tmpFile, table, displayTable, inScopeMacros)) {\n\t\t\t\t\t\t\t\t_lou_logMessage(LOU_LOG_ERROR,\n\t\t\t\t\t\t\t\t\t\t\"result of macro expansion was: %s\",\n\t\t\t\t\t\t\t\t\t\t_lou_showString(\n\t\t\t\t\t\t\t\t\t\t\t\ttmpFile.line, tmpFile.linelen, 0));\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tmacros = macros->tail;\n\t\t\t}\n\t\t}\n\t\tif (opcode == CTO_UpLow) {\n\t\t\tcompileError(file, \"The uplow opcode is deprecated.\");\n\t\t\treturn 0;\n\t\t}\n\t\tcompileError(file, \"opcode %s not defined.\",\n\t\t\t\t_lou_showString(token.chars, token.length, 0));\n\t\treturn 0;\n\t}\n\n\t/* now only opcodes follow that don't modify the display table */\n\tdefault:\n\t\tif (!table) return 1;\n\t\tswitch (opcode) {\n\t\tcase CTO_Locale:\n\t\t\tcompileWarning(file,\n\t\t\t\t\t\"The locale opcode is not implemented. Use the locale meta data \"\n\t\t\t\t\t\"instead.\");\n\t\t\treturn 1;\n\t\tcase CTO_Undefined: {\n\t\t\t// not passing pointer because compileBrailleIndicator may reallocate table\n\t\t\tTranslationTableOffset ruleOffset = (*table)->undefined;\n\t\t\tif (!compileBrailleIndicator(file, \"undefined character opcode\",\n\t\t\t\t\t\tCTO_Undefined, &ruleOffset, noback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->undefined = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_Match: {\n\t\t\tint ok = 0;\n\t\t\twidechar *patterns = NULL;\n\t\t\tTranslationTableRule *rule;\n\t\t\tTranslationTableOffset ruleOffset;\n\t\t\tCharsString ptn_before, ptn_after;\n\t\t\tTranslationTableOffset patternsOffset;\n\t\t\tint len, mrk;\n\t\t\tsize_t patternsByteSize = sizeof(*patterns) * 27720;\n\t\t\tpatterns = (widechar *)malloc(patternsByteSize);\n\t\t\tif (!patterns) _lou_outOfMemory();\n\t\t\tmemset(patterns, 0xffff, patternsByteSize);\n\t\t\tnoback = 1;\n\t\t\tgetCharacters(file, &ptn_before);\n\t\t\tgetRuleCharsText(file, &ruleChars);\n\t\t\tgetCharacters(file, &ptn_after);\n\t\t\tgetRuleDotsPattern(file, &ruleDots);\n\t\t\tif (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset,\n\t\t\t\t\t\t&rule, noback, nofor, table))\n\t\t\t\tgoto CTO_Match_cleanup;\n\t\t\tif (ptn_before.chars[0] == '-' && ptn_before.length == 1)\n\t\t\t\tlen = _lou_pattern_compile(\n\t\t\t\t\t\t&ptn_before.chars[0], 0, &patterns[1], 13841, *table, file);\n\t\t\telse\n\t\t\t\tlen = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length,\n\t\t\t\t\t\t&patterns[1], 13841, *table, file);\n\t\t\tif (!len) goto CTO_Match_cleanup;\n\t\t\tmrk = patterns[0] = len + 1;\n\t\t\t_lou_pattern_reverse(&patterns[1]);\n\t\t\tif (ptn_after.chars[0] == '-' && ptn_after.length == 1)\n\t\t\t\tlen = _lou_pattern_compile(\n\t\t\t\t\t\t&ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file);\n\t\t\telse\n\t\t\t\tlen = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length,\n\t\t\t\t\t\t&patterns[mrk], 13841, *table, file);\n\t\t\tif (!len) goto CTO_Match_cleanup;\n\t\t\tlen += mrk;\n\t\t\tif (!allocateSpaceInTranslationTable(\n\t\t\t\t\t\tfile, &patternsOffset, len * sizeof(widechar), table))\n\t\t\t\tgoto CTO_Match_cleanup;\n\t\t\t// allocateSpaceInTranslationTable may have moved table, so make sure rule is\n\t\t\t// still valid\n\t\t\trule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];\n\t\t\tmemcpy(&(*table)->ruleArea[patternsOffset], patterns, len * sizeof(widechar));\n\t\t\trule->patterns = patternsOffset;\n\t\t\tok = 1;\n\t\tCTO_Match_cleanup:\n\t\t\tfree(patterns);\n\t\t\treturn ok;\n\t\t}\n\n\t\tcase CTO_BackMatch: {\n\t\t\tint ok = 0;\n\t\t\twidechar *patterns = NULL;\n\t\t\tTranslationTableRule *rule;\n\t\t\tTranslationTableOffset ruleOffset;\n\t\t\tCharsString ptn_before, ptn_after;\n\t\t\tTranslationTableOffset patternOffset;\n\t\t\tint len, mrk;\n\t\t\tsize_t patternsByteSize = sizeof(*patterns) * 27720;\n\t\t\tpatterns = (widechar *)malloc(patternsByteSize);\n\t\t\tif (!patterns) _lou_outOfMemory();\n\t\t\tmemset(patterns, 0xffff, patternsByteSize);\n\t\t\tnofor = 1;\n\t\t\tgetCharacters(file, &ptn_before);\n\t\t\tgetRuleCharsText(file, &ruleChars);\n\t\t\tgetCharacters(file, &ptn_after);\n\t\t\tgetRuleDotsPattern(file, &ruleDots);\n\t\t\tif (!addRule(file, opcode, &ruleChars, &ruleDots, 0, 0, &ruleOffset, &rule,\n\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\tgoto CTO_BackMatch_cleanup;\n\t\t\tif (ptn_before.chars[0] == '-' && ptn_before.length == 1)\n\t\t\t\tlen = _lou_pattern_compile(\n\t\t\t\t\t\t&ptn_before.chars[0], 0, &patterns[1], 13841, *table, file);\n\t\t\telse\n\t\t\t\tlen = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length,\n\t\t\t\t\t\t&patterns[1], 13841, *table, file);\n\t\t\tif (!len) goto CTO_BackMatch_cleanup;\n\t\t\tmrk = patterns[0] = len + 1;\n\t\t\t_lou_pattern_reverse(&patterns[1]);\n\t\t\tif (ptn_after.chars[0] == '-' && ptn_after.length == 1)\n\t\t\t\tlen = _lou_pattern_compile(\n\t\t\t\t\t\t&ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file);\n\t\t\telse\n\t\t\t\tlen = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length,\n\t\t\t\t\t\t&patterns[mrk], 13841, *table, file);\n\t\t\tif (!len) goto CTO_BackMatch_cleanup;\n\t\t\tlen += mrk;\n\t\t\tif (!allocateSpaceInTranslationTable(\n\t\t\t\t\t\tfile, &patternOffset, len * sizeof(widechar), table))\n\t\t\t\tgoto CTO_BackMatch_cleanup;\n\t\t\t// allocateSpaceInTranslationTable may have moved table, so make sure rule is\n\t\t\t// still valid\n\t\t\trule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];\n\t\t\tmemcpy(&(*table)->ruleArea[patternOffset], patterns, len * sizeof(widechar));\n\t\t\trule->patterns = patternOffset;\n\t\t\tok = 1;\n\t\tCTO_BackMatch_cleanup:\n\t\t\tfree(patterns);\n\t\t\treturn ok;\n\t\t}\n\n\t\tcase CTO_CapsLetter:\n\t\tcase CTO_BegCapsWord:\n\t\tcase CTO_EndCapsWord:\n\t\tcase CTO_BegCaps:\n\t\tcase CTO_EndCaps:\n\t\tcase CTO_BegCapsPhrase:\n\t\tcase CTO_EndCapsPhrase:\n\t\tcase CTO_LenCapsPhrase:\n\t\t/* these 8 general purpose opcodes are compiled further down to more specific\n\t\t * internal opcodes:\n\t\t * - modeletter\n\t\t * - begmodeword\n\t\t * - endmodeword\n\t\t * - begmode\n\t\t * - endmode\n\t\t * - begmodephrase\n\t\t * - endmodephrase\n\t\t * - lenmodephrase\n\t\t */\n\t\tcase CTO_ModeLetter:\n\t\tcase CTO_BegModeWord:\n\t\tcase CTO_EndModeWord:\n\t\tcase CTO_BegMode:\n\t\tcase CTO_EndMode:\n\t\tcase CTO_BegModePhrase:\n\t\tcase CTO_EndModePhrase:\n\t\tcase CTO_LenModePhrase: {\n\t\t\tTranslationTableCharacterAttributes mode;\n\t\t\tint i;\n\t\t\tswitch (opcode) {\n\t\t\tcase CTO_CapsLetter:\n\t\t\tcase CTO_BegCapsWord:\n\t\t\tcase CTO_EndCapsWord:\n\t\t\tcase CTO_BegCaps:\n\t\t\tcase CTO_EndCaps:\n\t\t\tcase CTO_BegCapsPhrase:\n\t\t\tcase CTO_EndCapsPhrase:\n\t\t\tcase CTO_LenCapsPhrase:\n\t\t\t\tmode = CTC_UpperCase;\n\t\t\t\ti = 0;\n\t\t\t\topcode += (CTO_ModeLetter - CTO_CapsLetter);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (!getToken(file, &token, \"attribute name\")) return 0;\n\t\t\t\tif (!(*table)->characterClasses && !allocateCharacterClasses(*table)) {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tconst CharacterClass *characterClass = findCharacterClass(&token, *table);\n\t\t\t\tif (!characterClass) {\n\t\t\t\t\tcharacterClass =\n\t\t\t\t\t\t\taddCharacterClass(file, token.chars, token.length, *table, 1);\n\t\t\t\t\tif (!characterClass) return 0;\n\t\t\t\t}\n\t\t\t\tmode = characterClass->attribute;\n\t\t\t\tif (!(mode == CTC_UpperCase || mode == CTC_Digit) && mode >= CTC_Space &&\n\t\t\t\t\t\tmode <= CTC_LitDigit) {\n\t\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\t\"mode must be \\\"uppercase\\\", \\\"digit\\\", or a custom \"\n\t\t\t\t\t\t\t\"attribute name.\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t/* check if this mode is already defined and if the number of modes does\n\t\t\t\t * not exceed the maximal number */\n\t\t\t\tif (mode == CTC_UpperCase)\n\t\t\t\t\ti = 0;\n\t\t\t\telse {\n\t\t\t\t\tfor (i = 1; i < MAX_MODES && (*table)->modes[i].value; i++) {\n\t\t\t\t\t\tif ((*table)->modes[i].mode == mode) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (i == MAX_MODES) {\n\t\t\t\t\t\tcompileError(file, \"Max number of modes (%i) reached\", MAX_MODES);\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!(*table)->modes[i].value)\n\t\t\t\t(*table)->modes[i] = (EmphasisClass){ plain_text, mode,\n\t\t\t\t\t0x1 << (MAX_EMPH_CLASSES + i), MAX_EMPH_CLASSES + i };\n\t\t\tswitch (opcode) {\n\t\t\tcase CTO_BegModePhrase: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"first word capital sign\",\n\t\t\t\t\t\t\tCTO_BegCapsPhraseRule + (8 * i), &ruleOffset, noback, nofor,\n\t\t\t\t\t\t\ttable))\n\t\t\t\t\treturn 0;\n\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset] = ruleOffset;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcase CTO_EndModePhrase: {\n\t\t\t\tTranslationTableOffset ruleOffset;\n\t\t\t\tswitch (compileBeforeAfter(file)) {\n\t\t\t\tcase 1:\t // before\n\t\t\t\t\tif ((*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset]) {\n\t\t\t\t\t\tcompileError(\n\t\t\t\t\t\t\t\tfile, \"Capital sign after last word already defined.\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t\t// table\n\t\t\t\t\truleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i]\n\t\t\t\t\t\t\t\t\t\t\t\t\t[endPhraseBeforeOffset];\n\t\t\t\t\tif (!compileBrailleIndicator(file, \"capital sign before last word\",\n\t\t\t\t\t\t\t\tCTO_EndCapsPhraseBeforeRule + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseBeforeOffset] =\n\t\t\t\t\t\t\truleOffset;\n\t\t\t\t\treturn 1;\n\t\t\t\tcase 2:\t // after\n\t\t\t\t\tif ((*table)->emphRules[MAX_EMPH_CLASSES + i]\n\t\t\t\t\t\t\t\t\t\t   [endPhraseBeforeOffset]) {\n\t\t\t\t\t\tcompileError(\n\t\t\t\t\t\t\t\tfile, \"Capital sign before last word already defined.\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t\t// table\n\t\t\t\t\truleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i]\n\t\t\t\t\t\t\t\t\t\t\t\t\t[endPhraseAfterOffset];\n\t\t\t\t\tif (!compileBrailleIndicator(file, \"capital sign after last word\",\n\t\t\t\t\t\t\t\tCTO_EndCapsPhraseAfterRule + (8 * i), &ruleOffset, noback,\n\t\t\t\t\t\t\t\tnofor, table))\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset] =\n\t\t\t\t\t\t\truleOffset;\n\t\t\t\t\treturn 1;\n\t\t\t\tdefault:  // error\n\t\t\t\t\tcompileError(file, \"Invalid lastword indicator location.\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase CTO_BegMode: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"first letter capital sign\",\n\t\t\t\t\t\t\tCTO_BegCapsRule + (8 * i), &ruleOffset, noback, nofor, table))\n\t\t\t\t\treturn 0;\n\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset] = ruleOffset;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcase CTO_EndMode: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"last letter capital sign\",\n\t\t\t\t\t\t\tCTO_EndCapsRule + (8 * i), &ruleOffset, noback, nofor, table))\n\t\t\t\t\treturn 0;\n\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset] = ruleOffset;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcase CTO_ModeLetter: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"single letter capital sign\",\n\t\t\t\t\t\t\tCTO_CapsLetterRule + (8 * i), &ruleOffset, noback, nofor,\n\t\t\t\t\t\t\ttable))\n\t\t\t\t\treturn 0;\n\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset] = ruleOffset;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcase CTO_BegModeWord: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"capital word\",\n\t\t\t\t\t\t\tCTO_BegCapsWordRule + (8 * i), &ruleOffset, noback, nofor,\n\t\t\t\t\t\t\ttable))\n\t\t\t\t\treturn 0;\n\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset] = ruleOffset;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcase CTO_EndModeWord: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"capital word stop\",\n\t\t\t\t\t\t\tCTO_EndCapsWordRule + (8 * i), &ruleOffset, noback, nofor,\n\t\t\t\t\t\t\ttable))\n\t\t\t\t\treturn 0;\n\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset] = ruleOffset;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcase CTO_LenModePhrase:\n\t\t\t\treturn (*table)->emphRules[MAX_EMPH_CLASSES + i][lenPhraseOffset] =\n\t\t\t\t\t\t\t   compileNumber(file);\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t/* these 8 general purpose emphasis opcodes are compiled further down to more\n\t\t * specific internal opcodes:\n\t\t * - emphletter\n\t\t * - begemphword\n\t\t * - endemphword\n\t\t * - begemph\n\t\t * - endemph\n\t\t * - begemphphrase\n\t\t * - endemphphrase\n\t\t * - lenemphphrase\n\t\t */\n\t\tcase CTO_EmphClass:\n\t\t\tif (!getToken(file, &emphClass, \"emphasis class\")) {\n\t\t\t\tcompileError(file, \"emphclass must be followed by a valid class name.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tint k, i;\n\t\t\tchar *s = malloc(sizeof(char) * (emphClass.length + 1));\n\t\t\tfor (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k];\n\t\t\ts[k++] = '\\0';\n\t\t\tfor (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++)\n\t\t\t\tif (strcmp(s, (*table)->emphClassNames[i]) == 0) {\n\t\t\t\t\t_lou_logMessage(LOU_LOG_WARN, \"Duplicate emphasis class: %s\", s);\n\t\t\t\t\twarningCount++;\n\t\t\t\t\tfree(s);\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\tif (i == MAX_EMPH_CLASSES) {\n\t\t\t\t_lou_logMessage(LOU_LOG_ERROR,\n\t\t\t\t\t\t\"Max number of emphasis classes (%i) reached\", MAX_EMPH_CLASSES);\n\t\t\t\terrorCount++;\n\t\t\t\tfree(s);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tswitch (i) {\n\t\t\t/* For backwards compatibility (i.e. because programs will assume\n\t\t\t * the first 3 typeform bits are `italic', `underline' and `bold')\n\t\t\t * we require that the first 3 emphclass definitions are (in that\n\t\t\t * order):\n\t\t\t *\n\t\t\t *   emphclass italic\n\t\t\t *   emphclass underline\n\t\t\t *   emphclass bold\n\t\t\t *\n\t\t\t * While it would be possible to use the emphclass opcode only for\n\t\t\t * defining _additional_ classes (not allowing for them to be called\n\t\t\t * italic, underline or bold), thereby reducing the amount of\n\t\t\t * boilerplate, we deliberately choose not to do that in order to\n\t\t\t * not give italic, underline and bold any special status. The\n\t\t\t * hope is that eventually all programs will use liblouis for\n\t\t\t * emphasis the recommended way (i.e. by looking up the supported\n\t\t\t * typeforms in the documentation or API) so that we can drop this\n\t\t\t * restriction.\n\t\t\t */\n\t\t\tcase 0:\n\t\t\t\tif (strcmp(s, \"italic\") != 0) {\n\t\t\t\t\t_lou_logMessage(LOU_LOG_ERROR,\n\t\t\t\t\t\t\t\"First emphasis class must be \\\"italic\\\" but got \"\n\t\t\t\t\t\t\t\"%s\",\n\t\t\t\t\t\t\ts);\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tfree(s);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tif (strcmp(s, \"underline\") != 0) {\n\t\t\t\t\t_lou_logMessage(LOU_LOG_ERROR,\n\t\t\t\t\t\t\t\"Second emphasis class must be \\\"underline\\\" but \"\n\t\t\t\t\t\t\t\"got \"\n\t\t\t\t\t\t\t\"%s\",\n\t\t\t\t\t\t\ts);\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tfree(s);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tif (strcmp(s, \"bold\") != 0) {\n\t\t\t\t\t_lou_logMessage(LOU_LOG_ERROR,\n\t\t\t\t\t\t\t\"Third emphasis class must be \\\"bold\\\" but got \"\n\t\t\t\t\t\t\t\"%s\",\n\t\t\t\t\t\t\ts);\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tfree(s);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t(*table)->emphClassNames[i] = s;\n\t\t\t(*table)->emphClasses[i] = (EmphasisClass){ emph_1\n\t\t\t\t\t\t<< i, /* relies on the order of typeforms emph_1..emph_10 */\n\t\t\t\t0, 0x1 << i, i };\n\t\t\treturn 1;\n\t\tcase CTO_EmphLetter:\n\t\tcase CTO_BegEmphWord:\n\t\tcase CTO_EndEmphWord:\n\t\tcase CTO_BegEmph:\n\t\tcase CTO_EndEmph:\n\t\tcase CTO_BegEmphPhrase:\n\t\tcase CTO_EndEmphPhrase:\n\t\tcase CTO_LenEmphPhrase:\n\t\tcase CTO_EmphModeChars:\n\t\tcase CTO_NoEmphChars: {\n\t\t\tif (!getToken(file, &token, \"emphasis class\")) return 0;\n\t\t\tif (!parseChars(file, &emphClass, &token)) return 0;\n\t\t\tchar *s = malloc(sizeof(char) * (emphClass.length + 1));\n\t\t\tint k, i;\n\t\t\tfor (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k];\n\t\t\ts[k++] = '\\0';\n\t\t\tfor (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++)\n\t\t\t\tif (strcmp(s, (*table)->emphClassNames[i]) == 0) break;\n\t\t\tif (i == MAX_EMPH_CLASSES || !(*table)->emphClassNames[i]) {\n\t\t\t\t_lou_logMessage(LOU_LOG_ERROR, \"Emphasis class %s not declared\", s);\n\t\t\t\terrorCount++;\n\t\t\t\tfree(s);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tint ok = 0;\n\t\t\tswitch (opcode) {\n\t\t\tcase CTO_EmphLetter: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset = (*table)->emphRules[i][letterOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"single letter\",\n\t\t\t\t\t\t\tCTO_Emph1LetterRule + letterOffset + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\tbreak;\n\t\t\t\t(*table)->emphRules[i][letterOffset] = ruleOffset;\n\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_BegEmphWord: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset = (*table)->emphRules[i][begWordOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"word\",\n\t\t\t\t\t\t\tCTO_Emph1LetterRule + begWordOffset + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\tbreak;\n\t\t\t\t(*table)->emphRules[i][begWordOffset] = ruleOffset;\n\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_EndEmphWord: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset = (*table)->emphRules[i][endWordOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"word stop\",\n\t\t\t\t\t\t\tCTO_Emph1LetterRule + endWordOffset + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\tbreak;\n\t\t\t\t(*table)->emphRules[i][endWordOffset] = ruleOffset;\n\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_BegEmph: {\n\t\t\t\t/* fail if both begemph and any of begemphphrase or begemphword are\n\t\t\t\t * defined */\n\t\t\t\tif ((*table)->emphRules[i][begWordOffset] ||\n\t\t\t\t\t\t(*table)->emphRules[i][begPhraseOffset]) {\n\t\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\t\"Cannot define emphasis for both no context and word or \"\n\t\t\t\t\t\t\t\"phrase context, i.e. cannot have both begemph and \"\n\t\t\t\t\t\t\t\"begemphword or begemphphrase.\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset = (*table)->emphRules[i][begOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"first letter\",\n\t\t\t\t\t\t\tCTO_Emph1LetterRule + begOffset + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\tbreak;\n\t\t\t\t(*table)->emphRules[i][begOffset] = ruleOffset;\n\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_EndEmph: {\n\t\t\t\tif ((*table)->emphRules[i][endWordOffset] ||\n\t\t\t\t\t\t(*table)->emphRules[i][endPhraseBeforeOffset] ||\n\t\t\t\t\t\t(*table)->emphRules[i][endPhraseAfterOffset]) {\n\t\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\t\"Cannot define emphasis for both no context and word or \"\n\t\t\t\t\t\t\t\"phrase context, i.e. cannot have both endemph and \"\n\t\t\t\t\t\t\t\"endemphword or endemphphrase.\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset = (*table)->emphRules[i][endOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"last letter\",\n\t\t\t\t\t\t\tCTO_Emph1LetterRule + endOffset + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\tbreak;\n\t\t\t\t(*table)->emphRules[i][endOffset] = ruleOffset;\n\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_BegEmphPhrase: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[i][begPhraseOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"first word\",\n\t\t\t\t\t\t\tCTO_Emph1LetterRule + begPhraseOffset + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\tbreak;\n\t\t\t\t(*table)->emphRules[i][begPhraseOffset] = ruleOffset;\n\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_EndEmphPhrase:\n\t\t\t\tswitch (compileBeforeAfter(file)) {\n\t\t\t\tcase 1: {  // before\n\t\t\t\t\tif ((*table)->emphRules[i][endPhraseAfterOffset]) {\n\t\t\t\t\t\tcompileError(file, \"last word after already defined.\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t\t// table\n\t\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t\t(*table)->emphRules[i][endPhraseBeforeOffset];\n\t\t\t\t\tif (!compileBrailleIndicator(file, \"last word before\",\n\t\t\t\t\t\t\t\tCTO_Emph1LetterRule + endPhraseBeforeOffset + (8 * i),\n\t\t\t\t\t\t\t\t&ruleOffset, noback, nofor, table))\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t(*table)->emphRules[i][endPhraseBeforeOffset] = ruleOffset;\n\t\t\t\t\tok = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 2: {  // after\n\t\t\t\t\tif ((*table)->emphRules[i][endPhraseBeforeOffset]) {\n\t\t\t\t\t\tcompileError(file, \"last word before already defined.\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t\t// table\n\t\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t\t(*table)->emphRules[i][endPhraseAfterOffset];\n\t\t\t\t\tif (!compileBrailleIndicator(file, \"last word after\",\n\t\t\t\t\t\t\t\tCTO_Emph1LetterRule + endPhraseAfterOffset + (8 * i),\n\t\t\t\t\t\t\t\t&ruleOffset, noback, nofor, table))\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t(*table)->emphRules[i][endPhraseAfterOffset] = ruleOffset;\n\t\t\t\t\tok = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:  // error\n\t\t\t\t\tcompileError(file, \"Invalid lastword indicator location.\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CTO_LenEmphPhrase:\n\t\t\t\tif (((*table)->emphRules[i][lenPhraseOffset] = compileNumber(file)))\n\t\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\tcase CTO_EmphModeChars: {\n\t\t\t\tif (!getRuleCharsText(file, &ruleChars)) break;\n\t\t\t\twidechar *emphmodechars = (*table)->emphModeChars[i];\n\t\t\t\tint len;\n\t\t\t\tfor (len = 0; len < EMPHMODECHARSSIZE && emphmodechars[len]; len++)\n\t\t\t\t\t;\n\t\t\t\tif (len + ruleChars.length > EMPHMODECHARSSIZE) {\n\t\t\t\t\tcompileError(file, \"More than %d characters\", EMPHMODECHARSSIZE);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tok = 1;\n\t\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\t\tif (!getChar(ruleChars.chars[k], *table, NULL)) {\n\t\t\t\t\t\tcompileError(file, \"Emphasis mode character undefined\");\n\t\t\t\t\t\tok = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\temphmodechars[len++] = ruleChars.chars[k];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_NoEmphChars: {\n\t\t\t\tif (!getRuleCharsText(file, &ruleChars)) break;\n\t\t\t\twidechar *noemphchars = (*table)->noEmphChars[i];\n\t\t\t\tint len;\n\t\t\t\tfor (len = 0; len < NOEMPHCHARSSIZE && noemphchars[len]; len++)\n\t\t\t\t\t;\n\t\t\t\tif (len + ruleChars.length > NOEMPHCHARSSIZE) {\n\t\t\t\t\tcompileError(file, \"More than %d characters\", NOEMPHCHARSSIZE);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tok = 1;\n\t\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\t\tif (!getChar(ruleChars.chars[k], *table, NULL)) {\n\t\t\t\t\t\tcompileError(file, \"Character undefined\");\n\t\t\t\t\t\tok = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tnoemphchars[len++] = ruleChars.chars[k];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfree(s);\n\t\t\treturn ok;\n\t\t}\n\t\tcase CTO_LetterSign: {\n\t\t\t// not passing pointer because compileBrailleIndicator may reallocate table\n\t\t\tTranslationTableOffset ruleOffset = (*table)->letterSign;\n\t\t\tif (!compileBrailleIndicator(file, \"letter sign\", CTO_LetterRule, &ruleOffset,\n\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->letterSign = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_NoLetsignBefore:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (((*table)->noLetsignBeforeCount + ruleChars.length) > LETSIGNBEFORESIZE) {\n\t\t\t\tcompileError(file, \"More than %d characters\", LETSIGNBEFORESIZE);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfor (int k = 0; k < ruleChars.length; k++)\n\t\t\t\t(*table)->noLetsignBefore[(*table)->noLetsignBeforeCount++] =\n\t\t\t\t\t\truleChars.chars[k];\n\t\t\treturn 1;\n\t\tcase CTO_NoLetsign:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (((*table)->noLetsignCount + ruleChars.length) > LETSIGNSIZE) {\n\t\t\t\tcompileError(file, \"More than %d characters\", LETSIGNSIZE);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfor (int k = 0; k < ruleChars.length; k++)\n\t\t\t\t(*table)->noLetsign[(*table)->noLetsignCount++] = ruleChars.chars[k];\n\t\t\treturn 1;\n\t\tcase CTO_NoLetsignAfter:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (((*table)->noLetsignAfterCount + ruleChars.length) > LETSIGNAFTERSIZE) {\n\t\t\t\tcompileError(file, \"More than %d characters\", LETSIGNAFTERSIZE);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfor (int k = 0; k < ruleChars.length; k++)\n\t\t\t\t(*table)->noLetsignAfter[(*table)->noLetsignAfterCount++] =\n\t\t\t\t\t\truleChars.chars[k];\n\t\t\treturn 1;\n\t\tcase CTO_NumberSign: {\n\t\t\t// not passing pointer because compileBrailleIndicator may reallocate table\n\t\t\tTranslationTableOffset ruleOffset = (*table)->numberSign;\n\t\t\tif (!compileBrailleIndicator(file, \"number sign\", CTO_NumberRule, &ruleOffset,\n\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->numberSign = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\n\t\tcase CTO_NumericModeChars:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Numeric mode character undefined: %s\",\n\t\t\t\t\t\t\t_lou_showString(&ruleChars.chars[k], 1, 0));\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_NumericMode;\n\t\t\t\t(*table)->usesNumericMode = 1;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_MidEndNumericModeChars:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Midendnumeric mode character undefined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_MidEndNumericMode;\n\t\t\t\t(*table)->usesNumericMode = 1;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_NumericNoContractChars:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Numeric no contraction character undefined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_NumericNoContract;\n\t\t\t\t(*table)->usesNumericMode = 1;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_NoContractSign: {\n\t\t\t// not passing pointer because compileBrailleIndicator may reallocate table\n\t\t\tTranslationTableOffset ruleOffset = (*table)->noContractSign;\n\t\t\tif (!compileBrailleIndicator(file, \"no contractions sign\", CTO_NoContractRule,\n\t\t\t\t\t\t&ruleOffset, noback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->noContractSign = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_SeqDelimiter:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Sequence delimiter character undefined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_SeqDelimiter;\n\t\t\t\t(*table)->usesSequences = 1;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_SeqBeforeChars:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Sequence before character undefined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_SeqBefore;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_SeqAfterChars:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Sequence after character undefined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_SeqAfter;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_SeqAfterPattern:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (((*table)->seqPatternsCount + ruleChars.length + 1) > SEQPATTERNSIZE) {\n\t\t\t\tcompileError(file, \"More than %d characters\", SEQPATTERNSIZE);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfor (int k = 0; k < ruleChars.length; k++)\n\t\t\t\t(*table)->seqPatterns[(*table)->seqPatternsCount++] = ruleChars.chars[k];\n\t\t\t(*table)->seqPatterns[(*table)->seqPatternsCount++] = 0;\n\t\t\treturn 1;\n\n\t\tcase CTO_SeqAfterExpression:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor ((*table)->seqAfterExpressionLength = 0;\n\t\t\t\t\t(*table)->seqAfterExpressionLength < ruleChars.length;\n\t\t\t\t\t(*table)->seqAfterExpressionLength++)\n\t\t\t\t(*table)->seqAfterExpression[(*table)->seqAfterExpressionLength] =\n\t\t\t\t\t\truleChars.chars[(*table)->seqAfterExpressionLength];\n\t\t\t(*table)->seqAfterExpression[(*table)->seqAfterExpressionLength] = 0;\n\t\t\treturn 1;\n\n\t\tcase CTO_CapsModeChars:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Capital mode character undefined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_CapsMode;\n\t\t\t\t(*table)->hasCapsModeChars = 1;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_BegComp: {\n\t\t\t// not passing pointer because compileBrailleIndicator may reallocate table\n\t\t\tTranslationTableOffset ruleOffset = (*table)->begComp;\n\t\t\tif (!compileBrailleIndicator(file, \"begin computer braille\", CTO_BegCompRule,\n\t\t\t\t\t\t&ruleOffset, noback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->begComp = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_EndComp: {\n\t\t\t// not passing pointer because compileBrailleIndicator may reallocate table\n\t\t\tTranslationTableOffset ruleOffset = (*table)->endComp;\n\t\t\tif (!compileBrailleIndicator(file, \"end computer braslle\", CTO_EndCompRule,\n\t\t\t\t\t\t&ruleOffset, noback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->endComp = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_NoCross:\n\t\t\tif (nocross) {\n\t\t\t\tcompileError(\n\t\t\t\t\t\tfile, \"%s already specified.\", _lou_findOpcodeName(CTO_NoCross));\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tnocross = 1;\n\t\t\tgoto doOpcode;\n\t\tcase CTO_Syllable:\n\t\t\t(*table)->syllables = 1;\n\t\tcase CTO_Always:\n\t\tcase CTO_LargeSign:\n\t\tcase CTO_WholeWord:\n\t\tcase CTO_PartWord:\n\t\tcase CTO_JoinNum:\n\t\tcase CTO_JoinableWord:\n\t\tcase CTO_LowWord:\n\t\tcase CTO_SuffixableWord:\n\t\tcase CTO_PrefixableWord:\n\t\tcase CTO_BegWord:\n\t\tcase CTO_BegMidWord:\n\t\tcase CTO_MidWord:\n\t\tcase CTO_MidEndWord:\n\t\tcase CTO_EndWord:\n\t\tcase CTO_PrePunc:\n\t\tcase CTO_PostPunc:\n\t\tcase CTO_BegNum:\n\t\tcase CTO_MidNum:\n\t\tcase CTO_EndNum:\n\t\tcase CTO_Repeated:\n\t\tcase CTO_RepWord:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (!getRuleDotsPattern(file, &ruleDots)) return 0;\n\t\t\tif (ruleDots.length == 0)\n\t\t\t\t// check that all characters in a rule with `=` as second operand are\n\t\t\t\t// defined (or based on another character)\n\t\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\t\tTranslationTableCharacter *c =\n\t\t\t\t\t\t\tgetChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\t\tif (!(c && (c->definitionRule || c->basechar))) {\n\t\t\t\t\t\tcompileError(file, \"Character %s is not defined\",\n\t\t\t\t\t\t\t\t_lou_showString(&ruleChars.chars[k], 1, 0));\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tTranslationTableRule *r;\n\t\t\tif (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, &r,\n\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\tif (nocross) r->nocross = 1;\n\t\t\treturn 1;\n\t\t\t// if (opcode == CTO_MidNum)\n\t\t\t// {\n\t\t\t//   TranslationTableCharacter *c = getChar(ruleChars.chars[0]);\n\t\t\t//   if(c)\n\t\t\t//     c->attributes |= CTC_NumericMode;\n\t\t\t// }\n\t\tcase CTO_RepEndWord:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tCharsString dots;\n\t\t\tif (!getToken(file, &dots, \"dots,dots operand\")) return 0;\n\t\t\tint len = dots.length;\n\t\t\tfor (int k = 0; k < len - 1; k++) {\n\t\t\t\tif (dots.chars[k] == ',') {\n\t\t\t\t\tdots.length = k;\n\t\t\t\t\tif (!parseDots(file, &ruleDots, &dots)) return 0;\n\t\t\t\t\truleDots.chars[ruleDots.length++] = ',';\n\t\t\t\t\tk++;\n\t\t\t\t\tif (k == len - 1 && dots.chars[k] == '=') {\n\t\t\t\t\t\t// check that all characters are defined (or based on another\n\t\t\t\t\t\t// character)\n\t\t\t\t\t\tfor (int l = 0; l < ruleChars.length; l++) {\n\t\t\t\t\t\t\tTranslationTableCharacter *c =\n\t\t\t\t\t\t\t\t\tgetChar(ruleChars.chars[l], *table, NULL);\n\t\t\t\t\t\t\tif (!(c && (c->definitionRule || c->basechar))) {\n\t\t\t\t\t\t\t\tcompileError(file, \"Character %s is not defined\",\n\t\t\t\t\t\t\t\t\t\t_lou_showString(&ruleChars.chars[l], 1, 0));\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tCharsString x, y;\n\t\t\t\t\t\tx.length = 0;\n\t\t\t\t\t\twhile (k < len) x.chars[x.length++] = dots.chars[k++];\n\t\t\t\t\t\tif (parseDots(file, &y, &x))\n\t\t\t\t\t\t\tfor (int l = 0; l < y.length; l++)\n\t\t\t\t\t\t\t\truleDots.chars[ruleDots.length++] = y.chars[l];\n\t\t\t\t\t}\n\t\t\t\t\treturn addRule(file, opcode, &ruleChars, &ruleDots, after, before,\n\t\t\t\t\t\t\tNULL, NULL, noback, nofor, table);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 0;\n\t\tcase CTO_CompDots:\n\t\tcase CTO_Comp6: {\n\t\t\tTranslationTableOffset ruleOffset;\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (ruleChars.length != 1) {\n\t\t\t\tcompileError(file, \"first operand must be 1 character\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (nofor || noback) {\n\t\t\t\tcompileWarning(file, \"nofor and noback not allowed on comp6 rules\");\n\t\t\t}\n\t\t\tif (!getRuleDotsPattern(file, &ruleDots)) return 0;\n\t\t\tif (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset,\n\t\t\t\t\t\tNULL, noback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_ExactDots:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (ruleChars.chars[0] != '@') {\n\t\t\t\tcompileError(file, \"The operand must begin with an at sign (@)\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfor (int k = 1; k < ruleChars.length; k++)\n\t\t\t\tscratchPad.chars[k - 1] = ruleChars.chars[k];\n\t\t\tscratchPad.length = ruleChars.length - 1;\n\t\t\tif (!parseDots(file, &ruleDots, &scratchPad)) return 0;\n\t\t\treturn addRule(file, opcode, &ruleChars, &ruleDots, before, after, NULL, NULL,\n\t\t\t\t\tnoback, nofor, table);\n\t\tcase CTO_CapsNoCont: {\n\t\t\tTranslationTableOffset ruleOffset;\n\t\t\truleChars.length = 1;\n\t\t\truleChars.chars[0] = 'a';\n\t\t\tif (!addRule(file, CTO_CapsNoContRule, &ruleChars, NULL, after, before,\n\t\t\t\t\t\t&ruleOffset, NULL, noback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->capsNoCont = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_Replace:\n\t\t\tif (getRuleCharsText(file, &ruleChars)) {\n\t\t\t\tif (atEndOfLine(file))\n\t\t\t\t\truleDots.length = ruleDots.chars[0] = 0;\n\t\t\t\telse {\n\t\t\t\t\tgetRuleDotsText(file, &ruleDots);\n\t\t\t\t\tif (ruleDots.chars[0] == '#')\n\t\t\t\t\t\truleDots.length = ruleDots.chars[0] = 0;\n\t\t\t\t\telse if (ruleDots.chars[0] == '\\\\' && ruleDots.chars[1] == '#')\n\t\t\t\t\t\tmemmove(&ruleDots.chars[0], &ruleDots.chars[1],\n\t\t\t\t\t\t\t\truleDots.length-- * CHARSIZE);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int k = 0; k < ruleChars.length; k++)\n\t\t\t\tputChar(file, ruleChars.chars[k], table, NULL);\n\t\t\tfor (int k = 0; k < ruleDots.length; k++)\n\t\t\t\tputChar(file, ruleDots.chars[k], table, NULL);\n\t\t\treturn addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL,\n\t\t\t\t\tnoback, nofor, table);\n\t\tcase CTO_Correct:\n\t\t\t(*table)->corrections = 1;\n\t\t\tgoto doPass;\n\t\tcase CTO_Pass2:\n\t\t\tif ((*table)->numPasses < 2) (*table)->numPasses = 2;\n\t\t\tgoto doPass;\n\t\tcase CTO_Pass3:\n\t\t\tif ((*table)->numPasses < 3) (*table)->numPasses = 3;\n\t\t\tgoto doPass;\n\t\tcase CTO_Pass4:\n\t\t\tif ((*table)->numPasses < 4) (*table)->numPasses = 4;\n\t\tdoPass:\n\t\tcase CTO_Context:\n\t\t\tif (!(nofor || noback)) {\n\t\t\t\tcompileError(file, \"%s or %s must be specified.\",\n\t\t\t\t\t\t_lou_findOpcodeName(CTO_NoFor), _lou_findOpcodeName(CTO_NoBack));\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\treturn compilePassOpcode(file, opcode, noback, nofor, table);\n\t\tcase CTO_Contraction:\n\t\tcase CTO_NoCont:\n\t\tcase CTO_CompBrl:\n\t\tcase CTO_Literal:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\t// check that all characters in a compbrl, contraction,\n\t\t\t// nocont or literal rule are defined (or based on another\n\t\t\t// character)\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!(c && (c->definitionRule || c->basechar))) {\n\t\t\t\t\tcompileError(file, \"Character %s is not defined\",\n\t\t\t\t\t\t\t_lou_showString(&ruleChars.chars[k], 1, 0));\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn addRule(file, opcode, &ruleChars, NULL, after, before, NULL, NULL,\n\t\t\t\t\tnoback, nofor, table);\n\t\tcase CTO_MultInd: {\n\t\t\truleChars.length = 0;\n\t\t\tif (!getToken(file, &token, \"multiple braille indicators\") ||\n\t\t\t\t\t!parseDots(file, &cells, &token))\n\t\t\t\treturn 0;\n\t\t\twhile (getToken(file, &token, \"multind opcodes\")) {\n\t\t\t\topcode = getOpcode(file, &token);\n\t\t\t\tif (opcode == CTO_None) {\n\t\t\t\t\tcompileError(file, \"opcode %s not defined.\",\n\t\t\t\t\t\t\t_lou_showString(token.chars, token.length, 0));\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tif (!(opcode >= CTO_CapsLetter && opcode < CTO_MultInd)) {\n\t\t\t\t\tcompileError(file, \"Not a braille indicator opcode.\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\truleChars.chars[ruleChars.length++] = (widechar)opcode;\n\t\t\t\tif (atEndOfLine(file)) break;\n\t\t\t}\n\t\t\treturn addRule(file, CTO_MultInd, &ruleChars, &cells, after, before, NULL,\n\t\t\t\t\tNULL, noback, nofor, table);\n\t\t}\n\n\t\tcase CTO_Class:\n\t\t\tcompileWarning(file, \"class is deprecated, use attribute instead\");\n\t\tcase CTO_Attribute: {\n\t\t\tif (nofor || noback) {\n\t\t\t\tcompileWarning(\n\t\t\t\t\t\tfile, \"nofor and noback not allowed before class/attribute\");\n\t\t\t}\n\t\t\tif ((opcode == CTO_Class && (*table)->usesAttributeOrClass == 1) ||\n\t\t\t\t\t(opcode == CTO_Attribute && (*table)->usesAttributeOrClass == 2)) {\n\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\"attribute and class rules must not be both present in a table\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (opcode == CTO_Class)\n\t\t\t\t(*table)->usesAttributeOrClass = 2;\n\t\t\telse\n\t\t\t\t(*table)->usesAttributeOrClass = 1;\n\t\t\tif (!getToken(file, &token, \"attribute name\")) {\n\t\t\t\tcompileError(file, \"Expected %s\", \"attribute name\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (!(*table)->characterClasses && !allocateCharacterClasses(*table)) {\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tTranslationTableCharacterAttributes attribute = 0;\n\t\t\t{\n\t\t\t\tint attrNumber = -1;\n\t\t\t\tswitch (token.chars[0]) {\n\t\t\t\tcase '0':\n\t\t\t\tcase '1':\n\t\t\t\tcase '2':\n\t\t\t\tcase '3':\n\t\t\t\tcase '4':\n\t\t\t\tcase '5':\n\t\t\t\tcase '6':\n\t\t\t\tcase '7':\n\t\t\t\tcase '8':\n\t\t\t\tcase '9':\n\t\t\t\t\tattrNumber = token.chars[0] - '0';\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (attrNumber >= 0) {\n\t\t\t\t\tif (opcode == CTO_Class) {\n\t\t\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\t\t\"Invalid class name: may not contain digits, use \"\n\t\t\t\t\t\t\t\t\"attribute instead of class\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (token.length > 1 || attrNumber > 7) {\n\t\t\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\t\t\"Invalid attribute name: must be a digit between 0 and 7 \"\n\t\t\t\t\t\t\t\t\"or a word containing only letters\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (!(*table)->numberedAttributes[attrNumber])\n\t\t\t\t\t\t// attribute not used before yet: assign it a value\n\t\t\t\t\t\t(*table)->numberedAttributes[attrNumber] =\n\t\t\t\t\t\t\t\tgetNextNumberedAttribute(*table);\n\t\t\t\t\tattribute = (*table)->numberedAttributes[attrNumber];\n\t\t\t\t} else {\n\t\t\t\t\tconst CharacterClass *namedAttr = findCharacterClass(&token, *table);\n\t\t\t\t\tif (!namedAttr) {\n\t\t\t\t\t\t// no class with that name: create one\n\t\t\t\t\t\tnamedAttr = addCharacterClass(\n\t\t\t\t\t\t\t\tfile, &token.chars[0], token.length, *table, 1);\n\t\t\t\t\t\tif (!namedAttr) return 0;\n\t\t\t\t\t}\n\t\t\t\t\t// there is a class with that name or a new class was successfully\n\t\t\t\t\t// created\n\t\t\t\t\tattribute = namedAttr->attribute;\n\t\t\t\t\tif (attribute == CTC_UpperCase || attribute == CTC_LowerCase)\n\t\t\t\t\t\tattribute |= CTC_Letter;\n\t\t\t\t}\n\t\t\t}\n\t\t\tCharsString characters;\n\t\t\tif (!getCharacters(file, &characters)) return 0;\n\t\t\tfor (int i = 0; i < characters.length; i++) {\n\t\t\t\t// get the character from the table, or if it is not defined yet,\n\t\t\t\t// define it\n\t\t\t\tTranslationTableCharacter *character =\n\t\t\t\t\t\tputChar(file, characters.chars[i], table, NULL);\n\t\t\t\t// set the attribute\n\t\t\t\tcharacter->attributes |= attribute;\n\t\t\t\t// also set the attribute on the associated dots (if any)\n\t\t\t\tif (character->basechar)\n\t\t\t\t\tcharacter = (TranslationTableCharacter *)&(*table)\n\t\t\t\t\t\t\t\t\t\t->ruleArea[character->basechar];\n\t\t\t\tif (character->definitionRule) {\n\t\t\t\t\tTranslationTableRule *defRule =\n\t\t\t\t\t\t\t(TranslationTableRule *)&(*table)\n\t\t\t\t\t\t\t\t\t->ruleArea[character->definitionRule];\n\t\t\t\t\tif (defRule->dotslen == 1) {\n\t\t\t\t\t\tTranslationTableCharacter *dots =\n\t\t\t\t\t\t\t\tgetDots(defRule->charsdots[defRule->charslen], *table);\n\t\t\t\t\t\tif (dots) dots->attributes |= attribute;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 1;\n\t\t}\n\n\t\t\t{\n\t\t\t\tTranslationTableCharacterAttributes *attributes;\n\t\t\t\tconst CharacterClass *class;\n\t\t\tcase CTO_After:\n\t\t\t\tattributes = &after;\n\t\t\t\tgoto doBeforeAfter;\n\t\t\tcase CTO_Before:\n\t\t\t\tattributes = &before;\n\t\t\tdoBeforeAfter:\n\t\t\t\tif (!(*table)->characterClasses) {\n\t\t\t\t\tif (!allocateCharacterClasses(*table)) return 0;\n\t\t\t\t}\n\t\t\t\tif (!getToken(file, &token, \"attribute name\")) return 0;\n\t\t\t\tif (!(class = findCharacterClass(&token, *table))) {\n\t\t\t\t\tcompileError(file, \"attribute not defined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t*attributes |= class->attribute;\n\t\t\t\tgoto doOpcode;\n\t\t\t}\n\t\tcase CTO_Base:\n\t\t\tif (nofor || noback) {\n\t\t\t\tcompileWarning(file, \"nofor and noback not allowed before base\");\n\t\t\t}\n\t\t\tif (!getToken(file, &token, \"attribute name\")) {\n\t\t\t\tcompileError(\n\t\t\t\t\t\tfile, \"base opcode must be followed by a valid attribute name.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (!(*table)->characterClasses && !allocateCharacterClasses(*table)) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tconst CharacterClass *mode = findCharacterClass(&token, *table);\n\t\t\tif (!mode) {\n\t\t\t\tmode = addCharacterClass(file, token.chars, token.length, *table, 1);\n\t\t\t\tif (!mode) return 0;\n\t\t\t}\n\t\t\tif (!(mode->attribute == CTC_UpperCase || mode->attribute == CTC_Digit) &&\n\t\t\t\t\tmode->attribute >= CTC_Space && mode->attribute <= CTC_LitDigit) {\n\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\"base opcode must be followed by \\\"uppercase\\\", \\\"digit\\\", or a \"\n\t\t\t\t\t\t\"custom attribute name.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (!getRuleCharsText(file, &token)) return 0;\n\t\t\tif (token.length != 1) {\n\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\"Exactly one character followed by one base character is \"\n\t\t\t\t\t\t\"required.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tTranslationTableOffset characterOffset;\n\t\t\tTranslationTableCharacter *character =\n\t\t\t\t\tputChar(file, token.chars[0], table, &characterOffset);\n\t\t\tif (!getRuleCharsText(file, &token)) return 0;\n\t\t\tif (token.length != 1) {\n\t\t\t\tcompileError(file, \"Exactly one base character is required.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (character->definitionRule) {\n\t\t\t\tTranslationTableRule *prevRule =\n\t\t\t\t\t\t(TranslationTableRule *)&(*table)\n\t\t\t\t\t\t\t\t->ruleArea[character->definitionRule];\n\t\t\t\t_lou_logMessage(LOU_LOG_DEBUG,\n\t\t\t\t\t\t\"%s:%d: Character already defined (%s). The base rule will take \"\n\t\t\t\t\t\t\"precedence.\",\n\t\t\t\t\t\tfile->fileName, file->lineNumber,\n\t\t\t\t\t\tprintSource(file, prevRule->sourceFile, prevRule->sourceLine));\n\t\t\t\tcharacter->definitionRule = 0;\n\t\t\t}\n\t\t\tTranslationTableOffset basechar;\n\t\t\tputChar(file, token.chars[0], table, &basechar);\n\t\t\t// putChar may have moved table, so make sure character is still valid\n\t\t\tcharacter = (TranslationTableCharacter *)&(*table)->ruleArea[characterOffset];\n\t\t\tif (character->basechar) {\n\t\t\t\tif (character->basechar == basechar &&\n\t\t\t\t\t\tcharacter->mode == mode->attribute) {\n\t\t\t\t\t_lou_logMessage(LOU_LOG_DEBUG, \"%s:%d: Duplicate base rule.\",\n\t\t\t\t\t\t\tfile->fileName, file->lineNumber);\n\t\t\t\t} else {\n\t\t\t\t\t_lou_logMessage(LOU_LOG_DEBUG,\n\t\t\t\t\t\t\t\"%s:%d: A different base rule already exists for this \"\n\t\t\t\t\t\t\t\"character (%s). The new rule will take precedence.\",\n\t\t\t\t\t\t\tfile->fileName, file->lineNumber,\n\t\t\t\t\t\t\tprintSource(\n\t\t\t\t\t\t\t\t\tfile, character->sourceFile, character->sourceLine));\n\t\t\t\t}\n\t\t\t}\n\t\t\tcharacter->basechar = basechar;\n\t\t\tcharacter->mode = mode->attribute;\n\t\t\tcharacter->sourceFile = file->sourceFile;\n\t\t\tcharacter->sourceLine = file->lineNumber;\n\t\t\t/* some other processing is done at the end of the compilation, in\n\t\t\t * finalizeTable() */\n\t\t\treturn 1;\n\t\tcase CTO_EmpMatchBefore:\n\t\t\tbefore |= CTC_EmpMatch;\n\t\t\tgoto doOpcode;\n\t\tcase CTO_EmpMatchAfter:\n\t\t\tafter |= CTC_EmpMatch;\n\t\t\tgoto doOpcode;\n\n\t\tcase CTO_SwapCc:\n\t\tcase CTO_SwapCd:\n\t\tcase CTO_SwapDd:\n\t\t\treturn compileSwap(file, opcode, noback, nofor, table);\n\t\tcase CTO_Hyphen:\n\t\tcase CTO_DecPoint:\n\t\t\t//\tcase CTO_Apostrophe:\n\t\t\t//\tcase CTO_Initial:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (!getRuleDotsPattern(file, &ruleDots)) return 0;\n\t\t\tif (ruleChars.length != 1 || ruleDots.length < 1) {\n\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\"One Unicode character and at least one cell are \"\n\t\t\t\t\t\t\"required.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\treturn addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL,\n\t\t\t\t\tnoback, nofor, table);\n\t\t\t// if (opcode == CTO_DecPoint)\n\t\t\t// {\n\t\t\t//   TranslationTableCharacter *c =\n\t\t\t//   getChar(ruleChars.chars[0]);\n\t\t\t//   if(c)\n\t\t\t//     c->attributes |= CTC_NumericMode;\n\t\t\t// }\n\t\tdefault:\n\t\t\tcompileError(file, \"unimplemented opcode.\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 0;\n}", "func_hash": 114188111189139492438388270487144198902, "file_name": "compileTranslationTable.c", "file_hash": 130160890521779483138755278607355501086, "cwe": ["CWE-787"], "cve": "CVE-2022-31783", "cve_desc": "Liblouis 3.21.0 has an out-of-bounds write in compileRule in compileTranslationTable.c, as demonstrated by lou_trace.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31783"}
{"idx": 482533, "project": "liblouis", "commit_id": "2e4772befb2b1c37cb4b9d6572945115ee28630a", "project_url": "https://github.com/liblouis/liblouis", "commit_url": "https://github.com/liblouis/liblouis/commit/2e4772befb2b1c37cb4b9d6572945115ee28630a", "commit_message": "Prevent an invalid memory writes in compileRule\n\nThanks to Han Zheng for reporting it\n\nFixes #1214", "target": 0, "func": "compileRule(FileInfo *file, TranslationTableHeader **table,\n\t\tDisplayTableHeader **displayTable, const MacroList **inScopeMacros) {\n\tCharsString token;\n\tTranslationTableOpcode opcode;\n\tCharsString ruleChars;\n\tCharsString ruleDots;\n\tCharsString cells;\n\tCharsString scratchPad;\n\tCharsString emphClass;\n\tTranslationTableCharacterAttributes after = 0;\n\tTranslationTableCharacterAttributes before = 0;\n\tint noback, nofor, nocross;\n\tnoback = nofor = nocross = 0;\ndoOpcode:\n\tif (!getToken(file, &token, NULL)) return 1;\t\t\t\t  /* blank line */\n\tif (token.chars[0] == '#' || token.chars[0] == '<') return 1; /* comment */\n\tif (file->lineNumber == 1 &&\n\t\t\t(eqasc2uni((unsigned char *)\"ISO\", token.chars, 3) ||\n\t\t\t\t\teqasc2uni((unsigned char *)\"UTF-8\", token.chars, 5))) {\n\t\tif (table)\n\t\t\tcompileHyphenation(file, &token, table);\n\t\telse\n\t\t\t/* ignore the whole file */\n\t\t\twhile (_lou_getALine(file))\n\t\t\t\t;\n\t\treturn 1;\n\t}\n\topcode = getOpcode(file, &token);\n\tswitch (opcode) {\n\tcase CTO_Macro: {\n\t\tconst Macro *macro;\n#ifdef ENABLE_MACROS\n\t\tif (!inScopeMacros) {\n\t\t\tcompileError(file, \"Defining macros only allowed in table files.\");\n\t\t\treturn 0;\n\t\t}\n\t\tif (compileMacro(file, ¯o)) {\n\t\t\t*inScopeMacros = cons_macro(macro, *inScopeMacros);\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n#else\n\t\tcompileError(file, \"Macro feature is disabled.\");\n\t\treturn 0;\n#endif\n\t}\n\tcase CTO_IncludeFile: {\n\t\tCharsString includedFile;\n\t\tif (!getToken(file, &token, \"include file name\")) return 0;\n\t\tif (!parseChars(file, &includedFile, &token)) return 0;\n\t\treturn includeFile(file, &includedFile, table, displayTable);\n\t}\n\tcase CTO_NoBack:\n\t\tif (nofor) {\n\t\t\tcompileError(file, \"%s already specified.\", _lou_findOpcodeName(CTO_NoFor));\n\t\t\treturn 0;\n\t\t}\n\t\tnoback = 1;\n\t\tgoto doOpcode;\n\tcase CTO_NoFor:\n\t\tif (noback) {\n\t\t\tcompileError(file, \"%s already specified.\", _lou_findOpcodeName(CTO_NoBack));\n\t\t\treturn 0;\n\t\t}\n\t\tnofor = 1;\n\t\tgoto doOpcode;\n\tcase CTO_Space:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_Space, noback, nofor, table, displayTable);\n\tcase CTO_Digit:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_Digit, noback, nofor, table, displayTable);\n\tcase CTO_LitDigit:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_LitDigit, noback, nofor, table, displayTable);\n\tcase CTO_Punctuation:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_Punctuation, noback, nofor, table, displayTable);\n\tcase CTO_Math:\n\t\treturn compileCharDef(file, opcode, CTC_Math, noback, nofor, table, displayTable);\n\tcase CTO_Sign:\n\t\treturn compileCharDef(file, opcode, CTC_Sign, noback, nofor, table, displayTable);\n\tcase CTO_Letter:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_Letter, noback, nofor, table, displayTable);\n\tcase CTO_UpperCase:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_UpperCase, noback, nofor, table, displayTable);\n\tcase CTO_LowerCase:\n\t\treturn compileCharDef(\n\t\t\t\tfile, opcode, CTC_LowerCase, noback, nofor, table, displayTable);\n\tcase CTO_Grouping:\n\t\treturn compileGrouping(file, noback, nofor, table, displayTable);\n\tcase CTO_Display:\n\t\tif (!displayTable) return 1;  // ignore\n\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\tif (!getRuleDotsPattern(file, &ruleDots)) return 0;\n\t\tif (ruleChars.length != 1 || ruleDots.length != 1) {\n\t\t\tcompileError(file, \"Exactly one character and one cell are required.\");\n\t\t\treturn 0;\n\t\t}\n\t\treturn putCharDotsMapping(\n\t\t\t\tfile, ruleChars.chars[0], ruleDots.chars[0], displayTable);\n\tcase CTO_UpLow:\n\tcase CTO_None: {\n\t\t// check if token is a macro name\n\t\tif (inScopeMacros) {\n\t\t\tconst MacroList *macros = *inScopeMacros;\n\t\t\twhile (macros) {\n\t\t\t\tconst Macro *m = macros->head;\n\t\t\t\tif (token.length == strlen(m->name) &&\n\t\t\t\t\t\teqasc2uni((unsigned char *)m->name, token.chars, token.length)) {\n\t\t\t\t\tif (!inScopeMacros) {\n\t\t\t\t\t\tcompileError(file, \"Calling macros only allowed in table files.\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\tFileInfo tmpFile;\n\t\t\t\t\tmemset(&tmpFile, 0, sizeof(tmpFile));\n\t\t\t\t\ttmpFile.fileName = file->fileName;\n\t\t\t\t\ttmpFile.sourceFile = file->sourceFile;\n\t\t\t\t\ttmpFile.lineNumber = file->lineNumber;\n\t\t\t\t\ttmpFile.encoding = noEncoding;\n\t\t\t\t\ttmpFile.status = 0;\n\t\t\t\t\ttmpFile.linepos = 0;\n\t\t\t\t\ttmpFile.linelen = 0;\n\t\t\t\t\tint argument_count = 0;\n\t\t\t\t\tCharsString *arguments =\n\t\t\t\t\t\t\tmalloc(m->argument_count * sizeof(CharsString));\n\t\t\t\t\twhile (argument_count < m->argument_count) {\n\t\t\t\t\t\tif (getToken(file, &token, \"macro argument\"))\n\t\t\t\t\t\t\targuments[argument_count++] = token;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (argument_count < m->argument_count) {\n\t\t\t\t\t\tcompileError(file, \"Expected %d arguments\", m->argument_count);\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\tint i = 0;\n\t\t\t\t\tint subst = 0;\n\t\t\t\t\tint next = subst < m->substitution_count ? m->substitutions[2 * subst]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t : m->definition_length;\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\twhile (i < next) {\n\t\t\t\t\t\t\twidechar c = m->definition[i++];\n\t\t\t\t\t\t\tif (c == '\\n') {\n\t\t\t\t\t\t\t\tif (!compileRule(&tmpFile, table, displayTable,\n\t\t\t\t\t\t\t\t\t\t\tinScopeMacros)) {\n\t\t\t\t\t\t\t\t\t_lou_logMessage(LOU_LOG_ERROR,\n\t\t\t\t\t\t\t\t\t\t\t\"result of macro expansion was: %s\",\n\t\t\t\t\t\t\t\t\t\t\t_lou_showString(\n\t\t\t\t\t\t\t\t\t\t\t\t\ttmpFile.line, tmpFile.linelen, 0));\n\t\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttmpFile.linepos = 0;\n\t\t\t\t\t\t\t\ttmpFile.linelen = 0;\n\t\t\t\t\t\t\t} else if (tmpFile.linelen >= MAXSTRING) {\n\t\t\t\t\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\t\t\t\t\"Line exceeds %d characters (post macro \"\n\t\t\t\t\t\t\t\t\t\t\"expansion)\",\n\t\t\t\t\t\t\t\t\t\tMAXSTRING);\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t} else\n\t\t\t\t\t\t\t\ttmpFile.line[tmpFile.linelen++] = c;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (subst < m->substitution_count) {\n\t\t\t\t\t\t\tCharsString arg =\n\t\t\t\t\t\t\t\t\targuments[m->substitutions[2 * subst + 1] - 1];\n\t\t\t\t\t\t\tfor (int j = 0; j < arg.length; j++)\n\t\t\t\t\t\t\t\ttmpFile.line[tmpFile.linelen++] = arg.chars[j];\n\t\t\t\t\t\t\tsubst++;\n\t\t\t\t\t\t\tnext = subst < m->substitution_count\n\t\t\t\t\t\t\t\t\t? m->substitutions[2 * subst]\n\t\t\t\t\t\t\t\t\t: m->definition_length;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (!compileRule(\n\t\t\t\t\t\t\t\t\t\t&tmpFile, table, displayTable, inScopeMacros)) {\n\t\t\t\t\t\t\t\t_lou_logMessage(LOU_LOG_ERROR,\n\t\t\t\t\t\t\t\t\t\t\"result of macro expansion was: %s\",\n\t\t\t\t\t\t\t\t\t\t_lou_showString(\n\t\t\t\t\t\t\t\t\t\t\t\ttmpFile.line, tmpFile.linelen, 0));\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tmacros = macros->tail;\n\t\t\t}\n\t\t}\n\t\tif (opcode == CTO_UpLow) {\n\t\t\tcompileError(file, \"The uplow opcode is deprecated.\");\n\t\t\treturn 0;\n\t\t}\n\t\tcompileError(file, \"opcode %s not defined.\",\n\t\t\t\t_lou_showString(token.chars, token.length, 0));\n\t\treturn 0;\n\t}\n\n\t/* now only opcodes follow that don't modify the display table */\n\tdefault:\n\t\tif (!table) return 1;\n\t\tswitch (opcode) {\n\t\tcase CTO_Locale:\n\t\t\tcompileWarning(file,\n\t\t\t\t\t\"The locale opcode is not implemented. Use the locale meta data \"\n\t\t\t\t\t\"instead.\");\n\t\t\treturn 1;\n\t\tcase CTO_Undefined: {\n\t\t\t// not passing pointer because compileBrailleIndicator may reallocate table\n\t\t\tTranslationTableOffset ruleOffset = (*table)->undefined;\n\t\t\tif (!compileBrailleIndicator(file, \"undefined character opcode\",\n\t\t\t\t\t\tCTO_Undefined, &ruleOffset, noback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->undefined = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_Match: {\n\t\t\tint ok = 0;\n\t\t\twidechar *patterns = NULL;\n\t\t\tTranslationTableRule *rule;\n\t\t\tTranslationTableOffset ruleOffset;\n\t\t\tCharsString ptn_before, ptn_after;\n\t\t\tTranslationTableOffset patternsOffset;\n\t\t\tint len, mrk;\n\t\t\tsize_t patternsByteSize = sizeof(*patterns) * 27720;\n\t\t\tpatterns = (widechar *)malloc(patternsByteSize);\n\t\t\tif (!patterns) _lou_outOfMemory();\n\t\t\tmemset(patterns, 0xffff, patternsByteSize);\n\t\t\tnoback = 1;\n\t\t\tgetCharacters(file, &ptn_before);\n\t\t\tgetRuleCharsText(file, &ruleChars);\n\t\t\tgetCharacters(file, &ptn_after);\n\t\t\tgetRuleDotsPattern(file, &ruleDots);\n\t\t\tif (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset,\n\t\t\t\t\t\t&rule, noback, nofor, table))\n\t\t\t\tgoto CTO_Match_cleanup;\n\t\t\tif (ptn_before.chars[0] == '-' && ptn_before.length == 1)\n\t\t\t\tlen = _lou_pattern_compile(\n\t\t\t\t\t\t&ptn_before.chars[0], 0, &patterns[1], 13841, *table, file);\n\t\t\telse\n\t\t\t\tlen = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length,\n\t\t\t\t\t\t&patterns[1], 13841, *table, file);\n\t\t\tif (!len) goto CTO_Match_cleanup;\n\t\t\tmrk = patterns[0] = len + 1;\n\t\t\t_lou_pattern_reverse(&patterns[1]);\n\t\t\tif (ptn_after.chars[0] == '-' && ptn_after.length == 1)\n\t\t\t\tlen = _lou_pattern_compile(\n\t\t\t\t\t\t&ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file);\n\t\t\telse\n\t\t\t\tlen = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length,\n\t\t\t\t\t\t&patterns[mrk], 13841, *table, file);\n\t\t\tif (!len) goto CTO_Match_cleanup;\n\t\t\tlen += mrk;\n\t\t\tif (!allocateSpaceInTranslationTable(\n\t\t\t\t\t\tfile, &patternsOffset, len * sizeof(widechar), table))\n\t\t\t\tgoto CTO_Match_cleanup;\n\t\t\t// allocateSpaceInTranslationTable may have moved table, so make sure rule is\n\t\t\t// still valid\n\t\t\trule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];\n\t\t\tmemcpy(&(*table)->ruleArea[patternsOffset], patterns, len * sizeof(widechar));\n\t\t\trule->patterns = patternsOffset;\n\t\t\tok = 1;\n\t\tCTO_Match_cleanup:\n\t\t\tfree(patterns);\n\t\t\treturn ok;\n\t\t}\n\n\t\tcase CTO_BackMatch: {\n\t\t\tint ok = 0;\n\t\t\twidechar *patterns = NULL;\n\t\t\tTranslationTableRule *rule;\n\t\t\tTranslationTableOffset ruleOffset;\n\t\t\tCharsString ptn_before, ptn_after;\n\t\t\tTranslationTableOffset patternOffset;\n\t\t\tint len, mrk;\n\t\t\tsize_t patternsByteSize = sizeof(*patterns) * 27720;\n\t\t\tpatterns = (widechar *)malloc(patternsByteSize);\n\t\t\tif (!patterns) _lou_outOfMemory();\n\t\t\tmemset(patterns, 0xffff, patternsByteSize);\n\t\t\tnofor = 1;\n\t\t\tgetCharacters(file, &ptn_before);\n\t\t\tgetRuleCharsText(file, &ruleChars);\n\t\t\tgetCharacters(file, &ptn_after);\n\t\t\tgetRuleDotsPattern(file, &ruleDots);\n\t\t\tif (!addRule(file, opcode, &ruleChars, &ruleDots, 0, 0, &ruleOffset, &rule,\n\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\tgoto CTO_BackMatch_cleanup;\n\t\t\tif (ptn_before.chars[0] == '-' && ptn_before.length == 1)\n\t\t\t\tlen = _lou_pattern_compile(\n\t\t\t\t\t\t&ptn_before.chars[0], 0, &patterns[1], 13841, *table, file);\n\t\t\telse\n\t\t\t\tlen = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length,\n\t\t\t\t\t\t&patterns[1], 13841, *table, file);\n\t\t\tif (!len) goto CTO_BackMatch_cleanup;\n\t\t\tmrk = patterns[0] = len + 1;\n\t\t\t_lou_pattern_reverse(&patterns[1]);\n\t\t\tif (ptn_after.chars[0] == '-' && ptn_after.length == 1)\n\t\t\t\tlen = _lou_pattern_compile(\n\t\t\t\t\t\t&ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file);\n\t\t\telse\n\t\t\t\tlen = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length,\n\t\t\t\t\t\t&patterns[mrk], 13841, *table, file);\n\t\t\tif (!len) goto CTO_BackMatch_cleanup;\n\t\t\tlen += mrk;\n\t\t\tif (!allocateSpaceInTranslationTable(\n\t\t\t\t\t\tfile, &patternOffset, len * sizeof(widechar), table))\n\t\t\t\tgoto CTO_BackMatch_cleanup;\n\t\t\t// allocateSpaceInTranslationTable may have moved table, so make sure rule is\n\t\t\t// still valid\n\t\t\trule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];\n\t\t\tmemcpy(&(*table)->ruleArea[patternOffset], patterns, len * sizeof(widechar));\n\t\t\trule->patterns = patternOffset;\n\t\t\tok = 1;\n\t\tCTO_BackMatch_cleanup:\n\t\t\tfree(patterns);\n\t\t\treturn ok;\n\t\t}\n\n\t\tcase CTO_CapsLetter:\n\t\tcase CTO_BegCapsWord:\n\t\tcase CTO_EndCapsWord:\n\t\tcase CTO_BegCaps:\n\t\tcase CTO_EndCaps:\n\t\tcase CTO_BegCapsPhrase:\n\t\tcase CTO_EndCapsPhrase:\n\t\tcase CTO_LenCapsPhrase:\n\t\t/* these 8 general purpose opcodes are compiled further down to more specific\n\t\t * internal opcodes:\n\t\t * - modeletter\n\t\t * - begmodeword\n\t\t * - endmodeword\n\t\t * - begmode\n\t\t * - endmode\n\t\t * - begmodephrase\n\t\t * - endmodephrase\n\t\t * - lenmodephrase\n\t\t */\n\t\tcase CTO_ModeLetter:\n\t\tcase CTO_BegModeWord:\n\t\tcase CTO_EndModeWord:\n\t\tcase CTO_BegMode:\n\t\tcase CTO_EndMode:\n\t\tcase CTO_BegModePhrase:\n\t\tcase CTO_EndModePhrase:\n\t\tcase CTO_LenModePhrase: {\n\t\t\tTranslationTableCharacterAttributes mode;\n\t\t\tint i;\n\t\t\tswitch (opcode) {\n\t\t\tcase CTO_CapsLetter:\n\t\t\tcase CTO_BegCapsWord:\n\t\t\tcase CTO_EndCapsWord:\n\t\t\tcase CTO_BegCaps:\n\t\t\tcase CTO_EndCaps:\n\t\t\tcase CTO_BegCapsPhrase:\n\t\t\tcase CTO_EndCapsPhrase:\n\t\t\tcase CTO_LenCapsPhrase:\n\t\t\t\tmode = CTC_UpperCase;\n\t\t\t\ti = 0;\n\t\t\t\topcode += (CTO_ModeLetter - CTO_CapsLetter);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (!getToken(file, &token, \"attribute name\")) return 0;\n\t\t\t\tif (!(*table)->characterClasses && !allocateCharacterClasses(*table)) {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tconst CharacterClass *characterClass = findCharacterClass(&token, *table);\n\t\t\t\tif (!characterClass) {\n\t\t\t\t\tcharacterClass =\n\t\t\t\t\t\t\taddCharacterClass(file, token.chars, token.length, *table, 1);\n\t\t\t\t\tif (!characterClass) return 0;\n\t\t\t\t}\n\t\t\t\tmode = characterClass->attribute;\n\t\t\t\tif (!(mode == CTC_UpperCase || mode == CTC_Digit) && mode >= CTC_Space &&\n\t\t\t\t\t\tmode <= CTC_LitDigit) {\n\t\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\t\"mode must be \\\"uppercase\\\", \\\"digit\\\", or a custom \"\n\t\t\t\t\t\t\t\"attribute name.\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t/* check if this mode is already defined and if the number of modes does\n\t\t\t\t * not exceed the maximal number */\n\t\t\t\tif (mode == CTC_UpperCase)\n\t\t\t\t\ti = 0;\n\t\t\t\telse {\n\t\t\t\t\tfor (i = 1; i < MAX_MODES && (*table)->modes[i].value; i++) {\n\t\t\t\t\t\tif ((*table)->modes[i].mode == mode) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (i == MAX_MODES) {\n\t\t\t\t\t\tcompileError(file, \"Max number of modes (%i) reached\", MAX_MODES);\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!(*table)->modes[i].value)\n\t\t\t\t(*table)->modes[i] = (EmphasisClass){ plain_text, mode,\n\t\t\t\t\t0x1 << (MAX_EMPH_CLASSES + i), MAX_EMPH_CLASSES + i };\n\t\t\tswitch (opcode) {\n\t\t\tcase CTO_BegModePhrase: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"first word capital sign\",\n\t\t\t\t\t\t\tCTO_BegCapsPhraseRule + (8 * i), &ruleOffset, noback, nofor,\n\t\t\t\t\t\t\ttable))\n\t\t\t\t\treturn 0;\n\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset] = ruleOffset;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcase CTO_EndModePhrase: {\n\t\t\t\tTranslationTableOffset ruleOffset;\n\t\t\t\tswitch (compileBeforeAfter(file)) {\n\t\t\t\tcase 1:\t // before\n\t\t\t\t\tif ((*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset]) {\n\t\t\t\t\t\tcompileError(\n\t\t\t\t\t\t\t\tfile, \"Capital sign after last word already defined.\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t\t// table\n\t\t\t\t\truleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i]\n\t\t\t\t\t\t\t\t\t\t\t\t\t[endPhraseBeforeOffset];\n\t\t\t\t\tif (!compileBrailleIndicator(file, \"capital sign before last word\",\n\t\t\t\t\t\t\t\tCTO_EndCapsPhraseBeforeRule + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseBeforeOffset] =\n\t\t\t\t\t\t\truleOffset;\n\t\t\t\t\treturn 1;\n\t\t\t\tcase 2:\t // after\n\t\t\t\t\tif ((*table)->emphRules[MAX_EMPH_CLASSES + i]\n\t\t\t\t\t\t\t\t\t\t   [endPhraseBeforeOffset]) {\n\t\t\t\t\t\tcompileError(\n\t\t\t\t\t\t\t\tfile, \"Capital sign before last word already defined.\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t\t// table\n\t\t\t\t\truleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i]\n\t\t\t\t\t\t\t\t\t\t\t\t\t[endPhraseAfterOffset];\n\t\t\t\t\tif (!compileBrailleIndicator(file, \"capital sign after last word\",\n\t\t\t\t\t\t\t\tCTO_EndCapsPhraseAfterRule + (8 * i), &ruleOffset, noback,\n\t\t\t\t\t\t\t\tnofor, table))\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset] =\n\t\t\t\t\t\t\truleOffset;\n\t\t\t\t\treturn 1;\n\t\t\t\tdefault:  // error\n\t\t\t\t\tcompileError(file, \"Invalid lastword indicator location.\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase CTO_BegMode: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"first letter capital sign\",\n\t\t\t\t\t\t\tCTO_BegCapsRule + (8 * i), &ruleOffset, noback, nofor, table))\n\t\t\t\t\treturn 0;\n\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset] = ruleOffset;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcase CTO_EndMode: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"last letter capital sign\",\n\t\t\t\t\t\t\tCTO_EndCapsRule + (8 * i), &ruleOffset, noback, nofor, table))\n\t\t\t\t\treturn 0;\n\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset] = ruleOffset;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcase CTO_ModeLetter: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"single letter capital sign\",\n\t\t\t\t\t\t\tCTO_CapsLetterRule + (8 * i), &ruleOffset, noback, nofor,\n\t\t\t\t\t\t\ttable))\n\t\t\t\t\treturn 0;\n\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset] = ruleOffset;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcase CTO_BegModeWord: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"capital word\",\n\t\t\t\t\t\t\tCTO_BegCapsWordRule + (8 * i), &ruleOffset, noback, nofor,\n\t\t\t\t\t\t\ttable))\n\t\t\t\t\treturn 0;\n\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset] = ruleOffset;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcase CTO_EndModeWord: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"capital word stop\",\n\t\t\t\t\t\t\tCTO_EndCapsWordRule + (8 * i), &ruleOffset, noback, nofor,\n\t\t\t\t\t\t\ttable))\n\t\t\t\t\treturn 0;\n\t\t\t\t(*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset] = ruleOffset;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tcase CTO_LenModePhrase:\n\t\t\t\treturn (*table)->emphRules[MAX_EMPH_CLASSES + i][lenPhraseOffset] =\n\t\t\t\t\t\t\t   compileNumber(file);\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t/* these 8 general purpose emphasis opcodes are compiled further down to more\n\t\t * specific internal opcodes:\n\t\t * - emphletter\n\t\t * - begemphword\n\t\t * - endemphword\n\t\t * - begemph\n\t\t * - endemph\n\t\t * - begemphphrase\n\t\t * - endemphphrase\n\t\t * - lenemphphrase\n\t\t */\n\t\tcase CTO_EmphClass:\n\t\t\tif (!getToken(file, &emphClass, \"emphasis class\")) {\n\t\t\t\tcompileError(file, \"emphclass must be followed by a valid class name.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tint k, i;\n\t\t\tchar *s = malloc(sizeof(char) * (emphClass.length + 1));\n\t\t\tfor (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k];\n\t\t\ts[k++] = '\\0';\n\t\t\tfor (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++)\n\t\t\t\tif (strcmp(s, (*table)->emphClassNames[i]) == 0) {\n\t\t\t\t\t_lou_logMessage(LOU_LOG_WARN, \"Duplicate emphasis class: %s\", s);\n\t\t\t\t\twarningCount++;\n\t\t\t\t\tfree(s);\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\tif (i == MAX_EMPH_CLASSES) {\n\t\t\t\t_lou_logMessage(LOU_LOG_ERROR,\n\t\t\t\t\t\t\"Max number of emphasis classes (%i) reached\", MAX_EMPH_CLASSES);\n\t\t\t\terrorCount++;\n\t\t\t\tfree(s);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tswitch (i) {\n\t\t\t/* For backwards compatibility (i.e. because programs will assume\n\t\t\t * the first 3 typeform bits are `italic', `underline' and `bold')\n\t\t\t * we require that the first 3 emphclass definitions are (in that\n\t\t\t * order):\n\t\t\t *\n\t\t\t *   emphclass italic\n\t\t\t *   emphclass underline\n\t\t\t *   emphclass bold\n\t\t\t *\n\t\t\t * While it would be possible to use the emphclass opcode only for\n\t\t\t * defining _additional_ classes (not allowing for them to be called\n\t\t\t * italic, underline or bold), thereby reducing the amount of\n\t\t\t * boilerplate, we deliberately choose not to do that in order to\n\t\t\t * not give italic, underline and bold any special status. The\n\t\t\t * hope is that eventually all programs will use liblouis for\n\t\t\t * emphasis the recommended way (i.e. by looking up the supported\n\t\t\t * typeforms in the documentation or API) so that we can drop this\n\t\t\t * restriction.\n\t\t\t */\n\t\t\tcase 0:\n\t\t\t\tif (strcmp(s, \"italic\") != 0) {\n\t\t\t\t\t_lou_logMessage(LOU_LOG_ERROR,\n\t\t\t\t\t\t\t\"First emphasis class must be \\\"italic\\\" but got \"\n\t\t\t\t\t\t\t\"%s\",\n\t\t\t\t\t\t\ts);\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tfree(s);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tif (strcmp(s, \"underline\") != 0) {\n\t\t\t\t\t_lou_logMessage(LOU_LOG_ERROR,\n\t\t\t\t\t\t\t\"Second emphasis class must be \\\"underline\\\" but \"\n\t\t\t\t\t\t\t\"got \"\n\t\t\t\t\t\t\t\"%s\",\n\t\t\t\t\t\t\ts);\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tfree(s);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tif (strcmp(s, \"bold\") != 0) {\n\t\t\t\t\t_lou_logMessage(LOU_LOG_ERROR,\n\t\t\t\t\t\t\t\"Third emphasis class must be \\\"bold\\\" but got \"\n\t\t\t\t\t\t\t\"%s\",\n\t\t\t\t\t\t\ts);\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tfree(s);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t(*table)->emphClassNames[i] = s;\n\t\t\t(*table)->emphClasses[i] = (EmphasisClass){ emph_1\n\t\t\t\t\t\t<< i, /* relies on the order of typeforms emph_1..emph_10 */\n\t\t\t\t0, 0x1 << i, i };\n\t\t\treturn 1;\n\t\tcase CTO_EmphLetter:\n\t\tcase CTO_BegEmphWord:\n\t\tcase CTO_EndEmphWord:\n\t\tcase CTO_BegEmph:\n\t\tcase CTO_EndEmph:\n\t\tcase CTO_BegEmphPhrase:\n\t\tcase CTO_EndEmphPhrase:\n\t\tcase CTO_LenEmphPhrase:\n\t\tcase CTO_EmphModeChars:\n\t\tcase CTO_NoEmphChars: {\n\t\t\tif (!getToken(file, &token, \"emphasis class\")) return 0;\n\t\t\tif (!parseChars(file, &emphClass, &token)) return 0;\n\t\t\tchar *s = malloc(sizeof(char) * (emphClass.length + 1));\n\t\t\tint k, i;\n\t\t\tfor (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k];\n\t\t\ts[k++] = '\\0';\n\t\t\tfor (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++)\n\t\t\t\tif (strcmp(s, (*table)->emphClassNames[i]) == 0) break;\n\t\t\tif (i == MAX_EMPH_CLASSES || !(*table)->emphClassNames[i]) {\n\t\t\t\t_lou_logMessage(LOU_LOG_ERROR, \"Emphasis class %s not declared\", s);\n\t\t\t\terrorCount++;\n\t\t\t\tfree(s);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tint ok = 0;\n\t\t\tswitch (opcode) {\n\t\t\tcase CTO_EmphLetter: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset = (*table)->emphRules[i][letterOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"single letter\",\n\t\t\t\t\t\t\tCTO_Emph1LetterRule + letterOffset + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\tbreak;\n\t\t\t\t(*table)->emphRules[i][letterOffset] = ruleOffset;\n\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_BegEmphWord: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset = (*table)->emphRules[i][begWordOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"word\",\n\t\t\t\t\t\t\tCTO_Emph1LetterRule + begWordOffset + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\tbreak;\n\t\t\t\t(*table)->emphRules[i][begWordOffset] = ruleOffset;\n\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_EndEmphWord: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset = (*table)->emphRules[i][endWordOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"word stop\",\n\t\t\t\t\t\t\tCTO_Emph1LetterRule + endWordOffset + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\tbreak;\n\t\t\t\t(*table)->emphRules[i][endWordOffset] = ruleOffset;\n\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_BegEmph: {\n\t\t\t\t/* fail if both begemph and any of begemphphrase or begemphword are\n\t\t\t\t * defined */\n\t\t\t\tif ((*table)->emphRules[i][begWordOffset] ||\n\t\t\t\t\t\t(*table)->emphRules[i][begPhraseOffset]) {\n\t\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\t\"Cannot define emphasis for both no context and word or \"\n\t\t\t\t\t\t\t\"phrase context, i.e. cannot have both begemph and \"\n\t\t\t\t\t\t\t\"begemphword or begemphphrase.\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset = (*table)->emphRules[i][begOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"first letter\",\n\t\t\t\t\t\t\tCTO_Emph1LetterRule + begOffset + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\tbreak;\n\t\t\t\t(*table)->emphRules[i][begOffset] = ruleOffset;\n\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_EndEmph: {\n\t\t\t\tif ((*table)->emphRules[i][endWordOffset] ||\n\t\t\t\t\t\t(*table)->emphRules[i][endPhraseBeforeOffset] ||\n\t\t\t\t\t\t(*table)->emphRules[i][endPhraseAfterOffset]) {\n\t\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\t\"Cannot define emphasis for both no context and word or \"\n\t\t\t\t\t\t\t\"phrase context, i.e. cannot have both endemph and \"\n\t\t\t\t\t\t\t\"endemphword or endemphphrase.\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset = (*table)->emphRules[i][endOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"last letter\",\n\t\t\t\t\t\t\tCTO_Emph1LetterRule + endOffset + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\tbreak;\n\t\t\t\t(*table)->emphRules[i][endOffset] = ruleOffset;\n\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_BegEmphPhrase: {\n\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t// table\n\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t(*table)->emphRules[i][begPhraseOffset];\n\t\t\t\tif (!compileBrailleIndicator(file, \"first word\",\n\t\t\t\t\t\t\tCTO_Emph1LetterRule + begPhraseOffset + (8 * i), &ruleOffset,\n\t\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\t\tbreak;\n\t\t\t\t(*table)->emphRules[i][begPhraseOffset] = ruleOffset;\n\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_EndEmphPhrase:\n\t\t\t\tswitch (compileBeforeAfter(file)) {\n\t\t\t\tcase 1: {  // before\n\t\t\t\t\tif ((*table)->emphRules[i][endPhraseAfterOffset]) {\n\t\t\t\t\t\tcompileError(file, \"last word after already defined.\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t\t// table\n\t\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t\t(*table)->emphRules[i][endPhraseBeforeOffset];\n\t\t\t\t\tif (!compileBrailleIndicator(file, \"last word before\",\n\t\t\t\t\t\t\t\tCTO_Emph1LetterRule + endPhraseBeforeOffset + (8 * i),\n\t\t\t\t\t\t\t\t&ruleOffset, noback, nofor, table))\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t(*table)->emphRules[i][endPhraseBeforeOffset] = ruleOffset;\n\t\t\t\t\tok = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 2: {  // after\n\t\t\t\t\tif ((*table)->emphRules[i][endPhraseBeforeOffset]) {\n\t\t\t\t\t\tcompileError(file, \"last word before already defined.\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// not passing pointer because compileBrailleIndicator may reallocate\n\t\t\t\t\t// table\n\t\t\t\t\tTranslationTableOffset ruleOffset =\n\t\t\t\t\t\t\t(*table)->emphRules[i][endPhraseAfterOffset];\n\t\t\t\t\tif (!compileBrailleIndicator(file, \"last word after\",\n\t\t\t\t\t\t\t\tCTO_Emph1LetterRule + endPhraseAfterOffset + (8 * i),\n\t\t\t\t\t\t\t\t&ruleOffset, noback, nofor, table))\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t(*table)->emphRules[i][endPhraseAfterOffset] = ruleOffset;\n\t\t\t\t\tok = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:  // error\n\t\t\t\t\tcompileError(file, \"Invalid lastword indicator location.\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CTO_LenEmphPhrase:\n\t\t\t\tif (((*table)->emphRules[i][lenPhraseOffset] = compileNumber(file)))\n\t\t\t\t\tok = 1;\n\t\t\t\tbreak;\n\t\t\tcase CTO_EmphModeChars: {\n\t\t\t\tif (!getRuleCharsText(file, &ruleChars)) break;\n\t\t\t\twidechar *emphmodechars = (*table)->emphModeChars[i];\n\t\t\t\tint len;\n\t\t\t\tfor (len = 0; len < EMPHMODECHARSSIZE && emphmodechars[len]; len++)\n\t\t\t\t\t;\n\t\t\t\tif (len + ruleChars.length > EMPHMODECHARSSIZE) {\n\t\t\t\t\tcompileError(file, \"More than %d characters\", EMPHMODECHARSSIZE);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tok = 1;\n\t\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\t\tif (!getChar(ruleChars.chars[k], *table, NULL)) {\n\t\t\t\t\t\tcompileError(file, \"Emphasis mode character undefined\");\n\t\t\t\t\t\tok = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\temphmodechars[len++] = ruleChars.chars[k];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CTO_NoEmphChars: {\n\t\t\t\tif (!getRuleCharsText(file, &ruleChars)) break;\n\t\t\t\twidechar *noemphchars = (*table)->noEmphChars[i];\n\t\t\t\tint len;\n\t\t\t\tfor (len = 0; len < NOEMPHCHARSSIZE && noemphchars[len]; len++)\n\t\t\t\t\t;\n\t\t\t\tif (len + ruleChars.length > NOEMPHCHARSSIZE) {\n\t\t\t\t\tcompileError(file, \"More than %d characters\", NOEMPHCHARSSIZE);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tok = 1;\n\t\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\t\tif (!getChar(ruleChars.chars[k], *table, NULL)) {\n\t\t\t\t\t\tcompileError(file, \"Character undefined\");\n\t\t\t\t\t\tok = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tnoemphchars[len++] = ruleChars.chars[k];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfree(s);\n\t\t\treturn ok;\n\t\t}\n\t\tcase CTO_LetterSign: {\n\t\t\t// not passing pointer because compileBrailleIndicator may reallocate table\n\t\t\tTranslationTableOffset ruleOffset = (*table)->letterSign;\n\t\t\tif (!compileBrailleIndicator(file, \"letter sign\", CTO_LetterRule, &ruleOffset,\n\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->letterSign = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_NoLetsignBefore:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (((*table)->noLetsignBeforeCount + ruleChars.length) > LETSIGNBEFORESIZE) {\n\t\t\t\tcompileError(file, \"More than %d characters\", LETSIGNBEFORESIZE);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfor (int k = 0; k < ruleChars.length; k++)\n\t\t\t\t(*table)->noLetsignBefore[(*table)->noLetsignBeforeCount++] =\n\t\t\t\t\t\truleChars.chars[k];\n\t\t\treturn 1;\n\t\tcase CTO_NoLetsign:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (((*table)->noLetsignCount + ruleChars.length) > LETSIGNSIZE) {\n\t\t\t\tcompileError(file, \"More than %d characters\", LETSIGNSIZE);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfor (int k = 0; k < ruleChars.length; k++)\n\t\t\t\t(*table)->noLetsign[(*table)->noLetsignCount++] = ruleChars.chars[k];\n\t\t\treturn 1;\n\t\tcase CTO_NoLetsignAfter:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (((*table)->noLetsignAfterCount + ruleChars.length) > LETSIGNAFTERSIZE) {\n\t\t\t\tcompileError(file, \"More than %d characters\", LETSIGNAFTERSIZE);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfor (int k = 0; k < ruleChars.length; k++)\n\t\t\t\t(*table)->noLetsignAfter[(*table)->noLetsignAfterCount++] =\n\t\t\t\t\t\truleChars.chars[k];\n\t\t\treturn 1;\n\t\tcase CTO_NumberSign: {\n\t\t\t// not passing pointer because compileBrailleIndicator may reallocate table\n\t\t\tTranslationTableOffset ruleOffset = (*table)->numberSign;\n\t\t\tif (!compileBrailleIndicator(file, \"number sign\", CTO_NumberRule, &ruleOffset,\n\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->numberSign = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\n\t\tcase CTO_NumericModeChars:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Numeric mode character undefined: %s\",\n\t\t\t\t\t\t\t_lou_showString(&ruleChars.chars[k], 1, 0));\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_NumericMode;\n\t\t\t\t(*table)->usesNumericMode = 1;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_MidEndNumericModeChars:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Midendnumeric mode character undefined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_MidEndNumericMode;\n\t\t\t\t(*table)->usesNumericMode = 1;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_NumericNoContractChars:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Numeric no contraction character undefined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_NumericNoContract;\n\t\t\t\t(*table)->usesNumericMode = 1;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_NoContractSign: {\n\t\t\t// not passing pointer because compileBrailleIndicator may reallocate table\n\t\t\tTranslationTableOffset ruleOffset = (*table)->noContractSign;\n\t\t\tif (!compileBrailleIndicator(file, \"no contractions sign\", CTO_NoContractRule,\n\t\t\t\t\t\t&ruleOffset, noback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->noContractSign = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_SeqDelimiter:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Sequence delimiter character undefined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_SeqDelimiter;\n\t\t\t\t(*table)->usesSequences = 1;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_SeqBeforeChars:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Sequence before character undefined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_SeqBefore;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_SeqAfterChars:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Sequence after character undefined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_SeqAfter;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_SeqAfterPattern:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (((*table)->seqPatternsCount + ruleChars.length + 1) > SEQPATTERNSIZE) {\n\t\t\t\tcompileError(file, \"More than %d characters\", SEQPATTERNSIZE);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfor (int k = 0; k < ruleChars.length; k++)\n\t\t\t\t(*table)->seqPatterns[(*table)->seqPatternsCount++] = ruleChars.chars[k];\n\t\t\t(*table)->seqPatterns[(*table)->seqPatternsCount++] = 0;\n\t\t\treturn 1;\n\n\t\tcase CTO_SeqAfterExpression:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif ((ruleChars.length + 1) > SEQPATTERNSIZE) {\n\t\t\t\tcompileError(file, \"More than %d characters\", SEQPATTERNSIZE);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfor (int k = 0; k < ruleChars.length; k++)\n\t\t\t\t(*table)->seqAfterExpression[k] = ruleChars.chars[k];\n\t\t\t(*table)->seqAfterExpression[ruleChars.length] = 0;\n\t\t\t(*table)->seqAfterExpressionLength = ruleChars.length;\n\t\t\treturn 1;\n\n\t\tcase CTO_CapsModeChars:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!c) {\n\t\t\t\t\tcompileError(file, \"Capital mode character undefined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tc->attributes |= CTC_CapsMode;\n\t\t\t\t(*table)->hasCapsModeChars = 1;\n\t\t\t}\n\t\t\treturn 1;\n\n\t\tcase CTO_BegComp: {\n\t\t\t// not passing pointer because compileBrailleIndicator may reallocate table\n\t\t\tTranslationTableOffset ruleOffset = (*table)->begComp;\n\t\t\tif (!compileBrailleIndicator(file, \"begin computer braille\", CTO_BegCompRule,\n\t\t\t\t\t\t&ruleOffset, noback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->begComp = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_EndComp: {\n\t\t\t// not passing pointer because compileBrailleIndicator may reallocate table\n\t\t\tTranslationTableOffset ruleOffset = (*table)->endComp;\n\t\t\tif (!compileBrailleIndicator(file, \"end computer braslle\", CTO_EndCompRule,\n\t\t\t\t\t\t&ruleOffset, noback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->endComp = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_NoCross:\n\t\t\tif (nocross) {\n\t\t\t\tcompileError(\n\t\t\t\t\t\tfile, \"%s already specified.\", _lou_findOpcodeName(CTO_NoCross));\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tnocross = 1;\n\t\t\tgoto doOpcode;\n\t\tcase CTO_Syllable:\n\t\t\t(*table)->syllables = 1;\n\t\tcase CTO_Always:\n\t\tcase CTO_LargeSign:\n\t\tcase CTO_WholeWord:\n\t\tcase CTO_PartWord:\n\t\tcase CTO_JoinNum:\n\t\tcase CTO_JoinableWord:\n\t\tcase CTO_LowWord:\n\t\tcase CTO_SuffixableWord:\n\t\tcase CTO_PrefixableWord:\n\t\tcase CTO_BegWord:\n\t\tcase CTO_BegMidWord:\n\t\tcase CTO_MidWord:\n\t\tcase CTO_MidEndWord:\n\t\tcase CTO_EndWord:\n\t\tcase CTO_PrePunc:\n\t\tcase CTO_PostPunc:\n\t\tcase CTO_BegNum:\n\t\tcase CTO_MidNum:\n\t\tcase CTO_EndNum:\n\t\tcase CTO_Repeated:\n\t\tcase CTO_RepWord:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (!getRuleDotsPattern(file, &ruleDots)) return 0;\n\t\t\tif (ruleDots.length == 0)\n\t\t\t\t// check that all characters in a rule with `=` as second operand are\n\t\t\t\t// defined (or based on another character)\n\t\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\t\tTranslationTableCharacter *c =\n\t\t\t\t\t\t\tgetChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\t\tif (!(c && (c->definitionRule || c->basechar))) {\n\t\t\t\t\t\tcompileError(file, \"Character %s is not defined\",\n\t\t\t\t\t\t\t\t_lou_showString(&ruleChars.chars[k], 1, 0));\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tTranslationTableRule *r;\n\t\t\tif (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, &r,\n\t\t\t\t\t\tnoback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\tif (nocross) r->nocross = 1;\n\t\t\treturn 1;\n\t\t\t// if (opcode == CTO_MidNum)\n\t\t\t// {\n\t\t\t//   TranslationTableCharacter *c = getChar(ruleChars.chars[0]);\n\t\t\t//   if(c)\n\t\t\t//     c->attributes |= CTC_NumericMode;\n\t\t\t// }\n\t\tcase CTO_RepEndWord:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tCharsString dots;\n\t\t\tif (!getToken(file, &dots, \"dots,dots operand\")) return 0;\n\t\t\tint len = dots.length;\n\t\t\tfor (int k = 0; k < len - 1; k++) {\n\t\t\t\tif (dots.chars[k] == ',') {\n\t\t\t\t\tdots.length = k;\n\t\t\t\t\tif (!parseDots(file, &ruleDots, &dots)) return 0;\n\t\t\t\t\truleDots.chars[ruleDots.length++] = ',';\n\t\t\t\t\tk++;\n\t\t\t\t\tif (k == len - 1 && dots.chars[k] == '=') {\n\t\t\t\t\t\t// check that all characters are defined (or based on another\n\t\t\t\t\t\t// character)\n\t\t\t\t\t\tfor (int l = 0; l < ruleChars.length; l++) {\n\t\t\t\t\t\t\tTranslationTableCharacter *c =\n\t\t\t\t\t\t\t\t\tgetChar(ruleChars.chars[l], *table, NULL);\n\t\t\t\t\t\t\tif (!(c && (c->definitionRule || c->basechar))) {\n\t\t\t\t\t\t\t\tcompileError(file, \"Character %s is not defined\",\n\t\t\t\t\t\t\t\t\t\t_lou_showString(&ruleChars.chars[l], 1, 0));\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tCharsString x, y;\n\t\t\t\t\t\tx.length = 0;\n\t\t\t\t\t\twhile (k < len) x.chars[x.length++] = dots.chars[k++];\n\t\t\t\t\t\tif (parseDots(file, &y, &x))\n\t\t\t\t\t\t\tfor (int l = 0; l < y.length; l++)\n\t\t\t\t\t\t\t\truleDots.chars[ruleDots.length++] = y.chars[l];\n\t\t\t\t\t}\n\t\t\t\t\treturn addRule(file, opcode, &ruleChars, &ruleDots, after, before,\n\t\t\t\t\t\t\tNULL, NULL, noback, nofor, table);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 0;\n\t\tcase CTO_CompDots:\n\t\tcase CTO_Comp6: {\n\t\t\tTranslationTableOffset ruleOffset;\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (ruleChars.length != 1) {\n\t\t\t\tcompileError(file, \"first operand must be 1 character\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (nofor || noback) {\n\t\t\t\tcompileWarning(file, \"nofor and noback not allowed on comp6 rules\");\n\t\t\t}\n\t\t\tif (!getRuleDotsPattern(file, &ruleDots)) return 0;\n\t\t\tif (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset,\n\t\t\t\t\t\tNULL, noback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_ExactDots:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (ruleChars.chars[0] != '@') {\n\t\t\t\tcompileError(file, \"The operand must begin with an at sign (@)\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfor (int k = 1; k < ruleChars.length; k++)\n\t\t\t\tscratchPad.chars[k - 1] = ruleChars.chars[k];\n\t\t\tscratchPad.length = ruleChars.length - 1;\n\t\t\tif (!parseDots(file, &ruleDots, &scratchPad)) return 0;\n\t\t\treturn addRule(file, opcode, &ruleChars, &ruleDots, before, after, NULL, NULL,\n\t\t\t\t\tnoback, nofor, table);\n\t\tcase CTO_CapsNoCont: {\n\t\t\tTranslationTableOffset ruleOffset;\n\t\t\truleChars.length = 1;\n\t\t\truleChars.chars[0] = 'a';\n\t\t\tif (!addRule(file, CTO_CapsNoContRule, &ruleChars, NULL, after, before,\n\t\t\t\t\t\t&ruleOffset, NULL, noback, nofor, table))\n\t\t\t\treturn 0;\n\t\t\t(*table)->capsNoCont = ruleOffset;\n\t\t\treturn 1;\n\t\t}\n\t\tcase CTO_Replace:\n\t\t\tif (getRuleCharsText(file, &ruleChars)) {\n\t\t\t\tif (atEndOfLine(file))\n\t\t\t\t\truleDots.length = ruleDots.chars[0] = 0;\n\t\t\t\telse {\n\t\t\t\t\tgetRuleDotsText(file, &ruleDots);\n\t\t\t\t\tif (ruleDots.chars[0] == '#')\n\t\t\t\t\t\truleDots.length = ruleDots.chars[0] = 0;\n\t\t\t\t\telse if (ruleDots.chars[0] == '\\\\' && ruleDots.chars[1] == '#')\n\t\t\t\t\t\tmemmove(&ruleDots.chars[0], &ruleDots.chars[1],\n\t\t\t\t\t\t\t\truleDots.length-- * CHARSIZE);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int k = 0; k < ruleChars.length; k++)\n\t\t\t\tputChar(file, ruleChars.chars[k], table, NULL);\n\t\t\tfor (int k = 0; k < ruleDots.length; k++)\n\t\t\t\tputChar(file, ruleDots.chars[k], table, NULL);\n\t\t\treturn addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL,\n\t\t\t\t\tnoback, nofor, table);\n\t\tcase CTO_Correct:\n\t\t\t(*table)->corrections = 1;\n\t\t\tgoto doPass;\n\t\tcase CTO_Pass2:\n\t\t\tif ((*table)->numPasses < 2) (*table)->numPasses = 2;\n\t\t\tgoto doPass;\n\t\tcase CTO_Pass3:\n\t\t\tif ((*table)->numPasses < 3) (*table)->numPasses = 3;\n\t\t\tgoto doPass;\n\t\tcase CTO_Pass4:\n\t\t\tif ((*table)->numPasses < 4) (*table)->numPasses = 4;\n\t\tdoPass:\n\t\tcase CTO_Context:\n\t\t\tif (!(nofor || noback)) {\n\t\t\t\tcompileError(file, \"%s or %s must be specified.\",\n\t\t\t\t\t\t_lou_findOpcodeName(CTO_NoFor), _lou_findOpcodeName(CTO_NoBack));\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\treturn compilePassOpcode(file, opcode, noback, nofor, table);\n\t\tcase CTO_Contraction:\n\t\tcase CTO_NoCont:\n\t\tcase CTO_CompBrl:\n\t\tcase CTO_Literal:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\t// check that all characters in a compbrl, contraction,\n\t\t\t// nocont or literal rule are defined (or based on another\n\t\t\t// character)\n\t\t\tfor (int k = 0; k < ruleChars.length; k++) {\n\t\t\t\tTranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);\n\t\t\t\tif (!(c && (c->definitionRule || c->basechar))) {\n\t\t\t\t\tcompileError(file, \"Character %s is not defined\",\n\t\t\t\t\t\t\t_lou_showString(&ruleChars.chars[k], 1, 0));\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn addRule(file, opcode, &ruleChars, NULL, after, before, NULL, NULL,\n\t\t\t\t\tnoback, nofor, table);\n\t\tcase CTO_MultInd: {\n\t\t\truleChars.length = 0;\n\t\t\tif (!getToken(file, &token, \"multiple braille indicators\") ||\n\t\t\t\t\t!parseDots(file, &cells, &token))\n\t\t\t\treturn 0;\n\t\t\twhile (getToken(file, &token, \"multind opcodes\")) {\n\t\t\t\topcode = getOpcode(file, &token);\n\t\t\t\tif (opcode == CTO_None) {\n\t\t\t\t\tcompileError(file, \"opcode %s not defined.\",\n\t\t\t\t\t\t\t_lou_showString(token.chars, token.length, 0));\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tif (!(opcode >= CTO_CapsLetter && opcode < CTO_MultInd)) {\n\t\t\t\t\tcompileError(file, \"Not a braille indicator opcode.\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\truleChars.chars[ruleChars.length++] = (widechar)opcode;\n\t\t\t\tif (atEndOfLine(file)) break;\n\t\t\t}\n\t\t\treturn addRule(file, CTO_MultInd, &ruleChars, &cells, after, before, NULL,\n\t\t\t\t\tNULL, noback, nofor, table);\n\t\t}\n\n\t\tcase CTO_Class:\n\t\t\tcompileWarning(file, \"class is deprecated, use attribute instead\");\n\t\tcase CTO_Attribute: {\n\t\t\tif (nofor || noback) {\n\t\t\t\tcompileWarning(\n\t\t\t\t\t\tfile, \"nofor and noback not allowed before class/attribute\");\n\t\t\t}\n\t\t\tif ((opcode == CTO_Class && (*table)->usesAttributeOrClass == 1) ||\n\t\t\t\t\t(opcode == CTO_Attribute && (*table)->usesAttributeOrClass == 2)) {\n\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\"attribute and class rules must not be both present in a table\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (opcode == CTO_Class)\n\t\t\t\t(*table)->usesAttributeOrClass = 2;\n\t\t\telse\n\t\t\t\t(*table)->usesAttributeOrClass = 1;\n\t\t\tif (!getToken(file, &token, \"attribute name\")) {\n\t\t\t\tcompileError(file, \"Expected %s\", \"attribute name\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (!(*table)->characterClasses && !allocateCharacterClasses(*table)) {\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tTranslationTableCharacterAttributes attribute = 0;\n\t\t\t{\n\t\t\t\tint attrNumber = -1;\n\t\t\t\tswitch (token.chars[0]) {\n\t\t\t\tcase '0':\n\t\t\t\tcase '1':\n\t\t\t\tcase '2':\n\t\t\t\tcase '3':\n\t\t\t\tcase '4':\n\t\t\t\tcase '5':\n\t\t\t\tcase '6':\n\t\t\t\tcase '7':\n\t\t\t\tcase '8':\n\t\t\t\tcase '9':\n\t\t\t\t\tattrNumber = token.chars[0] - '0';\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (attrNumber >= 0) {\n\t\t\t\t\tif (opcode == CTO_Class) {\n\t\t\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\t\t\"Invalid class name: may not contain digits, use \"\n\t\t\t\t\t\t\t\t\"attribute instead of class\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (token.length > 1 || attrNumber > 7) {\n\t\t\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\t\t\"Invalid attribute name: must be a digit between 0 and 7 \"\n\t\t\t\t\t\t\t\t\"or a word containing only letters\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (!(*table)->numberedAttributes[attrNumber])\n\t\t\t\t\t\t// attribute not used before yet: assign it a value\n\t\t\t\t\t\t(*table)->numberedAttributes[attrNumber] =\n\t\t\t\t\t\t\t\tgetNextNumberedAttribute(*table);\n\t\t\t\t\tattribute = (*table)->numberedAttributes[attrNumber];\n\t\t\t\t} else {\n\t\t\t\t\tconst CharacterClass *namedAttr = findCharacterClass(&token, *table);\n\t\t\t\t\tif (!namedAttr) {\n\t\t\t\t\t\t// no class with that name: create one\n\t\t\t\t\t\tnamedAttr = addCharacterClass(\n\t\t\t\t\t\t\t\tfile, &token.chars[0], token.length, *table, 1);\n\t\t\t\t\t\tif (!namedAttr) return 0;\n\t\t\t\t\t}\n\t\t\t\t\t// there is a class with that name or a new class was successfully\n\t\t\t\t\t// created\n\t\t\t\t\tattribute = namedAttr->attribute;\n\t\t\t\t\tif (attribute == CTC_UpperCase || attribute == CTC_LowerCase)\n\t\t\t\t\t\tattribute |= CTC_Letter;\n\t\t\t\t}\n\t\t\t}\n\t\t\tCharsString characters;\n\t\t\tif (!getCharacters(file, &characters)) return 0;\n\t\t\tfor (int i = 0; i < characters.length; i++) {\n\t\t\t\t// get the character from the table, or if it is not defined yet,\n\t\t\t\t// define it\n\t\t\t\tTranslationTableCharacter *character =\n\t\t\t\t\t\tputChar(file, characters.chars[i], table, NULL);\n\t\t\t\t// set the attribute\n\t\t\t\tcharacter->attributes |= attribute;\n\t\t\t\t// also set the attribute on the associated dots (if any)\n\t\t\t\tif (character->basechar)\n\t\t\t\t\tcharacter = (TranslationTableCharacter *)&(*table)\n\t\t\t\t\t\t\t\t\t\t->ruleArea[character->basechar];\n\t\t\t\tif (character->definitionRule) {\n\t\t\t\t\tTranslationTableRule *defRule =\n\t\t\t\t\t\t\t(TranslationTableRule *)&(*table)\n\t\t\t\t\t\t\t\t\t->ruleArea[character->definitionRule];\n\t\t\t\t\tif (defRule->dotslen == 1) {\n\t\t\t\t\t\tTranslationTableCharacter *dots =\n\t\t\t\t\t\t\t\tgetDots(defRule->charsdots[defRule->charslen], *table);\n\t\t\t\t\t\tif (dots) dots->attributes |= attribute;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 1;\n\t\t}\n\n\t\t\t{\n\t\t\t\tTranslationTableCharacterAttributes *attributes;\n\t\t\t\tconst CharacterClass *class;\n\t\t\tcase CTO_After:\n\t\t\t\tattributes = &after;\n\t\t\t\tgoto doBeforeAfter;\n\t\t\tcase CTO_Before:\n\t\t\t\tattributes = &before;\n\t\t\tdoBeforeAfter:\n\t\t\t\tif (!(*table)->characterClasses) {\n\t\t\t\t\tif (!allocateCharacterClasses(*table)) return 0;\n\t\t\t\t}\n\t\t\t\tif (!getToken(file, &token, \"attribute name\")) return 0;\n\t\t\t\tif (!(class = findCharacterClass(&token, *table))) {\n\t\t\t\t\tcompileError(file, \"attribute not defined\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t*attributes |= class->attribute;\n\t\t\t\tgoto doOpcode;\n\t\t\t}\n\t\tcase CTO_Base:\n\t\t\tif (nofor || noback) {\n\t\t\t\tcompileWarning(file, \"nofor and noback not allowed before base\");\n\t\t\t}\n\t\t\tif (!getToken(file, &token, \"attribute name\")) {\n\t\t\t\tcompileError(\n\t\t\t\t\t\tfile, \"base opcode must be followed by a valid attribute name.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (!(*table)->characterClasses && !allocateCharacterClasses(*table)) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tconst CharacterClass *mode = findCharacterClass(&token, *table);\n\t\t\tif (!mode) {\n\t\t\t\tmode = addCharacterClass(file, token.chars, token.length, *table, 1);\n\t\t\t\tif (!mode) return 0;\n\t\t\t}\n\t\t\tif (!(mode->attribute == CTC_UpperCase || mode->attribute == CTC_Digit) &&\n\t\t\t\t\tmode->attribute >= CTC_Space && mode->attribute <= CTC_LitDigit) {\n\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\"base opcode must be followed by \\\"uppercase\\\", \\\"digit\\\", or a \"\n\t\t\t\t\t\t\"custom attribute name.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (!getRuleCharsText(file, &token)) return 0;\n\t\t\tif (token.length != 1) {\n\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\"Exactly one character followed by one base character is \"\n\t\t\t\t\t\t\"required.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tTranslationTableOffset characterOffset;\n\t\t\tTranslationTableCharacter *character =\n\t\t\t\t\tputChar(file, token.chars[0], table, &characterOffset);\n\t\t\tif (!getRuleCharsText(file, &token)) return 0;\n\t\t\tif (token.length != 1) {\n\t\t\t\tcompileError(file, \"Exactly one base character is required.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (character->definitionRule) {\n\t\t\t\tTranslationTableRule *prevRule =\n\t\t\t\t\t\t(TranslationTableRule *)&(*table)\n\t\t\t\t\t\t\t\t->ruleArea[character->definitionRule];\n\t\t\t\t_lou_logMessage(LOU_LOG_DEBUG,\n\t\t\t\t\t\t\"%s:%d: Character already defined (%s). The base rule will take \"\n\t\t\t\t\t\t\"precedence.\",\n\t\t\t\t\t\tfile->fileName, file->lineNumber,\n\t\t\t\t\t\tprintSource(file, prevRule->sourceFile, prevRule->sourceLine));\n\t\t\t\tcharacter->definitionRule = 0;\n\t\t\t}\n\t\t\tTranslationTableOffset basechar;\n\t\t\tputChar(file, token.chars[0], table, &basechar);\n\t\t\t// putChar may have moved table, so make sure character is still valid\n\t\t\tcharacter = (TranslationTableCharacter *)&(*table)->ruleArea[characterOffset];\n\t\t\tif (character->basechar) {\n\t\t\t\tif (character->basechar == basechar &&\n\t\t\t\t\t\tcharacter->mode == mode->attribute) {\n\t\t\t\t\t_lou_logMessage(LOU_LOG_DEBUG, \"%s:%d: Duplicate base rule.\",\n\t\t\t\t\t\t\tfile->fileName, file->lineNumber);\n\t\t\t\t} else {\n\t\t\t\t\t_lou_logMessage(LOU_LOG_DEBUG,\n\t\t\t\t\t\t\t\"%s:%d: A different base rule already exists for this \"\n\t\t\t\t\t\t\t\"character (%s). The new rule will take precedence.\",\n\t\t\t\t\t\t\tfile->fileName, file->lineNumber,\n\t\t\t\t\t\t\tprintSource(\n\t\t\t\t\t\t\t\t\tfile, character->sourceFile, character->sourceLine));\n\t\t\t\t}\n\t\t\t}\n\t\t\tcharacter->basechar = basechar;\n\t\t\tcharacter->mode = mode->attribute;\n\t\t\tcharacter->sourceFile = file->sourceFile;\n\t\t\tcharacter->sourceLine = file->lineNumber;\n\t\t\t/* some other processing is done at the end of the compilation, in\n\t\t\t * finalizeTable() */\n\t\t\treturn 1;\n\t\tcase CTO_EmpMatchBefore:\n\t\t\tbefore |= CTC_EmpMatch;\n\t\t\tgoto doOpcode;\n\t\tcase CTO_EmpMatchAfter:\n\t\t\tafter |= CTC_EmpMatch;\n\t\t\tgoto doOpcode;\n\n\t\tcase CTO_SwapCc:\n\t\tcase CTO_SwapCd:\n\t\tcase CTO_SwapDd:\n\t\t\treturn compileSwap(file, opcode, noback, nofor, table);\n\t\tcase CTO_Hyphen:\n\t\tcase CTO_DecPoint:\n\t\t\t//\tcase CTO_Apostrophe:\n\t\t\t//\tcase CTO_Initial:\n\t\t\tif (!getRuleCharsText(file, &ruleChars)) return 0;\n\t\t\tif (!getRuleDotsPattern(file, &ruleDots)) return 0;\n\t\t\tif (ruleChars.length != 1 || ruleDots.length < 1) {\n\t\t\t\tcompileError(file,\n\t\t\t\t\t\t\"One Unicode character and at least one cell are \"\n\t\t\t\t\t\t\"required.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\treturn addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL,\n\t\t\t\t\tnoback, nofor, table);\n\t\t\t// if (opcode == CTO_DecPoint)\n\t\t\t// {\n\t\t\t//   TranslationTableCharacter *c =\n\t\t\t//   getChar(ruleChars.chars[0]);\n\t\t\t//   if(c)\n\t\t\t//     c->attributes |= CTC_NumericMode;\n\t\t\t// }\n\t\tdefault:\n\t\t\tcompileError(file, \"unimplemented opcode.\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 0;\n}", "func_hash": 188995041946566375099409962387038802381, "file_name": "compileTranslationTable.c", "file_hash": 129515444966510079462991982245291196170, "cwe": ["CWE-787"], "cve": "CVE-2022-31783", "cve_desc": "Liblouis 3.21.0 has an out-of-bounds write in compileRule in compileTranslationTable.c, as demonstrated by lou_trace.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31783"}
{"idx": 215038, "project": "gst-plugins-good", "commit_id": "b31c504645a814c59d91d49e4fe218acaf93f4ca", "project_url": "https://github.com/GStreamer/gst-plugins-good", "commit_url": "https://github.com/GStreamer/gst-plugins-good/commit/b31c504645a814c59d91d49e4fe218acaf93f4ca", "commit_message": "flxdec: Don't unref() parent in the chain function\n\nWe don't own the reference here, it is owned by the caller and given to\nus for the scope of this function. Leftover mistake from 0.10 porting.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=774897", "target": 1, "func": "gst_flxdec_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)\n{\n  GstCaps *caps;\n  guint avail;\n  GstFlowReturn res = GST_FLOW_OK;\n\n  GstFlxDec *flxdec;\n  FlxHeader *flxh;\n\n  g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);\n  flxdec = (GstFlxDec *) parent;\n  g_return_val_if_fail (flxdec != NULL, GST_FLOW_ERROR);\n\n  gst_adapter_push (flxdec->adapter, buf);\n  avail = gst_adapter_available (flxdec->adapter);\n\n  if (flxdec->state == GST_FLXDEC_READ_HEADER) {\n    if (avail >= FlxHeaderSize) {\n      const guint8 *data = gst_adapter_map (flxdec->adapter, FlxHeaderSize);\n      GstCaps *templ;\n\n      memcpy ((gchar *) & flxdec->hdr, data, FlxHeaderSize);\n      FLX_HDR_FIX_ENDIANNESS (&(flxdec->hdr));\n      gst_adapter_unmap (flxdec->adapter);\n      gst_adapter_flush (flxdec->adapter, FlxHeaderSize);\n\n      flxh = &flxdec->hdr;\n\n      /* check header */\n      if (flxh->type != FLX_MAGICHDR_FLI &&\n          flxh->type != FLX_MAGICHDR_FLC && flxh->type != FLX_MAGICHDR_FLX)\n        goto wrong_type;\n\n      GST_LOG (\"size      :  %d\", flxh->size);\n      GST_LOG (\"frames    :  %d\", flxh->frames);\n      GST_LOG (\"width     :  %d\", flxh->width);\n      GST_LOG (\"height    :  %d\", flxh->height);\n      GST_LOG (\"depth     :  %d\", flxh->depth);\n      GST_LOG (\"speed     :  %d\", flxh->speed);\n\n      flxdec->next_time = 0;\n\n      if (flxh->type == FLX_MAGICHDR_FLI) {\n        flxdec->frame_time = JIFFIE * flxh->speed;\n      } else if (flxh->speed == 0) {\n        flxdec->frame_time = GST_SECOND / 70;\n      } else {\n        flxdec->frame_time = flxh->speed * GST_MSECOND;\n      }\n\n      flxdec->duration = flxh->frames * flxdec->frame_time;\n      GST_LOG (\"duration   :  %\" GST_TIME_FORMAT,\n          GST_TIME_ARGS (flxdec->duration));\n\n      templ = gst_pad_get_pad_template_caps (flxdec->srcpad);\n      caps = gst_caps_copy (templ);\n      gst_caps_unref (templ);\n      gst_caps_set_simple (caps,\n          \"width\", G_TYPE_INT, flxh->width,\n          \"height\", G_TYPE_INT, flxh->height,\n          \"framerate\", GST_TYPE_FRACTION, (gint) GST_MSECOND,\n          (gint) flxdec->frame_time / 1000, NULL);\n\n      gst_pad_set_caps (flxdec->srcpad, caps);\n      gst_caps_unref (caps);\n\n      if (flxh->depth <= 8)\n        flxdec->converter =\n            flx_colorspace_converter_new (flxh->width, flxh->height);\n\n      if (flxh->type == FLX_MAGICHDR_FLC || flxh->type == FLX_MAGICHDR_FLX) {\n        GST_LOG (\"(FLC) aspect_dx :  %d\", flxh->aspect_dx);\n        GST_LOG (\"(FLC) aspect_dy :  %d\", flxh->aspect_dy);\n        GST_LOG (\"(FLC) oframe1   :  0x%08x\", flxh->oframe1);\n        GST_LOG (\"(FLC) oframe2   :  0x%08x\", flxh->oframe2);\n      }\n\n      flxdec->size = ((guint) flxh->width * (guint) flxh->height);\n\n      /* create delta and output frame */\n      flxdec->frame_data = g_malloc (flxdec->size);\n      flxdec->delta_data = g_malloc (flxdec->size);\n\n      flxdec->state = GST_FLXDEC_PLAYING;\n    }\n  } else if (flxdec->state == GST_FLXDEC_PLAYING) {\n    GstBuffer *out;\n\n    /* while we have enough data in the adapter */\n    while (avail >= FlxFrameChunkSize && res == GST_FLOW_OK) {\n      FlxFrameChunk flxfh;\n      guchar *chunk;\n      const guint8 *data;\n      GstMapInfo map;\n\n      chunk = NULL;\n      data = gst_adapter_map (flxdec->adapter, FlxFrameChunkSize);\n      memcpy (&flxfh, data, FlxFrameChunkSize);\n      FLX_FRAME_CHUNK_FIX_ENDIANNESS (&flxfh);\n      gst_adapter_unmap (flxdec->adapter);\n\n      switch (flxfh.id) {\n        case FLX_FRAME_TYPE:\n          /* check if we have the complete frame */\n          if (avail < flxfh.size)\n            goto need_more_data;\n\n          /* flush header */\n          gst_adapter_flush (flxdec->adapter, FlxFrameChunkSize);\n\n          chunk = gst_adapter_take (flxdec->adapter,\n              flxfh.size - FlxFrameChunkSize);\n          FLX_FRAME_TYPE_FIX_ENDIANNESS ((FlxFrameType *) chunk);\n          if (((FlxFrameType *) chunk)->chunks == 0)\n            break;\n\n          /* create 32 bits output frame */\n//          res = gst_pad_alloc_buffer_and_set_caps (flxdec->srcpad,\n//              GST_BUFFER_OFFSET_NONE,\n//              flxdec->size * 4, GST_PAD_CAPS (flxdec->srcpad), &out);\n//          if (res != GST_FLOW_OK)\n//            break;\n\n          out = gst_buffer_new_and_alloc (flxdec->size * 4);\n\n          /* decode chunks */\n          if (!flx_decode_chunks (flxdec,\n                  ((FlxFrameType *) chunk)->chunks,\n                  chunk + FlxFrameTypeSize, flxdec->frame_data)) {\n            GST_ELEMENT_ERROR (flxdec, STREAM, DECODE,\n                (\"%s\", \"Could not decode chunk\"), NULL);\n            return GST_FLOW_ERROR;\n          }\n\n          /* save copy of the current frame for possible delta. */\n          memcpy (flxdec->delta_data, flxdec->frame_data, flxdec->size);\n\n          gst_buffer_map (out, &map, GST_MAP_WRITE);\n          /* convert current frame. */\n          flx_colorspace_convert (flxdec->converter, flxdec->frame_data,\n              map.data);\n          gst_buffer_unmap (out, &map);\n\n          GST_BUFFER_TIMESTAMP (out) = flxdec->next_time;\n          flxdec->next_time += flxdec->frame_time;\n\n          res = gst_pad_push (flxdec->srcpad, out);\n          break;\n        default:\n          /* check if we have the complete frame */\n          if (avail < flxfh.size)\n            goto need_more_data;\n\n          gst_adapter_flush (flxdec->adapter, flxfh.size);\n          break;\n      }\n\n      g_free (chunk);\n\n      avail = gst_adapter_available (flxdec->adapter);\n    }\n  }\nneed_more_data:\n  return res;\n\n  /* ERRORS */\nwrong_type:\n  {\n    GST_ELEMENT_ERROR (flxdec, STREAM, WRONG_TYPE, (NULL),\n        (\"not a flx file (type %x)\", flxh->type));\n    gst_object_unref (flxdec);\n    return GST_FLOW_ERROR;\n  }\n}", "func_hash": 293682781429111556527181973502820056353, "file_name": "gstflxdec.c", "file_hash": 257993996858330004218595538099349772474, "cwe": ["CWE-125"], "cve": "CVE-2016-9810", "cve_desc": "The gst_decode_chain_free_internal function in the flxdex decoder in gst-plugins-good in GStreamer before 1.10.2 allows remote attackers to cause a denial of service (invalid memory read and crash) via an invalid file, which triggers an incorrect unref call.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-9810"}
{"idx": 482692, "project": "gst-plugins-good", "commit_id": "b31c504645a814c59d91d49e4fe218acaf93f4ca", "project_url": "https://github.com/GStreamer/gst-plugins-good", "commit_url": "https://github.com/GStreamer/gst-plugins-good/commit/b31c504645a814c59d91d49e4fe218acaf93f4ca", "commit_message": "flxdec: Don't unref() parent in the chain function\n\nWe don't own the reference here, it is owned by the caller and given to\nus for the scope of this function. Leftover mistake from 0.10 porting.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=774897", "target": 0, "func": "gst_flxdec_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)\n{\n  GstCaps *caps;\n  guint avail;\n  GstFlowReturn res = GST_FLOW_OK;\n\n  GstFlxDec *flxdec;\n  FlxHeader *flxh;\n\n  g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);\n  flxdec = (GstFlxDec *) parent;\n  g_return_val_if_fail (flxdec != NULL, GST_FLOW_ERROR);\n\n  gst_adapter_push (flxdec->adapter, buf);\n  avail = gst_adapter_available (flxdec->adapter);\n\n  if (flxdec->state == GST_FLXDEC_READ_HEADER) {\n    if (avail >= FlxHeaderSize) {\n      const guint8 *data = gst_adapter_map (flxdec->adapter, FlxHeaderSize);\n      GstCaps *templ;\n\n      memcpy ((gchar *) & flxdec->hdr, data, FlxHeaderSize);\n      FLX_HDR_FIX_ENDIANNESS (&(flxdec->hdr));\n      gst_adapter_unmap (flxdec->adapter);\n      gst_adapter_flush (flxdec->adapter, FlxHeaderSize);\n\n      flxh = &flxdec->hdr;\n\n      /* check header */\n      if (flxh->type != FLX_MAGICHDR_FLI &&\n          flxh->type != FLX_MAGICHDR_FLC && flxh->type != FLX_MAGICHDR_FLX)\n        goto wrong_type;\n\n      GST_LOG (\"size      :  %d\", flxh->size);\n      GST_LOG (\"frames    :  %d\", flxh->frames);\n      GST_LOG (\"width     :  %d\", flxh->width);\n      GST_LOG (\"height    :  %d\", flxh->height);\n      GST_LOG (\"depth     :  %d\", flxh->depth);\n      GST_LOG (\"speed     :  %d\", flxh->speed);\n\n      flxdec->next_time = 0;\n\n      if (flxh->type == FLX_MAGICHDR_FLI) {\n        flxdec->frame_time = JIFFIE * flxh->speed;\n      } else if (flxh->speed == 0) {\n        flxdec->frame_time = GST_SECOND / 70;\n      } else {\n        flxdec->frame_time = flxh->speed * GST_MSECOND;\n      }\n\n      flxdec->duration = flxh->frames * flxdec->frame_time;\n      GST_LOG (\"duration   :  %\" GST_TIME_FORMAT,\n          GST_TIME_ARGS (flxdec->duration));\n\n      templ = gst_pad_get_pad_template_caps (flxdec->srcpad);\n      caps = gst_caps_copy (templ);\n      gst_caps_unref (templ);\n      gst_caps_set_simple (caps,\n          \"width\", G_TYPE_INT, flxh->width,\n          \"height\", G_TYPE_INT, flxh->height,\n          \"framerate\", GST_TYPE_FRACTION, (gint) GST_MSECOND,\n          (gint) flxdec->frame_time / 1000, NULL);\n\n      gst_pad_set_caps (flxdec->srcpad, caps);\n      gst_caps_unref (caps);\n\n      if (flxh->depth <= 8)\n        flxdec->converter =\n            flx_colorspace_converter_new (flxh->width, flxh->height);\n\n      if (flxh->type == FLX_MAGICHDR_FLC || flxh->type == FLX_MAGICHDR_FLX) {\n        GST_LOG (\"(FLC) aspect_dx :  %d\", flxh->aspect_dx);\n        GST_LOG (\"(FLC) aspect_dy :  %d\", flxh->aspect_dy);\n        GST_LOG (\"(FLC) oframe1   :  0x%08x\", flxh->oframe1);\n        GST_LOG (\"(FLC) oframe2   :  0x%08x\", flxh->oframe2);\n      }\n\n      flxdec->size = ((guint) flxh->width * (guint) flxh->height);\n\n      /* create delta and output frame */\n      flxdec->frame_data = g_malloc (flxdec->size);\n      flxdec->delta_data = g_malloc (flxdec->size);\n\n      flxdec->state = GST_FLXDEC_PLAYING;\n    }\n  } else if (flxdec->state == GST_FLXDEC_PLAYING) {\n    GstBuffer *out;\n\n    /* while we have enough data in the adapter */\n    while (avail >= FlxFrameChunkSize && res == GST_FLOW_OK) {\n      FlxFrameChunk flxfh;\n      guchar *chunk;\n      const guint8 *data;\n      GstMapInfo map;\n\n      chunk = NULL;\n      data = gst_adapter_map (flxdec->adapter, FlxFrameChunkSize);\n      memcpy (&flxfh, data, FlxFrameChunkSize);\n      FLX_FRAME_CHUNK_FIX_ENDIANNESS (&flxfh);\n      gst_adapter_unmap (flxdec->adapter);\n\n      switch (flxfh.id) {\n        case FLX_FRAME_TYPE:\n          /* check if we have the complete frame */\n          if (avail < flxfh.size)\n            goto need_more_data;\n\n          /* flush header */\n          gst_adapter_flush (flxdec->adapter, FlxFrameChunkSize);\n\n          chunk = gst_adapter_take (flxdec->adapter,\n              flxfh.size - FlxFrameChunkSize);\n          FLX_FRAME_TYPE_FIX_ENDIANNESS ((FlxFrameType *) chunk);\n          if (((FlxFrameType *) chunk)->chunks == 0)\n            break;\n\n          /* create 32 bits output frame */\n//          res = gst_pad_alloc_buffer_and_set_caps (flxdec->srcpad,\n//              GST_BUFFER_OFFSET_NONE,\n//              flxdec->size * 4, GST_PAD_CAPS (flxdec->srcpad), &out);\n//          if (res != GST_FLOW_OK)\n//            break;\n\n          out = gst_buffer_new_and_alloc (flxdec->size * 4);\n\n          /* decode chunks */\n          if (!flx_decode_chunks (flxdec,\n                  ((FlxFrameType *) chunk)->chunks,\n                  chunk + FlxFrameTypeSize, flxdec->frame_data)) {\n            GST_ELEMENT_ERROR (flxdec, STREAM, DECODE,\n                (\"%s\", \"Could not decode chunk\"), NULL);\n            return GST_FLOW_ERROR;\n          }\n\n          /* save copy of the current frame for possible delta. */\n          memcpy (flxdec->delta_data, flxdec->frame_data, flxdec->size);\n\n          gst_buffer_map (out, &map, GST_MAP_WRITE);\n          /* convert current frame. */\n          flx_colorspace_convert (flxdec->converter, flxdec->frame_data,\n              map.data);\n          gst_buffer_unmap (out, &map);\n\n          GST_BUFFER_TIMESTAMP (out) = flxdec->next_time;\n          flxdec->next_time += flxdec->frame_time;\n\n          res = gst_pad_push (flxdec->srcpad, out);\n          break;\n        default:\n          /* check if we have the complete frame */\n          if (avail < flxfh.size)\n            goto need_more_data;\n\n          gst_adapter_flush (flxdec->adapter, flxfh.size);\n          break;\n      }\n\n      g_free (chunk);\n\n      avail = gst_adapter_available (flxdec->adapter);\n    }\n  }\nneed_more_data:\n  return res;\n\n  /* ERRORS */\nwrong_type:\n  {\n    GST_ELEMENT_ERROR (flxdec, STREAM, WRONG_TYPE, (NULL),\n        (\"not a flx file (type %x)\", flxh->type));\n    return GST_FLOW_ERROR;\n  }\n}", "func_hash": 307699482792832838844638071066338187796, "file_name": "gstflxdec.c", "file_hash": 15220895690601023240129213899493293437, "cwe": ["CWE-125"], "cve": "CVE-2016-9810", "cve_desc": "The gst_decode_chain_free_internal function in the flxdex decoder in gst-plugins-good in GStreamer before 1.10.2 allows remote attackers to cause a denial of service (invalid memory read and crash) via an invalid file, which triggers an incorrect unref call.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-9810"}
{"idx": 215073, "project": "linux", "commit_id": "24f6008564183aa120d07c03d9289519c2fe02af", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/24f6008564183aa120d07c03d9289519c2fe02af", "commit_message": "cgroup-v1: Require capabilities to set release_agent\n\nThe cgroup release_agent is called with call_usermodehelper.  The function\ncall_usermodehelper starts the release_agent with a full set fo capabilities.\nTherefore require capabilities when setting the release_agaent.\n\nReported-by: Tabitha Sable \nTested-by: Tabitha Sable \nFixes: 81a6a5cdd2c5 (\"Task Control Groups: automatic userspace notification of idle cgroups\")\nCc: stable@vger.kernel.org # v2.6.24+\nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: Tejun Heo ", "target": 1, "func": "static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,\n\t\t\t\t\t  char *buf, size_t nbytes, loff_t off)\n{\n\tstruct cgroup *cgrp;\n\n\tBUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);\n\n\tcgrp = cgroup_kn_lock_live(of->kn, false);\n\tif (!cgrp)\n\t\treturn -ENODEV;\n\tspin_lock(&release_agent_path_lock);\n\tstrlcpy(cgrp->root->release_agent_path, strstrip(buf),\n\t\tsizeof(cgrp->root->release_agent_path));\n\tspin_unlock(&release_agent_path_lock);\n\tcgroup_kn_unlock(of->kn);\n\treturn nbytes;\n}", "func_hash": 62903931031364372249216035169426622389, "file_name": "cgroup-v1.c", "file_hash": 159693224935670518088988394061249784059, "cwe": ["CWE-269"], "cve": "CVE-2022-0492", "cve_desc": "A vulnerability was found in the Linux kernel\u2019s cgroup_release_agent_write in the kernel/cgroup/cgroup-v1.c function. This flaw, under certain circumstances, allows the use of the cgroups v1 release_agent feature to escalate privileges and bypass the namespace isolation unexpectedly.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0492"}
{"idx": 483053, "project": "linux", "commit_id": "24f6008564183aa120d07c03d9289519c2fe02af", "project_url": "https://github.com/torvalds/linux", "commit_url": "https://github.com/torvalds/linux/commit/24f6008564183aa120d07c03d9289519c2fe02af", "commit_message": "cgroup-v1: Require capabilities to set release_agent\n\nThe cgroup release_agent is called with call_usermodehelper.  The function\ncall_usermodehelper starts the release_agent with a full set fo capabilities.\nTherefore require capabilities when setting the release_agaent.\n\nReported-by: Tabitha Sable \nTested-by: Tabitha Sable \nFixes: 81a6a5cdd2c5 (\"Task Control Groups: automatic userspace notification of idle cgroups\")\nCc: stable@vger.kernel.org # v2.6.24+\nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: Tejun Heo ", "target": 0, "func": "static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,\n\t\t\t\t\t  char *buf, size_t nbytes, loff_t off)\n{\n\tstruct cgroup *cgrp;\n\n\tBUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);\n\n\t/*\n\t * Release agent gets called with all capabilities,\n\t * require capabilities to set release agent.\n\t */\n\tif ((of->file->f_cred->user_ns != &init_user_ns) ||\n\t    !capable(CAP_SYS_ADMIN))\n\t\treturn -EPERM;\n\n\tcgrp = cgroup_kn_lock_live(of->kn, false);\n\tif (!cgrp)\n\t\treturn -ENODEV;\n\tspin_lock(&release_agent_path_lock);\n\tstrlcpy(cgrp->root->release_agent_path, strstrip(buf),\n\t\tsizeof(cgrp->root->release_agent_path));\n\tspin_unlock(&release_agent_path_lock);\n\tcgroup_kn_unlock(of->kn);\n\treturn nbytes;\n}", "func_hash": 43963490668592516286761666416958152261, "file_name": "cgroup-v1.c", "file_hash": 124298823051510119794232043748065237512, "cwe": ["CWE-269"], "cve": "CVE-2022-0492", "cve_desc": "A vulnerability was found in the Linux kernel\u2019s cgroup_release_agent_write in the kernel/cgroup/cgroup-v1.c function. This flaw, under certain circumstances, allows the use of the cgroups v1 release_agent feature to escalate privileges and bypass the namespace isolation unexpectedly.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0492"}
{"idx": 215103, "project": "mongo", "commit_id": "a5e2f9b0a236462a6d1ca129583c617f111367b4", "project_url": "https://github.com/mongodb/mongo", "commit_url": "https://github.com/mongodb/mongo/commit/a5e2f9b0a236462a6d1ca129583c617f111367b4", "commit_message": "SERVER-59071 Treat '$sample' as unsharded when connecting directly to shards\n\n(cherry picked from commit f3604b901d688c194de5e430c7fbab060c9dc8e0)", "target": 1, "func": "createRandomCursorExecutor(const CollectionPtr& coll,\n                           const boost::intrusive_ptr& expCtx,\n                           long long sampleSize,\n                           long long numRecords,\n                           boost::optional bucketUnpacker) {\n    OperationContext* opCtx = expCtx->opCtx;\n\n    // Verify that we are already under a collection lock. We avoid taking locks ourselves in this\n    // function because double-locking forces any PlanExecutor we create to adopt a NO_YIELD policy.\n    invariant(opCtx->lockState()->isCollectionLockedForMode(coll->ns(), MODE_IS));\n\n    static const double kMaxSampleRatioForRandCursor = 0.05;\n    if (!expCtx->ns.isTimeseriesBucketsCollection()) {\n        if (sampleSize > numRecords * kMaxSampleRatioForRandCursor || numRecords <= 100) {\n            return std::pair{nullptr, false};\n        }\n    } else {\n        // Suppose that a time-series bucket collection is observed to contain 200 buckets, and the\n        // 'gTimeseriesBucketMaxCount' parameter is set to 1000. If all buckets are full, then the\n        // maximum possible measurment count would be 200 * 1000 = 200,000. While the\n        // 'SampleFromTimeseriesBucket' plan is more efficient when the sample size is small\n        // relative to the total number of measurements in the time-series collection, for larger\n        // sample sizes the top-k sort based sample is faster. Experiments have approximated that\n        // the tipping point is roughly when the requested sample size is greater than 1% of the\n        // maximum possible number of measurements in the collection (i.e. numBuckets *\n        // maxMeasurementsPerBucket).\n        static const double kCoefficient = 0.01;\n        if (sampleSize > kCoefficient * numRecords * gTimeseriesBucketMaxCount) {\n            return std::pair{nullptr, false};\n        }\n    }\n\n    // Attempt to get a random cursor from the RecordStore.\n    auto rsRandCursor = coll->getRecordStore()->getRandomCursor(opCtx);\n    if (!rsRandCursor) {\n        // The storage engine has no random cursor support.\n        return std::pair{nullptr, false};\n    }\n\n    // Build a MultiIteratorStage and pass it the random-sampling RecordCursor.\n    auto ws = std::make_unique();\n    std::unique_ptr root =\n        std::make_unique(expCtx.get(), ws.get(), coll);\n    static_cast(root.get())->addIterator(std::move(rsRandCursor));\n\n    // If the incoming operation is sharded, use the CSS to infer the filtering metadata for the\n    // collection, otherwise treat it as unsharded\n    auto collectionFilter =\n        CollectionShardingState::get(opCtx, coll->ns())\n            ->getOwnershipFilter(\n                opCtx, CollectionShardingState::OrphanCleanupPolicy::kDisallowOrphanCleanup);\n\n    TrialStage* trialStage = nullptr;\n\n    // Because 'numRecords' includes orphan documents, our initial decision to optimize the $sample\n    // cursor may have been mistaken. For sharded collections, build a TRIAL plan that will switch\n    // to a collection scan if the ratio of orphaned to owned documents encountered over the first\n    // 100 works() is such that we would have chosen not to optimize.\n    static const size_t kMaxPresampleSize = 100;\n    if (collectionFilter.isSharded() && !expCtx->ns.isTimeseriesBucketsCollection()) {\n        // The ratio of owned to orphaned documents must be at least equal to the ratio between the\n        // requested sampleSize and the maximum permitted sampleSize for the original constraints to\n        // be satisfied. For instance, if there are 200 documents and the sampleSize is 5, then at\n        // least (5 / (200*0.05)) = (5/10) = 50% of those documents must be owned. If less than 5%\n        // of the documents in the collection are owned, we default to the backup plan.\n        const auto minAdvancedToWorkRatio = std::max(\n            sampleSize / (numRecords * kMaxSampleRatioForRandCursor), kMaxSampleRatioForRandCursor);\n        // The trial plan is SHARDING_FILTER-MULTI_ITERATOR.\n        auto randomCursorPlan = std::make_unique(\n            expCtx.get(), collectionFilter, ws.get(), std::move(root));\n        // The backup plan is SHARDING_FILTER-COLLSCAN.\n        std::unique_ptr collScanPlan = std::make_unique(\n            expCtx.get(), coll, CollectionScanParams{}, ws.get(), nullptr);\n        collScanPlan = std::make_unique(\n            expCtx.get(), collectionFilter, ws.get(), std::move(collScanPlan));\n        // Place a TRIAL stage at the root of the plan tree, and pass it the trial and backup plans.\n        root = std::make_unique(expCtx.get(),\n                                            ws.get(),\n                                            std::move(randomCursorPlan),\n                                            std::move(collScanPlan),\n                                            kMaxPresampleSize,\n                                            minAdvancedToWorkRatio);\n        trialStage = static_cast(root.get());\n    } else if (expCtx->ns.isTimeseriesBucketsCollection()) {\n        // Use a 'TrialStage' to run a trial between 'SampleFromTimeseriesBucket' and\n        // 'UnpackTimeseriesBucket' with $sample left in the pipeline in-place. If the buckets are\n        // not sufficiently full, or the 'SampleFromTimeseriesBucket' plan draws too many\n        // duplicates, then we will fall back to the 'TrialStage' backup plan. This backup plan uses\n        // the top-k sort sampling approach.\n        //\n        // Suppose the 'gTimeseriesBucketMaxCount' is 1000, but each bucket only contains 500\n        // documents on average. The observed trial advanced/work ratio approximates the average\n        // bucket fullness, noted here as \"abf\". In this example, abf = 500 / 1000 = 0.5.\n        // Experiments have shown that the optimized 'SampleFromTimeseriesBucket' algorithm performs\n        // better than backup plan when\n        //\n        //     sampleSize < 0.02 * abf * numRecords * gTimeseriesBucketMaxCount\n        //\n        //  This inequality can be rewritten as\n        //\n        //     abf > sampleSize / (0.02 * numRecords * gTimeseriesBucketMaxCount)\n        //\n        // Therefore, if the advanced/work ratio exceeds this threshold, we will use the\n        // 'SampleFromTimeseriesBucket' plan. Note that as the sample size requested by the user\n        // becomes larger with respect to the number of buckets, we require a higher advanced/work\n        // ratio in order to justify using 'SampleFromTimeseriesBucket'.\n        //\n        // Additionally, we require the 'TrialStage' to approximate the abf as at least 0.25. When\n        // buckets are mostly empty, the 'SampleFromTimeseriesBucket' will be inefficient due to a\n        // lot of sampling \"misses\".\n        static const auto kCoefficient = 0.02;\n        static const auto kMinBucketFullness = 0.25;\n        const auto minAdvancedToWorkRatio = std::max(\n            std::min(sampleSize / (kCoefficient * numRecords * gTimeseriesBucketMaxCount), 1.0),\n            kMinBucketFullness);\n\n        auto arhashPlan = std::make_unique(\n            expCtx.get(),\n            ws.get(),\n            std::move(root),\n            *bucketUnpacker,\n            // By using a quantity slightly higher than 'kMaxPresampleSize', we ensure that the\n            // 'SampleFromTimeseriesBucket' stage won't fail due to too many consecutive sampling\n            // attempts during the 'TrialStage's trial period.\n            kMaxPresampleSize + 5,\n            sampleSize,\n            gTimeseriesBucketMaxCount);\n\n        std::unique_ptr collScanPlan = std::make_unique(\n            expCtx.get(), coll, CollectionScanParams{}, ws.get(), nullptr);\n\n        auto topkSortPlan = std::make_unique(\n            expCtx.get(), ws.get(), std::move(collScanPlan), *bucketUnpacker);\n\n        root = std::make_unique(expCtx.get(),\n                                            ws.get(),\n                                            std::move(arhashPlan),\n                                            std::move(topkSortPlan),\n                                            kMaxPresampleSize,\n                                            minAdvancedToWorkRatio);\n        trialStage = static_cast(root.get());\n    }\n\n    auto execStatus = plan_executor_factory::make(expCtx,\n                                                  std::move(ws),\n                                                  std::move(root),\n                                                  &coll,\n                                                  opCtx->inMultiDocumentTransaction()\n                                                      ? PlanYieldPolicy::YieldPolicy::INTERRUPT_ONLY\n                                                      : PlanYieldPolicy::YieldPolicy::YIELD_AUTO,\n                                                  QueryPlannerParams::RETURN_OWNED_DATA);\n    if (!execStatus.isOK()) {\n        return execStatus.getStatus();\n    }\n\n    // For sharded collections, the root of the plan tree is a TrialStage that may have chosen\n    // either a random-sampling cursor trial plan or a COLLSCAN backup plan. We can only optimize\n    // the $sample aggregation stage if the trial plan was chosen.\n    return std::pair{std::move(execStatus.getValue()),\n                     !trialStage || !trialStage->pickedBackupPlan()};\n}", "func_hash": 101223003381904306346527857489543984398, "file_name": "None", "file_hash": null, "cwe": ["CWE-617"], "cve": "CVE-2021-32037", "cve_desc": "An authorized user may trigger an invariant which may result in denial of service or server exit if a relevant aggregation request is sent to a shard. Usually, the requests are sent via mongos and special privileges are required in order to know the address of the shards and to log in to the shards of an auth enabled environment.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32037"}
{"idx": 483469, "project": "mongo", "commit_id": "a5e2f9b0a236462a6d1ca129583c617f111367b4", "project_url": "https://github.com/mongodb/mongo", "commit_url": "https://github.com/mongodb/mongo/commit/a5e2f9b0a236462a6d1ca129583c617f111367b4", "commit_message": "SERVER-59071 Treat '$sample' as unsharded when connecting directly to shards\n\n(cherry picked from commit f3604b901d688c194de5e430c7fbab060c9dc8e0)", "target": 0, "func": "createRandomCursorExecutor(const CollectionPtr& coll,\n                           const boost::intrusive_ptr& expCtx,\n                           long long sampleSize,\n                           long long numRecords,\n                           boost::optional bucketUnpacker) {\n    OperationContext* opCtx = expCtx->opCtx;\n\n    // Verify that we are already under a collection lock. We avoid taking locks ourselves in this\n    // function because double-locking forces any PlanExecutor we create to adopt a NO_YIELD policy.\n    invariant(opCtx->lockState()->isCollectionLockedForMode(coll->ns(), MODE_IS));\n\n    static const double kMaxSampleRatioForRandCursor = 0.05;\n    if (!expCtx->ns.isTimeseriesBucketsCollection()) {\n        if (sampleSize > numRecords * kMaxSampleRatioForRandCursor || numRecords <= 100) {\n            return std::pair{nullptr, false};\n        }\n    } else {\n        // Suppose that a time-series bucket collection is observed to contain 200 buckets, and the\n        // 'gTimeseriesBucketMaxCount' parameter is set to 1000. If all buckets are full, then the\n        // maximum possible measurment count would be 200 * 1000 = 200,000. While the\n        // 'SampleFromTimeseriesBucket' plan is more efficient when the sample size is small\n        // relative to the total number of measurements in the time-series collection, for larger\n        // sample sizes the top-k sort based sample is faster. Experiments have approximated that\n        // the tipping point is roughly when the requested sample size is greater than 1% of the\n        // maximum possible number of measurements in the collection (i.e. numBuckets *\n        // maxMeasurementsPerBucket).\n        static const double kCoefficient = 0.01;\n        if (sampleSize > kCoefficient * numRecords * gTimeseriesBucketMaxCount) {\n            return std::pair{nullptr, false};\n        }\n    }\n\n    // Attempt to get a random cursor from the RecordStore.\n    auto rsRandCursor = coll->getRecordStore()->getRandomCursor(opCtx);\n    if (!rsRandCursor) {\n        // The storage engine has no random cursor support.\n        return std::pair{nullptr, false};\n    }\n\n    // Build a MultiIteratorStage and pass it the random-sampling RecordCursor.\n    auto ws = std::make_unique();\n    std::unique_ptr root =\n        std::make_unique(expCtx.get(), ws.get(), coll);\n    static_cast(root.get())->addIterator(std::move(rsRandCursor));\n\n    TrialStage* trialStage = nullptr;\n\n    // Because 'numRecords' includes orphan documents, our initial decision to optimize the $sample\n    // cursor may have been mistaken. For sharded collections, build a TRIAL plan that will switch\n    // to a collection scan if the ratio of orphaned to owned documents encountered over the first\n    // 100 works() is such that we would have chosen not to optimize.\n    static const size_t kMaxPresampleSize = 100;\n    if (auto css = CollectionShardingState::get(opCtx, coll->ns());\n        css->getCollectionDescription(opCtx).isSharded() &&\n        !expCtx->ns.isTimeseriesBucketsCollection()) {\n        // The ratio of owned to orphaned documents must be at least equal to the ratio between the\n        // requested sampleSize and the maximum permitted sampleSize for the original constraints to\n        // be satisfied. For instance, if there are 200 documents and the sampleSize is 5, then at\n        // least (5 / (200*0.05)) = (5/10) = 50% of those documents must be owned. If less than 5%\n        // of the documents in the collection are owned, we default to the backup plan.\n        const auto minAdvancedToWorkRatio = std::max(\n            sampleSize / (numRecords * kMaxSampleRatioForRandCursor), kMaxSampleRatioForRandCursor);\n        // Since the incoming operation is sharded, use the CSS to infer the filtering metadata for\n        // the collection. We get the shard ownership filter after checking to see if the collection\n        // is sharded to avoid an invariant from being fired in this call.\n        auto collectionFilter = css->getOwnershipFilter(\n            opCtx, CollectionShardingState::OrphanCleanupPolicy::kDisallowOrphanCleanup);\n        // The trial plan is SHARDING_FILTER-MULTI_ITERATOR.\n        auto randomCursorPlan = std::make_unique(\n            expCtx.get(), collectionFilter, ws.get(), std::move(root));\n        // The backup plan is SHARDING_FILTER-COLLSCAN.\n        std::unique_ptr collScanPlan = std::make_unique(\n            expCtx.get(), coll, CollectionScanParams{}, ws.get(), nullptr);\n        collScanPlan = std::make_unique(\n            expCtx.get(), collectionFilter, ws.get(), std::move(collScanPlan));\n        // Place a TRIAL stage at the root of the plan tree, and pass it the trial and backup plans.\n        root = std::make_unique(expCtx.get(),\n                                            ws.get(),\n                                            std::move(randomCursorPlan),\n                                            std::move(collScanPlan),\n                                            kMaxPresampleSize,\n                                            minAdvancedToWorkRatio);\n        trialStage = static_cast(root.get());\n    } else if (expCtx->ns.isTimeseriesBucketsCollection()) {\n        // Use a 'TrialStage' to run a trial between 'SampleFromTimeseriesBucket' and\n        // 'UnpackTimeseriesBucket' with $sample left in the pipeline in-place. If the buckets are\n        // not sufficiently full, or the 'SampleFromTimeseriesBucket' plan draws too many\n        // duplicates, then we will fall back to the 'TrialStage' backup plan. This backup plan uses\n        // the top-k sort sampling approach.\n        //\n        // Suppose the 'gTimeseriesBucketMaxCount' is 1000, but each bucket only contains 500\n        // documents on average. The observed trial advanced/work ratio approximates the average\n        // bucket fullness, noted here as \"abf\". In this example, abf = 500 / 1000 = 0.5.\n        // Experiments have shown that the optimized 'SampleFromTimeseriesBucket' algorithm performs\n        // better than backup plan when\n        //\n        //     sampleSize < 0.02 * abf * numRecords * gTimeseriesBucketMaxCount\n        //\n        //  This inequality can be rewritten as\n        //\n        //     abf > sampleSize / (0.02 * numRecords * gTimeseriesBucketMaxCount)\n        //\n        // Therefore, if the advanced/work ratio exceeds this threshold, we will use the\n        // 'SampleFromTimeseriesBucket' plan. Note that as the sample size requested by the user\n        // becomes larger with respect to the number of buckets, we require a higher advanced/work\n        // ratio in order to justify using 'SampleFromTimeseriesBucket'.\n        //\n        // Additionally, we require the 'TrialStage' to approximate the abf as at least 0.25. When\n        // buckets are mostly empty, the 'SampleFromTimeseriesBucket' will be inefficient due to a\n        // lot of sampling \"misses\".\n        static const auto kCoefficient = 0.02;\n        static const auto kMinBucketFullness = 0.25;\n        const auto minAdvancedToWorkRatio = std::max(\n            std::min(sampleSize / (kCoefficient * numRecords * gTimeseriesBucketMaxCount), 1.0),\n            kMinBucketFullness);\n\n        auto arhashPlan = std::make_unique(\n            expCtx.get(),\n            ws.get(),\n            std::move(root),\n            *bucketUnpacker,\n            // By using a quantity slightly higher than 'kMaxPresampleSize', we ensure that the\n            // 'SampleFromTimeseriesBucket' stage won't fail due to too many consecutive sampling\n            // attempts during the 'TrialStage's trial period.\n            kMaxPresampleSize + 5,\n            sampleSize,\n            gTimeseriesBucketMaxCount);\n\n        std::unique_ptr collScanPlan = std::make_unique(\n            expCtx.get(), coll, CollectionScanParams{}, ws.get(), nullptr);\n\n        auto topkSortPlan = std::make_unique(\n            expCtx.get(), ws.get(), std::move(collScanPlan), *bucketUnpacker);\n\n        root = std::make_unique(expCtx.get(),\n                                            ws.get(),\n                                            std::move(arhashPlan),\n                                            std::move(topkSortPlan),\n                                            kMaxPresampleSize,\n                                            minAdvancedToWorkRatio);\n        trialStage = static_cast(root.get());\n    }\n\n    auto execStatus = plan_executor_factory::make(expCtx,\n                                                  std::move(ws),\n                                                  std::move(root),\n                                                  &coll,\n                                                  opCtx->inMultiDocumentTransaction()\n                                                      ? PlanYieldPolicy::YieldPolicy::INTERRUPT_ONLY\n                                                      : PlanYieldPolicy::YieldPolicy::YIELD_AUTO,\n                                                  QueryPlannerParams::RETURN_OWNED_DATA);\n    if (!execStatus.isOK()) {\n        return execStatus.getStatus();\n    }\n\n    // For sharded collections, the root of the plan tree is a TrialStage that may have chosen\n    // either a random-sampling cursor trial plan or a COLLSCAN backup plan. We can only optimize\n    // the $sample aggregation stage if the trial plan was chosen.\n    return std::pair{std::move(execStatus.getValue()),\n                     !trialStage || !trialStage->pickedBackupPlan()};\n}", "func_hash": 53510909926140160570175197476495085795, "file_name": "None", "file_hash": null, "cwe": ["CWE-617"], "cve": "CVE-2021-32037", "cve_desc": "An authorized user may trigger an invariant which may result in denial of service or server exit if a relevant aggregation request is sent to a shard. Usually, the requests are sent via mongos and special privileges are required in order to know the address of the shards and to log in to the shards of an auth enabled environment.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32037"}
{"idx": 215142, "project": "open62541", "commit_id": "b79db1ac78146fc06b0b8435773d3967de2d659c", "project_url": "https://github.com/open62541/open62541", "commit_url": "https://github.com/open62541/open62541/commit/b79db1ac78146fc06b0b8435773d3967de2d659c", "commit_message": "fix(plugin): Add default limits for chunks and message size\n\nBased on a reported DoS vulnerability reported by Team82 (Claroty\nResearch).", "target": 1, "func": "setup_secureChannel(void) {\n    TestingPolicy(&dummyPolicy, dummyCertificate, &fCalled, &keySizes);\n    UA_SecureChannel_init(&testChannel, &UA_ConnectionConfig_default);\n    UA_SecureChannel_setSecurityPolicy(&testChannel, &dummyPolicy, &dummyCertificate);\n\n    testingConnection = createDummyConnection(65535, &sentData);\n    UA_Connection_attachSecureChannel(&testingConnection, &testChannel);\n    testChannel.connection = &testingConnection;\n\n    testChannel.state = UA_SECURECHANNELSTATE_OPEN;\n}", "func_hash": 129373646789395132978577350520275897854, "file_name": "check_securechannel.c", "file_hash": 237191463744761061393465477757063019069, "cwe": ["CWE-703"], "cve": "CVE-2022-25761", "cve_desc": "The package open62541/open62541 before 1.2.5, from 1.3-rc1 and before 1.3.1 are vulnerable to Denial of Service (DoS) due to a missing limitation on the number of received chunks - per single session or in total for all concurrent sessions. An attacker can exploit this vulnerability by sending an unlimited number of huge chunks (e.g. 2GB each) without sending the Final closing chunk.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-25761"}
{"idx": 484063, "project": "open62541", "commit_id": "b79db1ac78146fc06b0b8435773d3967de2d659c", "project_url": "https://github.com/open62541/open62541", "commit_url": "https://github.com/open62541/open62541/commit/b79db1ac78146fc06b0b8435773d3967de2d659c", "commit_message": "fix(plugin): Add default limits for chunks and message size\n\nBased on a reported DoS vulnerability reported by Team82 (Claroty\nResearch).", "target": 0, "func": "setup_secureChannel(void) {\n    TestingPolicy(&dummyPolicy, dummyCertificate, &fCalled, &keySizes);\n    UA_SecureChannel_init(&testChannel, &UA_ConnectionConfig_default);\n    UA_SecureChannel_setSecurityPolicy(&testChannel, &dummyPolicy, &dummyCertificate);\n\n    testingConnection =\n        createDummyConnection(UA_ConnectionConfig_default.sendBufferSize, &sentData);\n    UA_Connection_attachSecureChannel(&testingConnection, &testChannel);\n    testChannel.connection = &testingConnection;\n\n    testChannel.state = UA_SECURECHANNELSTATE_OPEN;\n}", "func_hash": 210099699353094700409954983864057205013, "file_name": "check_securechannel.c", "file_hash": 317936293844889222163489724834611177083, "cwe": ["CWE-703"], "cve": "CVE-2022-25761", "cve_desc": "The package open62541/open62541 before 1.2.5, from 1.3-rc1 and before 1.3.1 are vulnerable to Denial of Service (DoS) due to a missing limitation on the number of received chunks - per single session or in total for all concurrent sessions. An attacker can exploit this vulnerability by sending an unlimited number of huge chunks (e.g. 2GB each) without sending the Final closing chunk.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-25761"}
{"idx": 215188, "project": "libmobi", "commit_id": "ab5bf0e37e540eac682a14e628853b918626e72b", "project_url": "https://github.com/bfabiszewski/libmobi", "commit_url": "https://github.com/bfabiszewski/libmobi/commit/ab5bf0e37e540eac682a14e628853b918626e72b", "commit_message": "fix oob write bug inside libmobi", "target": 1, "func": "void mobi_buffer_move(MOBIBuffer *buf, const int offset, const size_t len) {\n    size_t aoffset = (size_t) abs(offset);\n    unsigned char *source = buf->data + buf->offset;\n    if (offset >= 0) {\n        if (buf->offset + aoffset + len > buf->maxlen) {\n            debug_print(\"%s\", \"End of buffer\\n\");\n            buf->error = MOBI_BUFFER_END;\n            return;\n        }\n        source += aoffset;\n    } else {\n        if (buf->offset < aoffset) {\n            debug_print(\"%s\", \"End of buffer\\n\");\n            buf->error = MOBI_BUFFER_END;\n            return;\n        }\n        source -= aoffset;\n    }\n    memmove(buf->data + buf->offset, source, len);\n    buf->offset += len;\n}", "func_hash": 63463081562925737105123134404328274929, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2021-3751", "cve_desc": "libmobi is vulnerable to Out-of-bounds Write", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3751"}
{"idx": 484732, "project": "libmobi", "commit_id": "ab5bf0e37e540eac682a14e628853b918626e72b", "project_url": "https://github.com/bfabiszewski/libmobi", "commit_url": "https://github.com/bfabiszewski/libmobi/commit/ab5bf0e37e540eac682a14e628853b918626e72b", "commit_message": "fix oob write bug inside libmobi", "target": 0, "func": "void mobi_buffer_move(MOBIBuffer *buf, const int offset, const size_t len) {\n    size_t aoffset = (size_t) abs(offset);\n    unsigned char *source = buf->data + buf->offset;\n    if (offset >= 0) {\n        if (buf->offset + aoffset + len > buf->maxlen) {\n            debug_print(\"%s\", \"End of buffer\\n\");\n            buf->error = MOBI_BUFFER_END;\n            return;\n        }\n        source += aoffset;\n    } else {\n        if ( (buf->offset < aoffset) || (buf->offset + len > buf->maxlen) ) {\n            debug_print(\"%s\", \"Beyond start/end of buffer\\n\");\n            buf->error = MOBI_BUFFER_END;\n            return;\n        }\n        source -= aoffset;\n    }\n    memmove(buf->data + buf->offset, source, len);\n    buf->offset += len;\n}", "func_hash": 144002101291977125414572650343381313849, "file_name": "None", "file_hash": null, "cwe": ["CWE-787"], "cve": "CVE-2021-3751", "cve_desc": "libmobi is vulnerable to Out-of-bounds Write", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3751"}
{"idx": 215262, "project": "qemu", "commit_id": "e73adfbeec9d4e008630c814759052ed945c3fed", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://git.qemu.org/?p=qemu.git;a=commit;h=e73adfbeec9d4e008630c814759052ed945c3fed", "commit_message": "cadence_gem: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Alexander Bulekov \nSigned-off-by: Jason Wang ", "target": 1, "func": "static void gem_transmit(CadenceGEMState *s)\n{\n    uint32_t desc[DESC_MAX_NUM_WORDS];\n    hwaddr packet_desc_addr;\n    uint8_t     *p;\n    unsigned    total_bytes;\n    int q = 0;\n\n    /* Do nothing if transmit is not enabled. */\n    if (!(s->regs[GEM_NWCTRL] & GEM_NWCTRL_TXENA)) {\n        return;\n    }\n\n    DB_PRINT(\"\\n\");\n\n    /* The packet we will hand off to QEMU.\n     * Packets scattered across multiple descriptors are gathered to this\n     * one contiguous buffer first.\n     */\n    p = s->tx_packet;\n    total_bytes = 0;\n\n    for (q = s->num_priority_queues - 1; q >= 0; q--) {\n        /* read current descriptor */\n        packet_desc_addr = gem_get_tx_desc_addr(s, q);\n\n        DB_PRINT(\"read descriptor 0x%\" HWADDR_PRIx \"\\n\", packet_desc_addr);\n        address_space_read(&s->dma_as, packet_desc_addr,\n                           MEMTXATTRS_UNSPECIFIED, desc,\n                           sizeof(uint32_t) * gem_get_desc_len(s, false));\n        /* Handle all descriptors owned by hardware */\n        while (tx_desc_get_used(desc) == 0) {\n\n            /* Do nothing if transmit is not enabled. */\n            if (!(s->regs[GEM_NWCTRL] & GEM_NWCTRL_TXENA)) {\n                return;\n            }\n            print_gem_tx_desc(desc, q);\n\n            /* The real hardware would eat this (and possibly crash).\n             * For QEMU let's lend a helping hand.\n             */\n            if ((tx_desc_get_buffer(s, desc) == 0) ||\n                (tx_desc_get_length(desc) == 0)) {\n                DB_PRINT(\"Invalid TX descriptor @ 0x%\" HWADDR_PRIx \"\\n\",\n                         packet_desc_addr);\n                break;\n            }\n\n            if (tx_desc_get_length(desc) > gem_get_max_buf_len(s, true) -\n                                               (p - s->tx_packet)) {\n                qemu_log_mask(LOG_GUEST_ERROR, \"TX descriptor @ 0x%\" \\\n                         HWADDR_PRIx \" too large: size 0x%x space 0x%zx\\n\",\n                         packet_desc_addr, tx_desc_get_length(desc),\n                         gem_get_max_buf_len(s, true) - (p - s->tx_packet));\n                gem_set_isr(s, q, GEM_INT_AMBA_ERR);\n                break;\n            }\n\n            /* Gather this fragment of the packet from \"dma memory\" to our\n             * contig buffer.\n             */\n            address_space_read(&s->dma_as, tx_desc_get_buffer(s, desc),\n                               MEMTXATTRS_UNSPECIFIED,\n                               p, tx_desc_get_length(desc));\n            p += tx_desc_get_length(desc);\n            total_bytes += tx_desc_get_length(desc);\n\n            /* Last descriptor for this packet; hand the whole thing off */\n            if (tx_desc_get_last(desc)) {\n                uint32_t desc_first[DESC_MAX_NUM_WORDS];\n                hwaddr desc_addr = gem_get_tx_desc_addr(s, q);\n\n                /* Modify the 1st descriptor of this packet to be owned by\n                 * the processor.\n                 */\n                address_space_read(&s->dma_as, desc_addr,\n                                   MEMTXATTRS_UNSPECIFIED, desc_first,\n                                   sizeof(desc_first));\n                tx_desc_set_used(desc_first);\n                address_space_write(&s->dma_as, desc_addr,\n                                    MEMTXATTRS_UNSPECIFIED, desc_first,\n                                    sizeof(desc_first));\n                /* Advance the hardware current descriptor past this packet */\n                if (tx_desc_get_wrap(desc)) {\n                    s->tx_desc_addr[q] = gem_get_tx_queue_base_addr(s, q);\n                } else {\n                    s->tx_desc_addr[q] = packet_desc_addr +\n                                         4 * gem_get_desc_len(s, false);\n                }\n                DB_PRINT(\"TX descriptor next: 0x%08x\\n\", s->tx_desc_addr[q]);\n\n                s->regs[GEM_TXSTATUS] |= GEM_TXSTATUS_TXCMPL;\n                gem_set_isr(s, q, GEM_INT_TXCMPL);\n\n                /* Handle interrupt consequences */\n                gem_update_int_status(s);\n\n                /* Is checksum offload enabled? */\n                if (s->regs[GEM_DMACFG] & GEM_DMACFG_TXCSUM_OFFL) {\n                    net_checksum_calculate(s->tx_packet, total_bytes, CSUM_ALL);\n                }\n\n                /* Update MAC statistics */\n                gem_transmit_updatestats(s, s->tx_packet, total_bytes);\n\n                /* Send the packet somewhere */\n                if (s->phy_loop || (s->regs[GEM_NWCTRL] &\n                                    GEM_NWCTRL_LOCALLOOP)) {\n                    gem_receive(qemu_get_queue(s->nic), s->tx_packet,\n                                total_bytes);\n                } else {\n                    qemu_send_packet(qemu_get_queue(s->nic), s->tx_packet,\n                                     total_bytes);\n                }\n\n                /* Prepare for next packet */\n                p = s->tx_packet;\n                total_bytes = 0;\n            }\n\n            /* read next descriptor */\n            if (tx_desc_get_wrap(desc)) {\n\n                if (s->regs[GEM_DMACFG] & GEM_DMACFG_ADDR_64B) {\n                    packet_desc_addr = s->regs[GEM_TBQPH];\n                    packet_desc_addr <<= 32;\n                } else {\n                    packet_desc_addr = 0;\n                }\n                packet_desc_addr |= gem_get_tx_queue_base_addr(s, q);\n            } else {\n                packet_desc_addr += 4 * gem_get_desc_len(s, false);\n            }\n            DB_PRINT(\"read descriptor 0x%\" HWADDR_PRIx \"\\n\", packet_desc_addr);\n            address_space_read(&s->dma_as, packet_desc_addr,\n                               MEMTXATTRS_UNSPECIFIED, desc,\n                               sizeof(uint32_t) * gem_get_desc_len(s, false));\n        }\n\n        if (tx_desc_get_used(desc)) {\n            s->regs[GEM_TXSTATUS] |= GEM_TXSTATUS_USED;\n            /* IRQ TXUSED is defined only for queue 0 */\n            if (q == 0) {\n                gem_set_isr(s, 0, GEM_INT_TXUSED);\n            }\n            gem_update_int_status(s);\n        }\n    }\n}", "func_hash": 96949803014582607595727068395060090256, "file_name": "cadence_gem.c", "file_hash": 142576312399333534516163795241152257631, "cwe": ["CWE-835"], "cve": "CVE-2021-3416", "cve_desc": "A potential stack overflow via infinite loop issue was found in various NIC emulators of QEMU in versions up to and including 5.2.0. The issue occurs in loopback mode of a NIC wherein reentrant DMA checks get bypassed. A guest user/process may use this flaw to consume CPU cycles or crash the QEMU process on the host resulting in DoS scenario.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3416"}
{"idx": 486796, "project": "qemu", "commit_id": "e73adfbeec9d4e008630c814759052ed945c3fed", "project_url": "https://github.com/bonzini/qemu", "commit_url": "https://git.qemu.org/?p=qemu.git;a=commit;h=e73adfbeec9d4e008630c814759052ed945c3fed", "commit_message": "cadence_gem: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Alexander Bulekov \nSigned-off-by: Jason Wang ", "target": 0, "func": "static void gem_transmit(CadenceGEMState *s)\n{\n    uint32_t desc[DESC_MAX_NUM_WORDS];\n    hwaddr packet_desc_addr;\n    uint8_t     *p;\n    unsigned    total_bytes;\n    int q = 0;\n\n    /* Do nothing if transmit is not enabled. */\n    if (!(s->regs[GEM_NWCTRL] & GEM_NWCTRL_TXENA)) {\n        return;\n    }\n\n    DB_PRINT(\"\\n\");\n\n    /* The packet we will hand off to QEMU.\n     * Packets scattered across multiple descriptors are gathered to this\n     * one contiguous buffer first.\n     */\n    p = s->tx_packet;\n    total_bytes = 0;\n\n    for (q = s->num_priority_queues - 1; q >= 0; q--) {\n        /* read current descriptor */\n        packet_desc_addr = gem_get_tx_desc_addr(s, q);\n\n        DB_PRINT(\"read descriptor 0x%\" HWADDR_PRIx \"\\n\", packet_desc_addr);\n        address_space_read(&s->dma_as, packet_desc_addr,\n                           MEMTXATTRS_UNSPECIFIED, desc,\n                           sizeof(uint32_t) * gem_get_desc_len(s, false));\n        /* Handle all descriptors owned by hardware */\n        while (tx_desc_get_used(desc) == 0) {\n\n            /* Do nothing if transmit is not enabled. */\n            if (!(s->regs[GEM_NWCTRL] & GEM_NWCTRL_TXENA)) {\n                return;\n            }\n            print_gem_tx_desc(desc, q);\n\n            /* The real hardware would eat this (and possibly crash).\n             * For QEMU let's lend a helping hand.\n             */\n            if ((tx_desc_get_buffer(s, desc) == 0) ||\n                (tx_desc_get_length(desc) == 0)) {\n                DB_PRINT(\"Invalid TX descriptor @ 0x%\" HWADDR_PRIx \"\\n\",\n                         packet_desc_addr);\n                break;\n            }\n\n            if (tx_desc_get_length(desc) > gem_get_max_buf_len(s, true) -\n                                               (p - s->tx_packet)) {\n                qemu_log_mask(LOG_GUEST_ERROR, \"TX descriptor @ 0x%\" \\\n                         HWADDR_PRIx \" too large: size 0x%x space 0x%zx\\n\",\n                         packet_desc_addr, tx_desc_get_length(desc),\n                         gem_get_max_buf_len(s, true) - (p - s->tx_packet));\n                gem_set_isr(s, q, GEM_INT_AMBA_ERR);\n                break;\n            }\n\n            /* Gather this fragment of the packet from \"dma memory\" to our\n             * contig buffer.\n             */\n            address_space_read(&s->dma_as, tx_desc_get_buffer(s, desc),\n                               MEMTXATTRS_UNSPECIFIED,\n                               p, tx_desc_get_length(desc));\n            p += tx_desc_get_length(desc);\n            total_bytes += tx_desc_get_length(desc);\n\n            /* Last descriptor for this packet; hand the whole thing off */\n            if (tx_desc_get_last(desc)) {\n                uint32_t desc_first[DESC_MAX_NUM_WORDS];\n                hwaddr desc_addr = gem_get_tx_desc_addr(s, q);\n\n                /* Modify the 1st descriptor of this packet to be owned by\n                 * the processor.\n                 */\n                address_space_read(&s->dma_as, desc_addr,\n                                   MEMTXATTRS_UNSPECIFIED, desc_first,\n                                   sizeof(desc_first));\n                tx_desc_set_used(desc_first);\n                address_space_write(&s->dma_as, desc_addr,\n                                    MEMTXATTRS_UNSPECIFIED, desc_first,\n                                    sizeof(desc_first));\n                /* Advance the hardware current descriptor past this packet */\n                if (tx_desc_get_wrap(desc)) {\n                    s->tx_desc_addr[q] = gem_get_tx_queue_base_addr(s, q);\n                } else {\n                    s->tx_desc_addr[q] = packet_desc_addr +\n                                         4 * gem_get_desc_len(s, false);\n                }\n                DB_PRINT(\"TX descriptor next: 0x%08x\\n\", s->tx_desc_addr[q]);\n\n                s->regs[GEM_TXSTATUS] |= GEM_TXSTATUS_TXCMPL;\n                gem_set_isr(s, q, GEM_INT_TXCMPL);\n\n                /* Handle interrupt consequences */\n                gem_update_int_status(s);\n\n                /* Is checksum offload enabled? */\n                if (s->regs[GEM_DMACFG] & GEM_DMACFG_TXCSUM_OFFL) {\n                    net_checksum_calculate(s->tx_packet, total_bytes, CSUM_ALL);\n                }\n\n                /* Update MAC statistics */\n                gem_transmit_updatestats(s, s->tx_packet, total_bytes);\n\n                /* Send the packet somewhere */\n                if (s->phy_loop || (s->regs[GEM_NWCTRL] &\n                                    GEM_NWCTRL_LOCALLOOP)) {\n                    qemu_receive_packet(qemu_get_queue(s->nic), s->tx_packet,\n                                        total_bytes);\n                } else {\n                    qemu_send_packet(qemu_get_queue(s->nic), s->tx_packet,\n                                     total_bytes);\n                }\n\n                /* Prepare for next packet */\n                p = s->tx_packet;\n                total_bytes = 0;\n            }\n\n            /* read next descriptor */\n            if (tx_desc_get_wrap(desc)) {\n\n                if (s->regs[GEM_DMACFG] & GEM_DMACFG_ADDR_64B) {\n                    packet_desc_addr = s->regs[GEM_TBQPH];\n                    packet_desc_addr <<= 32;\n                } else {\n                    packet_desc_addr = 0;\n                }\n                packet_desc_addr |= gem_get_tx_queue_base_addr(s, q);\n            } else {\n                packet_desc_addr += 4 * gem_get_desc_len(s, false);\n            }\n            DB_PRINT(\"read descriptor 0x%\" HWADDR_PRIx \"\\n\", packet_desc_addr);\n            address_space_read(&s->dma_as, packet_desc_addr,\n                               MEMTXATTRS_UNSPECIFIED, desc,\n                               sizeof(uint32_t) * gem_get_desc_len(s, false));\n        }\n\n        if (tx_desc_get_used(desc)) {\n            s->regs[GEM_TXSTATUS] |= GEM_TXSTATUS_USED;\n            /* IRQ TXUSED is defined only for queue 0 */\n            if (q == 0) {\n                gem_set_isr(s, 0, GEM_INT_TXUSED);\n            }\n            gem_update_int_status(s);\n        }\n    }\n}", "func_hash": 333706942896596885696237067919896756767, "file_name": "cadence_gem.c", "file_hash": 35811516595388673046749961470018191104, "cwe": ["CWE-835"], "cve": "CVE-2021-3416", "cve_desc": "A potential stack overflow via infinite loop issue was found in various NIC emulators of QEMU in versions up to and including 5.2.0. The issue occurs in loopback mode of a NIC wherein reentrant DMA checks get bypassed. A guest user/process may use this flaw to consume CPU cycles or crash the QEMU process on the host resulting in DoS scenario.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3416"}
{"idx": 215264, "project": "perl5", "commit_id": "66bbb51b93253a3f87d11c2695cfb7bdb782184a", "project_url": "https://github.com/perl/perl5", "commit_url": "https://github.com/perl/perl5/commit/66bbb51b93253a3f87d11c2695cfb7bdb782184a", "commit_message": "study_chunk: avoid mutating regexp program within GOSUB\n\ngh16947 and gh17743: studying GOSUB may restudy in an inner call\n(via a mix of recursion and enframing) something that an outer call\nis in the middle of looking at.  Let the outer frame deal with it.\n\n(CVE-2020-12723)\n\n(cherry picked from commit c4033e740bd18d9fbe3456a9db2ec2053cdc5271)", "target": 1, "func": "STATIC SSize_t\nS_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,\n                        SSize_t *minlenp, SSize_t *deltap,\n\t\t\tregnode *last,\n\t\t\tscan_data_t *data,\n\t\t\tI32 stopparen,\n                        U32 recursed_depth,\n\t\t\tregnode_ssc *and_withp,\n\t\t\tU32 flags, U32 depth)\n\t\t\t/* scanp: Start here (read-write). */\n\t\t\t/* deltap: Write maxlen-minlen here. */\n\t\t\t/* last: Stop before this one. */\n\t\t\t/* data: string data about the pattern */\n\t\t\t/* stopparen: treat close N as END */\n\t\t\t/* recursed: which subroutines have we recursed into */\n\t\t\t/* and_withp: Valid if flags & SCF_DO_STCLASS_OR */\n{\n    dVAR;\n    /* There must be at least this number of characters to match */\n    SSize_t min = 0;\n    I32 pars = 0, code;\n    regnode *scan = *scanp, *next;\n    SSize_t delta = 0;\n    int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);\n    int is_inf_internal = 0;\t\t/* The studied chunk is infinite */\n    I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;\n    scan_data_t data_fake;\n    SV *re_trie_maxbuff = NULL;\n    regnode *first_non_open = scan;\n    SSize_t stopmin = SSize_t_MAX;\n    scan_frame *frame = NULL;\n    GET_RE_DEBUG_FLAGS_DECL;\n\n    PERL_ARGS_ASSERT_STUDY_CHUNK;\n    RExC_study_started= 1;\n\n    Zero(&data_fake, 1, scan_data_t);\n\n    if ( depth == 0 ) {\n        while (first_non_open && OP(first_non_open) == OPEN)\n            first_non_open=regnext(first_non_open);\n    }\n\n\n  fake_study_recurse:\n    DEBUG_r(\n        RExC_study_chunk_recursed_count++;\n    );\n    DEBUG_OPTIMISE_MORE_r(\n    {\n        Perl_re_indentf( aTHX_  \"study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p\",\n            depth, (long)stopparen,\n            (unsigned long)RExC_study_chunk_recursed_count,\n            (unsigned long)depth, (unsigned long)recursed_depth,\n            scan,\n            last);\n        if (recursed_depth) {\n            U32 i;\n            U32 j;\n            for ( j = 0 ; j < recursed_depth ; j++ ) {\n                for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {\n                    if (\n                        PAREN_TEST(RExC_study_chunk_recursed +\n                                   ( j * RExC_study_chunk_recursed_bytes), i )\n                        && (\n                            !j ||\n                            !PAREN_TEST(RExC_study_chunk_recursed +\n                                   (( j - 1 ) * RExC_study_chunk_recursed_bytes), i)\n                        )\n                    ) {\n                        Perl_re_printf( aTHX_ \" %d\",(int)i);\n                        break;\n                    }\n                }\n                if ( j + 1 < recursed_depth ) {\n                    Perl_re_printf( aTHX_  \",\");\n                }\n            }\n        }\n        Perl_re_printf( aTHX_ \"\\n\");\n    }\n    );\n    while ( scan && OP(scan) != END && scan < last ){\n        UV min_subtract = 0;    /* How mmany chars to subtract from the minimum\n                                   node length to get a real minimum (because\n                                   the folded version may be shorter) */\n\tbool unfolded_multi_char = FALSE;\n\t/* Peephole optimizer: */\n        DEBUG_STUDYDATA(\"Peep\", data, depth, is_inf);\n        DEBUG_PEEP(\"Peep\", scan, depth, flags);\n\n\n        /* The reason we do this here is that we need to deal with things like\n         * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT\n         * parsing code, as each (?:..) is handled by a different invocation of\n         * reg() -- Yves\n         */\n        JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);\n\n        /* Follow the next-chain of the current node and optimize\n           away all the NOTHINGs from it.\n         */\n        rck_elide_nothing(scan);\n\n\t/* The principal pseudo-switch.  Cannot be a switch, since we\n\t   look into several different things.  */\n        if ( OP(scan) == DEFINEP ) {\n            SSize_t minlen = 0;\n            SSize_t deltanext = 0;\n            SSize_t fake_last_close = 0;\n            I32 f = SCF_IN_DEFINE;\n\n            StructCopy(&zero_scan_data, &data_fake, scan_data_t);\n            scan = regnext(scan);\n            assert( OP(scan) == IFTHEN );\n            DEBUG_PEEP(\"expect IFTHEN\", scan, depth, flags);\n\n            data_fake.last_closep= &fake_last_close;\n            minlen = *minlenp;\n            next = regnext(scan);\n            scan = NEXTOPER(NEXTOPER(scan));\n            DEBUG_PEEP(\"scan\", scan, depth, flags);\n            DEBUG_PEEP(\"next\", next, depth, flags);\n\n            /* we suppose the run is continuous, last=next...\n             * NOTE we dont use the return here! */\n            /* DEFINEP study_chunk() recursion */\n            (void)study_chunk(pRExC_state, &scan, &minlen,\n                              &deltanext, next, &data_fake, stopparen,\n                              recursed_depth, NULL, f, depth+1);\n\n            scan = next;\n        } else\n        if (\n            OP(scan) == BRANCH  ||\n            OP(scan) == BRANCHJ ||\n            OP(scan) == IFTHEN\n        ) {\n\t    next = regnext(scan);\n\t    code = OP(scan);\n\n            /* The op(next)==code check below is to see if we\n             * have \"BRANCH-BRANCH\", \"BRANCHJ-BRANCHJ\", \"IFTHEN-IFTHEN\"\n             * IFTHEN is special as it might not appear in pairs.\n             * Not sure whether BRANCH-BRANCHJ is possible, regardless\n             * we dont handle it cleanly. */\n\t    if (OP(next) == code || code == IFTHEN) {\n                /* NOTE - There is similar code to this block below for\n                 * handling TRIE nodes on a re-study.  If you change stuff here\n                 * check there too. */\n\t\tSSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;\n\t\tregnode_ssc accum;\n\t\tregnode * const startbranch=scan;\n\n                if (flags & SCF_DO_SUBSTR) {\n                    /* Cannot merge strings after this. */\n                    scan_commit(pRExC_state, data, minlenp, is_inf);\n                }\n\n                if (flags & SCF_DO_STCLASS)\n\t\t    ssc_init_zero(pRExC_state, &accum);\n\n\t\twhile (OP(scan) == code) {\n\t\t    SSize_t deltanext, minnext, fake;\n\t\t    I32 f = 0;\n\t\t    regnode_ssc this_class;\n\n                    DEBUG_PEEP(\"Branch\", scan, depth, flags);\n\n\t\t    num++;\n                    StructCopy(&zero_scan_data, &data_fake, scan_data_t);\n\t\t    if (data) {\n\t\t\tdata_fake.whilem_c = data->whilem_c;\n\t\t\tdata_fake.last_closep = data->last_closep;\n\t\t    }\n\t\t    else\n\t\t\tdata_fake.last_closep = &fake;\n\n\t\t    data_fake.pos_delta = delta;\n\t\t    next = regnext(scan);\n\n                    scan = NEXTOPER(scan); /* everything */\n                    if (code != BRANCH)    /* everything but BRANCH */\n\t\t\tscan = NEXTOPER(scan);\n\n\t\t    if (flags & SCF_DO_STCLASS) {\n\t\t\tssc_init(pRExC_state, &this_class);\n\t\t\tdata_fake.start_class = &this_class;\n\t\t\tf = SCF_DO_STCLASS_AND;\n\t\t    }\n\t\t    if (flags & SCF_WHILEM_VISITED_POS)\n\t\t\tf |= SCF_WHILEM_VISITED_POS;\n\n\t\t    /* we suppose the run is continuous, last=next...*/\n                    /* recurse study_chunk() for each BRANCH in an alternation */\n\t\t    minnext = study_chunk(pRExC_state, &scan, minlenp,\n                                      &deltanext, next, &data_fake, stopparen,\n                                      recursed_depth, NULL, f, depth+1);\n\n\t\t    if (min1 > minnext)\n\t\t\tmin1 = minnext;\n\t\t    if (deltanext == SSize_t_MAX) {\n\t\t\tis_inf = is_inf_internal = 1;\n\t\t\tmax1 = SSize_t_MAX;\n\t\t    } else if (max1 < minnext + deltanext)\n\t\t\tmax1 = minnext + deltanext;\n\t\t    scan = next;\n\t\t    if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))\n\t\t\tpars++;\n\t            if (data_fake.flags & SCF_SEEN_ACCEPT) {\n\t                if ( stopmin > minnext)\n\t                    stopmin = min + min1;\n\t                flags &= ~SCF_DO_SUBSTR;\n\t                if (data)\n\t                    data->flags |= SCF_SEEN_ACCEPT;\n\t            }\n\t\t    if (data) {\n\t\t\tif (data_fake.flags & SF_HAS_EVAL)\n\t\t\t    data->flags |= SF_HAS_EVAL;\n\t\t\tdata->whilem_c = data_fake.whilem_c;\n\t\t    }\n\t\t    if (flags & SCF_DO_STCLASS)\n\t\t\tssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);\n\t\t}\n\t\tif (code == IFTHEN && num < 2) /* Empty ELSE branch */\n\t\t    min1 = 0;\n\t\tif (flags & SCF_DO_SUBSTR) {\n\t\t    data->pos_min += min1;\n\t\t    if (data->pos_delta >= SSize_t_MAX - (max1 - min1))\n\t\t        data->pos_delta = SSize_t_MAX;\n\t\t    else\n\t\t        data->pos_delta += max1 - min1;\n\t\t    if (max1 != min1 || is_inf)\n\t\t\tdata->cur_is_floating = 1;\n\t\t}\n\t\tmin += min1;\n\t\tif (delta == SSize_t_MAX\n\t\t || SSize_t_MAX - delta - (max1 - min1) < 0)\n\t\t    delta = SSize_t_MAX;\n\t\telse\n\t\t    delta += max1 - min1;\n\t\tif (flags & SCF_DO_STCLASS_OR) {\n\t\t    ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);\n\t\t    if (min1) {\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\t\t\tflags &= ~SCF_DO_STCLASS;\n\t\t    }\n\t\t}\n\t\telse if (flags & SCF_DO_STCLASS_AND) {\n\t\t    if (min1) {\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);\n\t\t\tflags &= ~SCF_DO_STCLASS;\n\t\t    }\n\t\t    else {\n\t\t\t/* Switch to OR mode: cache the old value of\n\t\t\t * data->start_class */\n\t\t\tINIT_AND_WITHP;\n\t\t\tStructCopy(data->start_class, and_withp, regnode_ssc);\n\t\t\tflags &= ~SCF_DO_STCLASS_AND;\n\t\t\tStructCopy(&accum, data->start_class, regnode_ssc);\n\t\t\tflags |= SCF_DO_STCLASS_OR;\n\t\t    }\n\t\t}\n\n                if (PERL_ENABLE_TRIE_OPTIMISATION &&\n                        OP( startbranch ) == BRANCH )\n                {\n\t\t/* demq.\n\n                   Assuming this was/is a branch we are dealing with: 'scan'\n                   now points at the item that follows the branch sequence,\n                   whatever it is. We now start at the beginning of the\n                   sequence and look for subsequences of\n\n\t\t   BRANCH->EXACT=>x1\n\t\t   BRANCH->EXACT=>x2\n\t\t   tail\n\n                   which would be constructed from a pattern like\n                   /A|LIST|OF|WORDS/\n\n\t\t   If we can find such a subsequence we need to turn the first\n\t\t   element into a trie and then add the subsequent branch exact\n\t\t   strings to the trie.\n\n\t\t   We have two cases\n\n                     1. patterns where the whole set of branches can be\n                        converted.\n\n\t\t     2. patterns where only a subset can be converted.\n\n\t\t   In case 1 we can replace the whole set with a single regop\n\t\t   for the trie. In case 2 we need to keep the start and end\n\t\t   branches so\n\n\t\t     'BRANCH EXACT; BRANCH EXACT; BRANCH X'\n\t\t     becomes BRANCH TRIE; BRANCH X;\n\n\t\t  There is an additional case, that being where there is a\n\t\t  common prefix, which gets split out into an EXACT like node\n\t\t  preceding the TRIE node.\n\n\t\t  If x(1..n)==tail then we can do a simple trie, if not we make\n\t\t  a \"jump\" trie, such that when we match the appropriate word\n\t\t  we \"jump\" to the appropriate tail node. Essentially we turn\n\t\t  a nested if into a case structure of sorts.\n\n\t\t*/\n\n\t\t    int made=0;\n\t\t    if (!re_trie_maxbuff) {\n\t\t\tre_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);\n\t\t\tif (!SvIOK(re_trie_maxbuff))\n\t\t\t    sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);\n\t\t    }\n                    if ( SvIV(re_trie_maxbuff)>=0  ) {\n                        regnode *cur;\n                        regnode *first = (regnode *)NULL;\n                        regnode *last = (regnode *)NULL;\n                        regnode *tail = scan;\n                        U8 trietype = 0;\n                        U32 count=0;\n\n                        /* var tail is used because there may be a TAIL\n                           regop in the way. Ie, the exacts will point to the\n                           thing following the TAIL, but the last branch will\n                           point at the TAIL. So we advance tail. If we\n                           have nested (?:) we may have to move through several\n                           tails.\n                         */\n\n                        while ( OP( tail ) == TAIL ) {\n                            /* this is the TAIL generated by (?:) */\n                            tail = regnext( tail );\n                        }\n\n\n                        DEBUG_TRIE_COMPILE_r({\n                            regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);\n                            Perl_re_indentf( aTHX_  \"%s %\" UVuf \":%s\\n\",\n                              depth+1,\n                              \"Looking for TRIE'able sequences. Tail node is \",\n                              (UV) REGNODE_OFFSET(tail),\n                              SvPV_nolen_const( RExC_mysv )\n                            );\n                        });\n\n                        /*\n\n                            Step through the branches\n                                cur represents each branch,\n                                noper is the first thing to be matched as part\n                                      of that branch\n                                noper_next is the regnext() of that node.\n\n                            We normally handle a case like this\n                            /FOO[xyz]|BAR[pqr]/ via a \"jump trie\" but we also\n                            support building with NOJUMPTRIE, which restricts\n                            the trie logic to structures like /FOO|BAR/.\n\n                            If noper is a trieable nodetype then the branch is\n                            a possible optimization target. If we are building\n                            under NOJUMPTRIE then we require that noper_next is\n                            the same as scan (our current position in the regex\n                            program).\n\n                            Once we have two or more consecutive such branches\n                            we can create a trie of the EXACT's contents and\n                            stitch it in place into the program.\n\n                            If the sequence represents all of the branches in\n                            the alternation we replace the entire thing with a\n                            single TRIE node.\n\n                            Otherwise when it is a subsequence we need to\n                            stitch it in place and replace only the relevant\n                            branches. This means the first branch has to remain\n                            as it is used by the alternation logic, and its\n                            next pointer, and needs to be repointed at the item\n                            on the branch chain following the last branch we\n                            have optimized away.\n\n                            This could be either a BRANCH, in which case the\n                            subsequence is internal, or it could be the item\n                            following the branch sequence in which case the\n                            subsequence is at the end (which does not\n                            necessarily mean the first node is the start of the\n                            alternation).\n\n                            TRIE_TYPE(X) is a define which maps the optype to a\n                            trietype.\n\n                                optype          |  trietype\n                                ----------------+-----------\n                                NOTHING         | NOTHING\n                                EXACT           | EXACT\n                                EXACT_ONLY8     | EXACT\n                                EXACTFU         | EXACTFU\n                                EXACTFU_ONLY8   | EXACTFU\n                                EXACTFUP        | EXACTFU\n                                EXACTFAA        | EXACTFAA\n                                EXACTL          | EXACTL\n                                EXACTFLU8       | EXACTFLU8\n\n\n                        */\n#define TRIE_TYPE(X) ( ( NOTHING == (X) )                                   \\\n                       ? NOTHING                                            \\\n                       : ( EXACT == (X) || EXACT_ONLY8 == (X) )             \\\n                         ? EXACT                                            \\\n                         : (     EXACTFU == (X)                             \\\n                              || EXACTFU_ONLY8 == (X)                       \\\n                              || EXACTFUP == (X) )                          \\\n                           ? EXACTFU                                        \\\n                           : ( EXACTFAA == (X) )                            \\\n                             ? EXACTFAA                                     \\\n                             : ( EXACTL == (X) )                            \\\n                               ? EXACTL                                     \\\n                               : ( EXACTFLU8 == (X) )                       \\\n                                 ? EXACTFLU8                                \\\n                                 : 0 )\n\n                        /* dont use tail as the end marker for this traverse */\n                        for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {\n                            regnode * const noper = NEXTOPER( cur );\n                            U8 noper_type = OP( noper );\n                            U8 noper_trietype = TRIE_TYPE( noper_type );\n#if defined(DEBUGGING) || defined(NOJUMPTRIE)\n                            regnode * const noper_next = regnext( noper );\n                            U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;\n                            U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;\n#endif\n\n                            DEBUG_TRIE_COMPILE_r({\n                                regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);\n                                Perl_re_indentf( aTHX_  \"- %d:%s (%d)\",\n                                   depth+1,\n                                   REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );\n\n                                regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);\n                                Perl_re_printf( aTHX_  \" -> %d:%s\",\n                                    REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));\n\n                                if ( noper_next ) {\n                                  regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);\n                                  Perl_re_printf( aTHX_ \"\\t=> %d:%s\\t\",\n                                    REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));\n                                }\n                                Perl_re_printf( aTHX_  \"(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\\n\",\n                                   REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),\n\t\t\t\t   PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]\n\t\t\t\t);\n                            });\n\n                            /* Is noper a trieable nodetype that can be merged\n                             * with the current trie (if there is one)? */\n                            if ( noper_trietype\n                                  &&\n                                  (\n                                        ( noper_trietype == NOTHING )\n                                        || ( trietype == NOTHING )\n                                        || ( trietype == noper_trietype )\n                                  )\n#ifdef NOJUMPTRIE\n                                  && noper_next >= tail\n#endif\n                                  && count < U16_MAX)\n                            {\n                                /* Handle mergable triable node Either we are\n                                 * the first node in a new trieable sequence,\n                                 * in which case we do some bookkeeping,\n                                 * otherwise we update the end pointer. */\n                                if ( !first ) {\n                                    first = cur;\n\t\t\t\t    if ( noper_trietype == NOTHING ) {\n#if !defined(DEBUGGING) && !defined(NOJUMPTRIE)\n\t\t\t\t\tregnode * const noper_next = regnext( noper );\n                                        U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;\n\t\t\t\t\tU8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;\n#endif\n\n                                        if ( noper_next_trietype ) {\n\t\t\t\t\t    trietype = noper_next_trietype;\n                                        } else if (noper_next_type)  {\n                                            /* a NOTHING regop is 1 regop wide.\n                                             * We need at least two for a trie\n                                             * so we can't merge this in */\n                                            first = NULL;\n                                        }\n                                    } else {\n                                        trietype = noper_trietype;\n                                    }\n                                } else {\n                                    if ( trietype == NOTHING )\n                                        trietype = noper_trietype;\n                                    last = cur;\n                                }\n\t\t\t\tif (first)\n\t\t\t\t    count++;\n                            } /* end handle mergable triable node */\n                            else {\n                                /* handle unmergable node -\n                                 * noper may either be a triable node which can\n                                 * not be tried together with the current trie,\n                                 * or a non triable node */\n                                if ( last ) {\n                                    /* If last is set and trietype is not\n                                     * NOTHING then we have found at least two\n                                     * triable branch sequences in a row of a\n                                     * similar trietype so we can turn them\n                                     * into a trie. If/when we allow NOTHING to\n                                     * start a trie sequence this condition\n                                     * will be required, and it isn't expensive\n                                     * so we leave it in for now. */\n                                    if ( trietype && trietype != NOTHING )\n                                        make_trie( pRExC_state,\n                                                startbranch, first, cur, tail,\n                                                count, trietype, depth+1 );\n                                    last = NULL; /* note: we clear/update\n                                                    first, trietype etc below,\n                                                    so we dont do it here */\n                                }\n                                if ( noper_trietype\n#ifdef NOJUMPTRIE\n                                     && noper_next >= tail\n#endif\n                                ){\n                                    /* noper is triable, so we can start a new\n                                     * trie sequence */\n                                    count = 1;\n                                    first = cur;\n                                    trietype = noper_trietype;\n                                } else if (first) {\n                                    /* if we already saw a first but the\n                                     * current node is not triable then we have\n                                     * to reset the first information. */\n                                    count = 0;\n                                    first = NULL;\n                                    trietype = 0;\n                                }\n                            } /* end handle unmergable node */\n                        } /* loop over branches */\n                        DEBUG_TRIE_COMPILE_r({\n                            regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);\n                            Perl_re_indentf( aTHX_  \"- %s (%d)  \",\n                              depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));\n                            Perl_re_printf( aTHX_  \"(First==%d, Last==%d, Cur==%d, tt==%s)\\n\",\n                               REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),\n                               PL_reg_name[trietype]\n                            );\n\n                        });\n                        if ( last && trietype ) {\n                            if ( trietype != NOTHING ) {\n                                /* the last branch of the sequence was part of\n                                 * a trie, so we have to construct it here\n                                 * outside of the loop */\n                                made= make_trie( pRExC_state, startbranch,\n                                                 first, scan, tail, count,\n                                                 trietype, depth+1 );\n#ifdef TRIE_STUDY_OPT\n                                if ( ((made == MADE_EXACT_TRIE &&\n                                     startbranch == first)\n                                     || ( first_non_open == first )) &&\n                                     depth==0 ) {\n                                    flags |= SCF_TRIE_RESTUDY;\n                                    if ( startbranch == first\n                                         && scan >= tail )\n                                    {\n                                        RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;\n                                    }\n                                }\n#endif\n                            } else {\n                                /* at this point we know whatever we have is a\n                                 * NOTHING sequence/branch AND if 'startbranch'\n                                 * is 'first' then we can turn the whole thing\n                                 * into a NOTHING\n                                 */\n                                if ( startbranch == first ) {\n                                    regnode *opt;\n                                    /* the entire thing is a NOTHING sequence,\n                                     * something like this: (?:|) So we can\n                                     * turn it into a plain NOTHING op. */\n                                    DEBUG_TRIE_COMPILE_r({\n                                        regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);\n                                        Perl_re_indentf( aTHX_  \"- %s (%d) \\n\",\n                                          depth+1,\n                                          SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));\n\n                                    });\n                                    OP(startbranch)= NOTHING;\n                                    NEXT_OFF(startbranch)= tail - startbranch;\n                                    for ( opt= startbranch + 1; opt < tail ; opt++ )\n                                        OP(opt)= OPTIMIZED;\n                                }\n                            }\n                        } /* end if ( last) */\n                    } /* TRIE_MAXBUF is non zero */\n\n                } /* do trie */\n\n\t    }\n\t    else if ( code == BRANCHJ ) {  /* single branch is optimized. */\n\t\tscan = NEXTOPER(NEXTOPER(scan));\n\t    } else\t\t\t/* single branch is optimized. */\n\t\tscan = NEXTOPER(scan);\n\t    continue;\n        } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {\n            I32 paren = 0;\n            regnode *start = NULL;\n            regnode *end = NULL;\n            U32 my_recursed_depth= recursed_depth;\n\n            if (OP(scan) != SUSPEND) { /* GOSUB */\n                /* Do setup, note this code has side effects beyond\n                 * the rest of this block. Specifically setting\n                 * RExC_recurse[] must happen at least once during\n                 * study_chunk(). */\n                paren = ARG(scan);\n                RExC_recurse[ARG2L(scan)] = scan;\n                start = REGNODE_p(RExC_open_parens[paren]);\n                end   = REGNODE_p(RExC_close_parens[paren]);\n\n                /* NOTE we MUST always execute the above code, even\n                 * if we do nothing with a GOSUB */\n                if (\n                    ( flags & SCF_IN_DEFINE )\n                    ||\n                    (\n                        (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))\n                        &&\n                        ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )\n                    )\n                ) {\n                    /* no need to do anything here if we are in a define. */\n                    /* or we are after some kind of infinite construct\n                     * so we can skip recursing into this item.\n                     * Since it is infinite we will not change the maxlen\n                     * or delta, and if we miss something that might raise\n                     * the minlen it will merely pessimise a little.\n                     *\n                     * Iow /(?(DEFINE)(?foo|food))a+(?&foo)/\n                     * might result in a minlen of 1 and not of 4,\n                     * but this doesn't make us mismatch, just try a bit\n                     * harder than we should.\n                     * */\n                    scan= regnext(scan);\n                    continue;\n                }\n\n                if (\n                    !recursed_depth\n                    ||\n                    !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)\n                ) {\n                    /* it is quite possible that there are more efficient ways\n                     * to do this. We maintain a bitmap per level of recursion\n                     * of which patterns we have entered so we can detect if a\n                     * pattern creates a possible infinite loop. When we\n                     * recurse down a level we copy the previous levels bitmap\n                     * down. When we are at recursion level 0 we zero the top\n                     * level bitmap. It would be nice to implement a different\n                     * more efficient way of doing this. In particular the top\n                     * level bitmap may be unnecessary.\n                     */\n                    if (!recursed_depth) {\n                        Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);\n                    } else {\n                        Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),\n                             RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),\n                             RExC_study_chunk_recursed_bytes, U8);\n                    }\n                    /* we havent recursed into this paren yet, so recurse into it */\n                    DEBUG_STUDYDATA(\"gosub-set\", data, depth, is_inf);\n                    PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);\n                    my_recursed_depth= recursed_depth + 1;\n                } else {\n                    DEBUG_STUDYDATA(\"gosub-inf\", data, depth, is_inf);\n                    /* some form of infinite recursion, assume infinite length\n                     * */\n                    if (flags & SCF_DO_SUBSTR) {\n                        scan_commit(pRExC_state, data, minlenp, is_inf);\n                        data->cur_is_floating = 1;\n                    }\n                    is_inf = is_inf_internal = 1;\n                    if (flags & SCF_DO_STCLASS_OR) /* Allow everything */\n                        ssc_anything(data->start_class);\n                    flags &= ~SCF_DO_STCLASS;\n\n                    start= NULL; /* reset start so we dont recurse later on. */\n\t        }\n            } else {\n\t        paren = stopparen;\n                start = scan + 2;\n\t        end = regnext(scan);\n\t    }\n            if (start) {\n                scan_frame *newframe;\n                assert(end);\n                if (!RExC_frame_last) {\n                    Newxz(newframe, 1, scan_frame);\n                    SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);\n                    RExC_frame_head= newframe;\n                    RExC_frame_count++;\n                } else if (!RExC_frame_last->next_frame) {\n                    Newxz(newframe, 1, scan_frame);\n                    RExC_frame_last->next_frame= newframe;\n                    newframe->prev_frame= RExC_frame_last;\n                    RExC_frame_count++;\n                } else {\n                    newframe= RExC_frame_last->next_frame;\n                }\n                RExC_frame_last= newframe;\n\n                newframe->next_regnode = regnext(scan);\n                newframe->last_regnode = last;\n                newframe->stopparen = stopparen;\n                newframe->prev_recursed_depth = recursed_depth;\n                newframe->this_prev_frame= frame;\n\n                DEBUG_STUDYDATA(\"frame-new\", data, depth, is_inf);\n                DEBUG_PEEP(\"fnew\", scan, depth, flags);\n\n\t        frame = newframe;\n\t        scan =  start;\n\t        stopparen = paren;\n\t        last = end;\n                depth = depth + 1;\n                recursed_depth= my_recursed_depth;\n\n\t        continue;\n\t    }\n\t}\n\telse if (   OP(scan) == EXACT\n                 || OP(scan) == EXACT_ONLY8\n                 || OP(scan) == EXACTL)\n        {\n\t    SSize_t l = STR_LEN(scan);\n\t    UV uc;\n            assert(l);\n\t    if (UTF) {\n\t\tconst U8 * const s = (U8*)STRING(scan);\n\t\tuc = utf8_to_uvchr_buf(s, s + l, NULL);\n\t\tl = utf8_length(s, s + l);\n\t    } else {\n\t\tuc = *((U8*)STRING(scan));\n\t    }\n\t    min += l;\n\t    if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */\n\t\t/* The code below prefers earlier match for fixed\n\t\t   offset, later match for variable offset.  */\n\t\tif (data->last_end == -1) { /* Update the start info. */\n\t\t    data->last_start_min = data->pos_min;\n \t\t    data->last_start_max = is_inf\n \t\t\t? SSize_t_MAX : data->pos_min + data->pos_delta;\n\t\t}\n\t\tsv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));\n\t\tif (UTF)\n\t\t    SvUTF8_on(data->last_found);\n\t\t{\n\t\t    SV * const sv = data->last_found;\n\t\t    MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?\n\t\t\tmg_find(sv, PERL_MAGIC_utf8) : NULL;\n\t\t    if (mg && mg->mg_len >= 0)\n\t\t\tmg->mg_len += utf8_length((U8*)STRING(scan),\n                                              (U8*)STRING(scan)+STR_LEN(scan));\n\t\t}\n\t\tdata->last_end = data->pos_min + l;\n\t\tdata->pos_min += l; /* As in the first entry. */\n\t\tdata->flags &= ~SF_BEFORE_EOL;\n\t    }\n\n            /* ANDing the code point leaves at most it, and not in locale, and\n             * can't match null string */\n\t    if (flags & SCF_DO_STCLASS_AND) {\n                ssc_cp_and(data->start_class, uc);\n                ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n                ssc_clear_locale(data->start_class);\n\t    }\n\t    else if (flags & SCF_DO_STCLASS_OR) {\n                ssc_add_cp(data->start_class, uc);\n\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\n                /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */\n                ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n\t    }\n\t    flags &= ~SCF_DO_STCLASS;\n\t}\n        else if (PL_regkind[OP(scan)] == EXACT) {\n            /* But OP != EXACT!, so is EXACTFish */\n\t    SSize_t l = STR_LEN(scan);\n            const U8 * s = (U8*)STRING(scan);\n\n\t    /* Search for fixed substrings supports EXACT only. */\n\t    if (flags & SCF_DO_SUBSTR) {\n\t\tassert(data);\n                scan_commit(pRExC_state, data, minlenp, is_inf);\n\t    }\n\t    if (UTF) {\n\t\tl = utf8_length(s, s + l);\n\t    }\n\t    if (unfolded_multi_char) {\n                RExC_seen |= REG_UNFOLDED_MULTI_SEEN;\n\t    }\n\t    min += l - min_subtract;\n            assert (min >= 0);\n            delta += min_subtract;\n\t    if (flags & SCF_DO_SUBSTR) {\n\t\tdata->pos_min += l - min_subtract;\n\t\tif (data->pos_min < 0) {\n                    data->pos_min = 0;\n                }\n                data->pos_delta += min_subtract;\n\t\tif (min_subtract) {\n\t\t    data->cur_is_floating = 1; /* float */\n\t\t}\n\t    }\n\n            if (flags & SCF_DO_STCLASS) {\n                SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan);\n\n                assert(EXACTF_invlist);\n                if (flags & SCF_DO_STCLASS_AND) {\n                    if (OP(scan) != EXACTFL)\n                        ssc_clear_locale(data->start_class);\n                    ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n                    ANYOF_POSIXL_ZERO(data->start_class);\n                    ssc_intersection(data->start_class, EXACTF_invlist, FALSE);\n                }\n                else {  /* SCF_DO_STCLASS_OR */\n                    ssc_union(data->start_class, EXACTF_invlist, FALSE);\n                    ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\n                    /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */\n                    ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n                }\n                flags &= ~SCF_DO_STCLASS;\n                SvREFCNT_dec(EXACTF_invlist);\n            }\n\t}\n\telse if (REGNODE_VARIES(OP(scan))) {\n\t    SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;\n\t    I32 fl = 0, f = flags;\n\t    regnode * const oscan = scan;\n\t    regnode_ssc this_class;\n\t    regnode_ssc *oclass = NULL;\n\t    I32 next_is_eval = 0;\n\n\t    switch (PL_regkind[OP(scan)]) {\n\t    case WHILEM:\t\t/* End of (?:...)* . */\n\t\tscan = NEXTOPER(scan);\n\t\tgoto finish;\n\t    case PLUS:\n\t\tif (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {\n\t\t    next = NEXTOPER(scan);\n\t\t    if (   OP(next) == EXACT\n                        || OP(next) == EXACT_ONLY8\n                        || OP(next) == EXACTL\n                        || (flags & SCF_DO_STCLASS))\n                    {\n\t\t\tmincount = 1;\n\t\t\tmaxcount = REG_INFTY;\n\t\t\tnext = regnext(scan);\n\t\t\tscan = NEXTOPER(scan);\n\t\t\tgoto do_curly;\n\t\t    }\n\t\t}\n\t\tif (flags & SCF_DO_SUBSTR)\n\t\t    data->pos_min++;\n\t\tmin++;\n\t\t/* FALLTHROUGH */\n\t    case STAR:\n                next = NEXTOPER(scan);\n\n                /* This temporary node can now be turned into EXACTFU, and\n                 * must, as regexec.c doesn't handle it */\n                if (OP(next) == EXACTFU_S_EDGE) {\n                    OP(next) = EXACTFU;\n                }\n\n                if (     STR_LEN(next) == 1\n                    &&   isALPHA_A(* STRING(next))\n                    && (         OP(next) == EXACTFAA\n                        || (     OP(next) == EXACTFU\n                            && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next)))))\n                {\n                    /* These differ in just one bit */\n                    U8 mask = ~ ('A' ^ 'a');\n\n                    assert(isALPHA_A(* STRING(next)));\n\n                    /* Then replace it by an ANYOFM node, with\n                    * the mask set to the complement of the\n                    * bit that differs between upper and lower\n                    * case, and the lowest code point of the\n                    * pair (which the '&' forces) */\n                    OP(next) = ANYOFM;\n                    ARG_SET(next, *STRING(next) & mask);\n                    FLAGS(next) = mask;\n                }\n\n\t\tif (flags & SCF_DO_STCLASS) {\n\t\t    mincount = 0;\n\t\t    maxcount = REG_INFTY;\n\t\t    next = regnext(scan);\n\t\t    scan = NEXTOPER(scan);\n\t\t    goto do_curly;\n\t\t}\n\t\tif (flags & SCF_DO_SUBSTR) {\n                    scan_commit(pRExC_state, data, minlenp, is_inf);\n                    /* Cannot extend fixed substrings */\n\t\t    data->cur_is_floating = 1; /* float */\n\t\t}\n                is_inf = is_inf_internal = 1;\n                scan = regnext(scan);\n\t\tgoto optimize_curly_tail;\n\t    case CURLY:\n\t        if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)\n\t            && (scan->flags == stopparen))\n\t\t{\n\t\t    mincount = 1;\n\t\t    maxcount = 1;\n\t\t} else {\n\t\t    mincount = ARG1(scan);\n\t\t    maxcount = ARG2(scan);\n\t\t}\n\t\tnext = regnext(scan);\n\t\tif (OP(scan) == CURLYX) {\n\t\t    I32 lp = (data ? *(data->last_closep) : 0);\n\t\t    scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);\n\t\t}\n\t\tscan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;\n\t\tnext_is_eval = (OP(scan) == EVAL);\n\t      do_curly:\n\t\tif (flags & SCF_DO_SUBSTR) {\n                    if (mincount == 0)\n                        scan_commit(pRExC_state, data, minlenp, is_inf);\n                    /* Cannot extend fixed substrings */\n\t\t    pos_before = data->pos_min;\n\t\t}\n\t\tif (data) {\n\t\t    fl = data->flags;\n\t\t    data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);\n\t\t    if (is_inf)\n\t\t\tdata->flags |= SF_IS_INF;\n\t\t}\n\t\tif (flags & SCF_DO_STCLASS) {\n\t\t    ssc_init(pRExC_state, &this_class);\n\t\t    oclass = data->start_class;\n\t\t    data->start_class = &this_class;\n\t\t    f |= SCF_DO_STCLASS_AND;\n\t\t    f &= ~SCF_DO_STCLASS_OR;\n\t\t}\n\t        /* Exclude from super-linear cache processing any {n,m}\n\t\t   regops for which the combination of input pos and regex\n\t\t   pos is not enough information to determine if a match\n\t\t   will be possible.\n\n\t\t   For example, in the regex /foo(bar\\s*){4,8}baz/ with the\n\t\t   regex pos at the \\s*, the prospects for a match depend not\n\t\t   only on the input position but also on how many (bar\\s*)\n\t\t   repeats into the {4,8} we are. */\n               if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))\n\t\t    f &= ~SCF_WHILEM_VISITED_POS;\n\n\t\t/* This will finish on WHILEM, setting scan, or on NULL: */\n                /* recurse study_chunk() on loop bodies */\n\t\tminnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,\n                                  last, data, stopparen, recursed_depth, NULL,\n                                  (mincount == 0\n                                   ? (f & ~SCF_DO_SUBSTR)\n                                   : f)\n                                  ,depth+1);\n\n\t\tif (flags & SCF_DO_STCLASS)\n\t\t    data->start_class = oclass;\n\t\tif (mincount == 0 || minnext == 0) {\n\t\t    if (flags & SCF_DO_STCLASS_OR) {\n\t\t\tssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);\n\t\t    }\n\t\t    else if (flags & SCF_DO_STCLASS_AND) {\n\t\t\t/* Switch to OR mode: cache the old value of\n\t\t\t * data->start_class */\n\t\t\tINIT_AND_WITHP;\n\t\t\tStructCopy(data->start_class, and_withp, regnode_ssc);\n\t\t\tflags &= ~SCF_DO_STCLASS_AND;\n\t\t\tStructCopy(&this_class, data->start_class, regnode_ssc);\n\t\t\tflags |= SCF_DO_STCLASS_OR;\n                        ANYOF_FLAGS(data->start_class)\n                                                |= SSC_MATCHES_EMPTY_STRING;\n\t\t    }\n\t\t} else {\t\t/* Non-zero len */\n\t\t    if (flags & SCF_DO_STCLASS_OR) {\n\t\t\tssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\t\t    }\n\t\t    else if (flags & SCF_DO_STCLASS_AND)\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);\n\t\t    flags &= ~SCF_DO_STCLASS;\n\t\t}\n\t\tif (!scan) \t\t/* It was not CURLYX, but CURLY. */\n\t\t    scan = next;\n\t\tif (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)\n\t\t    /* ? quantifier ok, except for (?{ ... }) */\n\t\t    && (next_is_eval || !(mincount == 0 && maxcount == 1))\n\t\t    && (minnext == 0) && (deltanext == 0)\n\t\t    && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))\n                    && maxcount <= REG_INFTY/3) /* Complement check for big\n                                                   count */\n\t\t{\n\t\t    _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),\n                        Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),\n                            \"Quantifier unexpected on zero-length expression \"\n                            \"in regex m/%\" UTF8f \"/\",\n\t\t\t     UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,\n\t\t\t\t  RExC_precomp)));\n                }\n\n                if ( ( minnext > 0 && mincount >= SSize_t_MAX / minnext )\n                    || min >= SSize_t_MAX - minnext * mincount )\n                {\n                    FAIL(\"Regexp out of space\");\n                }\n\n\t\tmin += minnext * mincount;\n\t\tis_inf_internal |= deltanext == SSize_t_MAX\n                         || (maxcount == REG_INFTY && minnext + deltanext > 0);\n\t\tis_inf |= is_inf_internal;\n                if (is_inf) {\n\t\t    delta = SSize_t_MAX;\n                } else {\n\t\t    delta += (minnext + deltanext) * maxcount\n                             - minnext * mincount;\n                }\n\t\t/* Try powerful optimization CURLYX => CURLYN. */\n\t\tif (  OP(oscan) == CURLYX && data\n\t\t      && data->flags & SF_IN_PAR\n\t\t      && !(data->flags & SF_HAS_EVAL)\n\t\t      && !deltanext && minnext == 1 ) {\n\t\t    /* Try to optimize to CURLYN.  */\n\t\t    regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;\n\t\t    regnode * const nxt1 = nxt;\n#ifdef DEBUGGING\n\t\t    regnode *nxt2;\n#endif\n\n\t\t    /* Skip open. */\n\t\t    nxt = regnext(nxt);\n\t\t    if (!REGNODE_SIMPLE(OP(nxt))\n\t\t\t&& !(PL_regkind[OP(nxt)] == EXACT\n\t\t\t     && STR_LEN(nxt) == 1))\n\t\t\tgoto nogo;\n#ifdef DEBUGGING\n\t\t    nxt2 = nxt;\n#endif\n\t\t    nxt = regnext(nxt);\n\t\t    if (OP(nxt) != CLOSE)\n\t\t\tgoto nogo;\n\t\t    if (RExC_open_parens) {\n\n                        /*open->CURLYM*/\n                        RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);\n\n                        /*close->while*/\n                        RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;\n\t\t    }\n\t\t    /* Now we know that nxt2 is the only contents: */\n\t\t    oscan->flags = (U8)ARG(nxt);\n\t\t    OP(oscan) = CURLYN;\n\t\t    OP(nxt1) = NOTHING;\t/* was OPEN. */\n\n#ifdef DEBUGGING\n\t\t    OP(nxt1 + 1) = OPTIMIZED; /* was count. */\n\t\t    NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */\n\t\t    NEXT_OFF(nxt2) = 0;\t/* just for consistency with CURLY. */\n\t\t    OP(nxt) = OPTIMIZED;\t/* was CLOSE. */\n\t\t    OP(nxt + 1) = OPTIMIZED; /* was count. */\n\t\t    NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */\n#endif\n\t\t}\n\t      nogo:\n\n\t\t/* Try optimization CURLYX => CURLYM. */\n\t\tif (  OP(oscan) == CURLYX && data\n\t\t      && !(data->flags & SF_HAS_PAR)\n\t\t      && !(data->flags & SF_HAS_EVAL)\n\t\t      && !deltanext\t/* atom is fixed width */\n\t\t      && minnext != 0\t/* CURLYM can't handle zero width */\n\n                         /* Nor characters whose fold at run-time may be\n                          * multi-character */\n                      && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)\n\t\t) {\n\t\t    /* XXXX How to optimize if data == 0? */\n\t\t    /* Optimize to a simpler form.  */\n\t\t    regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */\n\t\t    regnode *nxt2;\n\n\t\t    OP(oscan) = CURLYM;\n\t\t    while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/\n\t\t\t    && (OP(nxt2) != WHILEM))\n\t\t\tnxt = nxt2;\n\t\t    OP(nxt2)  = SUCCEED; /* Whas WHILEM */\n\t\t    /* Need to optimize away parenths. */\n\t\t    if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {\n\t\t\t/* Set the parenth number.  */\n\t\t\tregnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/\n\n\t\t\toscan->flags = (U8)ARG(nxt);\n\t\t\tif (RExC_open_parens) {\n                             /*open->CURLYM*/\n                            RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);\n\n                            /*close->NOTHING*/\n                            RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)\n                                                         + 1;\n\t\t\t}\n\t\t\tOP(nxt1) = OPTIMIZED;\t/* was OPEN. */\n\t\t\tOP(nxt) = OPTIMIZED;\t/* was CLOSE. */\n\n#ifdef DEBUGGING\n\t\t\tOP(nxt1 + 1) = OPTIMIZED; /* was count. */\n\t\t\tOP(nxt + 1) = OPTIMIZED; /* was count. */\n\t\t\tNEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */\n\t\t\tNEXT_OFF(nxt + 1) = 0; /* just for consistency. */\n#endif\n#if 0\n\t\t\twhile ( nxt1 && (OP(nxt1) != WHILEM)) {\n\t\t\t    regnode *nnxt = regnext(nxt1);\n\t\t\t    if (nnxt == nxt) {\n\t\t\t\tif (reg_off_by_arg[OP(nxt1)])\n\t\t\t\t    ARG_SET(nxt1, nxt2 - nxt1);\n\t\t\t\telse if (nxt2 - nxt1 < U16_MAX)\n\t\t\t\t    NEXT_OFF(nxt1) = nxt2 - nxt1;\n\t\t\t\telse\n\t\t\t\t    OP(nxt) = NOTHING;\t/* Cannot beautify */\n\t\t\t    }\n\t\t\t    nxt1 = nnxt;\n\t\t\t}\n#endif\n\t\t\t/* Optimize again: */\n                        /* recurse study_chunk() on optimised CURLYX => CURLYM */\n\t\t\tstudy_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,\n                                    NULL, stopparen, recursed_depth, NULL, 0,\n                                    depth+1);\n\t\t    }\n\t\t    else\n\t\t\toscan->flags = 0;\n\t\t}\n\t\telse if ((OP(oscan) == CURLYX)\n\t\t\t && (flags & SCF_WHILEM_VISITED_POS)\n\t\t\t /* See the comment on a similar expression above.\n\t\t\t    However, this time it's not a subexpression\n\t\t\t    we care about, but the expression itself. */\n\t\t\t && (maxcount == REG_INFTY)\n\t\t\t && data) {\n\t\t    /* This stays as CURLYX, we can put the count/of pair. */\n\t\t    /* Find WHILEM (as in regexec.c) */\n\t\t    regnode *nxt = oscan + NEXT_OFF(oscan);\n\n\t\t    if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */\n\t\t\tnxt += ARG(nxt);\n                    nxt = PREVOPER(nxt);\n                    if (nxt->flags & 0xf) {\n                        /* we've already set whilem count on this node */\n                    } else if (++data->whilem_c < 16) {\n                        assert(data->whilem_c <= RExC_whilem_seen);\n                        nxt->flags = (U8)(data->whilem_c\n                            | (RExC_whilem_seen << 4)); /* On WHILEM */\n                    }\n\t\t}\n\t\tif (data && fl & (SF_HAS_PAR|SF_IN_PAR))\n\t\t    pars++;\n\t\tif (flags & SCF_DO_SUBSTR) {\n\t\t    SV *last_str = NULL;\n                    STRLEN last_chrs = 0;\n\t\t    int counted = mincount != 0;\n\n                    if (data->last_end > 0 && mincount != 0) { /* Ends with a\n                                                                  string. */\n\t\t\tSSize_t b = pos_before >= data->last_start_min\n\t\t\t    ? pos_before : data->last_start_min;\n\t\t\tSTRLEN l;\n\t\t\tconst char * const s = SvPV_const(data->last_found, l);\n\t\t\tSSize_t old = b - data->last_start_min;\n                        assert(old >= 0);\n\n\t\t\tif (UTF)\n\t\t\t    old = utf8_hop_forward((U8*)s, old,\n                                               (U8 *) SvEND(data->last_found))\n                                - (U8*)s;\n\t\t\tl -= old;\n\t\t\t/* Get the added string: */\n\t\t\tlast_str = newSVpvn_utf8(s  + old, l, UTF);\n                        last_chrs = UTF ? utf8_length((U8*)(s + old),\n                                            (U8*)(s + old + l)) : l;\n\t\t\tif (deltanext == 0 && pos_before == b) {\n\t\t\t    /* What was added is a constant string */\n\t\t\t    if (mincount > 1) {\n\n\t\t\t\tSvGROW(last_str, (mincount * l) + 1);\n\t\t\t\trepeatcpy(SvPVX(last_str) + l,\n\t\t\t\t\t  SvPVX_const(last_str), l,\n                                          mincount - 1);\n\t\t\t\tSvCUR_set(last_str, SvCUR(last_str) * mincount);\n\t\t\t\t/* Add additional parts. */\n\t\t\t\tSvCUR_set(data->last_found,\n\t\t\t\t\t  SvCUR(data->last_found) - l);\n\t\t\t\tsv_catsv(data->last_found, last_str);\n\t\t\t\t{\n\t\t\t\t    SV * sv = data->last_found;\n\t\t\t\t    MAGIC *mg =\n\t\t\t\t\tSvUTF8(sv) && SvMAGICAL(sv) ?\n\t\t\t\t\tmg_find(sv, PERL_MAGIC_utf8) : NULL;\n\t\t\t\t    if (mg && mg->mg_len >= 0)\n\t\t\t\t\tmg->mg_len += last_chrs * (mincount-1);\n\t\t\t\t}\n                                last_chrs *= mincount;\n\t\t\t\tdata->last_end += l * (mincount - 1);\n\t\t\t    }\n\t\t\t} else {\n\t\t\t    /* start offset must point into the last copy */\n\t\t\t    data->last_start_min += minnext * (mincount - 1);\n\t\t\t    data->last_start_max =\n                              is_inf\n                               ? SSize_t_MAX\n\t\t\t       : data->last_start_max +\n                                 (maxcount - 1) * (minnext + data->pos_delta);\n\t\t\t}\n\t\t    }\n\t\t    /* It is counted once already... */\n\t\t    data->pos_min += minnext * (mincount - counted);\n#if 0\nPerl_re_printf( aTHX_  \"counted=%\" UVuf \" deltanext=%\" UVuf\n                              \" SSize_t_MAX=%\" UVuf \" minnext=%\" UVuf\n                              \" maxcount=%\" UVuf \" mincount=%\" UVuf \"\\n\",\n    (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,\n    (UV)mincount);\nif (deltanext != SSize_t_MAX)\nPerl_re_printf( aTHX_  \"LHS=%\" UVuf \" RHS=%\" UVuf \"\\n\",\n    (UV)(-counted * deltanext + (minnext + deltanext) * maxcount\n          - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));\n#endif\n\t\t    if (deltanext == SSize_t_MAX\n                        || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)\n\t\t        data->pos_delta = SSize_t_MAX;\n\t\t    else\n\t\t        data->pos_delta += - counted * deltanext +\n\t\t\t(minnext + deltanext) * maxcount - minnext * mincount;\n\t\t    if (mincount != maxcount) {\n\t\t\t /* Cannot extend fixed substrings found inside\n\t\t\t    the group.  */\n                        scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\t\tif (mincount && last_str) {\n\t\t\t    SV * const sv = data->last_found;\n\t\t\t    MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?\n\t\t\t\tmg_find(sv, PERL_MAGIC_utf8) : NULL;\n\n\t\t\t    if (mg)\n\t\t\t\tmg->mg_len = -1;\n\t\t\t    sv_setsv(sv, last_str);\n\t\t\t    data->last_end = data->pos_min;\n\t\t\t    data->last_start_min = data->pos_min - last_chrs;\n\t\t\t    data->last_start_max = is_inf\n\t\t\t\t? SSize_t_MAX\n\t\t\t\t: data->pos_min + data->pos_delta - last_chrs;\n\t\t\t}\n\t\t\tdata->cur_is_floating = 1; /* float */\n\t\t    }\n\t\t    SvREFCNT_dec(last_str);\n\t\t}\n\t\tif (data && (fl & SF_HAS_EVAL))\n\t\t    data->flags |= SF_HAS_EVAL;\n\t      optimize_curly_tail:\n\t\trck_elide_nothing(oscan);\n\t\tcontinue;\n\n\t    default:\n#ifdef DEBUGGING\n                Perl_croak(aTHX_ \"panic: unexpected varying REx opcode %d\",\n                                                                    OP(scan));\n#endif\n            case REF:\n            case CLUMP:\n\t\tif (flags & SCF_DO_SUBSTR) {\n                    /* Cannot expect anything... */\n                    scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\t    data->cur_is_floating = 1; /* float */\n\t\t}\n\t\tis_inf = is_inf_internal = 1;\n\t\tif (flags & SCF_DO_STCLASS_OR) {\n                    if (OP(scan) == CLUMP) {\n                        /* Actually is any start char, but very few code points\n                         * aren't start characters */\n                        ssc_match_all_cp(data->start_class);\n                    }\n                    else {\n                        ssc_anything(data->start_class);\n                    }\n                }\n\t\tflags &= ~SCF_DO_STCLASS;\n\t\tbreak;\n\t    }\n\t}\n\telse if (OP(scan) == LNBREAK) {\n\t    if (flags & SCF_DO_STCLASS) {\n    \t        if (flags & SCF_DO_STCLASS_AND) {\n                    ssc_intersection(data->start_class,\n                                    PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);\n                    ssc_clear_locale(data->start_class);\n                    ANYOF_FLAGS(data->start_class)\n                                                &= ~SSC_MATCHES_EMPTY_STRING;\n                }\n                else if (flags & SCF_DO_STCLASS_OR) {\n                    ssc_union(data->start_class,\n                              PL_XPosix_ptrs[_CC_VERTSPACE],\n                              FALSE);\n\t\t    ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\n                    /* See commit msg for\n                     * 749e076fceedeb708a624933726e7989f2302f6a */\n                    ANYOF_FLAGS(data->start_class)\n                                                &= ~SSC_MATCHES_EMPTY_STRING;\n                }\n\t\tflags &= ~SCF_DO_STCLASS;\n            }\n\t    min++;\n            if (delta != SSize_t_MAX)\n                delta++;    /* Because of the 2 char string cr-lf */\n            if (flags & SCF_DO_SUBSTR) {\n                /* Cannot expect anything... */\n                scan_commit(pRExC_state, data, minlenp, is_inf);\n    \t        data->pos_min += 1;\n                if (data->pos_delta != SSize_t_MAX) {\n                    data->pos_delta += 1;\n                }\n\t\tdata->cur_is_floating = 1; /* float */\n    \t    }\n\t}\n\telse if (REGNODE_SIMPLE(OP(scan))) {\n\n\t    if (flags & SCF_DO_SUBSTR) {\n                scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\tdata->pos_min++;\n\t    }\n\t    min++;\n\t    if (flags & SCF_DO_STCLASS) {\n                bool invert = 0;\n                SV* my_invlist = NULL;\n                U8 namedclass;\n\n                /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */\n                ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n\n\t\t/* Some of the logic below assumes that switching\n\t\t   locale on will only add false positives. */\n\t\tswitch (OP(scan)) {\n\n\t\tdefault:\n#ifdef DEBUGGING\n                   Perl_croak(aTHX_ \"panic: unexpected simple REx opcode %d\",\n                                                                     OP(scan));\n#endif\n\t\tcase SANY:\n\t\t    if (flags & SCF_DO_STCLASS_OR) /* Allow everything */\n\t\t\tssc_match_all_cp(data->start_class);\n\t\t    break;\n\n\t\tcase REG_ANY:\n                    {\n                        SV* REG_ANY_invlist = _new_invlist(2);\n                        REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,\n                                                            '\\n');\n                        if (flags & SCF_DO_STCLASS_OR) {\n                            ssc_union(data->start_class,\n                                      REG_ANY_invlist,\n                                      TRUE /* TRUE => invert, hence all but \\n\n                                            */\n                                      );\n                        }\n                        else if (flags & SCF_DO_STCLASS_AND) {\n                            ssc_intersection(data->start_class,\n                                             REG_ANY_invlist,\n                                             TRUE  /* TRUE => invert */\n                                             );\n                            ssc_clear_locale(data->start_class);\n                        }\n                        SvREFCNT_dec_NN(REG_ANY_invlist);\n\t\t    }\n\t\t    break;\n\n                case ANYOFD:\n                case ANYOFL:\n                case ANYOFPOSIXL:\n                case ANYOFH:\n                case ANYOF:\n\t\t    if (flags & SCF_DO_STCLASS_AND)\n\t\t\tssc_and(pRExC_state, data->start_class,\n                                (regnode_charclass *) scan);\n\t\t    else\n\t\t\tssc_or(pRExC_state, data->start_class,\n                                                          (regnode_charclass *) scan);\n\t\t    break;\n\n                case NANYOFM:\n                case ANYOFM:\n                  {\n                    SV* cp_list = get_ANYOFM_contents(scan);\n\n                    if (flags & SCF_DO_STCLASS_OR) {\n                        ssc_union(data->start_class, cp_list, invert);\n                    }\n                    else if (flags & SCF_DO_STCLASS_AND) {\n                        ssc_intersection(data->start_class, cp_list, invert);\n                    }\n\n                    SvREFCNT_dec_NN(cp_list);\n                    break;\n                  }\n\n\t\tcase NPOSIXL:\n                    invert = 1;\n                    /* FALLTHROUGH */\n\n\t\tcase POSIXL:\n                    namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;\n                    if (flags & SCF_DO_STCLASS_AND) {\n                        bool was_there = cBOOL(\n                                          ANYOF_POSIXL_TEST(data->start_class,\n                                                                 namedclass));\n                        ANYOF_POSIXL_ZERO(data->start_class);\n                        if (was_there) {    /* Do an AND */\n                            ANYOF_POSIXL_SET(data->start_class, namedclass);\n                        }\n                        /* No individual code points can now match */\n                        data->start_class->invlist\n                                                = sv_2mortal(_new_invlist(0));\n                    }\n                    else {\n                        int complement = namedclass + ((invert) ? -1 : 1);\n\n                        assert(flags & SCF_DO_STCLASS_OR);\n\n                        /* If the complement of this class was already there,\n                         * the result is that they match all code points,\n                         * (\\d + \\D == everything).  Remove the classes from\n                         * future consideration.  Locale is not relevant in\n                         * this case */\n                        if (ANYOF_POSIXL_TEST(data->start_class, complement)) {\n                            ssc_match_all_cp(data->start_class);\n                            ANYOF_POSIXL_CLEAR(data->start_class, namedclass);\n                            ANYOF_POSIXL_CLEAR(data->start_class, complement);\n                        }\n                        else {  /* The usual case; just add this class to the\n                                   existing set */\n                            ANYOF_POSIXL_SET(data->start_class, namedclass);\n                        }\n                    }\n                    break;\n\n                case NPOSIXA:   /* For these, we always know the exact set of\n                                   what's matched */\n                    invert = 1;\n                    /* FALLTHROUGH */\n\t\tcase POSIXA:\n                    my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);\n                    goto join_posix_and_ascii;\n\n\t\tcase NPOSIXD:\n\t\tcase NPOSIXU:\n                    invert = 1;\n                    /* FALLTHROUGH */\n\t\tcase POSIXD:\n\t\tcase POSIXU:\n                    my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);\n\n                    /* NPOSIXD matches all upper Latin1 code points unless the\n                     * target string being matched is UTF-8, which is\n                     * unknowable until match time.  Since we are going to\n                     * invert, we want to get rid of all of them so that the\n                     * inversion will match all */\n                    if (OP(scan) == NPOSIXD) {\n                        _invlist_subtract(my_invlist, PL_UpperLatin1,\n                                          &my_invlist);\n                    }\n\n                  join_posix_and_ascii:\n\n                    if (flags & SCF_DO_STCLASS_AND) {\n                        ssc_intersection(data->start_class, my_invlist, invert);\n                        ssc_clear_locale(data->start_class);\n                    }\n                    else {\n                        assert(flags & SCF_DO_STCLASS_OR);\n                        ssc_union(data->start_class, my_invlist, invert);\n                    }\n                    SvREFCNT_dec(my_invlist);\n\t\t}\n\t\tif (flags & SCF_DO_STCLASS_OR)\n\t\t    ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\t\tflags &= ~SCF_DO_STCLASS;\n\t    }\n\t}\n\telse if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {\n\t    data->flags |= (OP(scan) == MEOL\n\t\t\t    ? SF_BEFORE_MEOL\n\t\t\t    : SF_BEFORE_SEOL);\n            scan_commit(pRExC_state, data, minlenp, is_inf);\n\n\t}\n\telse if (  PL_regkind[OP(scan)] == BRANCHJ\n\t\t /* Lookbehind, or need to calculate parens/evals/stclass: */\n\t\t   && (scan->flags || data || (flags & SCF_DO_STCLASS))\n\t\t   && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))\n        {\n            if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY\n                || OP(scan) == UNLESSM )\n            {\n                /* Negative Lookahead/lookbehind\n                   In this case we can't do fixed string optimisation.\n                */\n\n                SSize_t deltanext, minnext, fake = 0;\n                regnode *nscan;\n                regnode_ssc intrnl;\n                int f = 0;\n\n                StructCopy(&zero_scan_data, &data_fake, scan_data_t);\n                if (data) {\n                    data_fake.whilem_c = data->whilem_c;\n                    data_fake.last_closep = data->last_closep;\n\t\t}\n                else\n                    data_fake.last_closep = &fake;\n\t\tdata_fake.pos_delta = delta;\n                if ( flags & SCF_DO_STCLASS && !scan->flags\n                     && OP(scan) == IFMATCH ) { /* Lookahead */\n                    ssc_init(pRExC_state, &intrnl);\n                    data_fake.start_class = &intrnl;\n                    f |= SCF_DO_STCLASS_AND;\n\t\t}\n                if (flags & SCF_WHILEM_VISITED_POS)\n                    f |= SCF_WHILEM_VISITED_POS;\n                next = regnext(scan);\n                nscan = NEXTOPER(NEXTOPER(scan));\n\n                /* recurse study_chunk() for lookahead body */\n                minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,\n                                      last, &data_fake, stopparen,\n                                      recursed_depth, NULL, f, depth+1);\n                if (scan->flags) {\n                    if (   deltanext < 0\n                        || deltanext > (I32) U8_MAX\n                        || minnext > (I32)U8_MAX\n                        || minnext + deltanext > (I32)U8_MAX)\n                    {\n\t\t\tFAIL2(\"Lookbehind longer than %\" UVuf \" not implemented\",\n                              (UV)U8_MAX);\n                    }\n\n                    /* The 'next_off' field has been repurposed to count the\n                     * additional starting positions to try beyond the initial\n                     * one.  (This leaves it at 0 for non-variable length\n                     * matches to avoid breakage for those not using this\n                     * extension) */\n                    if (deltanext) {\n                        scan->next_off = deltanext;\n                        ckWARNexperimental(RExC_parse,\n                            WARN_EXPERIMENTAL__VLB,\n                            \"Variable length lookbehind is experimental\");\n                    }\n                    scan->flags = (U8)minnext + deltanext;\n                }\n                if (data) {\n                    if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))\n                        pars++;\n                    if (data_fake.flags & SF_HAS_EVAL)\n                        data->flags |= SF_HAS_EVAL;\n                    data->whilem_c = data_fake.whilem_c;\n                }\n                if (f & SCF_DO_STCLASS_AND) {\n\t\t    if (flags & SCF_DO_STCLASS_OR) {\n\t\t\t/* OR before, AND after: ideally we would recurse with\n\t\t\t * data_fake to get the AND applied by study of the\n\t\t\t * remainder of the pattern, and then derecurse;\n\t\t\t * *** HACK *** for now just treat as \"no information\".\n\t\t\t * See [perl #56690].\n\t\t\t */\n\t\t\tssc_init(pRExC_state, data->start_class);\n\t\t    }  else {\n                        /* AND before and after: combine and continue.  These\n                         * assertions are zero-length, so can match an EMPTY\n                         * string */\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);\n                        ANYOF_FLAGS(data->start_class)\n                                                   |= SSC_MATCHES_EMPTY_STRING;\n\t\t    }\n                }\n\t    }\n#if PERL_ENABLE_POSITIVE_ASSERTION_STUDY\n            else {\n                /* Positive Lookahead/lookbehind\n                   In this case we can do fixed string optimisation,\n                   but we must be careful about it. Note in the case of\n                   lookbehind the positions will be offset by the minimum\n                   length of the pattern, something we won't know about\n                   until after the recurse.\n                */\n                SSize_t deltanext, fake = 0;\n                regnode *nscan;\n                regnode_ssc intrnl;\n                int f = 0;\n                /* We use SAVEFREEPV so that when the full compile\n                    is finished perl will clean up the allocated\n                    minlens when it's all done. This way we don't\n                    have to worry about freeing them when we know\n                    they wont be used, which would be a pain.\n                 */\n                SSize_t *minnextp;\n                Newx( minnextp, 1, SSize_t );\n                SAVEFREEPV(minnextp);\n\n                if (data) {\n                    StructCopy(data, &data_fake, scan_data_t);\n                    if ((flags & SCF_DO_SUBSTR) && data->last_found) {\n                        f |= SCF_DO_SUBSTR;\n                        if (scan->flags)\n                            scan_commit(pRExC_state, &data_fake, minlenp, is_inf);\n                        data_fake.last_found=newSVsv(data->last_found);\n                    }\n                }\n                else\n                    data_fake.last_closep = &fake;\n                data_fake.flags = 0;\n                data_fake.substrs[0].flags = 0;\n                data_fake.substrs[1].flags = 0;\n\t\tdata_fake.pos_delta = delta;\n                if (is_inf)\n\t            data_fake.flags |= SF_IS_INF;\n                if ( flags & SCF_DO_STCLASS && !scan->flags\n                     && OP(scan) == IFMATCH ) { /* Lookahead */\n                    ssc_init(pRExC_state, &intrnl);\n                    data_fake.start_class = &intrnl;\n                    f |= SCF_DO_STCLASS_AND;\n                }\n                if (flags & SCF_WHILEM_VISITED_POS)\n                    f |= SCF_WHILEM_VISITED_POS;\n                next = regnext(scan);\n                nscan = NEXTOPER(NEXTOPER(scan));\n\n                /* positive lookahead study_chunk() recursion */\n                *minnextp = study_chunk(pRExC_state, &nscan, minnextp,\n                                        &deltanext, last, &data_fake,\n                                        stopparen, recursed_depth, NULL,\n                                        f, depth+1);\n                if (scan->flags) {\n                    assert(0);  /* This code has never been tested since this\n                                   is normally not compiled */\n                    if (   deltanext < 0\n                        || deltanext > (I32) U8_MAX\n                        || *minnextp > (I32)U8_MAX\n                        || *minnextp + deltanext > (I32)U8_MAX)\n                    {\n\t\t\tFAIL2(\"Lookbehind longer than %\" UVuf \" not implemented\",\n                              (UV)U8_MAX);\n                    }\n\n                    if (deltanext) {\n                        scan->next_off = deltanext;\n                    }\n                    scan->flags = (U8)*minnextp + deltanext;\n                }\n\n                *minnextp += min;\n\n                if (f & SCF_DO_STCLASS_AND) {\n                    ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);\n                    ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;\n                }\n                if (data) {\n                    if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))\n                        pars++;\n                    if (data_fake.flags & SF_HAS_EVAL)\n                        data->flags |= SF_HAS_EVAL;\n                    data->whilem_c = data_fake.whilem_c;\n                    if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {\n                        int i;\n                        if (RExC_rx->minlen<*minnextp)\n                            RExC_rx->minlen=*minnextp;\n                        scan_commit(pRExC_state, &data_fake, minnextp, is_inf);\n                        SvREFCNT_dec_NN(data_fake.last_found);\n\n                        for (i = 0; i < 2; i++) {\n                            if (data_fake.substrs[i].minlenp != minlenp) {\n                                data->substrs[i].min_offset =\n                                            data_fake.substrs[i].min_offset;\n                                data->substrs[i].max_offset =\n                                            data_fake.substrs[i].max_offset;\n                                data->substrs[i].minlenp =\n                                            data_fake.substrs[i].minlenp;\n                                data->substrs[i].lookbehind += scan->flags;\n                            }\n                        }\n                    }\n                }\n\t    }\n#endif\n\t}\n\n\telse if (OP(scan) == OPEN) {\n\t    if (stopparen != (I32)ARG(scan))\n\t        pars++;\n\t}\n\telse if (OP(scan) == CLOSE) {\n\t    if (stopparen == (I32)ARG(scan)) {\n\t        break;\n\t    }\n\t    if ((I32)ARG(scan) == is_par) {\n\t\tnext = regnext(scan);\n\n\t\tif ( next && (OP(next) != WHILEM) && next < last)\n\t\t    is_par = 0;\t\t/* Disable optimization */\n\t    }\n\t    if (data)\n\t\t*(data->last_closep) = ARG(scan);\n\t}\n\telse if (OP(scan) == EVAL) {\n\t\tif (data)\n\t\t    data->flags |= SF_HAS_EVAL;\n\t}\n\telse if ( PL_regkind[OP(scan)] == ENDLIKE ) {\n\t    if (flags & SCF_DO_SUBSTR) {\n                scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\tflags &= ~SCF_DO_SUBSTR;\n\t    }\n\t    if (data && OP(scan)==ACCEPT) {\n\t        data->flags |= SCF_SEEN_ACCEPT;\n\t        if (stopmin > min)\n\t            stopmin = min;\n\t    }\n\t}\n\telse if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */\n\t{\n\t\tif (flags & SCF_DO_SUBSTR) {\n                    scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\t    data->cur_is_floating = 1; /* float */\n\t\t}\n\t\tis_inf = is_inf_internal = 1;\n\t\tif (flags & SCF_DO_STCLASS_OR) /* Allow everything */\n\t\t    ssc_anything(data->start_class);\n\t\tflags &= ~SCF_DO_STCLASS;\n\t}\n\telse if (OP(scan) == GPOS) {\n            if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&\n\t        !(delta || is_inf || (data && data->pos_delta)))\n\t    {\n                if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))\n                    RExC_rx->intflags |= PREGf_ANCH_GPOS;\n\t        if (RExC_rx->gofs < (STRLEN)min)\n\t\t    RExC_rx->gofs = min;\n            } else {\n                RExC_rx->intflags |= PREGf_GPOS_FLOAT;\n                RExC_rx->gofs = 0;\n            }\n\t}\n#ifdef TRIE_STUDY_OPT\n#ifdef FULL_TRIE_STUDY\n        else if (PL_regkind[OP(scan)] == TRIE) {\n            /* NOTE - There is similar code to this block above for handling\n               BRANCH nodes on the initial study.  If you change stuff here\n               check there too. */\n            regnode *trie_node= scan;\n            regnode *tail= regnext(scan);\n            reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];\n            SSize_t max1 = 0, min1 = SSize_t_MAX;\n            regnode_ssc accum;\n\n            if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */\n                /* Cannot merge strings after this. */\n                scan_commit(pRExC_state, data, minlenp, is_inf);\n            }\n            if (flags & SCF_DO_STCLASS)\n                ssc_init_zero(pRExC_state, &accum);\n\n            if (!trie->jump) {\n                min1= trie->minlen;\n                max1= trie->maxlen;\n            } else {\n                const regnode *nextbranch= NULL;\n                U32 word;\n\n                for ( word=1 ; word <= trie->wordcount ; word++)\n                {\n                    SSize_t deltanext=0, minnext=0, f = 0, fake;\n                    regnode_ssc this_class;\n\n                    StructCopy(&zero_scan_data, &data_fake, scan_data_t);\n                    if (data) {\n                        data_fake.whilem_c = data->whilem_c;\n                        data_fake.last_closep = data->last_closep;\n                    }\n                    else\n                        data_fake.last_closep = &fake;\n\t\t    data_fake.pos_delta = delta;\n                    if (flags & SCF_DO_STCLASS) {\n                        ssc_init(pRExC_state, &this_class);\n                        data_fake.start_class = &this_class;\n                        f = SCF_DO_STCLASS_AND;\n                    }\n                    if (flags & SCF_WHILEM_VISITED_POS)\n                        f |= SCF_WHILEM_VISITED_POS;\n\n                    if (trie->jump[word]) {\n                        if (!nextbranch)\n                            nextbranch = trie_node + trie->jump[0];\n                        scan= trie_node + trie->jump[word];\n                        /* We go from the jump point to the branch that follows\n                           it. Note this means we need the vestigal unused\n                           branches even though they arent otherwise used. */\n                        /* optimise study_chunk() for TRIE */\n                        minnext = study_chunk(pRExC_state, &scan, minlenp,\n                            &deltanext, (regnode *)nextbranch, &data_fake,\n                            stopparen, recursed_depth, NULL, f, depth+1);\n                    }\n                    if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)\n                        nextbranch= regnext((regnode*)nextbranch);\n\n                    if (min1 > (SSize_t)(minnext + trie->minlen))\n                        min1 = minnext + trie->minlen;\n                    if (deltanext == SSize_t_MAX) {\n                        is_inf = is_inf_internal = 1;\n                        max1 = SSize_t_MAX;\n                    } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))\n                        max1 = minnext + deltanext + trie->maxlen;\n\n                    if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))\n                        pars++;\n                    if (data_fake.flags & SCF_SEEN_ACCEPT) {\n                        if ( stopmin > min + min1)\n\t                    stopmin = min + min1;\n\t                flags &= ~SCF_DO_SUBSTR;\n\t                if (data)\n\t                    data->flags |= SCF_SEEN_ACCEPT;\n\t            }\n                    if (data) {\n                        if (data_fake.flags & SF_HAS_EVAL)\n                            data->flags |= SF_HAS_EVAL;\n                        data->whilem_c = data_fake.whilem_c;\n                    }\n                    if (flags & SCF_DO_STCLASS)\n                        ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);\n                }\n            }\n            if (flags & SCF_DO_SUBSTR) {\n                data->pos_min += min1;\n                data->pos_delta += max1 - min1;\n                if (max1 != min1 || is_inf)\n                    data->cur_is_floating = 1; /* float */\n            }\n            min += min1;\n            if (delta != SSize_t_MAX) {\n                if (SSize_t_MAX - (max1 - min1) >= delta)\n                    delta += max1 - min1;\n                else\n                    delta = SSize_t_MAX;\n            }\n            if (flags & SCF_DO_STCLASS_OR) {\n                ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);\n                if (min1) {\n                    ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n                    flags &= ~SCF_DO_STCLASS;\n                }\n            }\n            else if (flags & SCF_DO_STCLASS_AND) {\n                if (min1) {\n                    ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);\n                    flags &= ~SCF_DO_STCLASS;\n                }\n                else {\n                    /* Switch to OR mode: cache the old value of\n                     * data->start_class */\n\t\t    INIT_AND_WITHP;\n                    StructCopy(data->start_class, and_withp, regnode_ssc);\n                    flags &= ~SCF_DO_STCLASS_AND;\n                    StructCopy(&accum, data->start_class, regnode_ssc);\n                    flags |= SCF_DO_STCLASS_OR;\n                }\n            }\n            scan= tail;\n            continue;\n        }\n#else\n\telse if (PL_regkind[OP(scan)] == TRIE) {\n\t    reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];\n\t    U8*bang=NULL;\n\n\t    min += trie->minlen;\n\t    delta += (trie->maxlen - trie->minlen);\n\t    flags &= ~SCF_DO_STCLASS; /* xxx */\n            if (flags & SCF_DO_SUBSTR) {\n                /* Cannot expect anything... */\n                scan_commit(pRExC_state, data, minlenp, is_inf);\n    \t        data->pos_min += trie->minlen;\n    \t        data->pos_delta += (trie->maxlen - trie->minlen);\n\t\tif (trie->maxlen != trie->minlen)\n\t\t    data->cur_is_floating = 1; /* float */\n    \t    }\n    \t    if (trie->jump) /* no more substrings -- for now /grr*/\n               flags &= ~SCF_DO_SUBSTR;\n\t}\n#endif /* old or new */\n#endif /* TRIE_STUDY_OPT */\n\n\t/* Else: zero-length, ignore. */\n\tscan = regnext(scan);\n    }\n\n  finish:\n    if (frame) {\n        /* we need to unwind recursion. */\n        depth = depth - 1;\n\n        DEBUG_STUDYDATA(\"frame-end\", data, depth, is_inf);\n        DEBUG_PEEP(\"fend\", scan, depth, flags);\n\n        /* restore previous context */\n        last = frame->last_regnode;\n        scan = frame->next_regnode;\n        stopparen = frame->stopparen;\n        recursed_depth = frame->prev_recursed_depth;\n\n        RExC_frame_last = frame->prev_frame;\n        frame = frame->this_prev_frame;\n        goto fake_study_recurse;\n    }\n\n    assert(!frame);\n    DEBUG_STUDYDATA(\"pre-fin\", data, depth, is_inf);\n\n    *scanp = scan;\n    *deltap = is_inf_internal ? SSize_t_MAX : delta;\n\n    if (flags & SCF_DO_SUBSTR && is_inf)\n\tdata->pos_delta = SSize_t_MAX - data->pos_min;\n    if (is_par > (I32)U8_MAX)\n\tis_par = 0;\n    if (is_par && pars==1 && data) {\n\tdata->flags |= SF_IN_PAR;\n\tdata->flags &= ~SF_HAS_PAR;\n    }\n    else if (pars && data) {\n\tdata->flags |= SF_HAS_PAR;\n\tdata->flags &= ~SF_IN_PAR;\n    }\n    if (flags & SCF_DO_STCLASS_OR)\n\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n    if (flags & SCF_TRIE_RESTUDY)\n        data->flags |= \tSCF_TRIE_RESTUDY;\n\n    DEBUG_STUDYDATA(\"post-fin\", data, depth, is_inf);\n\n    {\n        SSize_t final_minlen= min < stopmin ? min : stopmin;\n\n        if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {\n            if (final_minlen > SSize_t_MAX - delta)\n                RExC_maxlen = SSize_t_MAX;\n            else if (RExC_maxlen < final_minlen + delta)\n                RExC_maxlen = final_minlen + delta;\n        }\n        return final_minlen;\n    }\n    NOT_REACHED; /* NOTREACHED */", "func_hash": 124503767038519369207654054837018016597, "file_name": "regcomp.c", "file_hash": 257709146327047081328217382800700188887, "cwe": ["CWE-120"], "cve": "CVE-2020-12723", "cve_desc": "regcomp.c in Perl before 5.30.3 allows a buffer overflow via a crafted regular expression because of recursive S_study_chunk calls.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12723"}
{"idx": 486837, "project": "perl5", "commit_id": "66bbb51b93253a3f87d11c2695cfb7bdb782184a", "project_url": "https://github.com/perl/perl5", "commit_url": "https://github.com/perl/perl5/commit/66bbb51b93253a3f87d11c2695cfb7bdb782184a", "commit_message": "study_chunk: avoid mutating regexp program within GOSUB\n\ngh16947 and gh17743: studying GOSUB may restudy in an inner call\n(via a mix of recursion and enframing) something that an outer call\nis in the middle of looking at.  Let the outer frame deal with it.\n\n(CVE-2020-12723)\n\n(cherry picked from commit c4033e740bd18d9fbe3456a9db2ec2053cdc5271)", "target": 0, "func": "STATIC SSize_t\nS_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,\n                        SSize_t *minlenp, SSize_t *deltap,\n\t\t\tregnode *last,\n\t\t\tscan_data_t *data,\n\t\t\tI32 stopparen,\n                        U32 recursed_depth,\n\t\t\tregnode_ssc *and_withp,\n\t\t\tU32 flags, U32 depth, bool was_mutate_ok)\n\t\t\t/* scanp: Start here (read-write). */\n\t\t\t/* deltap: Write maxlen-minlen here. */\n\t\t\t/* last: Stop before this one. */\n\t\t\t/* data: string data about the pattern */\n\t\t\t/* stopparen: treat close N as END */\n\t\t\t/* recursed: which subroutines have we recursed into */\n\t\t\t/* and_withp: Valid if flags & SCF_DO_STCLASS_OR */\n{\n    dVAR;\n    /* There must be at least this number of characters to match */\n    SSize_t min = 0;\n    I32 pars = 0, code;\n    regnode *scan = *scanp, *next;\n    SSize_t delta = 0;\n    int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);\n    int is_inf_internal = 0;\t\t/* The studied chunk is infinite */\n    I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;\n    scan_data_t data_fake;\n    SV *re_trie_maxbuff = NULL;\n    regnode *first_non_open = scan;\n    SSize_t stopmin = SSize_t_MAX;\n    scan_frame *frame = NULL;\n    GET_RE_DEBUG_FLAGS_DECL;\n\n    PERL_ARGS_ASSERT_STUDY_CHUNK;\n    RExC_study_started= 1;\n\n    Zero(&data_fake, 1, scan_data_t);\n\n    if ( depth == 0 ) {\n        while (first_non_open && OP(first_non_open) == OPEN)\n            first_non_open=regnext(first_non_open);\n    }\n\n\n  fake_study_recurse:\n    DEBUG_r(\n        RExC_study_chunk_recursed_count++;\n    );\n    DEBUG_OPTIMISE_MORE_r(\n    {\n        Perl_re_indentf( aTHX_  \"study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p\",\n            depth, (long)stopparen,\n            (unsigned long)RExC_study_chunk_recursed_count,\n            (unsigned long)depth, (unsigned long)recursed_depth,\n            scan,\n            last);\n        if (recursed_depth) {\n            U32 i;\n            U32 j;\n            for ( j = 0 ; j < recursed_depth ; j++ ) {\n                for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {\n                    if (\n                        PAREN_TEST(RExC_study_chunk_recursed +\n                                   ( j * RExC_study_chunk_recursed_bytes), i )\n                        && (\n                            !j ||\n                            !PAREN_TEST(RExC_study_chunk_recursed +\n                                   (( j - 1 ) * RExC_study_chunk_recursed_bytes), i)\n                        )\n                    ) {\n                        Perl_re_printf( aTHX_ \" %d\",(int)i);\n                        break;\n                    }\n                }\n                if ( j + 1 < recursed_depth ) {\n                    Perl_re_printf( aTHX_  \",\");\n                }\n            }\n        }\n        Perl_re_printf( aTHX_ \"\\n\");\n    }\n    );\n    while ( scan && OP(scan) != END && scan < last ){\n        UV min_subtract = 0;    /* How mmany chars to subtract from the minimum\n                                   node length to get a real minimum (because\n                                   the folded version may be shorter) */\n\tbool unfolded_multi_char = FALSE;\n        /* avoid mutating ops if we are anywhere within the recursed or\n         * enframed handling for a GOSUB: the outermost level will handle it.\n         */\n        bool mutate_ok = was_mutate_ok && !(frame && frame->in_gosub);\n\t/* Peephole optimizer: */\n        DEBUG_STUDYDATA(\"Peep\", data, depth, is_inf);\n        DEBUG_PEEP(\"Peep\", scan, depth, flags);\n\n\n        /* The reason we do this here is that we need to deal with things like\n         * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT\n         * parsing code, as each (?:..) is handled by a different invocation of\n         * reg() -- Yves\n         */\n        if (mutate_ok)\n            JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);\n\n        /* Follow the next-chain of the current node and optimize\n           away all the NOTHINGs from it.\n         */\n        rck_elide_nothing(scan);\n\n\t/* The principal pseudo-switch.  Cannot be a switch, since we\n\t   look into several different things.  */\n        if ( OP(scan) == DEFINEP ) {\n            SSize_t minlen = 0;\n            SSize_t deltanext = 0;\n            SSize_t fake_last_close = 0;\n            I32 f = SCF_IN_DEFINE;\n\n            StructCopy(&zero_scan_data, &data_fake, scan_data_t);\n            scan = regnext(scan);\n            assert( OP(scan) == IFTHEN );\n            DEBUG_PEEP(\"expect IFTHEN\", scan, depth, flags);\n\n            data_fake.last_closep= &fake_last_close;\n            minlen = *minlenp;\n            next = regnext(scan);\n            scan = NEXTOPER(NEXTOPER(scan));\n            DEBUG_PEEP(\"scan\", scan, depth, flags);\n            DEBUG_PEEP(\"next\", next, depth, flags);\n\n            /* we suppose the run is continuous, last=next...\n             * NOTE we dont use the return here! */\n            /* DEFINEP study_chunk() recursion */\n            (void)study_chunk(pRExC_state, &scan, &minlen,\n                              &deltanext, next, &data_fake, stopparen,\n                              recursed_depth, NULL, f, depth+1, mutate_ok);\n\n            scan = next;\n        } else\n        if (\n            OP(scan) == BRANCH  ||\n            OP(scan) == BRANCHJ ||\n            OP(scan) == IFTHEN\n        ) {\n\t    next = regnext(scan);\n\t    code = OP(scan);\n\n            /* The op(next)==code check below is to see if we\n             * have \"BRANCH-BRANCH\", \"BRANCHJ-BRANCHJ\", \"IFTHEN-IFTHEN\"\n             * IFTHEN is special as it might not appear in pairs.\n             * Not sure whether BRANCH-BRANCHJ is possible, regardless\n             * we dont handle it cleanly. */\n\t    if (OP(next) == code || code == IFTHEN) {\n                /* NOTE - There is similar code to this block below for\n                 * handling TRIE nodes on a re-study.  If you change stuff here\n                 * check there too. */\n\t\tSSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;\n\t\tregnode_ssc accum;\n\t\tregnode * const startbranch=scan;\n\n                if (flags & SCF_DO_SUBSTR) {\n                    /* Cannot merge strings after this. */\n                    scan_commit(pRExC_state, data, minlenp, is_inf);\n                }\n\n                if (flags & SCF_DO_STCLASS)\n\t\t    ssc_init_zero(pRExC_state, &accum);\n\n\t\twhile (OP(scan) == code) {\n\t\t    SSize_t deltanext, minnext, fake;\n\t\t    I32 f = 0;\n\t\t    regnode_ssc this_class;\n\n                    DEBUG_PEEP(\"Branch\", scan, depth, flags);\n\n\t\t    num++;\n                    StructCopy(&zero_scan_data, &data_fake, scan_data_t);\n\t\t    if (data) {\n\t\t\tdata_fake.whilem_c = data->whilem_c;\n\t\t\tdata_fake.last_closep = data->last_closep;\n\t\t    }\n\t\t    else\n\t\t\tdata_fake.last_closep = &fake;\n\n\t\t    data_fake.pos_delta = delta;\n\t\t    next = regnext(scan);\n\n                    scan = NEXTOPER(scan); /* everything */\n                    if (code != BRANCH)    /* everything but BRANCH */\n\t\t\tscan = NEXTOPER(scan);\n\n\t\t    if (flags & SCF_DO_STCLASS) {\n\t\t\tssc_init(pRExC_state, &this_class);\n\t\t\tdata_fake.start_class = &this_class;\n\t\t\tf = SCF_DO_STCLASS_AND;\n\t\t    }\n\t\t    if (flags & SCF_WHILEM_VISITED_POS)\n\t\t\tf |= SCF_WHILEM_VISITED_POS;\n\n\t\t    /* we suppose the run is continuous, last=next...*/\n                    /* recurse study_chunk() for each BRANCH in an alternation */\n\t\t    minnext = study_chunk(pRExC_state, &scan, minlenp,\n                                      &deltanext, next, &data_fake, stopparen,\n                                      recursed_depth, NULL, f, depth+1,\n                                      mutate_ok);\n\n\t\t    if (min1 > minnext)\n\t\t\tmin1 = minnext;\n\t\t    if (deltanext == SSize_t_MAX) {\n\t\t\tis_inf = is_inf_internal = 1;\n\t\t\tmax1 = SSize_t_MAX;\n\t\t    } else if (max1 < minnext + deltanext)\n\t\t\tmax1 = minnext + deltanext;\n\t\t    scan = next;\n\t\t    if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))\n\t\t\tpars++;\n\t            if (data_fake.flags & SCF_SEEN_ACCEPT) {\n\t                if ( stopmin > minnext)\n\t                    stopmin = min + min1;\n\t                flags &= ~SCF_DO_SUBSTR;\n\t                if (data)\n\t                    data->flags |= SCF_SEEN_ACCEPT;\n\t            }\n\t\t    if (data) {\n\t\t\tif (data_fake.flags & SF_HAS_EVAL)\n\t\t\t    data->flags |= SF_HAS_EVAL;\n\t\t\tdata->whilem_c = data_fake.whilem_c;\n\t\t    }\n\t\t    if (flags & SCF_DO_STCLASS)\n\t\t\tssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);\n\t\t}\n\t\tif (code == IFTHEN && num < 2) /* Empty ELSE branch */\n\t\t    min1 = 0;\n\t\tif (flags & SCF_DO_SUBSTR) {\n\t\t    data->pos_min += min1;\n\t\t    if (data->pos_delta >= SSize_t_MAX - (max1 - min1))\n\t\t        data->pos_delta = SSize_t_MAX;\n\t\t    else\n\t\t        data->pos_delta += max1 - min1;\n\t\t    if (max1 != min1 || is_inf)\n\t\t\tdata->cur_is_floating = 1;\n\t\t}\n\t\tmin += min1;\n\t\tif (delta == SSize_t_MAX\n\t\t || SSize_t_MAX - delta - (max1 - min1) < 0)\n\t\t    delta = SSize_t_MAX;\n\t\telse\n\t\t    delta += max1 - min1;\n\t\tif (flags & SCF_DO_STCLASS_OR) {\n\t\t    ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);\n\t\t    if (min1) {\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\t\t\tflags &= ~SCF_DO_STCLASS;\n\t\t    }\n\t\t}\n\t\telse if (flags & SCF_DO_STCLASS_AND) {\n\t\t    if (min1) {\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);\n\t\t\tflags &= ~SCF_DO_STCLASS;\n\t\t    }\n\t\t    else {\n\t\t\t/* Switch to OR mode: cache the old value of\n\t\t\t * data->start_class */\n\t\t\tINIT_AND_WITHP;\n\t\t\tStructCopy(data->start_class, and_withp, regnode_ssc);\n\t\t\tflags &= ~SCF_DO_STCLASS_AND;\n\t\t\tStructCopy(&accum, data->start_class, regnode_ssc);\n\t\t\tflags |= SCF_DO_STCLASS_OR;\n\t\t    }\n\t\t}\n\n                if (PERL_ENABLE_TRIE_OPTIMISATION\n                    && OP(startbranch) == BRANCH\n                    && mutate_ok\n                ) {\n\t\t/* demq.\n\n                   Assuming this was/is a branch we are dealing with: 'scan'\n                   now points at the item that follows the branch sequence,\n                   whatever it is. We now start at the beginning of the\n                   sequence and look for subsequences of\n\n\t\t   BRANCH->EXACT=>x1\n\t\t   BRANCH->EXACT=>x2\n\t\t   tail\n\n                   which would be constructed from a pattern like\n                   /A|LIST|OF|WORDS/\n\n\t\t   If we can find such a subsequence we need to turn the first\n\t\t   element into a trie and then add the subsequent branch exact\n\t\t   strings to the trie.\n\n\t\t   We have two cases\n\n                     1. patterns where the whole set of branches can be\n                        converted.\n\n\t\t     2. patterns where only a subset can be converted.\n\n\t\t   In case 1 we can replace the whole set with a single regop\n\t\t   for the trie. In case 2 we need to keep the start and end\n\t\t   branches so\n\n\t\t     'BRANCH EXACT; BRANCH EXACT; BRANCH X'\n\t\t     becomes BRANCH TRIE; BRANCH X;\n\n\t\t  There is an additional case, that being where there is a\n\t\t  common prefix, which gets split out into an EXACT like node\n\t\t  preceding the TRIE node.\n\n\t\t  If x(1..n)==tail then we can do a simple trie, if not we make\n\t\t  a \"jump\" trie, such that when we match the appropriate word\n\t\t  we \"jump\" to the appropriate tail node. Essentially we turn\n\t\t  a nested if into a case structure of sorts.\n\n\t\t*/\n\n\t\t    int made=0;\n\t\t    if (!re_trie_maxbuff) {\n\t\t\tre_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);\n\t\t\tif (!SvIOK(re_trie_maxbuff))\n\t\t\t    sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);\n\t\t    }\n                    if ( SvIV(re_trie_maxbuff)>=0  ) {\n                        regnode *cur;\n                        regnode *first = (regnode *)NULL;\n                        regnode *last = (regnode *)NULL;\n                        regnode *tail = scan;\n                        U8 trietype = 0;\n                        U32 count=0;\n\n                        /* var tail is used because there may be a TAIL\n                           regop in the way. Ie, the exacts will point to the\n                           thing following the TAIL, but the last branch will\n                           point at the TAIL. So we advance tail. If we\n                           have nested (?:) we may have to move through several\n                           tails.\n                         */\n\n                        while ( OP( tail ) == TAIL ) {\n                            /* this is the TAIL generated by (?:) */\n                            tail = regnext( tail );\n                        }\n\n\n                        DEBUG_TRIE_COMPILE_r({\n                            regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);\n                            Perl_re_indentf( aTHX_  \"%s %\" UVuf \":%s\\n\",\n                              depth+1,\n                              \"Looking for TRIE'able sequences. Tail node is \",\n                              (UV) REGNODE_OFFSET(tail),\n                              SvPV_nolen_const( RExC_mysv )\n                            );\n                        });\n\n                        /*\n\n                            Step through the branches\n                                cur represents each branch,\n                                noper is the first thing to be matched as part\n                                      of that branch\n                                noper_next is the regnext() of that node.\n\n                            We normally handle a case like this\n                            /FOO[xyz]|BAR[pqr]/ via a \"jump trie\" but we also\n                            support building with NOJUMPTRIE, which restricts\n                            the trie logic to structures like /FOO|BAR/.\n\n                            If noper is a trieable nodetype then the branch is\n                            a possible optimization target. If we are building\n                            under NOJUMPTRIE then we require that noper_next is\n                            the same as scan (our current position in the regex\n                            program).\n\n                            Once we have two or more consecutive such branches\n                            we can create a trie of the EXACT's contents and\n                            stitch it in place into the program.\n\n                            If the sequence represents all of the branches in\n                            the alternation we replace the entire thing with a\n                            single TRIE node.\n\n                            Otherwise when it is a subsequence we need to\n                            stitch it in place and replace only the relevant\n                            branches. This means the first branch has to remain\n                            as it is used by the alternation logic, and its\n                            next pointer, and needs to be repointed at the item\n                            on the branch chain following the last branch we\n                            have optimized away.\n\n                            This could be either a BRANCH, in which case the\n                            subsequence is internal, or it could be the item\n                            following the branch sequence in which case the\n                            subsequence is at the end (which does not\n                            necessarily mean the first node is the start of the\n                            alternation).\n\n                            TRIE_TYPE(X) is a define which maps the optype to a\n                            trietype.\n\n                                optype          |  trietype\n                                ----------------+-----------\n                                NOTHING         | NOTHING\n                                EXACT           | EXACT\n                                EXACT_ONLY8     | EXACT\n                                EXACTFU         | EXACTFU\n                                EXACTFU_ONLY8   | EXACTFU\n                                EXACTFUP        | EXACTFU\n                                EXACTFAA        | EXACTFAA\n                                EXACTL          | EXACTL\n                                EXACTFLU8       | EXACTFLU8\n\n\n                        */\n#define TRIE_TYPE(X) ( ( NOTHING == (X) )                                   \\\n                       ? NOTHING                                            \\\n                       : ( EXACT == (X) || EXACT_ONLY8 == (X) )             \\\n                         ? EXACT                                            \\\n                         : (     EXACTFU == (X)                             \\\n                              || EXACTFU_ONLY8 == (X)                       \\\n                              || EXACTFUP == (X) )                          \\\n                           ? EXACTFU                                        \\\n                           : ( EXACTFAA == (X) )                            \\\n                             ? EXACTFAA                                     \\\n                             : ( EXACTL == (X) )                            \\\n                               ? EXACTL                                     \\\n                               : ( EXACTFLU8 == (X) )                       \\\n                                 ? EXACTFLU8                                \\\n                                 : 0 )\n\n                        /* dont use tail as the end marker for this traverse */\n                        for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {\n                            regnode * const noper = NEXTOPER( cur );\n                            U8 noper_type = OP( noper );\n                            U8 noper_trietype = TRIE_TYPE( noper_type );\n#if defined(DEBUGGING) || defined(NOJUMPTRIE)\n                            regnode * const noper_next = regnext( noper );\n                            U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;\n                            U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;\n#endif\n\n                            DEBUG_TRIE_COMPILE_r({\n                                regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);\n                                Perl_re_indentf( aTHX_  \"- %d:%s (%d)\",\n                                   depth+1,\n                                   REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );\n\n                                regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);\n                                Perl_re_printf( aTHX_  \" -> %d:%s\",\n                                    REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));\n\n                                if ( noper_next ) {\n                                  regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);\n                                  Perl_re_printf( aTHX_ \"\\t=> %d:%s\\t\",\n                                    REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));\n                                }\n                                Perl_re_printf( aTHX_  \"(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\\n\",\n                                   REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),\n\t\t\t\t   PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]\n\t\t\t\t);\n                            });\n\n                            /* Is noper a trieable nodetype that can be merged\n                             * with the current trie (if there is one)? */\n                            if ( noper_trietype\n                                  &&\n                                  (\n                                        ( noper_trietype == NOTHING )\n                                        || ( trietype == NOTHING )\n                                        || ( trietype == noper_trietype )\n                                  )\n#ifdef NOJUMPTRIE\n                                  && noper_next >= tail\n#endif\n                                  && count < U16_MAX)\n                            {\n                                /* Handle mergable triable node Either we are\n                                 * the first node in a new trieable sequence,\n                                 * in which case we do some bookkeeping,\n                                 * otherwise we update the end pointer. */\n                                if ( !first ) {\n                                    first = cur;\n\t\t\t\t    if ( noper_trietype == NOTHING ) {\n#if !defined(DEBUGGING) && !defined(NOJUMPTRIE)\n\t\t\t\t\tregnode * const noper_next = regnext( noper );\n                                        U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;\n\t\t\t\t\tU8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;\n#endif\n\n                                        if ( noper_next_trietype ) {\n\t\t\t\t\t    trietype = noper_next_trietype;\n                                        } else if (noper_next_type)  {\n                                            /* a NOTHING regop is 1 regop wide.\n                                             * We need at least two for a trie\n                                             * so we can't merge this in */\n                                            first = NULL;\n                                        }\n                                    } else {\n                                        trietype = noper_trietype;\n                                    }\n                                } else {\n                                    if ( trietype == NOTHING )\n                                        trietype = noper_trietype;\n                                    last = cur;\n                                }\n\t\t\t\tif (first)\n\t\t\t\t    count++;\n                            } /* end handle mergable triable node */\n                            else {\n                                /* handle unmergable node -\n                                 * noper may either be a triable node which can\n                                 * not be tried together with the current trie,\n                                 * or a non triable node */\n                                if ( last ) {\n                                    /* If last is set and trietype is not\n                                     * NOTHING then we have found at least two\n                                     * triable branch sequences in a row of a\n                                     * similar trietype so we can turn them\n                                     * into a trie. If/when we allow NOTHING to\n                                     * start a trie sequence this condition\n                                     * will be required, and it isn't expensive\n                                     * so we leave it in for now. */\n                                    if ( trietype && trietype != NOTHING )\n                                        make_trie( pRExC_state,\n                                                startbranch, first, cur, tail,\n                                                count, trietype, depth+1 );\n                                    last = NULL; /* note: we clear/update\n                                                    first, trietype etc below,\n                                                    so we dont do it here */\n                                }\n                                if ( noper_trietype\n#ifdef NOJUMPTRIE\n                                     && noper_next >= tail\n#endif\n                                ){\n                                    /* noper is triable, so we can start a new\n                                     * trie sequence */\n                                    count = 1;\n                                    first = cur;\n                                    trietype = noper_trietype;\n                                } else if (first) {\n                                    /* if we already saw a first but the\n                                     * current node is not triable then we have\n                                     * to reset the first information. */\n                                    count = 0;\n                                    first = NULL;\n                                    trietype = 0;\n                                }\n                            } /* end handle unmergable node */\n                        } /* loop over branches */\n                        DEBUG_TRIE_COMPILE_r({\n                            regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);\n                            Perl_re_indentf( aTHX_  \"- %s (%d)  \",\n                              depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));\n                            Perl_re_printf( aTHX_  \"(First==%d, Last==%d, Cur==%d, tt==%s)\\n\",\n                               REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),\n                               PL_reg_name[trietype]\n                            );\n\n                        });\n                        if ( last && trietype ) {\n                            if ( trietype != NOTHING ) {\n                                /* the last branch of the sequence was part of\n                                 * a trie, so we have to construct it here\n                                 * outside of the loop */\n                                made= make_trie( pRExC_state, startbranch,\n                                                 first, scan, tail, count,\n                                                 trietype, depth+1 );\n#ifdef TRIE_STUDY_OPT\n                                if ( ((made == MADE_EXACT_TRIE &&\n                                     startbranch == first)\n                                     || ( first_non_open == first )) &&\n                                     depth==0 ) {\n                                    flags |= SCF_TRIE_RESTUDY;\n                                    if ( startbranch == first\n                                         && scan >= tail )\n                                    {\n                                        RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;\n                                    }\n                                }\n#endif\n                            } else {\n                                /* at this point we know whatever we have is a\n                                 * NOTHING sequence/branch AND if 'startbranch'\n                                 * is 'first' then we can turn the whole thing\n                                 * into a NOTHING\n                                 */\n                                if ( startbranch == first ) {\n                                    regnode *opt;\n                                    /* the entire thing is a NOTHING sequence,\n                                     * something like this: (?:|) So we can\n                                     * turn it into a plain NOTHING op. */\n                                    DEBUG_TRIE_COMPILE_r({\n                                        regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);\n                                        Perl_re_indentf( aTHX_  \"- %s (%d) \\n\",\n                                          depth+1,\n                                          SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));\n\n                                    });\n                                    OP(startbranch)= NOTHING;\n                                    NEXT_OFF(startbranch)= tail - startbranch;\n                                    for ( opt= startbranch + 1; opt < tail ; opt++ )\n                                        OP(opt)= OPTIMIZED;\n                                }\n                            }\n                        } /* end if ( last) */\n                    } /* TRIE_MAXBUF is non zero */\n\n                } /* do trie */\n\n\t    }\n\t    else if ( code == BRANCHJ ) {  /* single branch is optimized. */\n\t\tscan = NEXTOPER(NEXTOPER(scan));\n\t    } else\t\t\t/* single branch is optimized. */\n\t\tscan = NEXTOPER(scan);\n\t    continue;\n        } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {\n            I32 paren = 0;\n            regnode *start = NULL;\n            regnode *end = NULL;\n            U32 my_recursed_depth= recursed_depth;\n\n            if (OP(scan) != SUSPEND) { /* GOSUB */\n                /* Do setup, note this code has side effects beyond\n                 * the rest of this block. Specifically setting\n                 * RExC_recurse[] must happen at least once during\n                 * study_chunk(). */\n                paren = ARG(scan);\n                RExC_recurse[ARG2L(scan)] = scan;\n                start = REGNODE_p(RExC_open_parens[paren]);\n                end   = REGNODE_p(RExC_close_parens[paren]);\n\n                /* NOTE we MUST always execute the above code, even\n                 * if we do nothing with a GOSUB */\n                if (\n                    ( flags & SCF_IN_DEFINE )\n                    ||\n                    (\n                        (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))\n                        &&\n                        ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )\n                    )\n                ) {\n                    /* no need to do anything here if we are in a define. */\n                    /* or we are after some kind of infinite construct\n                     * so we can skip recursing into this item.\n                     * Since it is infinite we will not change the maxlen\n                     * or delta, and if we miss something that might raise\n                     * the minlen it will merely pessimise a little.\n                     *\n                     * Iow /(?(DEFINE)(?foo|food))a+(?&foo)/\n                     * might result in a minlen of 1 and not of 4,\n                     * but this doesn't make us mismatch, just try a bit\n                     * harder than we should.\n                     * */\n                    scan= regnext(scan);\n                    continue;\n                }\n\n                if (\n                    !recursed_depth\n                    ||\n                    !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)\n                ) {\n                    /* it is quite possible that there are more efficient ways\n                     * to do this. We maintain a bitmap per level of recursion\n                     * of which patterns we have entered so we can detect if a\n                     * pattern creates a possible infinite loop. When we\n                     * recurse down a level we copy the previous levels bitmap\n                     * down. When we are at recursion level 0 we zero the top\n                     * level bitmap. It would be nice to implement a different\n                     * more efficient way of doing this. In particular the top\n                     * level bitmap may be unnecessary.\n                     */\n                    if (!recursed_depth) {\n                        Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);\n                    } else {\n                        Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),\n                             RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),\n                             RExC_study_chunk_recursed_bytes, U8);\n                    }\n                    /* we havent recursed into this paren yet, so recurse into it */\n                    DEBUG_STUDYDATA(\"gosub-set\", data, depth, is_inf);\n                    PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);\n                    my_recursed_depth= recursed_depth + 1;\n                } else {\n                    DEBUG_STUDYDATA(\"gosub-inf\", data, depth, is_inf);\n                    /* some form of infinite recursion, assume infinite length\n                     * */\n                    if (flags & SCF_DO_SUBSTR) {\n                        scan_commit(pRExC_state, data, minlenp, is_inf);\n                        data->cur_is_floating = 1;\n                    }\n                    is_inf = is_inf_internal = 1;\n                    if (flags & SCF_DO_STCLASS_OR) /* Allow everything */\n                        ssc_anything(data->start_class);\n                    flags &= ~SCF_DO_STCLASS;\n\n                    start= NULL; /* reset start so we dont recurse later on. */\n\t        }\n            } else {\n\t        paren = stopparen;\n                start = scan + 2;\n\t        end = regnext(scan);\n\t    }\n            if (start) {\n                scan_frame *newframe;\n                assert(end);\n                if (!RExC_frame_last) {\n                    Newxz(newframe, 1, scan_frame);\n                    SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);\n                    RExC_frame_head= newframe;\n                    RExC_frame_count++;\n                } else if (!RExC_frame_last->next_frame) {\n                    Newxz(newframe, 1, scan_frame);\n                    RExC_frame_last->next_frame= newframe;\n                    newframe->prev_frame= RExC_frame_last;\n                    RExC_frame_count++;\n                } else {\n                    newframe= RExC_frame_last->next_frame;\n                }\n                RExC_frame_last= newframe;\n\n                newframe->next_regnode = regnext(scan);\n                newframe->last_regnode = last;\n                newframe->stopparen = stopparen;\n                newframe->prev_recursed_depth = recursed_depth;\n                newframe->this_prev_frame= frame;\n                newframe->in_gosub = (\n                    (frame && frame->in_gosub) || OP(scan) == GOSUB\n                );\n\n                DEBUG_STUDYDATA(\"frame-new\", data, depth, is_inf);\n                DEBUG_PEEP(\"fnew\", scan, depth, flags);\n\n\t        frame = newframe;\n\t        scan =  start;\n\t        stopparen = paren;\n\t        last = end;\n                depth = depth + 1;\n                recursed_depth= my_recursed_depth;\n\n\t        continue;\n\t    }\n\t}\n\telse if (   OP(scan) == EXACT\n                 || OP(scan) == EXACT_ONLY8\n                 || OP(scan) == EXACTL)\n        {\n\t    SSize_t l = STR_LEN(scan);\n\t    UV uc;\n            assert(l);\n\t    if (UTF) {\n\t\tconst U8 * const s = (U8*)STRING(scan);\n\t\tuc = utf8_to_uvchr_buf(s, s + l, NULL);\n\t\tl = utf8_length(s, s + l);\n\t    } else {\n\t\tuc = *((U8*)STRING(scan));\n\t    }\n\t    min += l;\n\t    if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */\n\t\t/* The code below prefers earlier match for fixed\n\t\t   offset, later match for variable offset.  */\n\t\tif (data->last_end == -1) { /* Update the start info. */\n\t\t    data->last_start_min = data->pos_min;\n \t\t    data->last_start_max = is_inf\n \t\t\t? SSize_t_MAX : data->pos_min + data->pos_delta;\n\t\t}\n\t\tsv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));\n\t\tif (UTF)\n\t\t    SvUTF8_on(data->last_found);\n\t\t{\n\t\t    SV * const sv = data->last_found;\n\t\t    MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?\n\t\t\tmg_find(sv, PERL_MAGIC_utf8) : NULL;\n\t\t    if (mg && mg->mg_len >= 0)\n\t\t\tmg->mg_len += utf8_length((U8*)STRING(scan),\n                                              (U8*)STRING(scan)+STR_LEN(scan));\n\t\t}\n\t\tdata->last_end = data->pos_min + l;\n\t\tdata->pos_min += l; /* As in the first entry. */\n\t\tdata->flags &= ~SF_BEFORE_EOL;\n\t    }\n\n            /* ANDing the code point leaves at most it, and not in locale, and\n             * can't match null string */\n\t    if (flags & SCF_DO_STCLASS_AND) {\n                ssc_cp_and(data->start_class, uc);\n                ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n                ssc_clear_locale(data->start_class);\n\t    }\n\t    else if (flags & SCF_DO_STCLASS_OR) {\n                ssc_add_cp(data->start_class, uc);\n\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\n                /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */\n                ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n\t    }\n\t    flags &= ~SCF_DO_STCLASS;\n\t}\n        else if (PL_regkind[OP(scan)] == EXACT) {\n            /* But OP != EXACT!, so is EXACTFish */\n\t    SSize_t l = STR_LEN(scan);\n            const U8 * s = (U8*)STRING(scan);\n\n\t    /* Search for fixed substrings supports EXACT only. */\n\t    if (flags & SCF_DO_SUBSTR) {\n\t\tassert(data);\n                scan_commit(pRExC_state, data, minlenp, is_inf);\n\t    }\n\t    if (UTF) {\n\t\tl = utf8_length(s, s + l);\n\t    }\n\t    if (unfolded_multi_char) {\n                RExC_seen |= REG_UNFOLDED_MULTI_SEEN;\n\t    }\n\t    min += l - min_subtract;\n            assert (min >= 0);\n            delta += min_subtract;\n\t    if (flags & SCF_DO_SUBSTR) {\n\t\tdata->pos_min += l - min_subtract;\n\t\tif (data->pos_min < 0) {\n                    data->pos_min = 0;\n                }\n                data->pos_delta += min_subtract;\n\t\tif (min_subtract) {\n\t\t    data->cur_is_floating = 1; /* float */\n\t\t}\n\t    }\n\n            if (flags & SCF_DO_STCLASS) {\n                SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan);\n\n                assert(EXACTF_invlist);\n                if (flags & SCF_DO_STCLASS_AND) {\n                    if (OP(scan) != EXACTFL)\n                        ssc_clear_locale(data->start_class);\n                    ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n                    ANYOF_POSIXL_ZERO(data->start_class);\n                    ssc_intersection(data->start_class, EXACTF_invlist, FALSE);\n                }\n                else {  /* SCF_DO_STCLASS_OR */\n                    ssc_union(data->start_class, EXACTF_invlist, FALSE);\n                    ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\n                    /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */\n                    ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n                }\n                flags &= ~SCF_DO_STCLASS;\n                SvREFCNT_dec(EXACTF_invlist);\n            }\n\t}\n\telse if (REGNODE_VARIES(OP(scan))) {\n\t    SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;\n\t    I32 fl = 0, f = flags;\n\t    regnode * const oscan = scan;\n\t    regnode_ssc this_class;\n\t    regnode_ssc *oclass = NULL;\n\t    I32 next_is_eval = 0;\n\n\t    switch (PL_regkind[OP(scan)]) {\n\t    case WHILEM:\t\t/* End of (?:...)* . */\n\t\tscan = NEXTOPER(scan);\n\t\tgoto finish;\n\t    case PLUS:\n\t\tif (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {\n\t\t    next = NEXTOPER(scan);\n\t\t    if (   OP(next) == EXACT\n                        || OP(next) == EXACT_ONLY8\n                        || OP(next) == EXACTL\n                        || (flags & SCF_DO_STCLASS))\n                    {\n\t\t\tmincount = 1;\n\t\t\tmaxcount = REG_INFTY;\n\t\t\tnext = regnext(scan);\n\t\t\tscan = NEXTOPER(scan);\n\t\t\tgoto do_curly;\n\t\t    }\n\t\t}\n\t\tif (flags & SCF_DO_SUBSTR)\n\t\t    data->pos_min++;\n\t\tmin++;\n\t\t/* FALLTHROUGH */\n\t    case STAR:\n                next = NEXTOPER(scan);\n\n                /* This temporary node can now be turned into EXACTFU, and\n                 * must, as regexec.c doesn't handle it */\n                if (OP(next) == EXACTFU_S_EDGE && mutate_ok) {\n                    OP(next) = EXACTFU;\n                }\n\n                if (     STR_LEN(next) == 1\n                    &&   isALPHA_A(* STRING(next))\n                    && (         OP(next) == EXACTFAA\n                        || (     OP(next) == EXACTFU\n                            && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next))))\n                    &&   mutate_ok\n                ) {\n                    /* These differ in just one bit */\n                    U8 mask = ~ ('A' ^ 'a');\n\n                    assert(isALPHA_A(* STRING(next)));\n\n                    /* Then replace it by an ANYOFM node, with\n                    * the mask set to the complement of the\n                    * bit that differs between upper and lower\n                    * case, and the lowest code point of the\n                    * pair (which the '&' forces) */\n                    OP(next) = ANYOFM;\n                    ARG_SET(next, *STRING(next) & mask);\n                    FLAGS(next) = mask;\n                }\n\n\t\tif (flags & SCF_DO_STCLASS) {\n\t\t    mincount = 0;\n\t\t    maxcount = REG_INFTY;\n\t\t    next = regnext(scan);\n\t\t    scan = NEXTOPER(scan);\n\t\t    goto do_curly;\n\t\t}\n\t\tif (flags & SCF_DO_SUBSTR) {\n                    scan_commit(pRExC_state, data, minlenp, is_inf);\n                    /* Cannot extend fixed substrings */\n\t\t    data->cur_is_floating = 1; /* float */\n\t\t}\n                is_inf = is_inf_internal = 1;\n                scan = regnext(scan);\n\t\tgoto optimize_curly_tail;\n\t    case CURLY:\n\t        if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)\n\t            && (scan->flags == stopparen))\n\t\t{\n\t\t    mincount = 1;\n\t\t    maxcount = 1;\n\t\t} else {\n\t\t    mincount = ARG1(scan);\n\t\t    maxcount = ARG2(scan);\n\t\t}\n\t\tnext = regnext(scan);\n\t\tif (OP(scan) == CURLYX) {\n\t\t    I32 lp = (data ? *(data->last_closep) : 0);\n\t\t    scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);\n\t\t}\n\t\tscan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;\n\t\tnext_is_eval = (OP(scan) == EVAL);\n\t      do_curly:\n\t\tif (flags & SCF_DO_SUBSTR) {\n                    if (mincount == 0)\n                        scan_commit(pRExC_state, data, minlenp, is_inf);\n                    /* Cannot extend fixed substrings */\n\t\t    pos_before = data->pos_min;\n\t\t}\n\t\tif (data) {\n\t\t    fl = data->flags;\n\t\t    data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);\n\t\t    if (is_inf)\n\t\t\tdata->flags |= SF_IS_INF;\n\t\t}\n\t\tif (flags & SCF_DO_STCLASS) {\n\t\t    ssc_init(pRExC_state, &this_class);\n\t\t    oclass = data->start_class;\n\t\t    data->start_class = &this_class;\n\t\t    f |= SCF_DO_STCLASS_AND;\n\t\t    f &= ~SCF_DO_STCLASS_OR;\n\t\t}\n\t        /* Exclude from super-linear cache processing any {n,m}\n\t\t   regops for which the combination of input pos and regex\n\t\t   pos is not enough information to determine if a match\n\t\t   will be possible.\n\n\t\t   For example, in the regex /foo(bar\\s*){4,8}baz/ with the\n\t\t   regex pos at the \\s*, the prospects for a match depend not\n\t\t   only on the input position but also on how many (bar\\s*)\n\t\t   repeats into the {4,8} we are. */\n               if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))\n\t\t    f &= ~SCF_WHILEM_VISITED_POS;\n\n\t\t/* This will finish on WHILEM, setting scan, or on NULL: */\n                /* recurse study_chunk() on loop bodies */\n\t\tminnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,\n                                  last, data, stopparen, recursed_depth, NULL,\n                                  (mincount == 0\n                                   ? (f & ~SCF_DO_SUBSTR)\n                                   : f)\n                                  , depth+1, mutate_ok);\n\n\t\tif (flags & SCF_DO_STCLASS)\n\t\t    data->start_class = oclass;\n\t\tif (mincount == 0 || minnext == 0) {\n\t\t    if (flags & SCF_DO_STCLASS_OR) {\n\t\t\tssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);\n\t\t    }\n\t\t    else if (flags & SCF_DO_STCLASS_AND) {\n\t\t\t/* Switch to OR mode: cache the old value of\n\t\t\t * data->start_class */\n\t\t\tINIT_AND_WITHP;\n\t\t\tStructCopy(data->start_class, and_withp, regnode_ssc);\n\t\t\tflags &= ~SCF_DO_STCLASS_AND;\n\t\t\tStructCopy(&this_class, data->start_class, regnode_ssc);\n\t\t\tflags |= SCF_DO_STCLASS_OR;\n                        ANYOF_FLAGS(data->start_class)\n                                                |= SSC_MATCHES_EMPTY_STRING;\n\t\t    }\n\t\t} else {\t\t/* Non-zero len */\n\t\t    if (flags & SCF_DO_STCLASS_OR) {\n\t\t\tssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\t\t    }\n\t\t    else if (flags & SCF_DO_STCLASS_AND)\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);\n\t\t    flags &= ~SCF_DO_STCLASS;\n\t\t}\n\t\tif (!scan) \t\t/* It was not CURLYX, but CURLY. */\n\t\t    scan = next;\n\t\tif (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)\n\t\t    /* ? quantifier ok, except for (?{ ... }) */\n\t\t    && (next_is_eval || !(mincount == 0 && maxcount == 1))\n\t\t    && (minnext == 0) && (deltanext == 0)\n\t\t    && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))\n                    && maxcount <= REG_INFTY/3) /* Complement check for big\n                                                   count */\n\t\t{\n\t\t    _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),\n                        Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),\n                            \"Quantifier unexpected on zero-length expression \"\n                            \"in regex m/%\" UTF8f \"/\",\n\t\t\t     UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,\n\t\t\t\t  RExC_precomp)));\n                }\n\n                if ( ( minnext > 0 && mincount >= SSize_t_MAX / minnext )\n                    || min >= SSize_t_MAX - minnext * mincount )\n                {\n                    FAIL(\"Regexp out of space\");\n                }\n\n\t\tmin += minnext * mincount;\n\t\tis_inf_internal |= deltanext == SSize_t_MAX\n                         || (maxcount == REG_INFTY && minnext + deltanext > 0);\n\t\tis_inf |= is_inf_internal;\n                if (is_inf) {\n\t\t    delta = SSize_t_MAX;\n                } else {\n\t\t    delta += (minnext + deltanext) * maxcount\n                             - minnext * mincount;\n                }\n\t\t/* Try powerful optimization CURLYX => CURLYN. */\n\t\tif (  OP(oscan) == CURLYX && data\n\t\t      && data->flags & SF_IN_PAR\n\t\t      && !(data->flags & SF_HAS_EVAL)\n\t\t      && !deltanext && minnext == 1\n                      && mutate_ok\n                ) {\n\t\t    /* Try to optimize to CURLYN.  */\n\t\t    regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;\n\t\t    regnode * const nxt1 = nxt;\n#ifdef DEBUGGING\n\t\t    regnode *nxt2;\n#endif\n\n\t\t    /* Skip open. */\n\t\t    nxt = regnext(nxt);\n\t\t    if (!REGNODE_SIMPLE(OP(nxt))\n\t\t\t&& !(PL_regkind[OP(nxt)] == EXACT\n\t\t\t     && STR_LEN(nxt) == 1))\n\t\t\tgoto nogo;\n#ifdef DEBUGGING\n\t\t    nxt2 = nxt;\n#endif\n\t\t    nxt = regnext(nxt);\n\t\t    if (OP(nxt) != CLOSE)\n\t\t\tgoto nogo;\n\t\t    if (RExC_open_parens) {\n\n                        /*open->CURLYM*/\n                        RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);\n\n                        /*close->while*/\n                        RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;\n\t\t    }\n\t\t    /* Now we know that nxt2 is the only contents: */\n\t\t    oscan->flags = (U8)ARG(nxt);\n\t\t    OP(oscan) = CURLYN;\n\t\t    OP(nxt1) = NOTHING;\t/* was OPEN. */\n\n#ifdef DEBUGGING\n\t\t    OP(nxt1 + 1) = OPTIMIZED; /* was count. */\n\t\t    NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */\n\t\t    NEXT_OFF(nxt2) = 0;\t/* just for consistency with CURLY. */\n\t\t    OP(nxt) = OPTIMIZED;\t/* was CLOSE. */\n\t\t    OP(nxt + 1) = OPTIMIZED; /* was count. */\n\t\t    NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */\n#endif\n\t\t}\n\t      nogo:\n\n\t\t/* Try optimization CURLYX => CURLYM. */\n\t\tif (  OP(oscan) == CURLYX && data\n\t\t      && !(data->flags & SF_HAS_PAR)\n\t\t      && !(data->flags & SF_HAS_EVAL)\n\t\t      && !deltanext\t/* atom is fixed width */\n\t\t      && minnext != 0\t/* CURLYM can't handle zero width */\n                         /* Nor characters whose fold at run-time may be\n                          * multi-character */\n                      && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)\n                      && mutate_ok\n\t\t) {\n\t\t    /* XXXX How to optimize if data == 0? */\n\t\t    /* Optimize to a simpler form.  */\n\t\t    regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */\n\t\t    regnode *nxt2;\n\n\t\t    OP(oscan) = CURLYM;\n\t\t    while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/\n\t\t\t    && (OP(nxt2) != WHILEM))\n\t\t\tnxt = nxt2;\n\t\t    OP(nxt2)  = SUCCEED; /* Whas WHILEM */\n\t\t    /* Need to optimize away parenths. */\n\t\t    if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {\n\t\t\t/* Set the parenth number.  */\n\t\t\tregnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/\n\n\t\t\toscan->flags = (U8)ARG(nxt);\n\t\t\tif (RExC_open_parens) {\n                             /*open->CURLYM*/\n                            RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);\n\n                            /*close->NOTHING*/\n                            RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)\n                                                         + 1;\n\t\t\t}\n\t\t\tOP(nxt1) = OPTIMIZED;\t/* was OPEN. */\n\t\t\tOP(nxt) = OPTIMIZED;\t/* was CLOSE. */\n\n#ifdef DEBUGGING\n\t\t\tOP(nxt1 + 1) = OPTIMIZED; /* was count. */\n\t\t\tOP(nxt + 1) = OPTIMIZED; /* was count. */\n\t\t\tNEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */\n\t\t\tNEXT_OFF(nxt + 1) = 0; /* just for consistency. */\n#endif\n#if 0\n\t\t\twhile ( nxt1 && (OP(nxt1) != WHILEM)) {\n\t\t\t    regnode *nnxt = regnext(nxt1);\n\t\t\t    if (nnxt == nxt) {\n\t\t\t\tif (reg_off_by_arg[OP(nxt1)])\n\t\t\t\t    ARG_SET(nxt1, nxt2 - nxt1);\n\t\t\t\telse if (nxt2 - nxt1 < U16_MAX)\n\t\t\t\t    NEXT_OFF(nxt1) = nxt2 - nxt1;\n\t\t\t\telse\n\t\t\t\t    OP(nxt) = NOTHING;\t/* Cannot beautify */\n\t\t\t    }\n\t\t\t    nxt1 = nnxt;\n\t\t\t}\n#endif\n\t\t\t/* Optimize again: */\n                        /* recurse study_chunk() on optimised CURLYX => CURLYM */\n\t\t\tstudy_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,\n                                    NULL, stopparen, recursed_depth, NULL, 0,\n                                    depth+1, mutate_ok);\n\t\t    }\n\t\t    else\n\t\t\toscan->flags = 0;\n\t\t}\n\t\telse if ((OP(oscan) == CURLYX)\n\t\t\t && (flags & SCF_WHILEM_VISITED_POS)\n\t\t\t /* See the comment on a similar expression above.\n\t\t\t    However, this time it's not a subexpression\n\t\t\t    we care about, but the expression itself. */\n\t\t\t && (maxcount == REG_INFTY)\n\t\t\t && data) {\n\t\t    /* This stays as CURLYX, we can put the count/of pair. */\n\t\t    /* Find WHILEM (as in regexec.c) */\n\t\t    regnode *nxt = oscan + NEXT_OFF(oscan);\n\n\t\t    if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */\n\t\t\tnxt += ARG(nxt);\n                    nxt = PREVOPER(nxt);\n                    if (nxt->flags & 0xf) {\n                        /* we've already set whilem count on this node */\n                    } else if (++data->whilem_c < 16) {\n                        assert(data->whilem_c <= RExC_whilem_seen);\n                        nxt->flags = (U8)(data->whilem_c\n                            | (RExC_whilem_seen << 4)); /* On WHILEM */\n                    }\n\t\t}\n\t\tif (data && fl & (SF_HAS_PAR|SF_IN_PAR))\n\t\t    pars++;\n\t\tif (flags & SCF_DO_SUBSTR) {\n\t\t    SV *last_str = NULL;\n                    STRLEN last_chrs = 0;\n\t\t    int counted = mincount != 0;\n\n                    if (data->last_end > 0 && mincount != 0) { /* Ends with a\n                                                                  string. */\n\t\t\tSSize_t b = pos_before >= data->last_start_min\n\t\t\t    ? pos_before : data->last_start_min;\n\t\t\tSTRLEN l;\n\t\t\tconst char * const s = SvPV_const(data->last_found, l);\n\t\t\tSSize_t old = b - data->last_start_min;\n                        assert(old >= 0);\n\n\t\t\tif (UTF)\n\t\t\t    old = utf8_hop_forward((U8*)s, old,\n                                               (U8 *) SvEND(data->last_found))\n                                - (U8*)s;\n\t\t\tl -= old;\n\t\t\t/* Get the added string: */\n\t\t\tlast_str = newSVpvn_utf8(s  + old, l, UTF);\n                        last_chrs = UTF ? utf8_length((U8*)(s + old),\n                                            (U8*)(s + old + l)) : l;\n\t\t\tif (deltanext == 0 && pos_before == b) {\n\t\t\t    /* What was added is a constant string */\n\t\t\t    if (mincount > 1) {\n\n\t\t\t\tSvGROW(last_str, (mincount * l) + 1);\n\t\t\t\trepeatcpy(SvPVX(last_str) + l,\n\t\t\t\t\t  SvPVX_const(last_str), l,\n                                          mincount - 1);\n\t\t\t\tSvCUR_set(last_str, SvCUR(last_str) * mincount);\n\t\t\t\t/* Add additional parts. */\n\t\t\t\tSvCUR_set(data->last_found,\n\t\t\t\t\t  SvCUR(data->last_found) - l);\n\t\t\t\tsv_catsv(data->last_found, last_str);\n\t\t\t\t{\n\t\t\t\t    SV * sv = data->last_found;\n\t\t\t\t    MAGIC *mg =\n\t\t\t\t\tSvUTF8(sv) && SvMAGICAL(sv) ?\n\t\t\t\t\tmg_find(sv, PERL_MAGIC_utf8) : NULL;\n\t\t\t\t    if (mg && mg->mg_len >= 0)\n\t\t\t\t\tmg->mg_len += last_chrs * (mincount-1);\n\t\t\t\t}\n                                last_chrs *= mincount;\n\t\t\t\tdata->last_end += l * (mincount - 1);\n\t\t\t    }\n\t\t\t} else {\n\t\t\t    /* start offset must point into the last copy */\n\t\t\t    data->last_start_min += minnext * (mincount - 1);\n\t\t\t    data->last_start_max =\n                              is_inf\n                               ? SSize_t_MAX\n\t\t\t       : data->last_start_max +\n                                 (maxcount - 1) * (minnext + data->pos_delta);\n\t\t\t}\n\t\t    }\n\t\t    /* It is counted once already... */\n\t\t    data->pos_min += minnext * (mincount - counted);\n#if 0\nPerl_re_printf( aTHX_  \"counted=%\" UVuf \" deltanext=%\" UVuf\n                              \" SSize_t_MAX=%\" UVuf \" minnext=%\" UVuf\n                              \" maxcount=%\" UVuf \" mincount=%\" UVuf \"\\n\",\n    (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,\n    (UV)mincount);\nif (deltanext != SSize_t_MAX)\nPerl_re_printf( aTHX_  \"LHS=%\" UVuf \" RHS=%\" UVuf \"\\n\",\n    (UV)(-counted * deltanext + (minnext + deltanext) * maxcount\n          - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));\n#endif\n\t\t    if (deltanext == SSize_t_MAX\n                        || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)\n\t\t        data->pos_delta = SSize_t_MAX;\n\t\t    else\n\t\t        data->pos_delta += - counted * deltanext +\n\t\t\t(minnext + deltanext) * maxcount - minnext * mincount;\n\t\t    if (mincount != maxcount) {\n\t\t\t /* Cannot extend fixed substrings found inside\n\t\t\t    the group.  */\n                        scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\t\tif (mincount && last_str) {\n\t\t\t    SV * const sv = data->last_found;\n\t\t\t    MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?\n\t\t\t\tmg_find(sv, PERL_MAGIC_utf8) : NULL;\n\n\t\t\t    if (mg)\n\t\t\t\tmg->mg_len = -1;\n\t\t\t    sv_setsv(sv, last_str);\n\t\t\t    data->last_end = data->pos_min;\n\t\t\t    data->last_start_min = data->pos_min - last_chrs;\n\t\t\t    data->last_start_max = is_inf\n\t\t\t\t? SSize_t_MAX\n\t\t\t\t: data->pos_min + data->pos_delta - last_chrs;\n\t\t\t}\n\t\t\tdata->cur_is_floating = 1; /* float */\n\t\t    }\n\t\t    SvREFCNT_dec(last_str);\n\t\t}\n\t\tif (data && (fl & SF_HAS_EVAL))\n\t\t    data->flags |= SF_HAS_EVAL;\n\t      optimize_curly_tail:\n\t\trck_elide_nothing(oscan);\n\t\tcontinue;\n\n\t    default:\n#ifdef DEBUGGING\n                Perl_croak(aTHX_ \"panic: unexpected varying REx opcode %d\",\n                                                                    OP(scan));\n#endif\n            case REF:\n            case CLUMP:\n\t\tif (flags & SCF_DO_SUBSTR) {\n                    /* Cannot expect anything... */\n                    scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\t    data->cur_is_floating = 1; /* float */\n\t\t}\n\t\tis_inf = is_inf_internal = 1;\n\t\tif (flags & SCF_DO_STCLASS_OR) {\n                    if (OP(scan) == CLUMP) {\n                        /* Actually is any start char, but very few code points\n                         * aren't start characters */\n                        ssc_match_all_cp(data->start_class);\n                    }\n                    else {\n                        ssc_anything(data->start_class);\n                    }\n                }\n\t\tflags &= ~SCF_DO_STCLASS;\n\t\tbreak;\n\t    }\n\t}\n\telse if (OP(scan) == LNBREAK) {\n\t    if (flags & SCF_DO_STCLASS) {\n    \t        if (flags & SCF_DO_STCLASS_AND) {\n                    ssc_intersection(data->start_class,\n                                    PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);\n                    ssc_clear_locale(data->start_class);\n                    ANYOF_FLAGS(data->start_class)\n                                                &= ~SSC_MATCHES_EMPTY_STRING;\n                }\n                else if (flags & SCF_DO_STCLASS_OR) {\n                    ssc_union(data->start_class,\n                              PL_XPosix_ptrs[_CC_VERTSPACE],\n                              FALSE);\n\t\t    ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\n                    /* See commit msg for\n                     * 749e076fceedeb708a624933726e7989f2302f6a */\n                    ANYOF_FLAGS(data->start_class)\n                                                &= ~SSC_MATCHES_EMPTY_STRING;\n                }\n\t\tflags &= ~SCF_DO_STCLASS;\n            }\n\t    min++;\n            if (delta != SSize_t_MAX)\n                delta++;    /* Because of the 2 char string cr-lf */\n            if (flags & SCF_DO_SUBSTR) {\n                /* Cannot expect anything... */\n                scan_commit(pRExC_state, data, minlenp, is_inf);\n    \t        data->pos_min += 1;\n                if (data->pos_delta != SSize_t_MAX) {\n                    data->pos_delta += 1;\n                }\n\t\tdata->cur_is_floating = 1; /* float */\n    \t    }\n\t}\n\telse if (REGNODE_SIMPLE(OP(scan))) {\n\n\t    if (flags & SCF_DO_SUBSTR) {\n                scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\tdata->pos_min++;\n\t    }\n\t    min++;\n\t    if (flags & SCF_DO_STCLASS) {\n                bool invert = 0;\n                SV* my_invlist = NULL;\n                U8 namedclass;\n\n                /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */\n                ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;\n\n\t\t/* Some of the logic below assumes that switching\n\t\t   locale on will only add false positives. */\n\t\tswitch (OP(scan)) {\n\n\t\tdefault:\n#ifdef DEBUGGING\n                   Perl_croak(aTHX_ \"panic: unexpected simple REx opcode %d\",\n                                                                     OP(scan));\n#endif\n\t\tcase SANY:\n\t\t    if (flags & SCF_DO_STCLASS_OR) /* Allow everything */\n\t\t\tssc_match_all_cp(data->start_class);\n\t\t    break;\n\n\t\tcase REG_ANY:\n                    {\n                        SV* REG_ANY_invlist = _new_invlist(2);\n                        REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,\n                                                            '\\n');\n                        if (flags & SCF_DO_STCLASS_OR) {\n                            ssc_union(data->start_class,\n                                      REG_ANY_invlist,\n                                      TRUE /* TRUE => invert, hence all but \\n\n                                            */\n                                      );\n                        }\n                        else if (flags & SCF_DO_STCLASS_AND) {\n                            ssc_intersection(data->start_class,\n                                             REG_ANY_invlist,\n                                             TRUE  /* TRUE => invert */\n                                             );\n                            ssc_clear_locale(data->start_class);\n                        }\n                        SvREFCNT_dec_NN(REG_ANY_invlist);\n\t\t    }\n\t\t    break;\n\n                case ANYOFD:\n                case ANYOFL:\n                case ANYOFPOSIXL:\n                case ANYOFH:\n                case ANYOF:\n\t\t    if (flags & SCF_DO_STCLASS_AND)\n\t\t\tssc_and(pRExC_state, data->start_class,\n                                (regnode_charclass *) scan);\n\t\t    else\n\t\t\tssc_or(pRExC_state, data->start_class,\n                                                          (regnode_charclass *) scan);\n\t\t    break;\n\n                case NANYOFM:\n                case ANYOFM:\n                  {\n                    SV* cp_list = get_ANYOFM_contents(scan);\n\n                    if (flags & SCF_DO_STCLASS_OR) {\n                        ssc_union(data->start_class, cp_list, invert);\n                    }\n                    else if (flags & SCF_DO_STCLASS_AND) {\n                        ssc_intersection(data->start_class, cp_list, invert);\n                    }\n\n                    SvREFCNT_dec_NN(cp_list);\n                    break;\n                  }\n\n\t\tcase NPOSIXL:\n                    invert = 1;\n                    /* FALLTHROUGH */\n\n\t\tcase POSIXL:\n                    namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;\n                    if (flags & SCF_DO_STCLASS_AND) {\n                        bool was_there = cBOOL(\n                                          ANYOF_POSIXL_TEST(data->start_class,\n                                                                 namedclass));\n                        ANYOF_POSIXL_ZERO(data->start_class);\n                        if (was_there) {    /* Do an AND */\n                            ANYOF_POSIXL_SET(data->start_class, namedclass);\n                        }\n                        /* No individual code points can now match */\n                        data->start_class->invlist\n                                                = sv_2mortal(_new_invlist(0));\n                    }\n                    else {\n                        int complement = namedclass + ((invert) ? -1 : 1);\n\n                        assert(flags & SCF_DO_STCLASS_OR);\n\n                        /* If the complement of this class was already there,\n                         * the result is that they match all code points,\n                         * (\\d + \\D == everything).  Remove the classes from\n                         * future consideration.  Locale is not relevant in\n                         * this case */\n                        if (ANYOF_POSIXL_TEST(data->start_class, complement)) {\n                            ssc_match_all_cp(data->start_class);\n                            ANYOF_POSIXL_CLEAR(data->start_class, namedclass);\n                            ANYOF_POSIXL_CLEAR(data->start_class, complement);\n                        }\n                        else {  /* The usual case; just add this class to the\n                                   existing set */\n                            ANYOF_POSIXL_SET(data->start_class, namedclass);\n                        }\n                    }\n                    break;\n\n                case NPOSIXA:   /* For these, we always know the exact set of\n                                   what's matched */\n                    invert = 1;\n                    /* FALLTHROUGH */\n\t\tcase POSIXA:\n                    my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);\n                    goto join_posix_and_ascii;\n\n\t\tcase NPOSIXD:\n\t\tcase NPOSIXU:\n                    invert = 1;\n                    /* FALLTHROUGH */\n\t\tcase POSIXD:\n\t\tcase POSIXU:\n                    my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);\n\n                    /* NPOSIXD matches all upper Latin1 code points unless the\n                     * target string being matched is UTF-8, which is\n                     * unknowable until match time.  Since we are going to\n                     * invert, we want to get rid of all of them so that the\n                     * inversion will match all */\n                    if (OP(scan) == NPOSIXD) {\n                        _invlist_subtract(my_invlist, PL_UpperLatin1,\n                                          &my_invlist);\n                    }\n\n                  join_posix_and_ascii:\n\n                    if (flags & SCF_DO_STCLASS_AND) {\n                        ssc_intersection(data->start_class, my_invlist, invert);\n                        ssc_clear_locale(data->start_class);\n                    }\n                    else {\n                        assert(flags & SCF_DO_STCLASS_OR);\n                        ssc_union(data->start_class, my_invlist, invert);\n                    }\n                    SvREFCNT_dec(my_invlist);\n\t\t}\n\t\tif (flags & SCF_DO_STCLASS_OR)\n\t\t    ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n\t\tflags &= ~SCF_DO_STCLASS;\n\t    }\n\t}\n\telse if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {\n\t    data->flags |= (OP(scan) == MEOL\n\t\t\t    ? SF_BEFORE_MEOL\n\t\t\t    : SF_BEFORE_SEOL);\n            scan_commit(pRExC_state, data, minlenp, is_inf);\n\n\t}\n\telse if (  PL_regkind[OP(scan)] == BRANCHJ\n\t\t /* Lookbehind, or need to calculate parens/evals/stclass: */\n\t\t   && (scan->flags || data || (flags & SCF_DO_STCLASS))\n\t\t   && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))\n        {\n            if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY\n                || OP(scan) == UNLESSM )\n            {\n                /* Negative Lookahead/lookbehind\n                   In this case we can't do fixed string optimisation.\n                */\n\n                SSize_t deltanext, minnext, fake = 0;\n                regnode *nscan;\n                regnode_ssc intrnl;\n                int f = 0;\n\n                StructCopy(&zero_scan_data, &data_fake, scan_data_t);\n                if (data) {\n                    data_fake.whilem_c = data->whilem_c;\n                    data_fake.last_closep = data->last_closep;\n\t\t}\n                else\n                    data_fake.last_closep = &fake;\n\t\tdata_fake.pos_delta = delta;\n                if ( flags & SCF_DO_STCLASS && !scan->flags\n                     && OP(scan) == IFMATCH ) { /* Lookahead */\n                    ssc_init(pRExC_state, &intrnl);\n                    data_fake.start_class = &intrnl;\n                    f |= SCF_DO_STCLASS_AND;\n\t\t}\n                if (flags & SCF_WHILEM_VISITED_POS)\n                    f |= SCF_WHILEM_VISITED_POS;\n                next = regnext(scan);\n                nscan = NEXTOPER(NEXTOPER(scan));\n\n                /* recurse study_chunk() for lookahead body */\n                minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,\n                                      last, &data_fake, stopparen,\n                                      recursed_depth, NULL, f, depth+1,\n                                      mutate_ok);\n                if (scan->flags) {\n                    if (   deltanext < 0\n                        || deltanext > (I32) U8_MAX\n                        || minnext > (I32)U8_MAX\n                        || minnext + deltanext > (I32)U8_MAX)\n                    {\n\t\t\tFAIL2(\"Lookbehind longer than %\" UVuf \" not implemented\",\n                              (UV)U8_MAX);\n                    }\n\n                    /* The 'next_off' field has been repurposed to count the\n                     * additional starting positions to try beyond the initial\n                     * one.  (This leaves it at 0 for non-variable length\n                     * matches to avoid breakage for those not using this\n                     * extension) */\n                    if (deltanext) {\n                        scan->next_off = deltanext;\n                        ckWARNexperimental(RExC_parse,\n                            WARN_EXPERIMENTAL__VLB,\n                            \"Variable length lookbehind is experimental\");\n                    }\n                    scan->flags = (U8)minnext + deltanext;\n                }\n                if (data) {\n                    if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))\n                        pars++;\n                    if (data_fake.flags & SF_HAS_EVAL)\n                        data->flags |= SF_HAS_EVAL;\n                    data->whilem_c = data_fake.whilem_c;\n                }\n                if (f & SCF_DO_STCLASS_AND) {\n\t\t    if (flags & SCF_DO_STCLASS_OR) {\n\t\t\t/* OR before, AND after: ideally we would recurse with\n\t\t\t * data_fake to get the AND applied by study of the\n\t\t\t * remainder of the pattern, and then derecurse;\n\t\t\t * *** HACK *** for now just treat as \"no information\".\n\t\t\t * See [perl #56690].\n\t\t\t */\n\t\t\tssc_init(pRExC_state, data->start_class);\n\t\t    }  else {\n                        /* AND before and after: combine and continue.  These\n                         * assertions are zero-length, so can match an EMPTY\n                         * string */\n\t\t\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);\n                        ANYOF_FLAGS(data->start_class)\n                                                   |= SSC_MATCHES_EMPTY_STRING;\n\t\t    }\n                }\n\t    }\n#if PERL_ENABLE_POSITIVE_ASSERTION_STUDY\n            else {\n                /* Positive Lookahead/lookbehind\n                   In this case we can do fixed string optimisation,\n                   but we must be careful about it. Note in the case of\n                   lookbehind the positions will be offset by the minimum\n                   length of the pattern, something we won't know about\n                   until after the recurse.\n                */\n                SSize_t deltanext, fake = 0;\n                regnode *nscan;\n                regnode_ssc intrnl;\n                int f = 0;\n                /* We use SAVEFREEPV so that when the full compile\n                    is finished perl will clean up the allocated\n                    minlens when it's all done. This way we don't\n                    have to worry about freeing them when we know\n                    they wont be used, which would be a pain.\n                 */\n                SSize_t *minnextp;\n                Newx( minnextp, 1, SSize_t );\n                SAVEFREEPV(minnextp);\n\n                if (data) {\n                    StructCopy(data, &data_fake, scan_data_t);\n                    if ((flags & SCF_DO_SUBSTR) && data->last_found) {\n                        f |= SCF_DO_SUBSTR;\n                        if (scan->flags)\n                            scan_commit(pRExC_state, &data_fake, minlenp, is_inf);\n                        data_fake.last_found=newSVsv(data->last_found);\n                    }\n                }\n                else\n                    data_fake.last_closep = &fake;\n                data_fake.flags = 0;\n                data_fake.substrs[0].flags = 0;\n                data_fake.substrs[1].flags = 0;\n\t\tdata_fake.pos_delta = delta;\n                if (is_inf)\n\t            data_fake.flags |= SF_IS_INF;\n                if ( flags & SCF_DO_STCLASS && !scan->flags\n                     && OP(scan) == IFMATCH ) { /* Lookahead */\n                    ssc_init(pRExC_state, &intrnl);\n                    data_fake.start_class = &intrnl;\n                    f |= SCF_DO_STCLASS_AND;\n                }\n                if (flags & SCF_WHILEM_VISITED_POS)\n                    f |= SCF_WHILEM_VISITED_POS;\n                next = regnext(scan);\n                nscan = NEXTOPER(NEXTOPER(scan));\n\n                /* positive lookahead study_chunk() recursion */\n                *minnextp = study_chunk(pRExC_state, &nscan, minnextp,\n                                        &deltanext, last, &data_fake,\n                                        stopparen, recursed_depth, NULL,\n                                        f, depth+1, mutate_ok);\n                if (scan->flags) {\n                    assert(0);  /* This code has never been tested since this\n                                   is normally not compiled */\n                    if (   deltanext < 0\n                        || deltanext > (I32) U8_MAX\n                        || *minnextp > (I32)U8_MAX\n                        || *minnextp + deltanext > (I32)U8_MAX)\n                    {\n\t\t\tFAIL2(\"Lookbehind longer than %\" UVuf \" not implemented\",\n                              (UV)U8_MAX);\n                    }\n\n                    if (deltanext) {\n                        scan->next_off = deltanext;\n                    }\n                    scan->flags = (U8)*minnextp + deltanext;\n                }\n\n                *minnextp += min;\n\n                if (f & SCF_DO_STCLASS_AND) {\n                    ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);\n                    ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;\n                }\n                if (data) {\n                    if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))\n                        pars++;\n                    if (data_fake.flags & SF_HAS_EVAL)\n                        data->flags |= SF_HAS_EVAL;\n                    data->whilem_c = data_fake.whilem_c;\n                    if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {\n                        int i;\n                        if (RExC_rx->minlen<*minnextp)\n                            RExC_rx->minlen=*minnextp;\n                        scan_commit(pRExC_state, &data_fake, minnextp, is_inf);\n                        SvREFCNT_dec_NN(data_fake.last_found);\n\n                        for (i = 0; i < 2; i++) {\n                            if (data_fake.substrs[i].minlenp != minlenp) {\n                                data->substrs[i].min_offset =\n                                            data_fake.substrs[i].min_offset;\n                                data->substrs[i].max_offset =\n                                            data_fake.substrs[i].max_offset;\n                                data->substrs[i].minlenp =\n                                            data_fake.substrs[i].minlenp;\n                                data->substrs[i].lookbehind += scan->flags;\n                            }\n                        }\n                    }\n                }\n\t    }\n#endif\n\t}\n\n\telse if (OP(scan) == OPEN) {\n\t    if (stopparen != (I32)ARG(scan))\n\t        pars++;\n\t}\n\telse if (OP(scan) == CLOSE) {\n\t    if (stopparen == (I32)ARG(scan)) {\n\t        break;\n\t    }\n\t    if ((I32)ARG(scan) == is_par) {\n\t\tnext = regnext(scan);\n\n\t\tif ( next && (OP(next) != WHILEM) && next < last)\n\t\t    is_par = 0;\t\t/* Disable optimization */\n\t    }\n\t    if (data)\n\t\t*(data->last_closep) = ARG(scan);\n\t}\n\telse if (OP(scan) == EVAL) {\n\t\tif (data)\n\t\t    data->flags |= SF_HAS_EVAL;\n\t}\n\telse if ( PL_regkind[OP(scan)] == ENDLIKE ) {\n\t    if (flags & SCF_DO_SUBSTR) {\n                scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\tflags &= ~SCF_DO_SUBSTR;\n\t    }\n\t    if (data && OP(scan)==ACCEPT) {\n\t        data->flags |= SCF_SEEN_ACCEPT;\n\t        if (stopmin > min)\n\t            stopmin = min;\n\t    }\n\t}\n\telse if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */\n\t{\n\t\tif (flags & SCF_DO_SUBSTR) {\n                    scan_commit(pRExC_state, data, minlenp, is_inf);\n\t\t    data->cur_is_floating = 1; /* float */\n\t\t}\n\t\tis_inf = is_inf_internal = 1;\n\t\tif (flags & SCF_DO_STCLASS_OR) /* Allow everything */\n\t\t    ssc_anything(data->start_class);\n\t\tflags &= ~SCF_DO_STCLASS;\n\t}\n\telse if (OP(scan) == GPOS) {\n            if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&\n\t        !(delta || is_inf || (data && data->pos_delta)))\n\t    {\n                if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))\n                    RExC_rx->intflags |= PREGf_ANCH_GPOS;\n\t        if (RExC_rx->gofs < (STRLEN)min)\n\t\t    RExC_rx->gofs = min;\n            } else {\n                RExC_rx->intflags |= PREGf_GPOS_FLOAT;\n                RExC_rx->gofs = 0;\n            }\n\t}\n#ifdef TRIE_STUDY_OPT\n#ifdef FULL_TRIE_STUDY\n        else if (PL_regkind[OP(scan)] == TRIE) {\n            /* NOTE - There is similar code to this block above for handling\n               BRANCH nodes on the initial study.  If you change stuff here\n               check there too. */\n            regnode *trie_node= scan;\n            regnode *tail= regnext(scan);\n            reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];\n            SSize_t max1 = 0, min1 = SSize_t_MAX;\n            regnode_ssc accum;\n\n            if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */\n                /* Cannot merge strings after this. */\n                scan_commit(pRExC_state, data, minlenp, is_inf);\n            }\n            if (flags & SCF_DO_STCLASS)\n                ssc_init_zero(pRExC_state, &accum);\n\n            if (!trie->jump) {\n                min1= trie->minlen;\n                max1= trie->maxlen;\n            } else {\n                const regnode *nextbranch= NULL;\n                U32 word;\n\n                for ( word=1 ; word <= trie->wordcount ; word++)\n                {\n                    SSize_t deltanext=0, minnext=0, f = 0, fake;\n                    regnode_ssc this_class;\n\n                    StructCopy(&zero_scan_data, &data_fake, scan_data_t);\n                    if (data) {\n                        data_fake.whilem_c = data->whilem_c;\n                        data_fake.last_closep = data->last_closep;\n                    }\n                    else\n                        data_fake.last_closep = &fake;\n\t\t    data_fake.pos_delta = delta;\n                    if (flags & SCF_DO_STCLASS) {\n                        ssc_init(pRExC_state, &this_class);\n                        data_fake.start_class = &this_class;\n                        f = SCF_DO_STCLASS_AND;\n                    }\n                    if (flags & SCF_WHILEM_VISITED_POS)\n                        f |= SCF_WHILEM_VISITED_POS;\n\n                    if (trie->jump[word]) {\n                        if (!nextbranch)\n                            nextbranch = trie_node + trie->jump[0];\n                        scan= trie_node + trie->jump[word];\n                        /* We go from the jump point to the branch that follows\n                           it. Note this means we need the vestigal unused\n                           branches even though they arent otherwise used. */\n                        /* optimise study_chunk() for TRIE */\n                        minnext = study_chunk(pRExC_state, &scan, minlenp,\n                            &deltanext, (regnode *)nextbranch, &data_fake,\n                            stopparen, recursed_depth, NULL, f, depth+1,\n                            mutate_ok);\n                    }\n                    if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)\n                        nextbranch= regnext((regnode*)nextbranch);\n\n                    if (min1 > (SSize_t)(minnext + trie->minlen))\n                        min1 = minnext + trie->minlen;\n                    if (deltanext == SSize_t_MAX) {\n                        is_inf = is_inf_internal = 1;\n                        max1 = SSize_t_MAX;\n                    } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))\n                        max1 = minnext + deltanext + trie->maxlen;\n\n                    if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))\n                        pars++;\n                    if (data_fake.flags & SCF_SEEN_ACCEPT) {\n                        if ( stopmin > min + min1)\n\t                    stopmin = min + min1;\n\t                flags &= ~SCF_DO_SUBSTR;\n\t                if (data)\n\t                    data->flags |= SCF_SEEN_ACCEPT;\n\t            }\n                    if (data) {\n                        if (data_fake.flags & SF_HAS_EVAL)\n                            data->flags |= SF_HAS_EVAL;\n                        data->whilem_c = data_fake.whilem_c;\n                    }\n                    if (flags & SCF_DO_STCLASS)\n                        ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);\n                }\n            }\n            if (flags & SCF_DO_SUBSTR) {\n                data->pos_min += min1;\n                data->pos_delta += max1 - min1;\n                if (max1 != min1 || is_inf)\n                    data->cur_is_floating = 1; /* float */\n            }\n            min += min1;\n            if (delta != SSize_t_MAX) {\n                if (SSize_t_MAX - (max1 - min1) >= delta)\n                    delta += max1 - min1;\n                else\n                    delta = SSize_t_MAX;\n            }\n            if (flags & SCF_DO_STCLASS_OR) {\n                ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);\n                if (min1) {\n                    ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n                    flags &= ~SCF_DO_STCLASS;\n                }\n            }\n            else if (flags & SCF_DO_STCLASS_AND) {\n                if (min1) {\n                    ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);\n                    flags &= ~SCF_DO_STCLASS;\n                }\n                else {\n                    /* Switch to OR mode: cache the old value of\n                     * data->start_class */\n\t\t    INIT_AND_WITHP;\n                    StructCopy(data->start_class, and_withp, regnode_ssc);\n                    flags &= ~SCF_DO_STCLASS_AND;\n                    StructCopy(&accum, data->start_class, regnode_ssc);\n                    flags |= SCF_DO_STCLASS_OR;\n                }\n            }\n            scan= tail;\n            continue;\n        }\n#else\n\telse if (PL_regkind[OP(scan)] == TRIE) {\n\t    reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];\n\t    U8*bang=NULL;\n\n\t    min += trie->minlen;\n\t    delta += (trie->maxlen - trie->minlen);\n\t    flags &= ~SCF_DO_STCLASS; /* xxx */\n            if (flags & SCF_DO_SUBSTR) {\n                /* Cannot expect anything... */\n                scan_commit(pRExC_state, data, minlenp, is_inf);\n    \t        data->pos_min += trie->minlen;\n    \t        data->pos_delta += (trie->maxlen - trie->minlen);\n\t\tif (trie->maxlen != trie->minlen)\n\t\t    data->cur_is_floating = 1; /* float */\n    \t    }\n    \t    if (trie->jump) /* no more substrings -- for now /grr*/\n               flags &= ~SCF_DO_SUBSTR;\n\t}\n#endif /* old or new */\n#endif /* TRIE_STUDY_OPT */\n\n\t/* Else: zero-length, ignore. */\n\tscan = regnext(scan);\n    }\n\n  finish:\n    if (frame) {\n        /* we need to unwind recursion. */\n        depth = depth - 1;\n\n        DEBUG_STUDYDATA(\"frame-end\", data, depth, is_inf);\n        DEBUG_PEEP(\"fend\", scan, depth, flags);\n\n        /* restore previous context */\n        last = frame->last_regnode;\n        scan = frame->next_regnode;\n        stopparen = frame->stopparen;\n        recursed_depth = frame->prev_recursed_depth;\n\n        RExC_frame_last = frame->prev_frame;\n        frame = frame->this_prev_frame;\n        goto fake_study_recurse;\n    }\n\n    assert(!frame);\n    DEBUG_STUDYDATA(\"pre-fin\", data, depth, is_inf);\n\n    *scanp = scan;\n    *deltap = is_inf_internal ? SSize_t_MAX : delta;\n\n    if (flags & SCF_DO_SUBSTR && is_inf)\n\tdata->pos_delta = SSize_t_MAX - data->pos_min;\n    if (is_par > (I32)U8_MAX)\n\tis_par = 0;\n    if (is_par && pars==1 && data) {\n\tdata->flags |= SF_IN_PAR;\n\tdata->flags &= ~SF_HAS_PAR;\n    }\n    else if (pars && data) {\n\tdata->flags |= SF_HAS_PAR;\n\tdata->flags &= ~SF_IN_PAR;\n    }\n    if (flags & SCF_DO_STCLASS_OR)\n\tssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);\n    if (flags & SCF_TRIE_RESTUDY)\n        data->flags |= \tSCF_TRIE_RESTUDY;\n\n    DEBUG_STUDYDATA(\"post-fin\", data, depth, is_inf);\n\n    {\n        SSize_t final_minlen= min < stopmin ? min : stopmin;\n\n        if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {\n            if (final_minlen > SSize_t_MAX - delta)\n                RExC_maxlen = SSize_t_MAX;\n            else if (RExC_maxlen < final_minlen + delta)\n                RExC_maxlen = final_minlen + delta;\n        }\n        return final_minlen;\n    }\n    NOT_REACHED; /* NOTREACHED */", "func_hash": 7575865277439549502998615595514633684, "file_name": "regcomp.c", "file_hash": 6878494453235899109541655885780527455, "cwe": ["CWE-120"], "cve": "CVE-2020-12723", "cve_desc": "regcomp.c in Perl before 5.30.3 allows a buffer overflow via a crafted regular expression because of recursive S_study_chunk calls.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12723"}
{"idx": 215312, "project": "linux-2.6", "commit_id": "9926e4c74300c4b31dee007298c6475d33369df0", "project_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6", "commit_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commitdiff;h=9926e4c74300c4b31dee007298c6475d33369df0", "commit_message": "CPU time limit patch / setrlimit(RLIMIT_CPU, 0) cheat fix\n\nAs discovered here today, the change in Kernel 2.6.17 intended to inhibit\nusers from setting RLIMIT_CPU to 0 (as that is equivalent to unlimited) by\n\"cheating\" and setting it to 1 in such a case, does not make a difference,\nas the check is done in the wrong place (too late), and only applies to the\nprofiling code.\n\nOn all systems I checked running kernels above 2.6.17, no matter what the\nhard and soft CPU time limits were before, a user could escape them by\nissuing in the shell (sh/bash/zsh) \"ulimit -t 0\", and then the user's\nprocess was not ever killed.\n\nAttached is a trivial patch to fix that.  Simply moving the check to a\nslightly earlier location (specifically, before the line that actually\nassigns the limit - *old_rlim = new_rlim), does the trick.\n\nDo note that at least the zsh (but not ash, dash, or bash) shell has the\nproblem of \"caching\" the limits set by the ulimit command, so when running\nzsh the fix will not immediately be evident - after entering \"ulimit -t 0\",\n\"ulimit -a\" will show \"-t: cpu time (seconds) 0\", even though the actual\nlimit as returned by getrlimit(...) will be 1.  It can be verified by\nopening a subshell (which will not have the values of the parent shell in\ncache) and checking in it, or just by running a CPU intensive command like\n\"echo '65536^1048576' | bc\" and verifying that it dumps core after one\nsecond.\n\nRegardless of whether that is a misfeature in the shell, perhaps it would\nbe better to return -EINVAL from setrlimit in such a case instead of\ncheating and setting to 1, as that does not really reflect the actual state\nof the process anymore.  I do not however know what the ground for that\ndecision was in the original 2.6.17 change, and whether there would be any\n\"backward\" compatibility issues, so I preferred not to touch that right\nnow.\n\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "target": 1, "func": "asmlinkage long sys_setrlimit(unsigned int resource, struct rlimit __user *rlim)\n{\n\tstruct rlimit new_rlim, *old_rlim;\n\tunsigned long it_prof_secs;\n\tint retval;\n\n\tif (resource >= RLIM_NLIMITS)\n\t\treturn -EINVAL;\n\tif (copy_from_user(&new_rlim, rlim, sizeof(*rlim)))\n\t\treturn -EFAULT;\n\tif (new_rlim.rlim_cur > new_rlim.rlim_max)\n\t\treturn -EINVAL;\n\told_rlim = current->signal->rlim + resource;\n\tif ((new_rlim.rlim_max > old_rlim->rlim_max) &&\n\t    !capable(CAP_SYS_RESOURCE))\n\t\treturn -EPERM;\n\tif (resource == RLIMIT_NOFILE && new_rlim.rlim_max > NR_OPEN)\n\t\treturn -EPERM;\n\n\tretval = security_task_setrlimit(resource, &new_rlim);\n\tif (retval)\n\t\treturn retval;\n\n\ttask_lock(current->group_leader);\n\t*old_rlim = new_rlim;\n\ttask_unlock(current->group_leader);\n\n\tif (resource != RLIMIT_CPU)\n\t\tgoto out;\n\n\t/*\n\t * RLIMIT_CPU handling.   Note that the kernel fails to return an error\n\t * code if it rejected the user's attempt to set RLIMIT_CPU.  This is a\n\t * very long-standing error, and fixing it now risks breakage of\n\t * applications, so we live with it\n\t */\n\tif (new_rlim.rlim_cur == RLIM_INFINITY)\n\t\tgoto out;\n\n\tit_prof_secs = cputime_to_secs(current->signal->it_prof_expires);\n\tif (it_prof_secs == 0 || new_rlim.rlim_cur <= it_prof_secs) {\n\t\tunsigned long rlim_cur = new_rlim.rlim_cur;\n\t\tcputime_t cputime;\n\n\t\tif (rlim_cur == 0) {\n\t\t\t/*\n\t\t\t * The caller is asking for an immediate RLIMIT_CPU\n\t\t\t * expiry.  But we use the zero value to mean \"it was\n\t\t\t * never set\".  So let's cheat and make it one second\n\t\t\t * instead\n\t\t\t */\n\t\t\trlim_cur = 1;\n\t\t}\n\t\tcputime = secs_to_cputime(rlim_cur);\n\t\tread_lock(&tasklist_lock);\n\t\tspin_lock_irq(¤t->sighand->siglock);\n\t\tset_process_cpu_timer(current, CPUCLOCK_PROF, &cputime, NULL);\n\t\tspin_unlock_irq(¤t->sighand->siglock);\n\t\tread_unlock(&tasklist_lock);\n\t}\nout:\n\treturn 0;\n}", "func_hash": 308291960942000103777374680863829169927, "file_name": "None", "file_hash": null, "cwe": ["CWE-20"], "cve": "CVE-2008-1294", "cve_desc": "Linux kernel 2.6.17, and other versions before 2.6.22, does not check when a user attempts to set RLIMIT_CPU to 0 until after the change is made, which allows local users to bypass intended resource limits.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2008-1294"}
{"idx": 487618, "project": "linux-2.6", "commit_id": "9926e4c74300c4b31dee007298c6475d33369df0", "project_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6", "commit_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commitdiff;h=9926e4c74300c4b31dee007298c6475d33369df0", "commit_message": "CPU time limit patch / setrlimit(RLIMIT_CPU, 0) cheat fix\n\nAs discovered here today, the change in Kernel 2.6.17 intended to inhibit\nusers from setting RLIMIT_CPU to 0 (as that is equivalent to unlimited) by\n\"cheating\" and setting it to 1 in such a case, does not make a difference,\nas the check is done in the wrong place (too late), and only applies to the\nprofiling code.\n\nOn all systems I checked running kernels above 2.6.17, no matter what the\nhard and soft CPU time limits were before, a user could escape them by\nissuing in the shell (sh/bash/zsh) \"ulimit -t 0\", and then the user's\nprocess was not ever killed.\n\nAttached is a trivial patch to fix that.  Simply moving the check to a\nslightly earlier location (specifically, before the line that actually\nassigns the limit - *old_rlim = new_rlim), does the trick.\n\nDo note that at least the zsh (but not ash, dash, or bash) shell has the\nproblem of \"caching\" the limits set by the ulimit command, so when running\nzsh the fix will not immediately be evident - after entering \"ulimit -t 0\",\n\"ulimit -a\" will show \"-t: cpu time (seconds) 0\", even though the actual\nlimit as returned by getrlimit(...) will be 1.  It can be verified by\nopening a subshell (which will not have the values of the parent shell in\ncache) and checking in it, or just by running a CPU intensive command like\n\"echo '65536^1048576' | bc\" and verifying that it dumps core after one\nsecond.\n\nRegardless of whether that is a misfeature in the shell, perhaps it would\nbe better to return -EINVAL from setrlimit in such a case instead of\ncheating and setting to 1, as that does not really reflect the actual state\nof the process anymore.  I do not however know what the ground for that\ndecision was in the original 2.6.17 change, and whether there would be any\n\"backward\" compatibility issues, so I preferred not to touch that right\nnow.\n\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "target": 0, "func": "asmlinkage long sys_setrlimit(unsigned int resource, struct rlimit __user *rlim)\n{\n\tstruct rlimit new_rlim, *old_rlim;\n\tunsigned long it_prof_secs;\n\tint retval;\n\n\tif (resource >= RLIM_NLIMITS)\n\t\treturn -EINVAL;\n\tif (copy_from_user(&new_rlim, rlim, sizeof(*rlim)))\n\t\treturn -EFAULT;\n\tif (new_rlim.rlim_cur > new_rlim.rlim_max)\n\t\treturn -EINVAL;\n\told_rlim = current->signal->rlim + resource;\n\tif ((new_rlim.rlim_max > old_rlim->rlim_max) &&\n\t    !capable(CAP_SYS_RESOURCE))\n\t\treturn -EPERM;\n\tif (resource == RLIMIT_NOFILE && new_rlim.rlim_max > NR_OPEN)\n\t\treturn -EPERM;\n\n\tretval = security_task_setrlimit(resource, &new_rlim);\n\tif (retval)\n\t\treturn retval;\n\n\tif (resource == RLIMIT_CPU && new_rlim.rlim_cur == 0) {\n\t\t/*\n\t\t * The caller is asking for an immediate RLIMIT_CPU\n\t\t * expiry.  But we use the zero value to mean \"it was\n\t\t * never set\".  So let's cheat and make it one second\n\t\t * instead\n\t\t */\n\t\tnew_rlim.rlim_cur = 1;\n\t}\n\n\ttask_lock(current->group_leader);\n\t*old_rlim = new_rlim;\n\ttask_unlock(current->group_leader);\n\n\tif (resource != RLIMIT_CPU)\n\t\tgoto out;\n\n\t/*\n\t * RLIMIT_CPU handling.   Note that the kernel fails to return an error\n\t * code if it rejected the user's attempt to set RLIMIT_CPU.  This is a\n\t * very long-standing error, and fixing it now risks breakage of\n\t * applications, so we live with it\n\t */\n\tif (new_rlim.rlim_cur == RLIM_INFINITY)\n\t\tgoto out;\n\n\tit_prof_secs = cputime_to_secs(current->signal->it_prof_expires);\n\tif (it_prof_secs == 0 || new_rlim.rlim_cur <= it_prof_secs) {\n\t\tunsigned long rlim_cur = new_rlim.rlim_cur;\n\t\tcputime_t cputime;\n\n\t\tcputime = secs_to_cputime(rlim_cur);\n\t\tread_lock(&tasklist_lock);\n\t\tspin_lock_irq(¤t->sighand->siglock);\n\t\tset_process_cpu_timer(current, CPUCLOCK_PROF, &cputime, NULL);\n\t\tspin_unlock_irq(¤t->sighand->siglock);\n\t\tread_unlock(&tasklist_lock);\n\t}\nout:\n\treturn 0;\n}", "func_hash": 187909105803248299994402329971280049548, "file_name": "None", "file_hash": null, "cwe": ["CWE-20"], "cve": "CVE-2008-1294", "cve_desc": "Linux kernel 2.6.17, and other versions before 2.6.22, does not check when a user attempts to set RLIMIT_CPU to 0 until after the change is made, which allows local users to bypass intended resource limits.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2008-1294"}
{"idx": 215374, "project": "linux-2.6", "commit_id": "328fc47ea0bcc27d9afa69c3ad6e52431cadd76c", "project_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6", "commit_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commitdiff;h=328fc47ea0bcc27d9afa69c3ad6e52431cadd76c", "commit_message": "sctp: correct bounds check in sctp_setsockopt_auth_key\n\nThe bonds check to prevent buffer overlflow was not exactly\nright.  It still allowed overflow of up to 8 bytes which is\nsizeof(struct sctp_authkey).\n\nSince optlen is already checked against the size of that struct,\nwe are guaranteed not to cause interger overflow either.\n\nSigned-off-by: Vlad Yasevich \nSigned-off-by: David S. Miller ", "target": 1, "func": "static int sctp_setsockopt_auth_key(struct sock *sk,\n\t\t\t\t    char __user *optval,\n\t\t\t\t    int optlen)\n{\n\tstruct sctp_authkey *authkey;\n\tstruct sctp_association *asoc;\n\tint ret;\n\n\tif (!sctp_auth_enable)\n\t\treturn -EACCES;\n\n\tif (optlen <= sizeof(struct sctp_authkey))\n\t\treturn -EINVAL;\n\n\tauthkey = kmalloc(optlen, GFP_KERNEL);\n\tif (!authkey)\n\t\treturn -ENOMEM;\n\n\tif (copy_from_user(authkey, optval, optlen)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}\n\n\tif (authkey->sca_keylength > optlen) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tasoc = sctp_id2assoc(sk, authkey->sca_assoc_id);\n\tif (!asoc && authkey->sca_assoc_id && sctp_style(sk, UDP)) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tret = sctp_auth_set_key(sctp_sk(sk)->ep, asoc, authkey);\nout:\n\tkfree(authkey);\n\treturn ret;\n}", "func_hash": 46314924383394303871242635983086014836, "file_name": "None", "file_hash": null, "cwe": ["CWE-189"], "cve": "CVE-2008-3526", "cve_desc": "Integer overflow in the sctp_setsockopt_auth_key function in net/sctp/socket.c in the Stream Control Transmission Protocol (sctp) implementation in the Linux kernel 2.6.24-rc1 through 2.6.26.3 allows remote attackers to cause a denial of service (panic) or possibly have unspecified other impact via a crafted sca_keylength field associated with the SCTP_AUTH_KEY option.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2008-3526"}
{"idx": 488919, "project": "linux-2.6", "commit_id": "328fc47ea0bcc27d9afa69c3ad6e52431cadd76c", "project_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6", "commit_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commitdiff;h=328fc47ea0bcc27d9afa69c3ad6e52431cadd76c", "commit_message": "sctp: correct bounds check in sctp_setsockopt_auth_key\n\nThe bonds check to prevent buffer overlflow was not exactly\nright.  It still allowed overflow of up to 8 bytes which is\nsizeof(struct sctp_authkey).\n\nSince optlen is already checked against the size of that struct,\nwe are guaranteed not to cause interger overflow either.\n\nSigned-off-by: Vlad Yasevich \nSigned-off-by: David S. Miller ", "target": 0, "func": "static int sctp_setsockopt_auth_key(struct sock *sk,\n\t\t\t\t    char __user *optval,\n\t\t\t\t    int optlen)\n{\n\tstruct sctp_authkey *authkey;\n\tstruct sctp_association *asoc;\n\tint ret;\n\n\tif (!sctp_auth_enable)\n\t\treturn -EACCES;\n\n\tif (optlen <= sizeof(struct sctp_authkey))\n\t\treturn -EINVAL;\n\n\tauthkey = kmalloc(optlen, GFP_KERNEL);\n\tif (!authkey)\n\t\treturn -ENOMEM;\n\n\tif (copy_from_user(authkey, optval, optlen)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}\n\n\tif (authkey->sca_keylength > optlen - sizeof(struct sctp_authkey)) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tasoc = sctp_id2assoc(sk, authkey->sca_assoc_id);\n\tif (!asoc && authkey->sca_assoc_id && sctp_style(sk, UDP)) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tret = sctp_auth_set_key(sctp_sk(sk)->ep, asoc, authkey);\nout:\n\tkfree(authkey);\n\treturn ret;\n}", "func_hash": 298167600420793747403712897523979919986, "file_name": "None", "file_hash": null, "cwe": ["CWE-189"], "cve": "CVE-2008-3526", "cve_desc": "Integer overflow in the sctp_setsockopt_auth_key function in net/sctp/socket.c in the Stream Control Transmission Protocol (sctp) implementation in the Linux kernel 2.6.24-rc1 through 2.6.26.3 allows remote attackers to cause a denial of service (panic) or possibly have unspecified other impact via a crafted sca_keylength field associated with the SCTP_AUTH_KEY option.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2008-3526"}
{"idx": 215391, "project": "linux-2.6", "commit_id": "ba0166708ef4da7eeb61dd92bbba4d5a749d6561", "project_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6", "commit_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commitdiff;h=ba0166708ef4da7eeb61dd92bbba4d5a749d6561", "commit_message": "sctp: Fix kernel panic while process protocol violation parameter\n\nSince call to function sctp_sf_abort_violation() need paramter 'arg' with\n'struct sctp_chunk' type, it will read the chunk type and chunk length from\nthe chunk_hdr member of chunk. But call to sctp_sf_violation_paramlen()\nalways with 'struct sctp_paramhdr' type's parameter, it will be passed to\nsctp_sf_abort_violation(). This may cause kernel panic.\n\n   sctp_sf_violation_paramlen()\n     |-- sctp_sf_abort_violation()\n        |-- sctp_make_abort_violation()\n\nThis patch fixed this problem. This patch also fix two place which called\nsctp_sf_violation_paramlen() with wrong paramter type.\n\nSigned-off-by: Wei Yongjun \nSigned-off-by: Vlad Yasevich \nSigned-off-by: David S. Miller ", "target": 1, "func": "static sctp_disposition_t sctp_sf_violation_paramlen(\n\t\t\t\t     const struct sctp_endpoint *ep,\n\t\t\t\t     const struct sctp_association *asoc,\n\t\t\t\t     const sctp_subtype_t type,\n\t\t\t\t     void *arg,\n\t\t\t\t     sctp_cmd_seq_t *commands) {\n\tstatic const char err_str[] = \"The following parameter had invalid length:\";\n\n\treturn sctp_sf_abort_violation(ep, asoc, arg, commands, err_str,\n\t\t\t\t\tsizeof(err_str));\n}", "func_hash": 31315788610604386259282762063646605709, "file_name": "None", "file_hash": null, "cwe": ["CWE-20"], "cve": "CVE-2008-4618", "cve_desc": "The Stream Control Transmission Protocol (sctp) implementation in the Linux kernel before 2.6.27 does not properly handle a protocol violation in which a parameter has an invalid length, which allows attackers to cause a denial of service (panic) via unspecified vectors, related to sctp_sf_violation_paramlen, sctp_sf_abort_violation, sctp_make_abort_violation, and incorrect data types in function calls.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2008-4618"}
{"idx": 489124, "project": "linux-2.6", "commit_id": "ba0166708ef4da7eeb61dd92bbba4d5a749d6561", "project_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6", "commit_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commitdiff;h=ba0166708ef4da7eeb61dd92bbba4d5a749d6561", "commit_message": "sctp: Fix kernel panic while process protocol violation parameter\n\nSince call to function sctp_sf_abort_violation() need paramter 'arg' with\n'struct sctp_chunk' type, it will read the chunk type and chunk length from\nthe chunk_hdr member of chunk. But call to sctp_sf_violation_paramlen()\nalways with 'struct sctp_paramhdr' type's parameter, it will be passed to\nsctp_sf_abort_violation(). This may cause kernel panic.\n\n   sctp_sf_violation_paramlen()\n     |-- sctp_sf_abort_violation()\n        |-- sctp_make_abort_violation()\n\nThis patch fixed this problem. This patch also fix two place which called\nsctp_sf_violation_paramlen() with wrong paramter type.\n\nSigned-off-by: Wei Yongjun \nSigned-off-by: Vlad Yasevich \nSigned-off-by: David S. Miller ", "target": 0, "func": "static sctp_disposition_t sctp_sf_violation_chunklen(\n\t\t\t\t     const struct sctp_endpoint *ep,\n\t\t\t\t     const struct sctp_association *asoc,\n\t\t\t\t     const sctp_subtype_t type,\n\t\t\t\t     void *arg,\n\t\t\t\t     sctp_cmd_seq_t *commands)\n{\n\tstatic const char err_str[]=\"The following chunk had invalid length:\";\n\n\treturn sctp_sf_abort_violation(ep, asoc, arg, commands, err_str,\n\t\t\t\t\tsizeof(err_str));\n}", "func_hash": 307853403397128900302576220100500126991, "file_name": "None", "file_hash": null, "cwe": ["CWE-20"], "cve": "CVE-2008-4618", "cve_desc": "The Stream Control Transmission Protocol (sctp) implementation in the Linux kernel before 2.6.27 does not properly handle a protocol violation in which a parameter has an invalid length, which allows attackers to cause a denial of service (panic) via unspecified vectors, related to sctp_sf_violation_paramlen, sctp_sf_abort_violation, sctp_make_abort_violation, and incorrect data types in function calls.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2008-4618"}
{"idx": 215399, "project": "linux-2.6", "commit_id": "efc7ffcb4237f8cb9938909041c4ed38f6e1bf40", "project_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6", "commit_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=efc7ffcb4237f8cb9938909041c4ed38f6e1bf40", "commit_message": "hfsplus: fix Buffer overflow with a corrupted image\n\nWhen an hfsplus image gets corrupted it might happen that the catalog\nnamelength field gets b0rked.  If we mount such an image the memcpy() in\nhfsplus_cat_build_key_uni() writes more than the 255 that fit in the name\nfield.  Depending on the size of the overwritten data, we either only get\nmemory corruption or also trigger an oops like this:\n\n[  221.628020] BUG: unable to handle kernel paging request at c82b0000\n[  221.629066] IP: [] hfsplus_find_cat+0x10d/0x151\n[  221.629066] *pde = 0ea29163 *pte = 082b0160\n[  221.629066] Oops: 0002 [#1] PREEMPT DEBUG_PAGEALLOC\n[  221.629066] Modules linked in:\n[  221.629066]\n[  221.629066] Pid: 4845, comm: mount Not tainted (2.6.27-rc4-00123-gd3ee1b4-dirty #28)\n[  221.629066] EIP: 0060:[] EFLAGS: 00010206 CPU: 0\n[  221.629066] EIP is at hfsplus_find_cat+0x10d/0x151\n[  221.629066] EAX: 00000029 EBX: 00016210 ECX: 000042c2 EDX: 00000002\n[  221.629066] ESI: c82d70ca EDI: c82b0000 EBP: c82d1bcc ESP: c82d199c\n[  221.629066]  DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 0068\n[  221.629066] Process mount (pid: 4845, ti=c82d1000 task=c8224060 task.ti=c82d1000)\n[  221.629066] Stack: c080b3c4 c82aa8f8 c82d19c2 00016210 c080b3be c82d1bd4 c82aa8f0 00000300\n[  221.629066]        01000000 750008b1 74006e00 74006900 65006c00 c82d6400 c013bd35 c8224060\n[  221.629066]        00000036 00000046 c82d19f0 00000082 c8224548 c8224060 00000036 c0d653cc\n[  221.629066] Call Trace:\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? trace_hardirqs_off_caller+0x14/0x9b\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? trace_hardirqs_off_caller+0x14/0x9b\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? native_sched_clock+0x82/0x96\n[  221.629066]  [] ? __kernel_text_address+0x1b/0x27\n[  221.629066]  [] ? dump_trace+0xca/0xd6\n[  221.629066]  [] ? save_stack_address+0x0/0x2c\n[  221.629066]  [] ? save_stack_trace+0x1c/0x3a\n[  221.629066]  [] ? save_trace+0x37/0x8d\n[  221.629066]  [] ? add_lock_to_list+0x67/0x8d\n[  221.629066]  [] ? validate_chain+0x8a4/0x9f4\n[  221.629066]  [] ? down+0xc/0x2f\n[  221.629066]  [] ? __lock_acquire+0x68a/0x6e0\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? trace_hardirqs_off_caller+0x14/0x9b\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? native_sched_clock+0x82/0x96\n[  221.629066]  [] ? mark_held_locks+0x43/0x5a\n[  221.629066]  [] ? trace_hardirqs_on+0xb/0xd\n[  221.629066]  [] ? trace_hardirqs_on_caller+0xf4/0x12f\n[  221.629066]  [] ? _spin_unlock_irqrestore+0x42/0x58\n[  221.629066]  [] ? down+0x2b/0x2f\n[  221.629066]  [] ? hfsplus_iget+0xa0/0x154\n[  221.629066]  [] ? hfsplus_fill_super+0x280/0x447\n[  221.629066]  [] ? native_sched_clock+0x82/0x96\n[  221.629066]  [] ? trace_hardirqs_off_caller+0x14/0x9b\n[  221.629066]  [] ? trace_hardirqs_off_caller+0x14/0x9b\n[  221.629066]  [] ? __lock_acquire+0x68a/0x6e0\n[  221.629066]  [] ? string+0x2b/0x74\n[  221.629066]  [] ? vsnprintf+0x2e9/0x512\n[  221.629066]  [] ? dump_trace+0xca/0xd6\n[  221.629066]  [] ? save_stack_trace+0x1c/0x3a\n[  221.629066]  [] ? save_stack_trace+0x1c/0x3a\n[  221.629066]  [] ? save_trace+0x37/0x8d\n[  221.629066]  [] ? add_lock_to_list+0x67/0x8d\n[  221.629066]  [] ? validate_chain+0x8a4/0x9f4\n[  221.629066]  [] ? up+0xc/0x2f\n[  221.629066]  [] ? __lock_acquire+0x68a/0x6e0\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? trace_hardirqs_off_caller+0x14/0x9b\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? native_sched_clock+0x82/0x96\n[  221.629066]  [] ? snprintf+0x1b/0x1d\n[  221.629066]  [] ? disk_name+0x25/0x67\n[  221.629066]  [] ? get_sb_bdev+0xcd/0x10b\n[  221.629066]  [] ? kstrdup+0x2a/0x4c\n[  221.629066]  [] ? hfsplus_get_sb+0x13/0x15\n[  221.629066]  [] ? hfsplus_fill_super+0x0/0x447\n[  221.629066]  [] ? vfs_kern_mount+0x3b/0x76\n[  221.629066]  [] ? do_kern_mount+0x32/0xba\n[  221.629066]  [] ? do_new_mount+0x46/0x74\n[  221.629066]  [] ? do_mount+0x175/0x193\n[  221.629066]  [] ? trace_hardirqs_on_caller+0xf4/0x12f\n[  221.629066]  [] ? __get_free_pages+0x1e/0x24\n[  221.629066]  [] ? lock_kernel+0x19/0x8c\n[  221.629066]  [] ? sys_mount+0x51/0x9b\n[  221.629066]  [] ? sys_mount+0x64/0x9b\n[  221.629066]  [] ? sysenter_do_call+0x12/0x31\n[  221.629066]  =======================\n[  221.629066] Code: 89 c2 c1 e2 08 c1 e8 08 09 c2 8b 85 e8 fd ff ff 66 89 50 06 89 c7 53 83 c7 08 56 57 68 c4 b3 80 c0 e8 8c 5c ef ff 89 d9 c1 e9 02  a5 89 d9 83 e1 03 74 02 f3 a4 83 c3 06 8b 95 e8 fd ff ff 0f\n[  221.629066] EIP: [] hfsplus_find_cat+0x10d/0x151 SS:ESP 0068:c82d199c\n[  221.629066] ---[ end trace e417a1d67f0d0066 ]---\n\nSince hfsplus_cat_build_key_uni() returns void and only has one callsite,\nthe check is performed at the callsite.\n\nSigned-off-by: Eric Sesterhenn \nReviewed-by: Pekka Enberg \nCc: Roman Zippel \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "target": 1, "func": "int hfsplus_find_cat(struct super_block *sb, u32 cnid,\n\t\t     struct hfs_find_data *fd)\n{\n\thfsplus_cat_entry tmp;\n\tint err;\n\tu16 type;\n\n\thfsplus_cat_build_key(sb, fd->search_key, cnid, NULL);\n\terr = hfs_brec_read(fd, &tmp, sizeof(hfsplus_cat_entry));\n\tif (err)\n\t\treturn err;\n\n\ttype = be16_to_cpu(tmp.type);\n\tif (type != HFSPLUS_FOLDER_THREAD && type != HFSPLUS_FILE_THREAD) {\n\t\tprintk(KERN_ERR \"hfs: found bad thread record in catalog\\n\");\n\t\treturn -EIO;\n\t}\n\n\thfsplus_cat_build_key_uni(fd->search_key, be32_to_cpu(tmp.thread.parentID),\n\t\t\t\t &tmp.thread.nodeName);\n\treturn hfs_brec_find(fd);\n}", "func_hash": 215695318616116738125696937571179709955, "file_name": "None", "file_hash": null, "cwe": ["CWE-119"], "cve": "CVE-2008-4933", "cve_desc": "Buffer overflow in the hfsplus_find_cat function in fs/hfsplus/catalog.c in the Linux kernel before 2.6.28-rc1 allows attackers to cause a denial of service (memory corruption or system crash) via an hfsplus filesystem image with an invalid catalog namelength field, related to the hfsplus_cat_build_key_uni function.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2008-4933"}
{"idx": 489215, "project": "linux-2.6", "commit_id": "efc7ffcb4237f8cb9938909041c4ed38f6e1bf40", "project_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6", "commit_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=efc7ffcb4237f8cb9938909041c4ed38f6e1bf40", "commit_message": "hfsplus: fix Buffer overflow with a corrupted image\n\nWhen an hfsplus image gets corrupted it might happen that the catalog\nnamelength field gets b0rked.  If we mount such an image the memcpy() in\nhfsplus_cat_build_key_uni() writes more than the 255 that fit in the name\nfield.  Depending on the size of the overwritten data, we either only get\nmemory corruption or also trigger an oops like this:\n\n[  221.628020] BUG: unable to handle kernel paging request at c82b0000\n[  221.629066] IP: [] hfsplus_find_cat+0x10d/0x151\n[  221.629066] *pde = 0ea29163 *pte = 082b0160\n[  221.629066] Oops: 0002 [#1] PREEMPT DEBUG_PAGEALLOC\n[  221.629066] Modules linked in:\n[  221.629066]\n[  221.629066] Pid: 4845, comm: mount Not tainted (2.6.27-rc4-00123-gd3ee1b4-dirty #28)\n[  221.629066] EIP: 0060:[] EFLAGS: 00010206 CPU: 0\n[  221.629066] EIP is at hfsplus_find_cat+0x10d/0x151\n[  221.629066] EAX: 00000029 EBX: 00016210 ECX: 000042c2 EDX: 00000002\n[  221.629066] ESI: c82d70ca EDI: c82b0000 EBP: c82d1bcc ESP: c82d199c\n[  221.629066]  DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 0068\n[  221.629066] Process mount (pid: 4845, ti=c82d1000 task=c8224060 task.ti=c82d1000)\n[  221.629066] Stack: c080b3c4 c82aa8f8 c82d19c2 00016210 c080b3be c82d1bd4 c82aa8f0 00000300\n[  221.629066]        01000000 750008b1 74006e00 74006900 65006c00 c82d6400 c013bd35 c8224060\n[  221.629066]        00000036 00000046 c82d19f0 00000082 c8224548 c8224060 00000036 c0d653cc\n[  221.629066] Call Trace:\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? trace_hardirqs_off_caller+0x14/0x9b\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? trace_hardirqs_off_caller+0x14/0x9b\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? native_sched_clock+0x82/0x96\n[  221.629066]  [] ? __kernel_text_address+0x1b/0x27\n[  221.629066]  [] ? dump_trace+0xca/0xd6\n[  221.629066]  [] ? save_stack_address+0x0/0x2c\n[  221.629066]  [] ? save_stack_trace+0x1c/0x3a\n[  221.629066]  [] ? save_trace+0x37/0x8d\n[  221.629066]  [] ? add_lock_to_list+0x67/0x8d\n[  221.629066]  [] ? validate_chain+0x8a4/0x9f4\n[  221.629066]  [] ? down+0xc/0x2f\n[  221.629066]  [] ? __lock_acquire+0x68a/0x6e0\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? trace_hardirqs_off_caller+0x14/0x9b\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? native_sched_clock+0x82/0x96\n[  221.629066]  [] ? mark_held_locks+0x43/0x5a\n[  221.629066]  [] ? trace_hardirqs_on+0xb/0xd\n[  221.629066]  [] ? trace_hardirqs_on_caller+0xf4/0x12f\n[  221.629066]  [] ? _spin_unlock_irqrestore+0x42/0x58\n[  221.629066]  [] ? down+0x2b/0x2f\n[  221.629066]  [] ? hfsplus_iget+0xa0/0x154\n[  221.629066]  [] ? hfsplus_fill_super+0x280/0x447\n[  221.629066]  [] ? native_sched_clock+0x82/0x96\n[  221.629066]  [] ? trace_hardirqs_off_caller+0x14/0x9b\n[  221.629066]  [] ? trace_hardirqs_off_caller+0x14/0x9b\n[  221.629066]  [] ? __lock_acquire+0x68a/0x6e0\n[  221.629066]  [] ? string+0x2b/0x74\n[  221.629066]  [] ? vsnprintf+0x2e9/0x512\n[  221.629066]  [] ? dump_trace+0xca/0xd6\n[  221.629066]  [] ? save_stack_trace+0x1c/0x3a\n[  221.629066]  [] ? save_stack_trace+0x1c/0x3a\n[  221.629066]  [] ? save_trace+0x37/0x8d\n[  221.629066]  [] ? add_lock_to_list+0x67/0x8d\n[  221.629066]  [] ? validate_chain+0x8a4/0x9f4\n[  221.629066]  [] ? up+0xc/0x2f\n[  221.629066]  [] ? __lock_acquire+0x68a/0x6e0\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? trace_hardirqs_off_caller+0x14/0x9b\n[  221.629066]  [] ? trace_hardirqs_off+0xb/0xd\n[  221.629066]  [] ? native_sched_clock+0x82/0x96\n[  221.629066]  [] ? snprintf+0x1b/0x1d\n[  221.629066]  [] ? disk_name+0x25/0x67\n[  221.629066]  [] ? get_sb_bdev+0xcd/0x10b\n[  221.629066]  [] ? kstrdup+0x2a/0x4c\n[  221.629066]  [] ? hfsplus_get_sb+0x13/0x15\n[  221.629066]  [] ? hfsplus_fill_super+0x0/0x447\n[  221.629066]  [] ? vfs_kern_mount+0x3b/0x76\n[  221.629066]  [] ? do_kern_mount+0x32/0xba\n[  221.629066]  [] ? do_new_mount+0x46/0x74\n[  221.629066]  [] ? do_mount+0x175/0x193\n[  221.629066]  [] ? trace_hardirqs_on_caller+0xf4/0x12f\n[  221.629066]  [] ? __get_free_pages+0x1e/0x24\n[  221.629066]  [] ? lock_kernel+0x19/0x8c\n[  221.629066]  [] ? sys_mount+0x51/0x9b\n[  221.629066]  [] ? sys_mount+0x64/0x9b\n[  221.629066]  [] ? sysenter_do_call+0x12/0x31\n[  221.629066]  =======================\n[  221.629066] Code: 89 c2 c1 e2 08 c1 e8 08 09 c2 8b 85 e8 fd ff ff 66 89 50 06 89 c7 53 83 c7 08 56 57 68 c4 b3 80 c0 e8 8c 5c ef ff 89 d9 c1 e9 02  a5 89 d9 83 e1 03 74 02 f3 a4 83 c3 06 8b 95 e8 fd ff ff 0f\n[  221.629066] EIP: [] hfsplus_find_cat+0x10d/0x151 SS:ESP 0068:c82d199c\n[  221.629066] ---[ end trace e417a1d67f0d0066 ]---\n\nSince hfsplus_cat_build_key_uni() returns void and only has one callsite,\nthe check is performed at the callsite.\n\nSigned-off-by: Eric Sesterhenn \nReviewed-by: Pekka Enberg \nCc: Roman Zippel \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "target": 0, "func": "int hfsplus_find_cat(struct super_block *sb, u32 cnid,\n\t\t     struct hfs_find_data *fd)\n{\n\thfsplus_cat_entry tmp;\n\tint err;\n\tu16 type;\n\n\thfsplus_cat_build_key(sb, fd->search_key, cnid, NULL);\n\terr = hfs_brec_read(fd, &tmp, sizeof(hfsplus_cat_entry));\n\tif (err)\n\t\treturn err;\n\n\ttype = be16_to_cpu(tmp.type);\n\tif (type != HFSPLUS_FOLDER_THREAD && type != HFSPLUS_FILE_THREAD) {\n\t\tprintk(KERN_ERR \"hfs: found bad thread record in catalog\\n\");\n\t\treturn -EIO;\n\t}\n\n\tif (be16_to_cpu(tmp.thread.nodeName.length) > 255) {\n\t\tprintk(KERN_ERR \"hfs: catalog name length corrupted\\n\");\n\t\treturn -EIO;\n\t}\n\n\thfsplus_cat_build_key_uni(fd->search_key, be32_to_cpu(tmp.thread.parentID),\n\t\t\t\t &tmp.thread.nodeName);\n\treturn hfs_brec_find(fd);\n}", "func_hash": 296624566166126910302983685635029664818, "file_name": "None", "file_hash": null, "cwe": ["CWE-119"], "cve": "CVE-2008-4933", "cve_desc": "Buffer overflow in the hfsplus_find_cat function in fs/hfsplus/catalog.c in the Linux kernel before 2.6.28-rc1 allows attackers to cause a denial of service (memory corruption or system crash) via an hfsplus filesystem image with an invalid catalog namelength field, related to the hfsplus_cat_build_key_uni function.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2008-4933"}
{"idx": 215400, "project": "linux-2.6", "commit_id": "649f1ee6c705aab644035a7998d7b574193a598a", "project_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6", "commit_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=649f1ee6c705aab644035a7998d7b574193a598a", "commit_message": "hfsplus: check read_mapping_page() return value\n\nWhile testing more corrupted images with hfsplus, i came across\none which triggered the following bug:\n\n[15840.675016] BUG: unable to handle kernel paging request at fffffffb\n[15840.675016] IP: [] kmap+0x15/0x56\n[15840.675016] *pde = 00008067 *pte = 00000000\n[15840.675016] Oops: 0000 [#1] PREEMPT DEBUG_PAGEALLOC\n[15840.675016] Modules linked in:\n[15840.675016]\n[15840.675016] Pid: 11575, comm: ln Not tainted (2.6.27-rc4-00123-gd3ee1b4-dirty #29)\n[15840.675016] EIP: 0060:[] EFLAGS: 00010202 CPU: 0\n[15840.675016] EIP is at kmap+0x15/0x56\n[15840.675016] EAX: 00000246 EBX: fffffffb ECX: 00000000 EDX: cab919c0\n[15840.675016] ESI: 000007dd EDI: cab0bcf4 EBP: cab0bc98 ESP: cab0bc94\n[15840.675016]  DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 0068\n[15840.675016] Process ln (pid: 11575, ti=cab0b000 task=cab919c0 task.ti=cab0b000)\n[15840.675016] Stack: 00000000 cab0bcdc c0231cfb 00000000 cab0bce0 00000800 ca9290c0 fffffffb\n[15840.675016]        cab145d0 cab919c0 cab15998 22222222 22222222 22222222 00000001 cab15960\n[15840.675016]        000007dd cab0bcf4 cab0bd04 c022cb3a cab0bcf4 cab15a6c ca9290c0 00000000\n[15840.675016] Call Trace:\n[15840.675016]  [] ? hfsplus_block_allocate+0x6f/0x2d3\n[15840.675016]  [] ? hfsplus_file_extend+0xc4/0x1db\n[15840.675016]  [] ? hfsplus_get_block+0x8c/0x19d\n[15840.675016]  [] ? sub_preempt_count+0x9d/0xab\n[15840.675016]  [] ? __block_prepare_write+0x147/0x311\n[15840.675016]  [] ? __grab_cache_page+0x52/0x73\n[15840.675016]  [] ? block_write_begin+0x79/0xd5\n[15840.675016]  [] ? hfsplus_get_block+0x0/0x19d\n[15840.675016]  [] ? cont_write_begin+0x27f/0x2af\n[15840.675016]  [] ? hfsplus_get_block+0x0/0x19d\n[15840.675016]  [] ? tick_program_event+0x28/0x4c\n[15840.675016]  [] ? trace_hardirqs_off+0xb/0xd\n[15840.675016]  [] ? hfsplus_write_begin+0x2d/0x32\n[15840.675016]  [] ? hfsplus_get_block+0x0/0x19d\n[15840.675016]  [] ? pagecache_write_begin+0x33/0x107\n[15840.675016]  [] ? __page_symlink+0x3c/0xae\n[15840.675016]  [] ? __mark_inode_dirty+0x12f/0x137\n[15840.675016]  [] ? page_symlink+0x19/0x1e\n[15840.675016]  [] ? hfsplus_symlink+0x41/0xa6\n[15840.675016]  [] ? vfs_symlink+0x99/0x101\n[15840.675016]  [] ? sys_symlinkat+0x6b/0xad\n[15840.675016]  [] ? sys_symlink+0x10/0x12\n[15840.675016]  [] ? sysenter_do_call+0x12/0x31\n[15840.675016]  =======================\n[15840.675016] Code: 00 00 75 10 83 3d 88 2f ec c0 02 75 07 89 d0 e8 12 56 05 00 5d c3 55 ba 06 00 00 00 89 e5 53 89 c3 b8 3d eb 7e c0 e8 16 74 00 00 <8b> 03 c1 e8 1e 69 c0 d8 02 00 00 05 b8 69 8e c0 2b 80 c4 02 00\n[15840.675016] EIP: [] kmap+0x15/0x56 SS:ESP 0068:cab0bc94\n[15840.675016] ---[ end trace 4fea40dad6b70e5f ]---\n\nThis happens because the return value of read_mapping_page() is passed on\nto kmap unchecked.  The bug is triggered after the first\nread_mapping_page() in hfsplus_block_allocate(), this patch fixes all\nthree usages in this functions but leaves the ones further down in the\nfile unchanged.\n\nSigned-off-by: Eric Sesterhenn \nCc: Roman Zippel \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "target": 1, "func": "int hfsplus_block_allocate(struct super_block *sb, u32 size, u32 offset, u32 *max)\n{\n\tstruct page *page;\n\tstruct address_space *mapping;\n\t__be32 *pptr, *curr, *end;\n\tu32 mask, start, len, n;\n\t__be32 val;\n\tint i;\n\n\tlen = *max;\n\tif (!len)\n\t\treturn size;\n\n\tdprint(DBG_BITMAP, \"block_allocate: %u,%u,%u\\n\", size, offset, len);\n\tmutex_lock(&HFSPLUS_SB(sb).alloc_file->i_mutex);\n\tmapping = HFSPLUS_SB(sb).alloc_file->i_mapping;\n\tpage = read_mapping_page(mapping, offset / PAGE_CACHE_BITS, NULL);\n\tpptr = kmap(page);\n\tcurr = pptr + (offset & (PAGE_CACHE_BITS - 1)) / 32;\n\ti = offset % 32;\n\toffset &= ~(PAGE_CACHE_BITS - 1);\n\tif ((size ^ offset) / PAGE_CACHE_BITS)\n\t\tend = pptr + PAGE_CACHE_BITS / 32;\n\telse\n\t\tend = pptr + ((size + 31) & (PAGE_CACHE_BITS - 1)) / 32;\n\n\t/* scan the first partial u32 for zero bits */\n\tval = *curr;\n\tif (~val) {\n\t\tn = be32_to_cpu(val);\n\t\tmask = (1U << 31) >> i;\n\t\tfor (; i < 32; mask >>= 1, i++) {\n\t\t\tif (!(n & mask))\n\t\t\t\tgoto found;\n\t\t}\n\t}\n\tcurr++;\n\n\t/* scan complete u32s for the first zero bit */\n\twhile (1) {\n\t\twhile (curr < end) {\n\t\t\tval = *curr;\n\t\t\tif (~val) {\n\t\t\t\tn = be32_to_cpu(val);\n\t\t\t\tmask = 1 << 31;\n\t\t\t\tfor (i = 0; i < 32; mask >>= 1, i++) {\n\t\t\t\t\tif (!(n & mask))\n\t\t\t\t\t\tgoto found;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurr++;\n\t\t}\n\t\tkunmap(page);\n\t\toffset += PAGE_CACHE_BITS;\n\t\tif (offset >= size)\n\t\t\tbreak;\n\t\tpage = read_mapping_page(mapping, offset / PAGE_CACHE_BITS,\n\t\t\t\t\t NULL);\n\t\tcurr = pptr = kmap(page);\n\t\tif ((size ^ offset) / PAGE_CACHE_BITS)\n\t\t\tend = pptr + PAGE_CACHE_BITS / 32;\n\t\telse\n\t\t\tend = pptr + ((size + 31) & (PAGE_CACHE_BITS - 1)) / 32;\n\t}\n\tdprint(DBG_BITMAP, \"bitmap full\\n\");\n\tstart = size;\n\tgoto out;\n\nfound:\n\tstart = offset + (curr - pptr) * 32 + i;\n\tif (start >= size) {\n\t\tdprint(DBG_BITMAP, \"bitmap full\\n\");\n\t\tgoto out;\n\t}\n\t/* do any partial u32 at the start */\n\tlen = min(size - start, len);\n\twhile (1) {\n\t\tn |= mask;\n\t\tif (++i >= 32)\n\t\t\tbreak;\n\t\tmask >>= 1;\n\t\tif (!--len || n & mask)\n\t\t\tgoto done;\n\t}\n\tif (!--len)\n\t\tgoto done;\n\t*curr++ = cpu_to_be32(n);\n\t/* do full u32s */\n\twhile (1) {\n\t\twhile (curr < end) {\n\t\t\tn = be32_to_cpu(*curr);\n\t\t\tif (len < 32)\n\t\t\t\tgoto last;\n\t\t\tif (n) {\n\t\t\t\tlen = 32;\n\t\t\t\tgoto last;\n\t\t\t}\n\t\t\t*curr++ = cpu_to_be32(0xffffffff);\n\t\t\tlen -= 32;\n\t\t}\n\t\tset_page_dirty(page);\n\t\tkunmap(page);\n\t\toffset += PAGE_CACHE_BITS;\n\t\tpage = read_mapping_page(mapping, offset / PAGE_CACHE_BITS,\n\t\t\t\t\t NULL);\n\t\tpptr = kmap(page);\n\t\tcurr = pptr;\n\t\tend = pptr + PAGE_CACHE_BITS / 32;\n\t}\nlast:\n\t/* do any partial u32 at end */\n\tmask = 1U << 31;\n\tfor (i = 0; i < len; i++) {\n\t\tif (n & mask)\n\t\t\tbreak;\n\t\tn |= mask;\n\t\tmask >>= 1;\n\t}\ndone:\n\t*curr = cpu_to_be32(n);\n\tset_page_dirty(page);\n\tkunmap(page);\n\t*max = offset + (curr - pptr) * 32 + i - start;\n\tHFSPLUS_SB(sb).free_blocks -= *max;\n\tsb->s_dirt = 1;\n\tdprint(DBG_BITMAP, \"-> %u,%u\\n\", start, *max);\nout:\n\tmutex_unlock(&HFSPLUS_SB(sb).alloc_file->i_mutex);\n\treturn start;\n}", "func_hash": 83147584987349782496711287280520974541, "file_name": "None", "file_hash": null, "cwe": ["CWE-20"], "cve": "CVE-2008-4934", "cve_desc": "The hfsplus_block_allocate function in fs/hfsplus/bitmap.c in the Linux kernel before 2.6.28-rc1 does not check a certain return value from the read_mapping_page function before calling kmap, which allows attackers to cause a denial of service (system crash) via a crafted hfsplus filesystem image.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2008-4934"}
{"idx": 489221, "project": "linux-2.6", "commit_id": "649f1ee6c705aab644035a7998d7b574193a598a", "project_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6", "commit_url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=649f1ee6c705aab644035a7998d7b574193a598a", "commit_message": "hfsplus: check read_mapping_page() return value\n\nWhile testing more corrupted images with hfsplus, i came across\none which triggered the following bug:\n\n[15840.675016] BUG: unable to handle kernel paging request at fffffffb\n[15840.675016] IP: [] kmap+0x15/0x56\n[15840.675016] *pde = 00008067 *pte = 00000000\n[15840.675016] Oops: 0000 [#1] PREEMPT DEBUG_PAGEALLOC\n[15840.675016] Modules linked in:\n[15840.675016]\n[15840.675016] Pid: 11575, comm: ln Not tainted (2.6.27-rc4-00123-gd3ee1b4-dirty #29)\n[15840.675016] EIP: 0060:[] EFLAGS: 00010202 CPU: 0\n[15840.675016] EIP is at kmap+0x15/0x56\n[15840.675016] EAX: 00000246 EBX: fffffffb ECX: 00000000 EDX: cab919c0\n[15840.675016] ESI: 000007dd EDI: cab0bcf4 EBP: cab0bc98 ESP: cab0bc94\n[15840.675016]  DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 0068\n[15840.675016] Process ln (pid: 11575, ti=cab0b000 task=cab919c0 task.ti=cab0b000)\n[15840.675016] Stack: 00000000 cab0bcdc c0231cfb 00000000 cab0bce0 00000800 ca9290c0 fffffffb\n[15840.675016]        cab145d0 cab919c0 cab15998 22222222 22222222 22222222 00000001 cab15960\n[15840.675016]        000007dd cab0bcf4 cab0bd04 c022cb3a cab0bcf4 cab15a6c ca9290c0 00000000\n[15840.675016] Call Trace:\n[15840.675016]  [] ? hfsplus_block_allocate+0x6f/0x2d3\n[15840.675016]  [] ? hfsplus_file_extend+0xc4/0x1db\n[15840.675016]  [] ? hfsplus_get_block+0x8c/0x19d\n[15840.675016]  [] ? sub_preempt_count+0x9d/0xab\n[15840.675016]  [] ? __block_prepare_write+0x147/0x311\n[15840.675016]  [] ? __grab_cache_page+0x52/0x73\n[15840.675016]  [] ? block_write_begin+0x79/0xd5\n[15840.675016]  [] ? hfsplus_get_block+0x0/0x19d\n[15840.675016]  [] ? cont_write_begin+0x27f/0x2af\n[15840.675016]  [] ? hfsplus_get_block+0x0/0x19d\n[15840.675016]  [] ? tick_program_event+0x28/0x4c\n[15840.675016]  [] ? trace_hardirqs_off+0xb/0xd\n[15840.675016]  [] ? hfsplus_write_begin+0x2d/0x32\n[15840.675016]  [] ? hfsplus_get_block+0x0/0x19d\n[15840.675016]  [] ? pagecache_write_begin+0x33/0x107\n[15840.675016]  [] ? __page_symlink+0x3c/0xae\n[15840.675016]  [] ? __mark_inode_dirty+0x12f/0x137\n[15840.675016]  [] ? page_symlink+0x19/0x1e\n[15840.675016]  [] ? hfsplus_symlink+0x41/0xa6\n[15840.675016]  [] ? vfs_symlink+0x99/0x101\n[15840.675016]  [] ? sys_symlinkat+0x6b/0xad\n[15840.675016]  [] ? sys_symlink+0x10/0x12\n[15840.675016]  [] ? sysenter_do_call+0x12/0x31\n[15840.675016]  =======================\n[15840.675016] Code: 00 00 75 10 83 3d 88 2f ec c0 02 75 07 89 d0 e8 12 56 05 00 5d c3 55 ba 06 00 00 00 89 e5 53 89 c3 b8 3d eb 7e c0 e8 16 74 00 00 <8b> 03 c1 e8 1e 69 c0 d8 02 00 00 05 b8 69 8e c0 2b 80 c4 02 00\n[15840.675016] EIP: [] kmap+0x15/0x56 SS:ESP 0068:cab0bc94\n[15840.675016] ---[ end trace 4fea40dad6b70e5f ]---\n\nThis happens because the return value of read_mapping_page() is passed on\nto kmap unchecked.  The bug is triggered after the first\nread_mapping_page() in hfsplus_block_allocate(), this patch fixes all\nthree usages in this functions but leaves the ones further down in the\nfile unchanged.\n\nSigned-off-by: Eric Sesterhenn \nCc: Roman Zippel \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "target": 0, "func": "int hfsplus_block_allocate(struct super_block *sb, u32 size, u32 offset, u32 *max)\n{\n\tstruct page *page;\n\tstruct address_space *mapping;\n\t__be32 *pptr, *curr, *end;\n\tu32 mask, start, len, n;\n\t__be32 val;\n\tint i;\n\n\tlen = *max;\n\tif (!len)\n\t\treturn size;\n\n\tdprint(DBG_BITMAP, \"block_allocate: %u,%u,%u\\n\", size, offset, len);\n\tmutex_lock(&HFSPLUS_SB(sb).alloc_file->i_mutex);\n\tmapping = HFSPLUS_SB(sb).alloc_file->i_mapping;\n\tpage = read_mapping_page(mapping, offset / PAGE_CACHE_BITS, NULL);\n\tif (IS_ERR(page)) {\n\t\tstart = size;\n\t\tgoto out;\n\t}\n\tpptr = kmap(page);\n\tcurr = pptr + (offset & (PAGE_CACHE_BITS - 1)) / 32;\n\ti = offset % 32;\n\toffset &= ~(PAGE_CACHE_BITS - 1);\n\tif ((size ^ offset) / PAGE_CACHE_BITS)\n\t\tend = pptr + PAGE_CACHE_BITS / 32;\n\telse\n\t\tend = pptr + ((size + 31) & (PAGE_CACHE_BITS - 1)) / 32;\n\n\t/* scan the first partial u32 for zero bits */\n\tval = *curr;\n\tif (~val) {\n\t\tn = be32_to_cpu(val);\n\t\tmask = (1U << 31) >> i;\n\t\tfor (; i < 32; mask >>= 1, i++) {\n\t\t\tif (!(n & mask))\n\t\t\t\tgoto found;\n\t\t}\n\t}\n\tcurr++;\n\n\t/* scan complete u32s for the first zero bit */\n\twhile (1) {\n\t\twhile (curr < end) {\n\t\t\tval = *curr;\n\t\t\tif (~val) {\n\t\t\t\tn = be32_to_cpu(val);\n\t\t\t\tmask = 1 << 31;\n\t\t\t\tfor (i = 0; i < 32; mask >>= 1, i++) {\n\t\t\t\t\tif (!(n & mask))\n\t\t\t\t\t\tgoto found;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurr++;\n\t\t}\n\t\tkunmap(page);\n\t\toffset += PAGE_CACHE_BITS;\n\t\tif (offset >= size)\n\t\t\tbreak;\n\t\tpage = read_mapping_page(mapping, offset / PAGE_CACHE_BITS,\n\t\t\t\t\t NULL);\n\t\tif (IS_ERR(page)) {\n\t\t\tstart = size;\n\t\t\tgoto out;\n\t\t}\n\t\tcurr = pptr = kmap(page);\n\t\tif ((size ^ offset) / PAGE_CACHE_BITS)\n\t\t\tend = pptr + PAGE_CACHE_BITS / 32;\n\t\telse\n\t\t\tend = pptr + ((size + 31) & (PAGE_CACHE_BITS - 1)) / 32;\n\t}\n\tdprint(DBG_BITMAP, \"bitmap full\\n\");\n\tstart = size;\n\tgoto out;\n\nfound:\n\tstart = offset + (curr - pptr) * 32 + i;\n\tif (start >= size) {\n\t\tdprint(DBG_BITMAP, \"bitmap full\\n\");\n\t\tgoto out;\n\t}\n\t/* do any partial u32 at the start */\n\tlen = min(size - start, len);\n\twhile (1) {\n\t\tn |= mask;\n\t\tif (++i >= 32)\n\t\t\tbreak;\n\t\tmask >>= 1;\n\t\tif (!--len || n & mask)\n\t\t\tgoto done;\n\t}\n\tif (!--len)\n\t\tgoto done;\n\t*curr++ = cpu_to_be32(n);\n\t/* do full u32s */\n\twhile (1) {\n\t\twhile (curr < end) {\n\t\t\tn = be32_to_cpu(*curr);\n\t\t\tif (len < 32)\n\t\t\t\tgoto last;\n\t\t\tif (n) {\n\t\t\t\tlen = 32;\n\t\t\t\tgoto last;\n\t\t\t}\n\t\t\t*curr++ = cpu_to_be32(0xffffffff);\n\t\t\tlen -= 32;\n\t\t}\n\t\tset_page_dirty(page);\n\t\tkunmap(page);\n\t\toffset += PAGE_CACHE_BITS;\n\t\tpage = read_mapping_page(mapping, offset / PAGE_CACHE_BITS,\n\t\t\t\t\t NULL);\n\t\tif (IS_ERR(page)) {\n\t\t\tstart = size;\n\t\t\tgoto out;\n\t\t}\n\t\tpptr = kmap(page);\n\t\tcurr = pptr;\n\t\tend = pptr + PAGE_CACHE_BITS / 32;\n\t}\nlast:\n\t/* do any partial u32 at end */\n\tmask = 1U << 31;\n\tfor (i = 0; i < len; i++) {\n\t\tif (n & mask)\n\t\t\tbreak;\n\t\tn |= mask;\n\t\tmask >>= 1;\n\t}\ndone:\n\t*curr = cpu_to_be32(n);\n\tset_page_dirty(page);\n\tkunmap(page);\n\t*max = offset + (curr - pptr) * 32 + i - start;\n\tHFSPLUS_SB(sb).free_blocks -= *max;\n\tsb->s_dirt = 1;\n\tdprint(DBG_BITMAP, \"-> %u,%u\\n\", start, *max);\nout:\n\tmutex_unlock(&HFSPLUS_SB(sb).alloc_file->i_mutex);\n\treturn start;\n}", "func_hash": 221598202771346823073737014328154892672, "file_name": "None", "file_hash": null, "cwe": ["CWE-20"], "cve": "CVE-2008-4934", "cve_desc": "The hfsplus_block_allocate function in fs/hfsplus/bitmap.c in the Linux kernel before 2.6.28-rc1 does not check a certain return value from the read_mapping_page function before calling kmap, which allows attackers to cause a denial of service (system crash) via a crafted hfsplus filesystem image.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2008-4934"}
{"idx": 215549, "project": "gzip", "commit_id": "a3db5806d012082b9e25cc36d09f19cd736a468f", "project_url": "http://git.savannah.gnu.org/cgit/gzip", "commit_url": "http://git.savannah.gnu.org/cgit/gzip.git/commit/?id=a3db5806d012082b9e25cc36d09f19cd736a468f", "commit_message": "gzip -d: do not clobber stack for valid input on x86_64\n\n* unlzw.c (unlzw): Avoid integer overflow.\nAki Helin reported the segfault along with an input to trigger the bug.\n* NEWS (Bug fixes): Mention it.", "target": 1, "func": "int unlzw(in, out)\n    int in, out;    /* input and output file descriptors */\n{\n    REG2   char_type  *stackp;\n    REG3   code_int   code;\n    REG4   int        finchar;\n    REG5   code_int   oldcode;\n    REG6   code_int   incode;\n    REG7   long       inbits;\n    REG8   long       posbits;\n    REG9   int        outpos;\n/*  REG10  int        insize; (global) */\n    REG11  unsigned   bitmask;\n    REG12  code_int   free_ent;\n    REG13  code_int   maxcode;\n    REG14  code_int   maxmaxcode;\n    REG15  int        n_bits;\n    REG16  int        rsize;\n\n#ifdef MAXSEG_64K\n    tab_prefix[0] = tab_prefix0;\n    tab_prefix[1] = tab_prefix1;\n#endif\n    maxbits = get_byte();\n    block_mode = maxbits & BLOCK_MODE;\n    if ((maxbits & LZW_RESERVED) != 0) {\n\tWARN((stderr, \"\\n%s: %s: warning, unknown flags 0x%x\\n\",\n\t      program_name, ifname, maxbits & LZW_RESERVED));\n    }\n    maxbits &= BIT_MASK;\n    maxmaxcode = MAXCODE(maxbits);\n\n    if (maxbits > BITS) {\n\tfprintf(stderr,\n\t\t\"\\n%s: %s: compressed with %d bits, can only handle %d bits\\n\",\n\t\tprogram_name, ifname, maxbits, BITS);\n\texit_code = ERROR;\n\treturn ERROR;\n    }\n    rsize = insize;\n    maxcode = MAXCODE(n_bits = INIT_BITS)-1;\n    bitmask = (1<= 0 ; --code) {\n\ttab_suffixof(code) = (char_type)code;\n    }\n    do {\n\tREG1 int i;\n\tint  e;\n\tint  o;\n\n    resetbuf:\n\te = insize-(o = (posbits>>3));\n\n\tfor (i = 0 ; i < e ; ++i) {\n\t    inbuf[i] = inbuf[i+o];\n\t}\n\tinsize = e;\n\tposbits = 0;\n\n\tif (insize < INBUF_EXTRA) {\n\t    rsize = read_buffer (in, (char *) inbuf + insize, INBUFSIZ);\n\t    if (rsize == -1) {\n\t\tread_error();\n\t    }\n\t    insize += rsize;\n\t    bytes_in += (off_t)rsize;\n\t}\n\tinbits = ((rsize != 0) ? ((long)insize - insize%n_bits)<<3 :\n\t\t  ((long)insize<<3)-(n_bits-1));\n\n\twhile (inbits > posbits) {\n\t    if (free_ent > maxcode) {\n\t\tposbits = ((posbits-1) +\n\t\t\t   ((n_bits<<3)-(posbits-1+(n_bits<<3))%(n_bits<<3)));\n\t\t++n_bits;\n\t\tif (n_bits == maxbits) {\n\t\t    maxcode = maxmaxcode;\n\t\t} else {\n\t\t    maxcode = MAXCODE(n_bits)-1;\n\t\t}\n\t\tbitmask = (1<= free_ent) { /* Special case for KwKwK string. */\n\t\tif (code > free_ent) {\n#ifdef DEBUG\n\t\t    char_type *p;\n\n\t\t    posbits -= n_bits;\n\t\t    p = &inbuf[posbits>>3];\n\t\t    fprintf(stderr,\n\t\t\t    \"code:%ld free_ent:%ld n_bits:%d insize:%u\\n\",\n\t\t\t    code, free_ent, n_bits, insize);\n\t\t    fprintf(stderr,\n\t\t\t    \"posbits:%ld inbuf:%02X %02X %02X %02X %02X\\n\",\n\t\t\t    posbits, p[-1],p[0],p[1],p[2],p[3]);\n#endif\n\t\t    if (!test && outpos > 0) {\n\t\t\twrite_buf(out, (char*)outbuf, outpos);\n\t\t\tbytes_out += (off_t)outpos;\n\t\t    }\n\t\t    gzip_error (to_stdout\n\t\t\t\t? \"corrupt input.\"\n\t\t\t\t: \"corrupt input. Use zcat to recover some data.\");\n\t\t}\n\t\t*--stackp = (char_type)finchar;\n\t\tcode = oldcode;\n\t    }\n\n\t    while ((cmp_code_int)code >= (cmp_code_int)256) {\n\t\t/* Generate output characters in reverse order */\n\t\t*--stackp = tab_suffixof(code);\n\t\tcode = tab_prefixof(code);\n\t    }\n\t    *--stackp =\t(char_type)(finchar = tab_suffixof(code));\n\n\t    /* And put them out in forward order */\n\t    {\n\t\tREG1 int\ti;\n\n\t\tif (outpos+(i = (de_stack-stackp)) >= OUTBUFSIZ) {\n\t\t    do {\n\t\t\tif (i > OUTBUFSIZ-outpos) i = OUTBUFSIZ-outpos;\n\n\t\t\tif (i > 0) {\n\t\t\t    memcpy(outbuf+outpos, stackp, i);\n\t\t\t    outpos += i;\n\t\t\t}\n\t\t\tif (outpos >= OUTBUFSIZ) {\n\t\t\t    if (!test) {\n\t\t\t\twrite_buf(out, (char*)outbuf, outpos);\n\t\t\t\tbytes_out += (off_t)outpos;\n\t\t\t    }\n\t\t\t    outpos = 0;\n\t\t\t}\n\t\t\tstackp+= i;\n\t\t    } while ((i = (de_stack-stackp)) > 0);\n\t\t} else {\n\t\t    memcpy(outbuf+outpos, stackp, i);\n\t\t    outpos += i;\n\t\t}\n\t    }\n\n\t    if ((code = free_ent) < maxmaxcode) { /* Generate the new entry. */\n\n\t\ttab_prefixof(code) = (unsigned short)oldcode;\n\t\ttab_suffixof(code) = (char_type)finchar;\n\t\tfree_ent = code+1;\n\t    }\n\t    oldcode = incode;\t/* Remember previous code.\t*/\n\t}\n    } while (rsize != 0);\n\n    if (!test && outpos > 0) {\n\twrite_buf(out, (char*)outbuf, outpos);\n\tbytes_out += (off_t)outpos;\n    }\n    return OK;\n}", "func_hash": 315113145353857602270748585965585984173, "file_name": "None", "file_hash": null, "cwe": ["CWE-189"], "cve": "CVE-2010-0001", "cve_desc": "Integer underflow in the unlzw function in unlzw.c in gzip before 1.4 on 64-bit platforms, as used in ncompress and probably others, allows remote attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a crafted archive that uses LZW compression, leading to an array index error.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2010-0001"}
{"idx": 491979, "project": "gzip", "commit_id": "a3db5806d012082b9e25cc36d09f19cd736a468f", "project_url": "http://git.savannah.gnu.org/cgit/gzip", "commit_url": "http://git.savannah.gnu.org/cgit/gzip.git/commit/?id=a3db5806d012082b9e25cc36d09f19cd736a468f", "commit_message": "gzip -d: do not clobber stack for valid input on x86_64\n\n* unlzw.c (unlzw): Avoid integer overflow.\nAki Helin reported the segfault along with an input to trigger the bug.\n* NEWS (Bug fixes): Mention it.", "target": 0, "func": "int unlzw(in, out)\n    int in, out;    /* input and output file descriptors */\n{\n    REG2   char_type  *stackp;\n    REG3   code_int   code;\n    REG4   int        finchar;\n    REG5   code_int   oldcode;\n    REG6   code_int   incode;\n    REG7   long       inbits;\n    REG8   long       posbits;\n    REG9   int        outpos;\n/*  REG10  int        insize; (global) */\n    REG11  unsigned   bitmask;\n    REG12  code_int   free_ent;\n    REG13  code_int   maxcode;\n    REG14  code_int   maxmaxcode;\n    REG15  int        n_bits;\n    REG16  int        rsize;\n\n#ifdef MAXSEG_64K\n    tab_prefix[0] = tab_prefix0;\n    tab_prefix[1] = tab_prefix1;\n#endif\n    maxbits = get_byte();\n    block_mode = maxbits & BLOCK_MODE;\n    if ((maxbits & LZW_RESERVED) != 0) {\n\tWARN((stderr, \"\\n%s: %s: warning, unknown flags 0x%x\\n\",\n\t      program_name, ifname, maxbits & LZW_RESERVED));\n    }\n    maxbits &= BIT_MASK;\n    maxmaxcode = MAXCODE(maxbits);\n\n    if (maxbits > BITS) {\n\tfprintf(stderr,\n\t\t\"\\n%s: %s: compressed with %d bits, can only handle %d bits\\n\",\n\t\tprogram_name, ifname, maxbits, BITS);\n\texit_code = ERROR;\n\treturn ERROR;\n    }\n    rsize = insize;\n    maxcode = MAXCODE(n_bits = INIT_BITS)-1;\n    bitmask = (1<= 0 ; --code) {\n\ttab_suffixof(code) = (char_type)code;\n    }\n    do {\n\tREG1 int i;\n\tint  e;\n\tint  o;\n\n    resetbuf:\n\to = posbits >> 3;\n\te = o <= insize ? insize - o : 0;\n\n\tfor (i = 0 ; i < e ; ++i) {\n\t    inbuf[i] = inbuf[i+o];\n\t}\n\tinsize = e;\n\tposbits = 0;\n\n\tif (insize < INBUF_EXTRA) {\n\t    rsize = read_buffer (in, (char *) inbuf + insize, INBUFSIZ);\n\t    if (rsize == -1) {\n\t\tread_error();\n\t    }\n\t    insize += rsize;\n\t    bytes_in += (off_t)rsize;\n\t}\n\tinbits = ((rsize != 0) ? ((long)insize - insize%n_bits)<<3 :\n\t\t  ((long)insize<<3)-(n_bits-1));\n\n\twhile (inbits > posbits) {\n\t    if (free_ent > maxcode) {\n\t\tposbits = ((posbits-1) +\n\t\t\t   ((n_bits<<3)-(posbits-1+(n_bits<<3))%(n_bits<<3)));\n\t\t++n_bits;\n\t\tif (n_bits == maxbits) {\n\t\t    maxcode = maxmaxcode;\n\t\t} else {\n\t\t    maxcode = MAXCODE(n_bits)-1;\n\t\t}\n\t\tbitmask = (1<= free_ent) { /* Special case for KwKwK string. */\n\t\tif (code > free_ent) {\n#ifdef DEBUG\n\t\t    char_type *p;\n\n\t\t    posbits -= n_bits;\n\t\t    p = &inbuf[posbits>>3];\n\t\t    fprintf(stderr,\n\t\t\t    \"code:%ld free_ent:%ld n_bits:%d insize:%u\\n\",\n\t\t\t    code, free_ent, n_bits, insize);\n\t\t    fprintf(stderr,\n\t\t\t    \"posbits:%ld inbuf:%02X %02X %02X %02X %02X\\n\",\n\t\t\t    posbits, p[-1],p[0],p[1],p[2],p[3]);\n#endif\n\t\t    if (!test && outpos > 0) {\n\t\t\twrite_buf(out, (char*)outbuf, outpos);\n\t\t\tbytes_out += (off_t)outpos;\n\t\t    }\n\t\t    gzip_error (to_stdout\n\t\t\t\t? \"corrupt input.\"\n\t\t\t\t: \"corrupt input. Use zcat to recover some data.\");\n\t\t}\n\t\t*--stackp = (char_type)finchar;\n\t\tcode = oldcode;\n\t    }\n\n\t    while ((cmp_code_int)code >= (cmp_code_int)256) {\n\t\t/* Generate output characters in reverse order */\n\t\t*--stackp = tab_suffixof(code);\n\t\tcode = tab_prefixof(code);\n\t    }\n\t    *--stackp =\t(char_type)(finchar = tab_suffixof(code));\n\n\t    /* And put them out in forward order */\n\t    {\n\t\tREG1 int\ti;\n\n\t\tif (outpos+(i = (de_stack-stackp)) >= OUTBUFSIZ) {\n\t\t    do {\n\t\t\tif (i > OUTBUFSIZ-outpos) i = OUTBUFSIZ-outpos;\n\n\t\t\tif (i > 0) {\n\t\t\t    memcpy(outbuf+outpos, stackp, i);\n\t\t\t    outpos += i;\n\t\t\t}\n\t\t\tif (outpos >= OUTBUFSIZ) {\n\t\t\t    if (!test) {\n\t\t\t\twrite_buf(out, (char*)outbuf, outpos);\n\t\t\t\tbytes_out += (off_t)outpos;\n\t\t\t    }\n\t\t\t    outpos = 0;\n\t\t\t}\n\t\t\tstackp+= i;\n\t\t    } while ((i = (de_stack-stackp)) > 0);\n\t\t} else {\n\t\t    memcpy(outbuf+outpos, stackp, i);\n\t\t    outpos += i;\n\t\t}\n\t    }\n\n\t    if ((code = free_ent) < maxmaxcode) { /* Generate the new entry. */\n\n\t\ttab_prefixof(code) = (unsigned short)oldcode;\n\t\ttab_suffixof(code) = (char_type)finchar;\n\t\tfree_ent = code+1;\n\t    }\n\t    oldcode = incode;\t/* Remember previous code.\t*/\n\t}\n    } while (rsize != 0);\n\n    if (!test && outpos > 0) {\n\twrite_buf(out, (char*)outbuf, outpos);\n\tbytes_out += (off_t)outpos;\n    }\n    return OK;\n}", "func_hash": 39547802204189321461886480230956054723, "file_name": "None", "file_hash": null, "cwe": ["CWE-189"], "cve": "CVE-2010-0001", "cve_desc": "Integer underflow in the unlzw function in unlzw.c in gzip before 1.4 on 64-bit platforms, as used in ncompress and probably others, allows remote attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a crafted archive that uses LZW compression, leading to an array index error.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2010-0001"}
{"idx": 215921, "project": "grep", "commit_id": "83a95bd8c8561875b948cadd417c653dbe7ef2e2", "project_url": "http://git.savannah.gnu.org/cgit/grep", "commit_url": "http://git.sv.gnu.org/cgit/grep.git/commit/?id=83a95bd8c8561875b948cadd417c653dbe7ef2e2", "commit_message": "grep -F: fix a heap buffer (read) overrun\n\ngrep's read buffer is often filled to its full size, except when\nreading the final buffer of a file.  In that case, the number of\nbytes read may be far less than the size of the buffer.  However, for\ncertain unusual pattern/text combinations, grep -F would mistakenly\nexamine bytes in that uninitialized region of memory when searching\nfor a match.  With carefully chosen inputs, one can cause grep -F to\nread beyond the end of that buffer altogether.  This problem arose via\ncommit v2.18-90-g73893ff with the introduction of a more efficient\nheuristic using what is now the memchr_kwset function. The use of\nthat function in bmexec_trans could leave TP much larger than EP,\nand the subsequent call to bm_delta2_search would mistakenly access\nbeyond end of the main input read buffer.\n\n* src/kwset.c (bmexec_trans): When TP reaches or exceeds EP,\ndo not call bm_delta2_search.\n* tests/kwset-abuse: New file.\n* tests/Makefile.am (TESTS): Add it.\n* THANKS.in: Update.\n* NEWS (Bug fixes): Mention it.\n\nPrior to this patch, this command would trigger a UMR:\n\n  printf %0360db 0 | valgrind src/grep -F $(printf %019dXb 0)\n\n  Use of uninitialised value of size 8\n     at 0x4142BE: bmexec_trans (kwset.c:657)\n     by 0x4143CA: bmexec (kwset.c:678)\n     by 0x414973: kwsexec (kwset.c:848)\n     by 0x414DC4: Fexecute (kwsearch.c:128)\n     by 0x404E2E: grepbuf (grep.c:1238)\n     by 0x4054BF: grep (grep.c:1417)\n     by 0x405CEB: grepdesc (grep.c:1645)\n     by 0x405EC1: grep_command_line_arg (grep.c:1692)\n     by 0x4077D4: main (grep.c:2570)\n\nSee the accompanying test for how to trigger the heap buffer overrun.\n\nThanks to Nima Aghdaii for testing and finding numerous\nways to break early iterations of this patch.", "target": 1, "func": "bmexec_trans (kwset_t kwset, char const *text, size_t size)\n{\n  unsigned char const *d1;\n  char const *ep, *sp, *tp;\n  int d;\n  int len = kwset->mind;\n  char const *trans = kwset->trans;\n\n  if (len == 0)\n    return 0;\n  if (len > size)\n    return -1;\n  if (len == 1)\n    {\n      tp = memchr_kwset (text, size, kwset);\n      return tp ? tp - text : -1;\n    }\n\n  d1 = kwset->delta;\n  sp = kwset->target + len;\n  tp = text + len;\n  char gc1 = kwset->gc1;\n  char gc2 = kwset->gc2;\n\n  /* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */\n  if (size > 12 * len)\n    /* 11 is not a bug, the initial offset happens only once. */\n    for (ep = text + size - 11 * len; tp <= ep; )\n      {\n        char const *tp0 = tp;\n        d = d1[U(tp[-1])], tp += d;\n        d = d1[U(tp[-1])], tp += d;\n        if (d != 0)\n          {\n            d = d1[U(tp[-1])], tp += d;\n            d = d1[U(tp[-1])], tp += d;\n            d = d1[U(tp[-1])], tp += d;\n            if (d != 0)\n              {\n                d = d1[U(tp[-1])], tp += d;\n                d = d1[U(tp[-1])], tp += d;\n                d = d1[U(tp[-1])], tp += d;\n                if (d != 0)\n                  {\n                    d = d1[U(tp[-1])], tp += d;\n                    d = d1[U(tp[-1])], tp += d;\n\n                    /* As a heuristic, prefer memchr to seeking by\n                       delta1 when the latter doesn't advance much.  */\n                    int advance_heuristic = 16 * sizeof (long);\n                    if (advance_heuristic <= tp - tp0)\n                      goto big_advance;\n                    tp--;\n                    tp = memchr_kwset (tp, text + size - tp, kwset);\n                    if (! tp)\n                      return -1;\n                    tp++;\n                  }\n              }\n          }\n        if (bm_delta2_search (&tp, ep, sp, len, trans, gc1, gc2, d1, kwset))\n          return tp - text;\n      big_advance:;\n      }\n\n  /* Now we have only a few characters left to search.  We\n     carefully avoid ever producing an out-of-bounds pointer. */\n  ep = text + size;\n  d = d1[U(tp[-1])];\n  while (d <= ep - tp)\n    {\n      d = d1[U((tp += d)[-1])];\n      if (d != 0)\n        continue;\n      if (bm_delta2_search (&tp, ep, sp, len, trans, gc1, gc2, NULL, kwset))\n        return tp - text;\n    }\n\n  return -1;\n}", "func_hash": 221145962274501315787647767738252319422, "file_name": "None", "file_hash": null, "cwe": ["CWE-119"], "cve": "CVE-2015-1345", "cve_desc": "The bmexec_trans function in kwset.c in grep 2.19 through 2.21 allows local users to cause a denial of service (out-of-bounds heap read and crash) via crafted input when using the -F option.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-1345"}
{"idx": 497809, "project": "grep", "commit_id": "83a95bd8c8561875b948cadd417c653dbe7ef2e2", "project_url": "http://git.savannah.gnu.org/cgit/grep", "commit_url": "http://git.sv.gnu.org/cgit/grep.git/commit/?id=83a95bd8c8561875b948cadd417c653dbe7ef2e2", "commit_message": "grep -F: fix a heap buffer (read) overrun\n\ngrep's read buffer is often filled to its full size, except when\nreading the final buffer of a file.  In that case, the number of\nbytes read may be far less than the size of the buffer.  However, for\ncertain unusual pattern/text combinations, grep -F would mistakenly\nexamine bytes in that uninitialized region of memory when searching\nfor a match.  With carefully chosen inputs, one can cause grep -F to\nread beyond the end of that buffer altogether.  This problem arose via\ncommit v2.18-90-g73893ff with the introduction of a more efficient\nheuristic using what is now the memchr_kwset function. The use of\nthat function in bmexec_trans could leave TP much larger than EP,\nand the subsequent call to bm_delta2_search would mistakenly access\nbeyond end of the main input read buffer.\n\n* src/kwset.c (bmexec_trans): When TP reaches or exceeds EP,\ndo not call bm_delta2_search.\n* tests/kwset-abuse: New file.\n* tests/Makefile.am (TESTS): Add it.\n* THANKS.in: Update.\n* NEWS (Bug fixes): Mention it.\n\nPrior to this patch, this command would trigger a UMR:\n\n  printf %0360db 0 | valgrind src/grep -F $(printf %019dXb 0)\n\n  Use of uninitialised value of size 8\n     at 0x4142BE: bmexec_trans (kwset.c:657)\n     by 0x4143CA: bmexec (kwset.c:678)\n     by 0x414973: kwsexec (kwset.c:848)\n     by 0x414DC4: Fexecute (kwsearch.c:128)\n     by 0x404E2E: grepbuf (grep.c:1238)\n     by 0x4054BF: grep (grep.c:1417)\n     by 0x405CEB: grepdesc (grep.c:1645)\n     by 0x405EC1: grep_command_line_arg (grep.c:1692)\n     by 0x4077D4: main (grep.c:2570)\n\nSee the accompanying test for how to trigger the heap buffer overrun.\n\nThanks to Nima Aghdaii for testing and finding numerous\nways to break early iterations of this patch.", "target": 0, "func": "bmexec_trans (kwset_t kwset, char const *text, size_t size)\n{\n  unsigned char const *d1;\n  char const *ep, *sp, *tp;\n  int d;\n  int len = kwset->mind;\n  char const *trans = kwset->trans;\n\n  if (len == 0)\n    return 0;\n  if (len > size)\n    return -1;\n  if (len == 1)\n    {\n      tp = memchr_kwset (text, size, kwset);\n      return tp ? tp - text : -1;\n    }\n\n  d1 = kwset->delta;\n  sp = kwset->target + len;\n  tp = text + len;\n  char gc1 = kwset->gc1;\n  char gc2 = kwset->gc2;\n\n  /* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */\n  if (size > 12 * len)\n    /* 11 is not a bug, the initial offset happens only once. */\n    for (ep = text + size - 11 * len; tp <= ep; )\n      {\n        char const *tp0 = tp;\n        d = d1[U(tp[-1])], tp += d;\n        d = d1[U(tp[-1])], tp += d;\n        if (d != 0)\n          {\n            d = d1[U(tp[-1])], tp += d;\n            d = d1[U(tp[-1])], tp += d;\n            d = d1[U(tp[-1])], tp += d;\n            if (d != 0)\n              {\n                d = d1[U(tp[-1])], tp += d;\n                d = d1[U(tp[-1])], tp += d;\n                d = d1[U(tp[-1])], tp += d;\n                if (d != 0)\n                  {\n                    d = d1[U(tp[-1])], tp += d;\n                    d = d1[U(tp[-1])], tp += d;\n\n                    /* As a heuristic, prefer memchr to seeking by\n                       delta1 when the latter doesn't advance much.  */\n                    int advance_heuristic = 16 * sizeof (long);\n                    if (advance_heuristic <= tp - tp0)\n                      goto big_advance;\n                    tp--;\n                    tp = memchr_kwset (tp, text + size - tp, kwset);\n                    if (! tp)\n                      return -1;\n                    tp++;\n                    if (ep <= tp)\n                      break;\n                  }\n              }\n          }\n        if (bm_delta2_search (&tp, ep, sp, len, trans, gc1, gc2, d1, kwset))\n          return tp - text;\n      big_advance:;\n      }\n\n  /* Now we have only a few characters left to search.  We\n     carefully avoid ever producing an out-of-bounds pointer. */\n  ep = text + size;\n  d = d1[U(tp[-1])];\n  while (d <= ep - tp)\n    {\n      d = d1[U((tp += d)[-1])];\n      if (d != 0)\n        continue;\n      if (bm_delta2_search (&tp, ep, sp, len, trans, gc1, gc2, NULL, kwset))\n        return tp - text;\n    }\n\n  return -1;\n}", "func_hash": 262967935690402821011816255604665485413, "file_name": "None", "file_hash": null, "cwe": ["CWE-119"], "cve": "CVE-2015-1345", "cve_desc": "The bmexec_trans function in kwset.c in grep 2.19 through 2.21 allows local users to cause a denial of service (out-of-bounds heap read and crash) via crafted input when using the -F option.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-1345"}
{"idx": 215948, "project": "nettle", "commit_id": "c71d2c9d20eeebb985e3872e4550137209e3ce4d", "project_url": "https://git.lysator.liu.se/nettle/nettle", "commit_url": "https://git.lysator.liu.se/nettle/nettle/commit/c71d2c9d20eeebb985e3872e4550137209e3ce4d", "commit_message": "Fixed miscomputation bugs in secp-256r1 modulo functions.", "target": 1, "func": "ecc_256_modp (const struct ecc_modulo *p, mp_limb_t *rp)\n{\n  mp_limb_t u1, u0;\n  mp_size_t n;\n\n  n = 2*p->size;\n  u1 = rp[--n];\n  u0 = rp[n-1];\n\n  /* This is not particularly fast, but should work well with assembly implementation. */\n  for (; n >= p->size; n--)\n    {\n      mp_limb_t q2, q1, q0, t, cy;\n\n      /*  = v * u1 + , with v = 2^32 - 1:\n\n\t   +---+---+\n\t   | u1| u0|\n\t   +---+---+\n\t       |-u1|\n\t     +-+-+-+\n\t     | u1|\n       +---+-+-+-+-+\n       | q2| q1| q0|\n       +---+---+---+\n      */\n      q1 = u1 - (u1 > u0);\n      q0 = u0 - u1;\n      t = u1 << 32;\n      q0 += t;\n      t = (u1 >> 32) + (q0 < t) + 1;\n      q1 += t;\n      q2 = q1 < t;\n\n      /* Compute candidate remainder */\n      u1 = u0 + (q1 << 32) - q1;\n      t = -(mp_limb_t) (u1 > q0);\n      u1 -= t & 0xffffffff;\n      q1 += t;\n      q2 += t + (q1 < t);\n\n      assert (q2 < 2);\n\n      /* We multiply by two low limbs of p, 2^96 - 1, so we could use\n\t shifts rather than mul. */\n      t = mpn_submul_1 (rp + n - 4, p->m, 2, q1);\n      t += cnd_sub_n (q2, rp + n - 3, p->m, 1);\n      t += (-q2) & 0xffffffff;\n\n      u0 = rp[n-2];\n      cy = (u0 < t);\n      u0 -= t;\n      t = (u1 < cy);\n      u1 -= cy;\n      u1 += cnd_add_n (t, rp + n - 4, p->m, 3);\n      u1 -= (-t) & 0xffffffff;\n    }\n  rp[2] = u0;\n  rp[3] = u1;\n}", "func_hash": 238786089108920286298904536145396627402, "file_name": "None", "file_hash": null, "cwe": ["CWE-310"], "cve": "CVE-2015-8803", "cve_desc": "The ecc_256_modp function in ecc-256.c in Nettle before 3.2 does not properly handle carry propagation and produces incorrect output in its implementation of the P-256 NIST elliptic curve, which allows attackers to have unspecified impact via unknown vectors, a different vulnerability than CVE-2015-8805.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-8803"}
{"idx": 498160, "project": "nettle", "commit_id": "c71d2c9d20eeebb985e3872e4550137209e3ce4d", "project_url": "https://git.lysator.liu.se/nettle/nettle", "commit_url": "https://git.lysator.liu.se/nettle/nettle/commit/c71d2c9d20eeebb985e3872e4550137209e3ce4d", "commit_message": "Fixed miscomputation bugs in secp-256r1 modulo functions.", "target": 0, "func": "ecc_256_modp (const struct ecc_modulo *p, mp_limb_t *rp)\n{\n  mp_limb_t u1, u0;\n  mp_size_t n;\n\n  n = 2*p->size;\n  u1 = rp[--n];\n  u0 = rp[n-1];\n\n  /* This is not particularly fast, but should work well with assembly implementation. */\n  for (; n >= p->size; n--)\n    {\n      mp_limb_t q2, q1, q0, t, cy;\n\n      /*  = v * u1 + , with v = 2^32 - 1:\n\n\t   +---+---+\n\t   | u1| u0|\n\t   +---+---+\n\t       |-u1|\n\t     +-+-+-+\n\t     | u1|\n       +---+-+-+-+-+\n       | q2| q1| q0|\n       +---+---+---+\n      */\n      q1 = u1 - (u1 > u0);\n      q0 = u0 - u1;\n      t = u1 << 32;\n      q0 += t;\n      t = (u1 >> 32) + (q0 < t) + 1;\n      q1 += t;\n      q2 = q1 < t;\n\n      /* Compute candidate remainder */\n      u1 = u0 + (q1 << 32) - q1;\n      t = -(mp_limb_t) (u1 > q0);\n      u1 -= t & 0xffffffff;\n      q1 += t;\n      q2 += t + (q1 < t);\n\n      assert (q2 < 2);\n\n      /*\n\t n-1 n-2 n-3 n-4\n        +---+---+---+---+\n        | u1| u0| u low |\n        +---+---+---+---+\n          - | q1(2^96-1)|\n            +-------+---+\n            |q2(2^.)|\n            +-------+\n\n\t We multiply by two low limbs of p, 2^96 - 1, so we could use\n\t shifts rather than mul.\n      */\n      t = mpn_submul_1 (rp + n - 4, p->m, 2, q1);\n      t += cnd_sub_n (q2, rp + n - 3, p->m, 1);\n      t += (-q2) & 0xffffffff;\n\n      u0 = rp[n-2];\n      cy = (u0 < t);\n      u0 -= t;\n      t = (u1 < cy);\n      u1 -= cy;\n\n      cy = cnd_add_n (t, rp + n - 4, p->m, 2);\n      u0 += cy;\n      u1 += (u0 < cy);\n      u1 -= (-t) & 0xffffffff;\n    }\n  rp[2] = u0;\n  rp[3] = u1;\n}", "func_hash": 9762716495291847327179594432373951677, "file_name": "None", "file_hash": null, "cwe": ["CWE-310"], "cve": "CVE-2015-8803", "cve_desc": "The ecc_256_modp function in ecc-256.c in Nettle before 3.2 does not properly handle carry propagation and produces incorrect output in its implementation of the P-256 NIST elliptic curve, which allows attackers to have unspecified impact via unknown vectors, a different vulnerability than CVE-2015-8805.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-8803"}
{"idx": 216027, "project": "tar", "commit_id": "cb07844454d8cc9fb21f53ace75975f91185a120", "project_url": "http://git.savannah.gnu.org/cgit/tar", "commit_url": "http://git.savannah.gnu.org/cgit/tar.git/commit/?id=cb07844454d8cc9fb21f53ace75975f91185a120", "commit_message": "Fix possible NULL dereference (savannah bug #55369)\n\n* src/sparse.c (pax_decode_header): Check return from find_next_block.", "target": 1, "func": "pax_decode_header (struct tar_sparse_file *file)\n{\n  if (file->stat_info->sparse_major > 0)\n    {\n      uintmax_t u;\n      char nbuf[UINTMAX_STRSIZE_BOUND];\n      union block *blk;\n      char *p;\n      size_t i;\n      off_t start;\n      \n#define COPY_BUF(b,buf,src) do                                     \\\n {                                                                 \\\n   char *endp = b->buffer + BLOCKSIZE;                             \\\n   char *dst = buf;                                                \\\n   do                                                              \\\n     {                                                             \\\n       if (dst == buf + UINTMAX_STRSIZE_BOUND -1)                  \\\n         {                                                         \\\n           ERROR ((0, 0, _(\"%s: numeric overflow in sparse archive member\"), \\\n\t          file->stat_info->orig_file_name));               \\\n           return false;                                           \\\n         }                                                         \\\n       if (src == endp)                                            \\\n\t {                                                         \\\n\t   set_next_block_after (b);                               \\\n           b = find_next_block ();                                 \\\n           src = b->buffer;                                        \\\n\t   endp = b->buffer + BLOCKSIZE;                           \\\n\t }                                                         \\\n       *dst = *src++;                                              \\\n     }                                                             \\\n   while (*dst++ != '\\n');                                         \\\n   dst[-1] = 0;                                                    \\\n } while (0)\n\n      start = current_block_ordinal ();\n      set_next_block_after (current_header);\n      blk = find_next_block ();\n      p = blk->buffer;\n      COPY_BUF (blk,nbuf,p);\n      if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t)))\n\t{\n\t  ERROR ((0, 0, _(\"%s: malformed sparse archive member\"),\n\t\t  file->stat_info->orig_file_name));\n\t  return false;\n\t}\n      file->stat_info->sparse_map_size = u;\n      file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size,\n\t\t\t\t\t     sizeof (*file->stat_info->sparse_map));\n      file->stat_info->sparse_map_avail = 0;\n      for (i = 0; i < file->stat_info->sparse_map_size; i++)\n\t{\n\t  struct sp_array sp;\n\n\t  COPY_BUF (blk,nbuf,p);\n\t  if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))\n\t    {\n\t      ERROR ((0, 0, _(\"%s: malformed sparse archive member\"),\n\t\t      file->stat_info->orig_file_name));\n\t      return false;\n\t    }\n\t  sp.offset = u;\n\t  COPY_BUF (blk,nbuf,p);\n\t  if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))\n\t    {\n\t      ERROR ((0, 0, _(\"%s: malformed sparse archive member\"),\n\t\t      file->stat_info->orig_file_name));\n\t      return false;\n\t    }\n\t  sp.numbytes = u;\n\t  sparse_add_map (file->stat_info, &sp);\n\t}\n      set_next_block_after (blk);\n\n      file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start);\n    }\n\n  return true;\n}", "func_hash": 160355660991121839913024673798590735910, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2019-9923", "cve_desc": "pax_decode_header in sparse.c in GNU Tar before 1.32 had a NULL pointer dereference when parsing certain archives that have malformed extended headers.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-9923"}
{"idx": 498918, "project": "tar", "commit_id": "cb07844454d8cc9fb21f53ace75975f91185a120", "project_url": "http://git.savannah.gnu.org/cgit/tar", "commit_url": "http://git.savannah.gnu.org/cgit/tar.git/commit/?id=cb07844454d8cc9fb21f53ace75975f91185a120", "commit_message": "Fix possible NULL dereference (savannah bug #55369)\n\n* src/sparse.c (pax_decode_header): Check return from find_next_block.", "target": 0, "func": "pax_decode_header (struct tar_sparse_file *file)\n{\n  if (file->stat_info->sparse_major > 0)\n    {\n      uintmax_t u;\n      char nbuf[UINTMAX_STRSIZE_BOUND];\n      union block *blk;\n      char *p;\n      size_t i;\n      off_t start;\n      \n#define COPY_BUF(b,buf,src) do                                     \\\n {                                                                 \\\n   char *endp = b->buffer + BLOCKSIZE;                             \\\n   char *dst = buf;                                                \\\n   do                                                              \\\n     {                                                             \\\n       if (dst == buf + UINTMAX_STRSIZE_BOUND -1)                  \\\n         {                                                         \\\n           ERROR ((0, 0, _(\"%s: numeric overflow in sparse archive member\"), \\\n\t          file->stat_info->orig_file_name));               \\\n           return false;                                           \\\n         }                                                         \\\n       if (src == endp)                                            \\\n\t {                                                         \\\n\t   set_next_block_after (b);                               \\\n           b = find_next_block ();                                 \\\n           if (!b)                                                 \\\n             FATAL_ERROR ((0, 0, _(\"Unexpected EOF in archive\"))); \\\n           src = b->buffer;                                        \\\n\t   endp = b->buffer + BLOCKSIZE;                           \\\n\t }                                                         \\\n       *dst = *src++;                                              \\\n     }                                                             \\\n   while (*dst++ != '\\n');                                         \\\n   dst[-1] = 0;                                                    \\\n } while (0)\n\n      start = current_block_ordinal ();\n      set_next_block_after (current_header);\n      blk = find_next_block ();\n      if (!blk)\n        FATAL_ERROR ((0, 0, _(\"Unexpected EOF in archive\")));\n      p = blk->buffer;\n      COPY_BUF (blk,nbuf,p);\n      if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t)))\n\t{\n\t  ERROR ((0, 0, _(\"%s: malformed sparse archive member\"),\n\t\t  file->stat_info->orig_file_name));\n\t  return false;\n\t}\n      file->stat_info->sparse_map_size = u;\n      file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size,\n\t\t\t\t\t     sizeof (*file->stat_info->sparse_map));\n      file->stat_info->sparse_map_avail = 0;\n      for (i = 0; i < file->stat_info->sparse_map_size; i++)\n\t{\n\t  struct sp_array sp;\n\n\t  COPY_BUF (blk,nbuf,p);\n\t  if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))\n\t    {\n\t      ERROR ((0, 0, _(\"%s: malformed sparse archive member\"),\n\t\t      file->stat_info->orig_file_name));\n\t      return false;\n\t    }\n\t  sp.offset = u;\n\t  COPY_BUF (blk,nbuf,p);\n\t  if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))\n\t    {\n\t      ERROR ((0, 0, _(\"%s: malformed sparse archive member\"),\n\t\t      file->stat_info->orig_file_name));\n\t      return false;\n\t    }\n\t  sp.numbytes = u;\n\t  sparse_add_map (file->stat_info, &sp);\n\t}\n      set_next_block_after (blk);\n\n      file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start);\n    }\n\n  return true;\n}", "func_hash": 43484957058485536945482588311169940116, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2019-9923", "cve_desc": "pax_decode_header in sparse.c in GNU Tar before 1.32 had a NULL pointer dereference when parsing certain archives that have malformed extended headers.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-9923"}
{"idx": 216126, "project": "openssl", "commit_id": "cca1cd9a3447dd067503e4a85ebd1679ee78a48e", "project_url": "https://github.com/openssl/openssl", "commit_url": "https://github.com/openssl/openssl/commit/cca1cd9a3447dd067503e4a85ebd1679ee78a48e", "commit_message": "Submitted by: Tomas Hoger \n\nFix for CVE-2010-0433 where some kerberos enabled versions of OpenSSL\ncould be crashed if the relevant tables were not present (e.g. chrooted).", "target": 1, "func": "    kssl_keytab_is_available(KSSL_CTX *kssl_ctx)\n{\n    krb5_context\t\tkrb5context = NULL;\n    krb5_keytab \t\tkrb5keytab = NULL;\n    krb5_keytab_entry           entry;\n    krb5_principal              princ = NULL;\n    krb5_error_code  \t\tkrb5rc = KRB5KRB_ERR_GENERIC;\n    int rc = 0;\n\n    if ((krb5rc = krb5_init_context(&krb5context)))\n        return(0);\n\n    /*\tkssl_ctx->keytab_file == NULL ==> use Kerberos default\n    */\n    if (kssl_ctx->keytab_file)\n    {\n        krb5rc = krb5_kt_resolve(krb5context, kssl_ctx->keytab_file,\n                                  &krb5keytab);\n        if (krb5rc)\n            goto exit;\n    }\n    else\n    {\n        krb5rc = krb5_kt_default(krb5context,&krb5keytab);\n        if (krb5rc)\n            goto exit;\n    }\n\n    /* the host key we are looking for */\n    krb5rc = krb5_sname_to_principal(krb5context, NULL, \n                                     kssl_ctx->service_name ? kssl_ctx->service_name: KRB5SVC,\n                                     KRB5_NT_SRV_HST, &princ);\n\n    krb5rc = krb5_kt_get_entry(krb5context, krb5keytab, \n                                princ,\n                                0 /* IGNORE_VNO */,\n                                0 /* IGNORE_ENCTYPE */,\n                                &entry);\n    if ( krb5rc == KRB5_KT_NOTFOUND ) {\n        rc = 1;\n        goto exit;\n    } else if ( krb5rc )\n        goto exit;\n    \n    krb5_kt_free_entry(krb5context, &entry);\n    rc = 1;\n\n  exit:\n    if (krb5keytab)     krb5_kt_close(krb5context, krb5keytab);\n    if (princ)          krb5_free_principal(krb5context, princ);\n    if (krb5context)\tkrb5_free_context(krb5context);\n    return(rc);\n}", "func_hash": 99893605133546740733833372677927547347, "file_name": "None", "file_hash": null, "cwe": ["CWE-20"], "cve": "CVE-2010-0433", "cve_desc": "The kssl_keytab_is_available function in ssl/kssl.c in OpenSSL before 0.9.8n, when Kerberos is enabled but Kerberos configuration files cannot be opened, does not check a certain return value, which allows remote attackers to cause a denial of service (NULL pointer dereference and daemon crash) via SSL cipher negotiation, as demonstrated by a chroot installation of Dovecot or stunnel without Kerberos configuration files inside the chroot.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2010-0433"}
{"idx": 500044, "project": "openssl", "commit_id": "cca1cd9a3447dd067503e4a85ebd1679ee78a48e", "project_url": "https://github.com/openssl/openssl", "commit_url": "https://github.com/openssl/openssl/commit/cca1cd9a3447dd067503e4a85ebd1679ee78a48e", "commit_message": "Submitted by: Tomas Hoger \n\nFix for CVE-2010-0433 where some kerberos enabled versions of OpenSSL\ncould be crashed if the relevant tables were not present (e.g. chrooted).", "target": 0, "func": "    kssl_keytab_is_available(KSSL_CTX *kssl_ctx)\n{\n    krb5_context\t\tkrb5context = NULL;\n    krb5_keytab \t\tkrb5keytab = NULL;\n    krb5_keytab_entry           entry;\n    krb5_principal              princ = NULL;\n    krb5_error_code  \t\tkrb5rc = KRB5KRB_ERR_GENERIC;\n    int rc = 0;\n\n    if ((krb5rc = krb5_init_context(&krb5context)))\n        return(0);\n\n    /*\tkssl_ctx->keytab_file == NULL ==> use Kerberos default\n    */\n    if (kssl_ctx->keytab_file)\n    {\n        krb5rc = krb5_kt_resolve(krb5context, kssl_ctx->keytab_file,\n                                  &krb5keytab);\n        if (krb5rc)\n            goto exit;\n    }\n    else\n    {\n        krb5rc = krb5_kt_default(krb5context,&krb5keytab);\n        if (krb5rc)\n            goto exit;\n    }\n\n    /* the host key we are looking for */\n    krb5rc = krb5_sname_to_principal(krb5context, NULL, \n                                     kssl_ctx->service_name ? kssl_ctx->service_name: KRB5SVC,\n                                     KRB5_NT_SRV_HST, &princ);\n\n    if (krb5rc)\n\tgoto exit;\n\n    krb5rc = krb5_kt_get_entry(krb5context, krb5keytab, \n                                princ,\n                                0 /* IGNORE_VNO */,\n                                0 /* IGNORE_ENCTYPE */,\n                                &entry);\n    if ( krb5rc == KRB5_KT_NOTFOUND ) {\n        rc = 1;\n        goto exit;\n    } else if ( krb5rc )\n        goto exit;\n    \n    krb5_kt_free_entry(krb5context, &entry);\n    rc = 1;\n\n  exit:\n    if (krb5keytab)     krb5_kt_close(krb5context, krb5keytab);\n    if (princ)          krb5_free_principal(krb5context, princ);\n    if (krb5context)\tkrb5_free_context(krb5context);\n    return(rc);\n}", "func_hash": 53603406923488065201694869344560864035, "file_name": "None", "file_hash": null, "cwe": ["CWE-20"], "cve": "CVE-2010-0433", "cve_desc": "The kssl_keytab_is_available function in ssl/kssl.c in OpenSSL before 0.9.8n, when Kerberos is enabled but Kerberos configuration files cannot be opened, does not check a certain return value, which allows remote attackers to cause a denial of service (NULL pointer dereference and daemon crash) via SSL cipher negotiation, as demonstrated by a chroot installation of Dovecot or stunnel without Kerberos configuration files inside the chroot.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2010-0433"}
{"idx": 216202, "project": "libssh", "commit_id": "4d8420f3282ed07fc99fc5e930c17df27ef1e9b2", "project_url": "http://git.libssh.org/projects/libssh", "commit_url": "http://git.libssh.org/projects/libssh.git/commit/?h=v0-5&id=4d8420f3282ed07fc99fc5e930c17df27ef1e9b2", "commit_message": "sftp: Fix bug in sftp_mkdir not returning on error.\n\nresolves: #84\n(cherry picked from commit a92c97b2e17715c1b3cdd693d14af6c3311d8e44)", "target": 1, "func": "int sftp_mkdir(sftp_session sftp, const char *directory, mode_t mode) {\n  sftp_status_message status = NULL;\n  sftp_message msg = NULL;\n  sftp_attributes errno_attr = NULL;\n  struct sftp_attributes_struct attr;\n  ssh_buffer buffer;\n  ssh_string path;\n  uint32_t id;\n\n  buffer = ssh_buffer_new();\n  if (buffer == NULL) {\n    ssh_set_error_oom(sftp->session);\n    return -1;\n  }\n\n  path = ssh_string_from_char(directory);\n  if (path == NULL) {\n    ssh_set_error_oom(sftp->session);\n    ssh_buffer_free(buffer);\n    return -1;\n  }\n\n  ZERO_STRUCT(attr);\n  attr.permissions = mode;\n  attr.flags = SSH_FILEXFER_ATTR_PERMISSIONS;\n\n  id = sftp_get_new_id(sftp);\n  if (buffer_add_u32(buffer, id) < 0 ||\n      buffer_add_ssh_string(buffer, path) < 0 ||\n      buffer_add_attributes(buffer, &attr) < 0 ||\n      sftp_packet_write(sftp, SSH_FXP_MKDIR, buffer) < 0) {\n    ssh_buffer_free(buffer);\n    ssh_string_free(path);\n  }\n  ssh_buffer_free(buffer);\n  ssh_string_free(path);\n\n  while (msg == NULL) {\n    if (sftp_read_and_dispatch(sftp) < 0) {\n      return -1;\n    }\n    msg = sftp_dequeue(sftp, id);\n  }\n\n  /* By specification, this command only returns SSH_FXP_STATUS */\n  if (msg->packet_type == SSH_FXP_STATUS) {\n    status = parse_status_msg(msg);\n    sftp_message_free(msg);\n    if (status == NULL) {\n      return -1;\n    }\n    sftp_set_error(sftp, status->status);\n    switch (status->status) {\n      case SSH_FX_FAILURE:\n        /*\n         * mkdir always returns a failure, even if the path already exists.\n         * To be POSIX conform and to be able to map it to EEXIST a stat\n         * call is needed here.\n         */\n        errno_attr = sftp_lstat(sftp, directory);\n        if (errno_attr != NULL) {\n          SAFE_FREE(errno_attr);\n          sftp_set_error(sftp, SSH_FX_FILE_ALREADY_EXISTS);\n        }\n        break;\n      case SSH_FX_OK:\n        status_msg_free(status);\n        return 0;\n        break;\n      default:\n        break;\n    }\n    /*\n     * The status should be SSH_FX_OK if the command was successful, if it\n     * didn't, then there was an error\n     */\n    ssh_set_error(sftp->session, SSH_REQUEST_DENIED,\n        \"SFTP server: %s\", status->errormsg);\n    status_msg_free(status);\n    return -1;\n  } else {\n    ssh_set_error(sftp->session, SSH_FATAL,\n        \"Received message %d when attempting to make directory\",\n        msg->packet_type);\n    sftp_message_free(msg);\n  }\n\n  return -1;\n}", "func_hash": 318072065183989103598769219049127518412, "file_name": "None", "file_hash": null, "cwe": ["CWE-399"], "cve": "CVE-2012-4559", "cve_desc": "Multiple double free vulnerabilities in the (1) agent_sign_data function in agent.c, (2) channel_request function in channels.c, (3) ssh_userauth_pubkey function in auth.c, (4) sftp_parse_attr_3 function in sftp.c, and (5) try_publickey_from_file function in keyfiles.c in libssh before 0.5.3 allow remote attackers to cause a denial of service (crash) and possibly execute arbitrary code via unspecified vectors.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2012-4559"}
{"idx": 500663, "project": "libssh", "commit_id": "4d8420f3282ed07fc99fc5e930c17df27ef1e9b2", "project_url": "http://git.libssh.org/projects/libssh", "commit_url": "http://git.libssh.org/projects/libssh.git/commit/?h=v0-5&id=4d8420f3282ed07fc99fc5e930c17df27ef1e9b2", "commit_message": "sftp: Fix bug in sftp_mkdir not returning on error.\n\nresolves: #84\n(cherry picked from commit a92c97b2e17715c1b3cdd693d14af6c3311d8e44)", "target": 0, "func": "int sftp_mkdir(sftp_session sftp, const char *directory, mode_t mode) {\n  sftp_status_message status = NULL;\n  sftp_message msg = NULL;\n  sftp_attributes errno_attr = NULL;\n  struct sftp_attributes_struct attr;\n  ssh_buffer buffer;\n  ssh_string path;\n  uint32_t id;\n\n  buffer = ssh_buffer_new();\n  if (buffer == NULL) {\n    ssh_set_error_oom(sftp->session);\n    return -1;\n  }\n\n  path = ssh_string_from_char(directory);\n  if (path == NULL) {\n    ssh_set_error_oom(sftp->session);\n    ssh_buffer_free(buffer);\n    return -1;\n  }\n\n  ZERO_STRUCT(attr);\n  attr.permissions = mode;\n  attr.flags = SSH_FILEXFER_ATTR_PERMISSIONS;\n\n  id = sftp_get_new_id(sftp);\n  if (buffer_add_u32(buffer, id) < 0 ||\n      buffer_add_ssh_string(buffer, path) < 0 ||\n      buffer_add_attributes(buffer, &attr) < 0 ||\n      sftp_packet_write(sftp, SSH_FXP_MKDIR, buffer) < 0) {\n    ssh_buffer_free(buffer);\n    ssh_string_free(path);\n    return -1;\n  }\n  ssh_buffer_free(buffer);\n  ssh_string_free(path);\n\n  while (msg == NULL) {\n    if (sftp_read_and_dispatch(sftp) < 0) {\n      return -1;\n    }\n    msg = sftp_dequeue(sftp, id);\n  }\n\n  /* By specification, this command only returns SSH_FXP_STATUS */\n  if (msg->packet_type == SSH_FXP_STATUS) {\n    status = parse_status_msg(msg);\n    sftp_message_free(msg);\n    if (status == NULL) {\n      return -1;\n    }\n    sftp_set_error(sftp, status->status);\n    switch (status->status) {\n      case SSH_FX_FAILURE:\n        /*\n         * mkdir always returns a failure, even if the path already exists.\n         * To be POSIX conform and to be able to map it to EEXIST a stat\n         * call is needed here.\n         */\n        errno_attr = sftp_lstat(sftp, directory);\n        if (errno_attr != NULL) {\n          SAFE_FREE(errno_attr);\n          sftp_set_error(sftp, SSH_FX_FILE_ALREADY_EXISTS);\n        }\n        break;\n      case SSH_FX_OK:\n        status_msg_free(status);\n        return 0;\n        break;\n      default:\n        break;\n    }\n    /*\n     * The status should be SSH_FX_OK if the command was successful, if it\n     * didn't, then there was an error\n     */\n    ssh_set_error(sftp->session, SSH_REQUEST_DENIED,\n        \"SFTP server: %s\", status->errormsg);\n    status_msg_free(status);\n    return -1;\n  } else {\n    ssh_set_error(sftp->session, SSH_FATAL,\n        \"Received message %d when attempting to make directory\",\n        msg->packet_type);\n    sftp_message_free(msg);\n  }\n\n  return -1;\n}", "func_hash": 57484647322304387183846447984144924668, "file_name": "None", "file_hash": null, "cwe": ["CWE-399"], "cve": "CVE-2012-4559", "cve_desc": "Multiple double free vulnerabilities in the (1) agent_sign_data function in agent.c, (2) channel_request function in channels.c, (3) ssh_userauth_pubkey function in auth.c, (4) sftp_parse_attr_3 function in sftp.c, and (5) try_publickey_from_file function in keyfiles.c in libssh before 0.5.3 allow remote attackers to cause a denial of service (crash) and possibly execute arbitrary code via unspecified vectors.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2012-4559"}
{"idx": 216515, "project": "openssl", "commit_id": "939b4960276b040fc0ed52232238fcc9e2e9ec21", "project_url": "https://github.com/openssl/openssl", "commit_url": "https://github.com/openssl/openssl/commit/939b4960276b040fc0ed52232238fcc9e2e9ec21", "commit_message": "Fix race condition in NewSessionTicket\n\nIf a NewSessionTicket is received by a multi-threaded client when\nattempting to reuse a previous ticket then a race condition can occur\npotentially leading to a double free of the ticket data.\n\nCVE-2015-1791\n\nThis also fixes RT#3808 where a session ID is changed for a session already\nin the client session cache. Since the session ID is the key to the cache\nthis breaks the cache access.\n\nParts of this patch were inspired by this Akamai change:\nhttps://github.com/akamai/openssl/commit/c0bf69a791239ceec64509f9f19fcafb2461b0d3\n\nReviewed-by: Rich Salz \n(cherry picked from commit 27c76b9b8010b536687318739c6f631ce4194688)\n\nConflicts:\n\tssl/ssl.h\n\tssl/ssl_err.c", "target": 1, "func": "int ssl3_get_new_session_ticket(SSL *s)\n{\n    int ok, al, ret = 0, ticklen;\n    long n;\n    const unsigned char *p;\n    unsigned char *d;\n\n    n = s->method->ssl_get_message(s,\n                                   SSL3_ST_CR_SESSION_TICKET_A,\n                                   SSL3_ST_CR_SESSION_TICKET_B,\n                                   SSL3_MT_NEWSESSION_TICKET, 16384, &ok);\n\n    if (!ok)\n        return ((int)n);\n\n    if (n < 6) {\n        /* need at least ticket_lifetime_hint + ticket length */\n        al = SSL_AD_DECODE_ERROR;\n        SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);\n        goto f_err;\n    }\n\n    p = d = (unsigned char *)s->init_msg;\n    n2l(p, s->session->tlsext_tick_lifetime_hint);\n    n2s(p, ticklen);\n    /* ticket_lifetime_hint + ticket_length + ticket */\n    if (ticklen + 6 != n) {\n        al = SSL_AD_DECODE_ERROR;\n        SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);\n        goto f_err;\n    }\n    if (s->session->tlsext_tick) {\n        OPENSSL_free(s->session->tlsext_tick);\n        s->session->tlsext_ticklen = 0;\n    }\n    s->session->tlsext_tick = OPENSSL_malloc(ticklen);\n    if (!s->session->tlsext_tick) {\n        SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);\n        goto err;\n    }\n    memcpy(s->session->tlsext_tick, p, ticklen);\n    s->session->tlsext_ticklen = ticklen;\n    /*\n     * There are two ways to detect a resumed ticket session. One is to set\n     * an appropriate session ID and then the server must return a match in\n     * ServerHello. This allows the normal client session ID matching to work\n     * and we know much earlier that the ticket has been accepted. The\n     * other way is to set zero length session ID when the ticket is\n     * presented and rely on the handshake to determine session resumption.\n     * We choose the former approach because this fits in with assumptions\n     * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is\n     * SHA256 is disabled) hash of the ticket.\n     */\n    EVP_Digest(p, ticklen,\n               s->session->session_id, &s->session->session_id_length,\n# ifndef OPENSSL_NO_SHA256\n               EVP_sha256(), NULL);\n# else\n               EVP_sha1(), NULL);\n# endif\n    ret = 1;\n    return (ret);\n f_err:\n    ssl3_send_alert(s, SSL3_AL_FATAL, al);\n err:\n    s->state = SSL_ST_ERR;\n    return (-1);\n}", "func_hash": 262201276305976211218627982974228415604, "file_name": "None", "file_hash": null, "cwe": ["CWE-362"], "cve": "CVE-2015-1791", "cve_desc": "Race condition in the ssl3_get_new_session_ticket function in ssl/s3_clnt.c in OpenSSL before 0.9.8zg, 1.0.0 before 1.0.0s, 1.0.1 before 1.0.1n, and 1.0.2 before 1.0.2b, when used for a multi-threaded client, allows remote attackers to cause a denial of service (double free and application crash) or possibly have unspecified other impact by providing a NewSessionTicket during an attempt to reuse a ticket that had been obtained earlier.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-1791"}
{"idx": 502735, "project": "openssl", "commit_id": "939b4960276b040fc0ed52232238fcc9e2e9ec21", "project_url": "https://github.com/openssl/openssl", "commit_url": "https://github.com/openssl/openssl/commit/939b4960276b040fc0ed52232238fcc9e2e9ec21", "commit_message": "Fix race condition in NewSessionTicket\n\nIf a NewSessionTicket is received by a multi-threaded client when\nattempting to reuse a previous ticket then a race condition can occur\npotentially leading to a double free of the ticket data.\n\nCVE-2015-1791\n\nThis also fixes RT#3808 where a session ID is changed for a session already\nin the client session cache. Since the session ID is the key to the cache\nthis breaks the cache access.\n\nParts of this patch were inspired by this Akamai change:\nhttps://github.com/akamai/openssl/commit/c0bf69a791239ceec64509f9f19fcafb2461b0d3\n\nReviewed-by: Rich Salz \n(cherry picked from commit 27c76b9b8010b536687318739c6f631ce4194688)\n\nConflicts:\n\tssl/ssl.h\n\tssl/ssl_err.c", "target": 0, "func": "int ssl3_get_new_session_ticket(SSL *s)\n{\n    int ok, al, ret = 0, ticklen;\n    long n;\n    const unsigned char *p;\n    unsigned char *d;\n\n    n = s->method->ssl_get_message(s,\n                                   SSL3_ST_CR_SESSION_TICKET_A,\n                                   SSL3_ST_CR_SESSION_TICKET_B,\n                                   SSL3_MT_NEWSESSION_TICKET, 16384, &ok);\n\n    if (!ok)\n        return ((int)n);\n\n    if (n < 6) {\n        /* need at least ticket_lifetime_hint + ticket length */\n        al = SSL_AD_DECODE_ERROR;\n        SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);\n        goto f_err;\n    }\n\n    p = d = (unsigned char *)s->init_msg;\n\n    if (s->session->session_id_length > 0) {\n        int i = s->session_ctx->session_cache_mode;\n        SSL_SESSION *new_sess;\n        /*\n         * We reused an existing session, so we need to replace it with a new\n         * one\n         */\n        if (i & SSL_SESS_CACHE_CLIENT) {\n            /*\n             * Remove the old session from the cache\n             */\n            if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {\n                if (s->session_ctx->remove_session_cb != NULL)\n                    s->session_ctx->remove_session_cb(s->session_ctx,\n                                                      s->session);\n            } else {\n                /* We carry on if this fails */\n                SSL_CTX_remove_session(s->session_ctx, s->session);\n            }\n        }\n\n        if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {\n            al = SSL_AD_INTERNAL_ERROR;\n            SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);\n            goto f_err;\n        }\n\n        SSL_SESSION_free(s->session);\n        s->session = new_sess;\n    }\n\n    n2l(p, s->session->tlsext_tick_lifetime_hint);\n    n2s(p, ticklen);\n    /* ticket_lifetime_hint + ticket_length + ticket */\n    if (ticklen + 6 != n) {\n        al = SSL_AD_DECODE_ERROR;\n        SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);\n        goto f_err;\n    }\n    if (s->session->tlsext_tick) {\n        OPENSSL_free(s->session->tlsext_tick);\n        s->session->tlsext_ticklen = 0;\n    }\n    s->session->tlsext_tick = OPENSSL_malloc(ticklen);\n    if (!s->session->tlsext_tick) {\n        SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);\n        goto err;\n    }\n    memcpy(s->session->tlsext_tick, p, ticklen);\n    s->session->tlsext_ticklen = ticklen;\n    /*\n     * There are two ways to detect a resumed ticket session. One is to set\n     * an appropriate session ID and then the server must return a match in\n     * ServerHello. This allows the normal client session ID matching to work\n     * and we know much earlier that the ticket has been accepted. The\n     * other way is to set zero length session ID when the ticket is\n     * presented and rely on the handshake to determine session resumption.\n     * We choose the former approach because this fits in with assumptions\n     * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is\n     * SHA256 is disabled) hash of the ticket.\n     */\n    EVP_Digest(p, ticklen,\n               s->session->session_id, &s->session->session_id_length,\n# ifndef OPENSSL_NO_SHA256\n               EVP_sha256(), NULL);\n# else\n               EVP_sha1(), NULL);\n# endif\n    ret = 1;\n    return (ret);\n f_err:\n    ssl3_send_alert(s, SSL3_AL_FATAL, al);\n err:\n    s->state = SSL_ST_ERR;\n    return (-1);\n}", "func_hash": 24541052959849141799219681889549728285, "file_name": "None", "file_hash": null, "cwe": ["CWE-362"], "cve": "CVE-2015-1791", "cve_desc": "Race condition in the ssl3_get_new_session_ticket function in ssl/s3_clnt.c in OpenSSL before 0.9.8zg, 1.0.0 before 1.0.0s, 1.0.1 before 1.0.1n, and 1.0.2 before 1.0.2b, when used for a multi-threaded client, allows remote attackers to cause a denial of service (double free and application crash) or possibly have unspecified other impact by providing a NewSessionTicket during an attempt to reuse a ticket that had been obtained earlier.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2015-1791"}
{"idx": 216637, "project": "guile", "commit_id": "245608911698adb3472803856019bdd5670b6614", "project_url": "http://git.savannah.gnu.org/cgit/guile", "commit_url": "http://git.savannah.gnu.org/cgit/guile.git/commit/?h=stable-2.0&id=245608911698adb3472803856019bdd5670b6614", "commit_message": "Remove 'umask' calls from 'mkdir'.\n\nFixes .\n\n* libguile/filesys.c (SCM_DEFINE): Remove calls to 'umask' when MODE is\nunbound; instead, use 0777 as the mode.  Update docstring to clarify\nthis.\n* doc/ref/posix.texi (File System): Adjust accordingly.\n* NEWS: Mention it.", "target": 1, "func": "SCM_DEFINE (scm_mkdir, \"mkdir\", 1, 1, 0,\n            (SCM path, SCM mode),\n\t    \"Create a new directory named by @var{path}.  If @var{mode} is omitted\\n\"\n\t    \"then the permissions of the directory file are set using the current\\n\"\n\t    \"umask.  Otherwise they are set to the decimal value specified with\\n\"\n\t    \"@var{mode}.  The return value is unspecified.\")\n#define FUNC_NAME s_scm_mkdir\n{\n  int rv;\n  mode_t mask;\n\n  if (SCM_UNBNDP (mode))\n    {\n      mask = umask (0);\n      umask (mask);\n      STRING_SYSCALL (path, c_path, rv = mkdir (c_path, 0777 ^ mask));\n    }\n  else\n    {\n      STRING_SYSCALL (path, c_path, rv = mkdir (c_path, scm_to_uint (mode)));\n    }\n  if (rv != 0)\n    SCM_SYSERROR;\n  return SCM_UNSPECIFIED;\n}", "func_hash": 128331080543585624737822334688372409592, "file_name": "None", "file_hash": null, "cwe": ["CWE-275"], "cve": "CVE-2016-8605", "cve_desc": "The mkdir procedure of GNU Guile temporarily changed the process' umask to zero. During that time window, in a multithreaded application, other threads could end up creating files with insecure permissions. For example, mkdir without the optional mode argument would create directories as 0777. This is fixed in Guile 2.0.13. Prior versions are affected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-8605"}
{"idx": 503867, "project": "guile", "commit_id": "245608911698adb3472803856019bdd5670b6614", "project_url": "http://git.savannah.gnu.org/cgit/guile", "commit_url": "http://git.savannah.gnu.org/cgit/guile.git/commit/?h=stable-2.0&id=245608911698adb3472803856019bdd5670b6614", "commit_message": "Remove 'umask' calls from 'mkdir'.\n\nFixes .\n\n* libguile/filesys.c (SCM_DEFINE): Remove calls to 'umask' when MODE is\nunbound; instead, use 0777 as the mode.  Update docstring to clarify\nthis.\n* doc/ref/posix.texi (File System): Adjust accordingly.\n* NEWS: Mention it.", "target": 0, "func": "SCM_DEFINE (scm_mkdir, \"mkdir\", 1, 1, 0,\n            (SCM path, SCM mode),\n\t    \"Create a new directory named by @var{path}.  If @var{mode} is omitted\\n\"\n\t    \"then the permissions of the directory are set to @code{#o777}\\n\"\n\t    \"masked with the current umask (@pxref{Processes, @code{umask}}).\\n\"\n\t    \"Otherwise they are set to the value specified with @var{mode}.\\n\"\n\t    \"The return value is unspecified.\")\n#define FUNC_NAME s_scm_mkdir\n{\n  int rv;\n  mode_t c_mode;\n\n  c_mode = SCM_UNBNDP (mode) ? 0777 : scm_to_uint (mode);\n\n  STRING_SYSCALL (path, c_path, rv = mkdir (c_path, c_mode));\n  if (rv != 0)\n    SCM_SYSERROR;\n\n  return SCM_UNSPECIFIED;\n}", "func_hash": 144536922752412825349714870039112918366, "file_name": "None", "file_hash": null, "cwe": ["CWE-275"], "cve": "CVE-2016-8605", "cve_desc": "The mkdir procedure of GNU Guile temporarily changed the process' umask to zero. During that time window, in a multithreaded application, other threads could end up creating files with insecure permissions. For example, mkdir without the optional mode argument would create directories as 0777. This is fixed in Guile 2.0.13. Prior versions are affected.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-8605"}
{"idx": 216654, "project": "core", "commit_id": "2c3f37672277b1f73f84722802aaa0ab1ab3e413", "project_url": "https://github.com/LibreOffice/core", "commit_url": "https://github.com/dovecot/core/commit/2c3f37672277b1f73f84722802aaa0ab1ab3e413", "commit_message": "auth: Don't crash expanding %variables when username isn't set.\n\nThis continues the auth-policy fix in\nc3d3faa4f72a676e183f34be960cff13a5a725ae", "target": 1, "func": "auth_request_get_var_expand_table_full(const struct auth_request *auth_request,\n\t\t\t\t       auth_request_escape_func_t *escape_func,\n\t\t\t\t       unsigned int *count)\n{\n\tconst unsigned int auth_count =\n\t\tN_ELEMENTS(auth_request_var_expand_static_tab);\n\tstruct var_expand_table *tab, *ret_tab;\n\tconst char *orig_user, *auth_user;\n\n\tif (escape_func == NULL)\n\t\tescape_func = escape_none;\n\n\t/* keep the extra fields at the beginning. the last static_tab field\n\t   contains the ending NULL-fields. */\n\ttab = ret_tab = t_malloc((*count + auth_count) * sizeof(*tab));\n\tmemset(tab, 0, *count * sizeof(*tab));\n\ttab += *count;\n\t*count += auth_count;\n\n\tmemcpy(tab, auth_request_var_expand_static_tab,\n\t       auth_count * sizeof(*tab));\n\n\ttab[0].value = escape_func(auth_request->user, auth_request);\n\ttab[1].value = escape_func(t_strcut(auth_request->user, '@'),\n\t\t\t\t   auth_request);\n\ttab[2].value = strchr(auth_request->user, '@');\n\tif (tab[2].value != NULL)\n\t\ttab[2].value = escape_func(tab[2].value+1, auth_request);\n\ttab[3].value = escape_func(auth_request->service, auth_request);\n\t/* tab[4] = we have no home dir */\n\tif (auth_request->local_ip.family != 0)\n\t\ttab[5].value = net_ip2addr(&auth_request->local_ip);\n\tif (auth_request->remote_ip.family != 0)\n\t\ttab[6].value = net_ip2addr(&auth_request->remote_ip);\n\ttab[7].value = dec2str(auth_request->client_pid);\n\tif (auth_request->mech_password != NULL) {\n\t\ttab[8].value = escape_func(auth_request->mech_password,\n\t\t\t\t\t   auth_request);\n\t}\n\tif (auth_request->userdb_lookup) {\n\t\ttab[9].value = auth_request->userdb == NULL ? \"\" :\n\t\t\tdec2str(auth_request->userdb->userdb->id);\n\t} else {\n\t\ttab[9].value = auth_request->passdb == NULL ? \"\" :\n\t\t\tdec2str(auth_request->passdb->passdb->id);\n\t}\n\ttab[10].value = auth_request->mech_name == NULL ? \"\" :\n\t\tescape_func(auth_request->mech_name, auth_request);\n\ttab[11].value = auth_request->secured ? \"secured\" : \"\";\n\ttab[12].value = dec2str(auth_request->local_port);\n\ttab[13].value = dec2str(auth_request->remote_port);\n\ttab[14].value = auth_request->valid_client_cert ? \"valid\" : \"\";\n\n\tif (auth_request->requested_login_user != NULL) {\n\t\tconst char *login_user = auth_request->requested_login_user;\n\n\t\ttab[15].value = escape_func(login_user, auth_request);\n\t\ttab[16].value = escape_func(t_strcut(login_user, '@'),\n\t\t\t\t\t    auth_request);\n\t\ttab[17].value = strchr(login_user, '@');\n\t\tif (tab[17].value != NULL) {\n\t\t\ttab[17].value = escape_func(tab[17].value+1,\n\t\t\t\t\t\t    auth_request);\n\t\t}\n\t}\n\ttab[18].value = auth_request->session_id == NULL ? NULL :\n\t\tescape_func(auth_request->session_id, auth_request);\n\tif (auth_request->real_local_ip.family != 0)\n\t\ttab[19].value = net_ip2addr(&auth_request->real_local_ip);\n\tif (auth_request->real_remote_ip.family != 0)\n\t\ttab[20].value = net_ip2addr(&auth_request->real_remote_ip);\n\ttab[21].value = dec2str(auth_request->real_local_port);\n\ttab[22].value = dec2str(auth_request->real_remote_port);\n\ttab[23].value = strchr(auth_request->user, '@');\n\tif (tab[23].value != NULL) {\n\t\ttab[23].value = escape_func(t_strcut(tab[23].value+1, '@'),\n\t\t\t\t\t    auth_request);\n\t}\n\ttab[24].value = strrchr(auth_request->user, '@');\n\tif (tab[24].value != NULL)\n\t\ttab[24].value = escape_func(tab[24].value+1, auth_request);\n\ttab[25].value = auth_request->master_user == NULL ? NULL :\n\t\tescape_func(auth_request->master_user, auth_request);\n\ttab[26].value = auth_request->session_pid == (pid_t)-1 ? NULL :\n\t\tdec2str(auth_request->session_pid);\n\n\torig_user = auth_request->original_username != NULL ?\n\t\tauth_request->original_username : auth_request->user;\n\ttab[27].value = escape_func(orig_user, auth_request);\n\ttab[28].value = escape_func(t_strcut(orig_user, '@'), auth_request);\n\ttab[29].value = strchr(orig_user, '@');\n\tif (tab[29].value != NULL)\n\t\ttab[29].value = escape_func(tab[29].value+1, auth_request);\n\n\tif (auth_request->master_user != NULL)\n\t\tauth_user = auth_request->master_user;\n\telse\n\t\tauth_user = orig_user;\n\ttab[30].value = escape_func(auth_user, auth_request);\n\ttab[31].value = escape_func(t_strcut(auth_user, '@'), auth_request);\n\ttab[32].value = strchr(auth_user, '@');\n\tif (tab[32].value != NULL)\n\t\ttab[32].value = escape_func(tab[32].value+1, auth_request);\n\tif (auth_request->local_name != NULL)\n\t\ttab[33].value = escape_func(auth_request->local_name, auth_request);\n\telse\n\t\ttab[33].value = \"\";\n\treturn ret_tab;\n}", "func_hash": 262295488878616392807601246569405637828, "file_name": "None", "file_hash": null, "cwe": ["CWE-20"], "cve": "CVE-2016-8652", "cve_desc": "The auth component in Dovecot before 2.2.27, when auth-policy is configured, allows a remote attackers to cause a denial of service (crash) by aborting authentication without setting a username.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-8652"}
{"idx": 503985, "project": "core", "commit_id": "2c3f37672277b1f73f84722802aaa0ab1ab3e413", "project_url": "https://github.com/LibreOffice/core", "commit_url": "https://github.com/dovecot/core/commit/2c3f37672277b1f73f84722802aaa0ab1ab3e413", "commit_message": "auth: Don't crash expanding %variables when username isn't set.\n\nThis continues the auth-policy fix in\nc3d3faa4f72a676e183f34be960cff13a5a725ae", "target": 0, "func": "auth_request_get_var_expand_table_full(const struct auth_request *auth_request,\n\t\t\t\t       auth_request_escape_func_t *escape_func,\n\t\t\t\t       unsigned int *count)\n{\n\tconst unsigned int auth_count =\n\t\tN_ELEMENTS(auth_request_var_expand_static_tab);\n\tstruct var_expand_table *tab, *ret_tab;\n\tconst char *orig_user, *auth_user, *username;\n\n\tif (escape_func == NULL)\n\t\tescape_func = escape_none;\n\n\t/* keep the extra fields at the beginning. the last static_tab field\n\t   contains the ending NULL-fields. */\n\ttab = ret_tab = t_malloc((*count + auth_count) * sizeof(*tab));\n\tmemset(tab, 0, *count * sizeof(*tab));\n\ttab += *count;\n\t*count += auth_count;\n\n\tmemcpy(tab, auth_request_var_expand_static_tab,\n\t       auth_count * sizeof(*tab));\n\n\tusername = auth_request->user != NULL ? auth_request->user : \"\";\n\ttab[0].value = escape_func(username, auth_request);\n\ttab[1].value = escape_func(t_strcut(username, '@'),\n\t\t\t\t   auth_request);\n\ttab[2].value = strchr(username, '@');\n\tif (tab[2].value != NULL)\n\t\ttab[2].value = escape_func(tab[2].value+1, auth_request);\n\ttab[3].value = escape_func(auth_request->service, auth_request);\n\t/* tab[4] = we have no home dir */\n\tif (auth_request->local_ip.family != 0)\n\t\ttab[5].value = net_ip2addr(&auth_request->local_ip);\n\tif (auth_request->remote_ip.family != 0)\n\t\ttab[6].value = net_ip2addr(&auth_request->remote_ip);\n\ttab[7].value = dec2str(auth_request->client_pid);\n\tif (auth_request->mech_password != NULL) {\n\t\ttab[8].value = escape_func(auth_request->mech_password,\n\t\t\t\t\t   auth_request);\n\t}\n\tif (auth_request->userdb_lookup) {\n\t\ttab[9].value = auth_request->userdb == NULL ? \"\" :\n\t\t\tdec2str(auth_request->userdb->userdb->id);\n\t} else {\n\t\ttab[9].value = auth_request->passdb == NULL ? \"\" :\n\t\t\tdec2str(auth_request->passdb->passdb->id);\n\t}\n\ttab[10].value = auth_request->mech_name == NULL ? \"\" :\n\t\tescape_func(auth_request->mech_name, auth_request);\n\ttab[11].value = auth_request->secured ? \"secured\" : \"\";\n\ttab[12].value = dec2str(auth_request->local_port);\n\ttab[13].value = dec2str(auth_request->remote_port);\n\ttab[14].value = auth_request->valid_client_cert ? \"valid\" : \"\";\n\n\tif (auth_request->requested_login_user != NULL) {\n\t\tconst char *login_user = auth_request->requested_login_user;\n\n\t\ttab[15].value = escape_func(login_user, auth_request);\n\t\ttab[16].value = escape_func(t_strcut(login_user, '@'),\n\t\t\t\t\t    auth_request);\n\t\ttab[17].value = strchr(login_user, '@');\n\t\tif (tab[17].value != NULL) {\n\t\t\ttab[17].value = escape_func(tab[17].value+1,\n\t\t\t\t\t\t    auth_request);\n\t\t}\n\t}\n\ttab[18].value = auth_request->session_id == NULL ? NULL :\n\t\tescape_func(auth_request->session_id, auth_request);\n\tif (auth_request->real_local_ip.family != 0)\n\t\ttab[19].value = net_ip2addr(&auth_request->real_local_ip);\n\tif (auth_request->real_remote_ip.family != 0)\n\t\ttab[20].value = net_ip2addr(&auth_request->real_remote_ip);\n\ttab[21].value = dec2str(auth_request->real_local_port);\n\ttab[22].value = dec2str(auth_request->real_remote_port);\n\ttab[23].value = strchr(username, '@');\n\tif (tab[23].value != NULL) {\n\t\ttab[23].value = escape_func(t_strcut(tab[23].value+1, '@'),\n\t\t\t\t\t    auth_request);\n\t}\n\ttab[24].value = strrchr(username, '@');\n\tif (tab[24].value != NULL)\n\t\ttab[24].value = escape_func(tab[24].value+1, auth_request);\n\ttab[25].value = auth_request->master_user == NULL ? NULL :\n\t\tescape_func(auth_request->master_user, auth_request);\n\ttab[26].value = auth_request->session_pid == (pid_t)-1 ? NULL :\n\t\tdec2str(auth_request->session_pid);\n\n\torig_user = auth_request->original_username != NULL ?\n\t\tauth_request->original_username : username;\n\ttab[27].value = escape_func(orig_user, auth_request);\n\ttab[28].value = escape_func(t_strcut(orig_user, '@'), auth_request);\n\ttab[29].value = strchr(orig_user, '@');\n\tif (tab[29].value != NULL)\n\t\ttab[29].value = escape_func(tab[29].value+1, auth_request);\n\n\tif (auth_request->master_user != NULL)\n\t\tauth_user = auth_request->master_user;\n\telse\n\t\tauth_user = orig_user;\n\ttab[30].value = escape_func(auth_user, auth_request);\n\ttab[31].value = escape_func(t_strcut(auth_user, '@'), auth_request);\n\ttab[32].value = strchr(auth_user, '@');\n\tif (tab[32].value != NULL)\n\t\ttab[32].value = escape_func(tab[32].value+1, auth_request);\n\tif (auth_request->local_name != NULL)\n\t\ttab[33].value = escape_func(auth_request->local_name, auth_request);\n\telse\n\t\ttab[33].value = \"\";\n\treturn ret_tab;\n}", "func_hash": 300800458657154811271321575901169213921, "file_name": "None", "file_hash": null, "cwe": ["CWE-20"], "cve": "CVE-2016-8652", "cve_desc": "The auth component in Dovecot before 2.2.27, when auth-policy is configured, allows a remote attackers to cause a denial of service (crash) by aborting authentication without setting a username.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2016-8652"}
{"idx": 216701, "project": "libtiff", "commit_id": "dc02f9050311a90b3c0655147cee09bfa7081cfc", "project_url": "https://github.com/vadz/libtiff", "commit_url": "https://github.com/vadz/libtiff/commit/dc02f9050311a90b3c0655147cee09bfa7081cfc", "commit_message": "* libtiff/tif_read.c: add protection against excessive memory\nallocation attempts in TIFFReadDirEntryArray() on short files.\nEffective for mmap'ed case. And non-mmap'ed case, but restricted\nto 64bit builds.\nFixes http://bugzilla.maptools.org/show_bug.cgi?id=2675", "target": 1, "func": "static enum TIFFReadDirEntryErr TIFFReadDirEntryArrayWithLimit(\n    TIFF* tif, TIFFDirEntry* direntry, uint32* count, uint32 desttypesize,\n    void** value, uint64 maxcount)\n{\n\tint typesize;\n\tuint32 datasize;\n\tvoid* data;\n        uint64 target_count64;\n\ttypesize=TIFFDataWidth(direntry->tdir_type);\n\n        target_count64 = (direntry->tdir_count > maxcount) ?\n                maxcount : direntry->tdir_count;\n\n\tif ((target_count64==0)||(typesize==0))\n\t{\n\t\t*value=0;\n\t\treturn(TIFFReadDirEntryErrOk);\n\t}\n        (void) desttypesize;\n\n        /* \n         * As a sanity check, make sure we have no more than a 2GB tag array \n         * in either the current data type or the dest data type.  This also\n         * avoids problems with overflow of tmsize_t on 32bit systems.\n         */\n\tif ((uint64)(2147483647/typesize)0);\n\tdata=_TIFFCheckMalloc(tif, *count, typesize, \"ReadDirEntryArray\");\n\tif (data==0)\n\t\treturn(TIFFReadDirEntryErrAlloc);\n\tif (!(tif->tif_flags&TIFF_BIGTIFF))\n\t{\n\t\tif (datasize<=4)\n\t\t\t_TIFFmemcpy(data,&direntry->tdir_offset,datasize);\n\t\telse\n\t\t{\n\t\t\tenum TIFFReadDirEntryErr err;\n\t\t\tuint32 offset = direntry->tdir_offset.toff_long;\n\t\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\t\tTIFFSwabLong(&offset);\n\t\t\terr=TIFFReadDirEntryData(tif,(uint64)offset,(tmsize_t)datasize,data);\n\t\t\tif (err!=TIFFReadDirEntryErrOk)\n\t\t\t{\n\t\t\t\t_TIFFfree(data);\n\t\t\t\treturn(err);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (datasize<=8)\n\t\t\t_TIFFmemcpy(data,&direntry->tdir_offset,datasize);\n\t\telse\n\t\t{\n\t\t\tenum TIFFReadDirEntryErr err;\n\t\t\tuint64 offset = direntry->tdir_offset.toff_long8;\n\t\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\t\tTIFFSwabLong8(&offset);\n\t\t\terr=TIFFReadDirEntryData(tif,offset,(tmsize_t)datasize,data);\n\t\t\tif (err!=TIFFReadDirEntryErrOk)\n\t\t\t{\n\t\t\t\t_TIFFfree(data);\n\t\t\t\treturn(err);\n\t\t\t}\n\t\t}\n\t}\n\t*value=data;\n\treturn(TIFFReadDirEntryErrOk);\n}", "func_hash": 251386727160240066128978497337284996796, "file_name": "None", "file_hash": null, "cwe": ["CWE-770"], "cve": "CVE-2017-12944", "cve_desc": "The TIFFReadDirEntryArray function in tif_read.c in LibTIFF 4.0.8 mishandles memory allocation for short files, which allows remote attackers to cause a denial of service (allocation failure and application crash) in the TIFFFetchStripThing function in tif_dirread.c during a tiff2pdf invocation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-12944"}
{"idx": 504608, "project": "libtiff", "commit_id": "dc02f9050311a90b3c0655147cee09bfa7081cfc", "project_url": "https://github.com/vadz/libtiff", "commit_url": "https://github.com/vadz/libtiff/commit/dc02f9050311a90b3c0655147cee09bfa7081cfc", "commit_message": "* libtiff/tif_read.c: add protection against excessive memory\nallocation attempts in TIFFReadDirEntryArray() on short files.\nEffective for mmap'ed case. And non-mmap'ed case, but restricted\nto 64bit builds.\nFixes http://bugzilla.maptools.org/show_bug.cgi?id=2675", "target": 0, "func": "static enum TIFFReadDirEntryErr TIFFReadDirEntryArrayWithLimit(\n    TIFF* tif, TIFFDirEntry* direntry, uint32* count, uint32 desttypesize,\n    void** value, uint64 maxcount)\n{\n\tint typesize;\n\tuint32 datasize;\n\tvoid* data;\n        uint64 target_count64;\n\ttypesize=TIFFDataWidth(direntry->tdir_type);\n\n        target_count64 = (direntry->tdir_count > maxcount) ?\n                maxcount : direntry->tdir_count;\n\n\tif ((target_count64==0)||(typesize==0))\n\t{\n\t\t*value=0;\n\t\treturn(TIFFReadDirEntryErrOk);\n\t}\n        (void) desttypesize;\n\n        /* \n         * As a sanity check, make sure we have no more than a 2GB tag array \n         * in either the current data type or the dest data type.  This also\n         * avoids problems with overflow of tmsize_t on 32bit systems.\n         */\n\tif ((uint64)(2147483647/typesize)0);\n\n\tif( isMapped(tif) && datasize > tif->tif_size )\n\t\treturn TIFFReadDirEntryErrIo;\n\n\tif( !isMapped(tif) &&\n\t\t(((tif->tif_flags&TIFF_BIGTIFF) && datasize > 8) ||\n\t\t(!(tif->tif_flags&TIFF_BIGTIFF) && datasize > 4)) )\n\t{\n\t\tdata = NULL;\n\t}\n\telse\n\t{\n\t\tdata=_TIFFCheckMalloc(tif, *count, typesize, \"ReadDirEntryArray\");\n\t\tif (data==0)\n\t\t\treturn(TIFFReadDirEntryErrAlloc);\n\t}\n\tif (!(tif->tif_flags&TIFF_BIGTIFF))\n\t{\n\t\tif (datasize<=4)\n\t\t\t_TIFFmemcpy(data,&direntry->tdir_offset,datasize);\n\t\telse\n\t\t{\n\t\t\tenum TIFFReadDirEntryErr err;\n\t\t\tuint32 offset = direntry->tdir_offset.toff_long;\n\t\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\t\tTIFFSwabLong(&offset);\n\t\t\tif( isMapped(tif) )\n\t\t\t\terr=TIFFReadDirEntryData(tif,(uint64)offset,(tmsize_t)datasize,data);\n\t\t\telse\n\t\t\t\terr=TIFFReadDirEntryDataAndRealloc(tif,(uint64)offset,(tmsize_t)datasize,&data);\n\t\t\tif (err!=TIFFReadDirEntryErrOk)\n\t\t\t{\n\t\t\t\t_TIFFfree(data);\n\t\t\t\treturn(err);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (datasize<=8)\n\t\t\t_TIFFmemcpy(data,&direntry->tdir_offset,datasize);\n\t\telse\n\t\t{\n\t\t\tenum TIFFReadDirEntryErr err;\n\t\t\tuint64 offset = direntry->tdir_offset.toff_long8;\n\t\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\t\tTIFFSwabLong8(&offset);\n\t\t\tif( isMapped(tif) )\n\t\t\t\terr=TIFFReadDirEntryData(tif,(uint64)offset,(tmsize_t)datasize,data);\n\t\t\telse\n\t\t\t\terr=TIFFReadDirEntryDataAndRealloc(tif,(uint64)offset,(tmsize_t)datasize,&data);\n\t\t\tif (err!=TIFFReadDirEntryErrOk)\n\t\t\t{\n\t\t\t\t_TIFFfree(data);\n\t\t\t\treturn(err);\n\t\t\t}\n\t\t}\n\t}\n\t*value=data;\n\treturn(TIFFReadDirEntryErrOk);\n}", "func_hash": 283163990857495325814682097643200308064, "file_name": "None", "file_hash": null, "cwe": ["CWE-770"], "cve": "CVE-2017-12944", "cve_desc": "The TIFFReadDirEntryArray function in tif_read.c in LibTIFF 4.0.8 mishandles memory allocation for short files, which allows remote attackers to cause a denial of service (allocation failure and application crash) in the TIFFFetchStripThing function in tif_dirread.c during a tiff2pdf invocation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2017-12944"}
{"idx": 216726, "project": "openssl", "commit_id": "f426625b6ae9a7831010750490a5f0ad689c5ba3", "project_url": "https://github.com/openssl/openssl", "commit_url": "https://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=f426625b6ae9a7831010750490a5f0ad689c5ba3", "commit_message": "Prevent over long nonces in ChaCha20-Poly1305\n\nChaCha20-Poly1305 is an AEAD cipher, and requires a unique nonce input for\nevery encryption operation. RFC 7539 specifies that the nonce value (IV)\nshould be 96 bits (12 bytes). OpenSSL allows a variable nonce length and\nfront pads the nonce with 0 bytes if it is less than 12 bytes. However it\nalso incorrectly allows a nonce to be set of up to 16 bytes. In this case\nonly the last 12 bytes are significant and any additional leading bytes are\nignored.\n\nIt is a requirement of using this cipher that nonce values are unique.\nMessages encrypted using a reused nonce value are susceptible to serious\nconfidentiality and integrity attacks. If an application changes the\ndefault nonce length to be longer than 12 bytes and then makes a change to\nthe leading bytes of the nonce expecting the new value to be a new unique\nnonce then such an application could inadvertently encrypt messages with a\nreused nonce.\n\nAdditionally the ignored bytes in a long nonce are not covered by the\nintegrity guarantee of this cipher. Any application that relies on the\nintegrity of these ignored leading bytes of a long nonce may be further\naffected.\n\nAny OpenSSL internal use of this cipher, including in SSL/TLS, is safe\nbecause no such use sets such a long nonce value. However user\napplications that use this cipher directly and set a non-default nonce\nlength to be longer than 12 bytes may be vulnerable.\n\nCVE-2019-1543\n\nFixes #8345\n\nReviewed-by: Paul Dale \nReviewed-by: Richard Levitte \n(Merged from https://github.com/openssl/openssl/pull/8406)\n\n(cherry picked from commit 2a3d0ee9d59156c48973592331404471aca886d6)", "target": 1, "func": "static int chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,\n                                  void *ptr)\n{\n    EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx);\n\n    switch(type) {\n    case EVP_CTRL_INIT:\n        if (actx == NULL)\n            actx = ctx->cipher_data\n                 = OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size());\n        if (actx == NULL) {\n            EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_INITIALIZATION_ERROR);\n            return 0;\n        }\n        actx->len.aad = 0;\n        actx->len.text = 0;\n        actx->aad = 0;\n        actx->mac_inited = 0;\n        actx->tag_len = 0;\n        actx->nonce_len = 12;\n        actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH;\n        memset(actx->tls_aad, 0, POLY1305_BLOCK_SIZE);\n        return 1;\n\n    case EVP_CTRL_COPY:\n        if (actx) {\n            EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr;\n\n            dst->cipher_data =\n                   OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size());\n            if (dst->cipher_data == NULL) {\n                EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_COPY_ERROR);\n                return 0;\n            }\n        }\n        return 1;\n\n    case EVP_CTRL_AEAD_SET_IVLEN:\n        if (arg <= 0 || arg > CHACHA_CTR_SIZE)\n            return 0;\n        actx->nonce_len = arg;\n        return 1;\n\n    case EVP_CTRL_AEAD_SET_IV_FIXED:\n        if (arg != 12)\n            return 0;\n        actx->nonce[0] = actx->key.counter[1]\n                       = CHACHA_U8TOU32((unsigned char *)ptr);\n        actx->nonce[1] = actx->key.counter[2]\n                       = CHACHA_U8TOU32((unsigned char *)ptr+4);\n        actx->nonce[2] = actx->key.counter[3]\n                       = CHACHA_U8TOU32((unsigned char *)ptr+8);\n        return 1;\n\n    case EVP_CTRL_AEAD_SET_TAG:\n        if (arg <= 0 || arg > POLY1305_BLOCK_SIZE)\n            return 0;\n        if (ptr != NULL) {\n            memcpy(actx->tag, ptr, arg);\n            actx->tag_len = arg;\n        }\n        return 1;\n\n    case EVP_CTRL_AEAD_GET_TAG:\n        if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !ctx->encrypt)\n            return 0;\n        memcpy(ptr, actx->tag, arg);\n        return 1;\n\n    case EVP_CTRL_AEAD_TLS1_AAD:\n        if (arg != EVP_AEAD_TLS1_AAD_LEN)\n            return 0;\n        {\n            unsigned int len;\n            unsigned char *aad = ptr;\n\n            memcpy(actx->tls_aad, ptr, EVP_AEAD_TLS1_AAD_LEN);\n            len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 |\n                  aad[EVP_AEAD_TLS1_AAD_LEN - 1];\n            aad = actx->tls_aad;\n            if (!ctx->encrypt) {\n                if (len < POLY1305_BLOCK_SIZE)\n                    return 0;\n                len -= POLY1305_BLOCK_SIZE;     /* discount attached tag */\n                aad[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8);\n                aad[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len;\n            }\n            actx->tls_payload_length = len;\n\n            /*\n             * merge record sequence number as per RFC7905\n             */\n            actx->key.counter[1] = actx->nonce[0];\n            actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad);\n            actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4);\n            actx->mac_inited = 0;\n\n            return POLY1305_BLOCK_SIZE;         /* tag length */\n        }\n\n    case EVP_CTRL_AEAD_SET_MAC_KEY:\n        /* no-op */\n        return 1;\n\n    default:\n        return -1;\n    }\n}", "func_hash": 82290393614199201513765816848927157706, "file_name": "None", "file_hash": null, "cwe": ["CWE-327"], "cve": "CVE-2019-1543", "cve_desc": "ChaCha20-Poly1305 is an AEAD cipher, and requires a unique nonce input for every encryption operation. RFC 7539 specifies that the nonce value (IV) should be 96 bits (12 bytes). OpenSSL allows a variable nonce length and front pads the nonce with 0 bytes if it is less than 12 bytes. However it also incorrectly allows a nonce to be set of up to 16 bytes. In this case only the last 12 bytes are significant and any additional leading bytes are ignored. It is a requirement of using this cipher that nonce values are unique. Messages encrypted using a reused nonce value are susceptible to serious confidentiality and integrity attacks. If an application changes the default nonce length to be longer than 12 bytes and then makes a change to the leading bytes of the nonce expecting the new value to be a new unique nonce then such an application could inadvertently encrypt messages with a reused nonce. Additionally the ignored bytes in a long nonce are not covered by the integrity guarantee of this cipher. Any application that relies on the integrity of these ignored leading bytes of a long nonce may be further affected. Any OpenSSL internal use of this cipher, including in SSL/TLS, is safe because no such use sets such a long nonce value. However user applications that use this cipher directly and set a non-default nonce length to be longer than 12 bytes may be vulnerable. OpenSSL versions 1.1.1 and 1.1.0 are affected by this issue. Due to the limited scope of affected deployments this has been assessed as low severity and therefore we are not creating new releases at this time. Fixed in OpenSSL 1.1.1c (Affected 1.1.1-1.1.1b). Fixed in OpenSSL 1.1.0k (Affected 1.1.0-1.1.0j).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-1543"}
{"idx": 505463, "project": "openssl", "commit_id": "f426625b6ae9a7831010750490a5f0ad689c5ba3", "project_url": "https://github.com/openssl/openssl", "commit_url": "https://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=f426625b6ae9a7831010750490a5f0ad689c5ba3", "commit_message": "Prevent over long nonces in ChaCha20-Poly1305\n\nChaCha20-Poly1305 is an AEAD cipher, and requires a unique nonce input for\nevery encryption operation. RFC 7539 specifies that the nonce value (IV)\nshould be 96 bits (12 bytes). OpenSSL allows a variable nonce length and\nfront pads the nonce with 0 bytes if it is less than 12 bytes. However it\nalso incorrectly allows a nonce to be set of up to 16 bytes. In this case\nonly the last 12 bytes are significant and any additional leading bytes are\nignored.\n\nIt is a requirement of using this cipher that nonce values are unique.\nMessages encrypted using a reused nonce value are susceptible to serious\nconfidentiality and integrity attacks. If an application changes the\ndefault nonce length to be longer than 12 bytes and then makes a change to\nthe leading bytes of the nonce expecting the new value to be a new unique\nnonce then such an application could inadvertently encrypt messages with a\nreused nonce.\n\nAdditionally the ignored bytes in a long nonce are not covered by the\nintegrity guarantee of this cipher. Any application that relies on the\nintegrity of these ignored leading bytes of a long nonce may be further\naffected.\n\nAny OpenSSL internal use of this cipher, including in SSL/TLS, is safe\nbecause no such use sets such a long nonce value. However user\napplications that use this cipher directly and set a non-default nonce\nlength to be longer than 12 bytes may be vulnerable.\n\nCVE-2019-1543\n\nFixes #8345\n\nReviewed-by: Paul Dale \nReviewed-by: Richard Levitte \n(Merged from https://github.com/openssl/openssl/pull/8406)\n\n(cherry picked from commit 2a3d0ee9d59156c48973592331404471aca886d6)", "target": 0, "func": "static int chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,\n                                  void *ptr)\n{\n    EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx);\n\n    switch(type) {\n    case EVP_CTRL_INIT:\n        if (actx == NULL)\n            actx = ctx->cipher_data\n                 = OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size());\n        if (actx == NULL) {\n            EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_INITIALIZATION_ERROR);\n            return 0;\n        }\n        actx->len.aad = 0;\n        actx->len.text = 0;\n        actx->aad = 0;\n        actx->mac_inited = 0;\n        actx->tag_len = 0;\n        actx->nonce_len = 12;\n        actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH;\n        memset(actx->tls_aad, 0, POLY1305_BLOCK_SIZE);\n        return 1;\n\n    case EVP_CTRL_COPY:\n        if (actx) {\n            EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr;\n\n            dst->cipher_data =\n                   OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size());\n            if (dst->cipher_data == NULL) {\n                EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_COPY_ERROR);\n                return 0;\n            }\n        }\n        return 1;\n\n    case EVP_CTRL_AEAD_SET_IVLEN:\n        if (arg <= 0 || arg > CHACHA20_POLY1305_MAX_IVLEN)\n            return 0;\n        actx->nonce_len = arg;\n        return 1;\n\n    case EVP_CTRL_AEAD_SET_IV_FIXED:\n        if (arg != 12)\n            return 0;\n        actx->nonce[0] = actx->key.counter[1]\n                       = CHACHA_U8TOU32((unsigned char *)ptr);\n        actx->nonce[1] = actx->key.counter[2]\n                       = CHACHA_U8TOU32((unsigned char *)ptr+4);\n        actx->nonce[2] = actx->key.counter[3]\n                       = CHACHA_U8TOU32((unsigned char *)ptr+8);\n        return 1;\n\n    case EVP_CTRL_AEAD_SET_TAG:\n        if (arg <= 0 || arg > POLY1305_BLOCK_SIZE)\n            return 0;\n        if (ptr != NULL) {\n            memcpy(actx->tag, ptr, arg);\n            actx->tag_len = arg;\n        }\n        return 1;\n\n    case EVP_CTRL_AEAD_GET_TAG:\n        if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !ctx->encrypt)\n            return 0;\n        memcpy(ptr, actx->tag, arg);\n        return 1;\n\n    case EVP_CTRL_AEAD_TLS1_AAD:\n        if (arg != EVP_AEAD_TLS1_AAD_LEN)\n            return 0;\n        {\n            unsigned int len;\n            unsigned char *aad = ptr;\n\n            memcpy(actx->tls_aad, ptr, EVP_AEAD_TLS1_AAD_LEN);\n            len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 |\n                  aad[EVP_AEAD_TLS1_AAD_LEN - 1];\n            aad = actx->tls_aad;\n            if (!ctx->encrypt) {\n                if (len < POLY1305_BLOCK_SIZE)\n                    return 0;\n                len -= POLY1305_BLOCK_SIZE;     /* discount attached tag */\n                aad[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8);\n                aad[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len;\n            }\n            actx->tls_payload_length = len;\n\n            /*\n             * merge record sequence number as per RFC7905\n             */\n            actx->key.counter[1] = actx->nonce[0];\n            actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad);\n            actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4);\n            actx->mac_inited = 0;\n\n            return POLY1305_BLOCK_SIZE;         /* tag length */\n        }\n\n    case EVP_CTRL_AEAD_SET_MAC_KEY:\n        /* no-op */\n        return 1;\n\n    default:\n        return -1;\n    }\n}", "func_hash": 319328437340198657902119470811531700376, "file_name": "None", "file_hash": null, "cwe": ["CWE-327"], "cve": "CVE-2019-1543", "cve_desc": "ChaCha20-Poly1305 is an AEAD cipher, and requires a unique nonce input for every encryption operation. RFC 7539 specifies that the nonce value (IV) should be 96 bits (12 bytes). OpenSSL allows a variable nonce length and front pads the nonce with 0 bytes if it is less than 12 bytes. However it also incorrectly allows a nonce to be set of up to 16 bytes. In this case only the last 12 bytes are significant and any additional leading bytes are ignored. It is a requirement of using this cipher that nonce values are unique. Messages encrypted using a reused nonce value are susceptible to serious confidentiality and integrity attacks. If an application changes the default nonce length to be longer than 12 bytes and then makes a change to the leading bytes of the nonce expecting the new value to be a new unique nonce then such an application could inadvertently encrypt messages with a reused nonce. Additionally the ignored bytes in a long nonce are not covered by the integrity guarantee of this cipher. Any application that relies on the integrity of these ignored leading bytes of a long nonce may be further affected. Any OpenSSL internal use of this cipher, including in SSL/TLS, is safe because no such use sets such a long nonce value. However user applications that use this cipher directly and set a non-default nonce length to be longer than 12 bytes may be vulnerable. OpenSSL versions 1.1.1 and 1.1.0 are affected by this issue. Due to the limited scope of affected deployments this has been assessed as low severity and therefore we are not creating new releases at this time. Fixed in OpenSSL 1.1.1c (Affected 1.1.1-1.1.1b). Fixed in OpenSSL 1.1.0k (Affected 1.1.0-1.1.0j).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-1543"}
{"idx": 216767, "project": "core", "commit_id": "ed4b7d5d1b30964216d61d3090a7b47a957f5b26", "project_url": "https://github.com/LibreOffice/core", "commit_url": "https://github.com/dovecot/core/commit/ed4b7d5d1b30964216d61d3090a7b47a957f5b26", "commit_message": "lib-smtp: smtp-command-parser - Fix infinite loop occurring when command stream ends in UTF-8 character.\n\nBroken by 8f08f1944be438a2422b604c08e5060b5c7bd72f.", "target": 1, "func": "static int smtp_command_parse_parameters(struct smtp_command_parser *parser)\n{\n\tconst unsigned char *p, *mp;\n\tuoff_t max_size = (parser->auth_response ?\n\t\tparser->limits.max_auth_size :\n\t\tparser->limits.max_parameters_size);\n\n\t/* We assume parameters to match textstr (HT, SP, Printable US-ASCII).\n\t   For command parameters, we also accept valid UTF-8 characters.\n\t */\n\tp = parser->cur + parser->state.poff;\n\twhile (p < parser->end) {\n\t\tunichar_t ch;\n\t\tint nch = 1;\n\n\t\tif (parser->auth_response)\n\t\t\tch = *p;\n\t\telse {\n\t\t\tnch = uni_utf8_get_char_n(p, (size_t)(p - parser->end),\n\t\t\t\t\t\t  &ch);\n\t\t}\n\t\tif (nch < 0) {\n\t\t\tsmtp_command_parser_error(parser,\n\t\t\t\tSMTP_COMMAND_PARSE_ERROR_BAD_COMMAND,\n\t\t\t\t\"Invalid UTF-8 character in command parameters\");\n\t\t\treturn -1;\n\t\t}\n\t\tif ((parser->auth_response || (ch & 0x80) == 0x00) &&\n\t\t    !smtp_char_is_textstr((unsigned char)ch))\n\t\t\tbreak;\n\t\tp += nch;\n\t}\n\tif (max_size > 0 && (uoff_t)(p - parser->cur) > max_size) {\n\t\tsmtp_command_parser_error(parser,\n\t\t\tSMTP_COMMAND_PARSE_ERROR_LINE_TOO_LONG,\n\t\t\t\"%s line is too long\",\n\t\t\t(parser->auth_response ?\n\t\t\t\t\"AUTH response\" : \"Command\"));\n\t\treturn -1;\n\t}\n\tparser->state.poff = p - parser->cur;\n\tif (p == parser->end)\n\t\treturn 0;\n\n\t/* In the interest of improved interoperability, SMTP receivers SHOULD\n\t   tolerate trailing white space before the terminating .\n\n\t   WSP =  SP / HTAB ; white space\n\n\t   --> Trim the end of the buffer\n\t */\n\tmp = p;\n\tif (mp > parser->cur) {\n\t\twhile (mp > parser->cur && (*(mp-1) == ' ' || *(mp-1) == '\\t'))\n\t\t\tmp--;\n\t}\n\n\tif (!parser->auth_response && mp > parser->cur && *parser->cur == ' ') {\n\t\tsmtp_command_parser_error(parser,\n\t\t\tSMTP_COMMAND_PARSE_ERROR_BAD_COMMAND,\n\t\t\t\"Duplicate space after command name\");\n\t\treturn -1;\n\t}\n\n\tparser->state.cmd_params = i_strdup_until(parser->cur, mp);\n\tparser->cur = p;\n\tparser->state.poff = 0;\n\treturn 1;\n}", "func_hash": 181341317141954506069810684888107522957, "file_name": "None", "file_hash": null, "cwe": ["CWE-835"], "cve": "CVE-2020-7046", "cve_desc": "lib-smtp in submission-login and lmtp in Dovecot 2.3.9 before 2.3.9.3 mishandles truncated UTF-8 data in command parameters, as demonstrated by the unauthenticated triggering of a submission-login infinite loop.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-7046"}
{"idx": 505654, "project": "core", "commit_id": "ed4b7d5d1b30964216d61d3090a7b47a957f5b26", "project_url": "https://github.com/LibreOffice/core", "commit_url": "https://github.com/dovecot/core/commit/ed4b7d5d1b30964216d61d3090a7b47a957f5b26", "commit_message": "lib-smtp: smtp-command-parser - Fix infinite loop occurring when command stream ends in UTF-8 character.\n\nBroken by 8f08f1944be438a2422b604c08e5060b5c7bd72f.", "target": 0, "func": "static int smtp_command_parse_parameters(struct smtp_command_parser *parser)\n{\n\tconst unsigned char *p, *mp;\n\tuoff_t max_size = (parser->auth_response ?\n\t\tparser->limits.max_auth_size :\n\t\tparser->limits.max_parameters_size);\n\tint nch = 1;\n\n\t/* We assume parameters to match textstr (HT, SP, Printable US-ASCII).\n\t   For command parameters, we also accept valid UTF-8 characters.\n\t */\n\tp = parser->cur + parser->state.poff;\n\twhile (p < parser->end) {\n\t\tunichar_t ch;\n\n\t\tif (parser->auth_response)\n\t\t\tch = *p;\n\t\telse {\n\t\t\tnch = uni_utf8_get_char_n(p, (size_t)(p - parser->end),\n\t\t\t\t\t\t  &ch);\n\t\t}\n\t\tif (nch == 0)\n\t\t\tbreak;\n\t\tif (nch < 0) {\n\t\t\tsmtp_command_parser_error(parser,\n\t\t\t\tSMTP_COMMAND_PARSE_ERROR_BAD_COMMAND,\n\t\t\t\t\"Invalid UTF-8 character in command parameters\");\n\t\t\treturn -1;\n\t\t}\n\t\tif ((parser->auth_response || (ch & 0x80) == 0x00) &&\n\t\t    !smtp_char_is_textstr((unsigned char)ch))\n\t\t\tbreak;\n\t\tp += nch;\n\t}\n\tif (max_size > 0 && (uoff_t)(p - parser->cur) > max_size) {\n\t\tsmtp_command_parser_error(parser,\n\t\t\tSMTP_COMMAND_PARSE_ERROR_LINE_TOO_LONG,\n\t\t\t\"%s line is too long\",\n\t\t\t(parser->auth_response ?\n\t\t\t\t\"AUTH response\" : \"Command\"));\n\t\treturn -1;\n\t}\n\tparser->state.poff = p - parser->cur;\n\tif (p == parser->end || nch == 0)\n\t\treturn 0;\n\n\t/* In the interest of improved interoperability, SMTP receivers SHOULD\n\t   tolerate trailing white space before the terminating .\n\n\t   WSP =  SP / HTAB ; white space\n\n\t   --> Trim the end of the buffer\n\t */\n\tmp = p;\n\tif (mp > parser->cur) {\n\t\twhile (mp > parser->cur && (*(mp-1) == ' ' || *(mp-1) == '\\t'))\n\t\t\tmp--;\n\t}\n\n\tif (!parser->auth_response && mp > parser->cur && *parser->cur == ' ') {\n\t\tsmtp_command_parser_error(parser,\n\t\t\tSMTP_COMMAND_PARSE_ERROR_BAD_COMMAND,\n\t\t\t\"Duplicate space after command name\");\n\t\treturn -1;\n\t}\n\n\tparser->state.cmd_params = i_strdup_until(parser->cur, mp);\n\tparser->cur = p;\n\tparser->state.poff = 0;\n\treturn 1;\n}", "func_hash": 290259003832263006605358025642064625220, "file_name": "None", "file_hash": null, "cwe": ["CWE-835"], "cve": "CVE-2020-7046", "cve_desc": "lib-smtp in submission-login and lmtp in Dovecot 2.3.9 before 2.3.9.3 mishandles truncated UTF-8 data in command parameters, as demonstrated by the unauthenticated triggering of a submission-login infinite loop.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-7046"}
{"idx": 216800, "project": "core", "commit_id": "69ad3c902ea4bbf9f21ab1857d8923f975dc6145", "project_url": "https://github.com/LibreOffice/core", "commit_url": "https://github.com/dovecot/core/commit/69ad3c902ea4bbf9f21ab1857d8923f975dc6145", "commit_message": "auth: mech-rpa - Fail on zero len buffer", "target": 1, "func": "rpa_read_buffer(pool_t pool, const unsigned char **data,\n\t\tconst unsigned char *end, unsigned char **buffer)\n{\n\tconst unsigned char *p = *data;\n\tunsigned int len;\n\n\tif (p > end)\n\t\treturn 0;\n\n\tlen = *p++;\n\tif (p + len > end)\n\t\treturn 0;\n\n\t*buffer = p_malloc(pool, len);\n\tmemcpy(*buffer, p, len);\n\n\t*data += 1 + len;\n\n\treturn len;\n}", "func_hash": 29472874834578262075169131407750507339, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2020-12674", "cve_desc": "In Dovecot before 2.3.11.3, sending a specially formatted RPA request will crash the auth service because a length of zero is mishandled.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12674"}
{"idx": 506428, "project": "core", "commit_id": "69ad3c902ea4bbf9f21ab1857d8923f975dc6145", "project_url": "https://github.com/LibreOffice/core", "commit_url": "https://github.com/dovecot/core/commit/69ad3c902ea4bbf9f21ab1857d8923f975dc6145", "commit_message": "auth: mech-rpa - Fail on zero len buffer", "target": 0, "func": "rpa_read_buffer(pool_t pool, const unsigned char **data,\n\t\tconst unsigned char *end, unsigned char **buffer)\n{\n\tconst unsigned char *p = *data;\n\tunsigned int len;\n\n\tif (p > end)\n\t\treturn 0;\n\n\tlen = *p++;\n\tif (p + len > end || len == 0)\n\t\treturn 0;\n\n\t*buffer = p_malloc(pool, len);\n\tmemcpy(*buffer, p, len);\n\n\t*data += 1 + len;\n\n\treturn len;\n}", "func_hash": 42033596058129329438262094419912462932, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2020-12674", "cve_desc": "In Dovecot before 2.3.11.3, sending a specially formatted RPA request will crash the auth service because a length of zero is mishandled.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-12674"}
{"idx": 216812, "project": "openssl", "commit_id": "97ab3c4b538840037812c8d9164d09a1f4bf11a1", "project_url": "https://github.com/openssl/openssl", "commit_url": "https://github.com/openssl/openssl/commit/97ab3c4b538840037812c8d9164d09a1f4bf11a1", "commit_message": "Add a test for GENERAL_NAME_cmp\n\nBased on a boringssl test contributed by David Benjamin\n\nReviewed-by: Tomas Mraz ", "target": 1, "func": "int setup_tests(void)\n{\n    ADD_ALL_TESTS(call_run_cert, OSSL_NELEM(name_fns));\n    return 1;\n}", "func_hash": 99734093470067216462803129850987630150, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2020-1971", "cve_desc": "The X.509 GeneralName type is a generic type for representing different types of names. One of those name types is known as EDIPartyName. OpenSSL provides a function GENERAL_NAME_cmp which compares different instances of a GENERAL_NAME to see if they are equal or not. This function behaves incorrectly when both GENERAL_NAMEs contain an EDIPARTYNAME. A NULL pointer dereference and a crash may occur leading to a possible denial of service attack. OpenSSL itself uses the GENERAL_NAME_cmp function for two purposes: 1) Comparing CRL distribution point names between an available CRL and a CRL distribution point embedded in an X509 certificate 2) When verifying that a timestamp response token signer matches the timestamp authority name (exposed via the API functions TS_RESP_verify_response and TS_RESP_verify_token) If an attacker can control both items being compared then that attacker could trigger a crash. For example if the attacker can trick a client or server into checking a malicious certificate against a malicious CRL then this may occur. Note that some applications automatically download CRLs based on a URL embedded in a certificate. This checking happens prior to the signatures on the certificate and CRL being verified. OpenSSL's s_server, s_client and verify tools have support for the \"-crl_download\" option which implements automatic CRL downloading and this attack has been demonstrated to work against those tools. Note that an unrelated bug means that affected versions of OpenSSL cannot parse or construct correct encodings of EDIPARTYNAME. However it is possible to construct a malformed EDIPARTYNAME that OpenSSL's parser will accept and hence trigger this attack. All OpenSSL 1.1.1 and 1.0.2 versions are affected by this issue. Other OpenSSL releases are out of support and have not been checked. Fixed in OpenSSL 1.1.1i (Affected 1.1.1-1.1.1h). Fixed in OpenSSL 1.0.2x (Affected 1.0.2-1.0.2w).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1971"}
{"idx": 506696, "project": "openssl", "commit_id": "97ab3c4b538840037812c8d9164d09a1f4bf11a1", "project_url": "https://github.com/openssl/openssl", "commit_url": "https://github.com/openssl/openssl/commit/97ab3c4b538840037812c8d9164d09a1f4bf11a1", "commit_message": "Add a test for GENERAL_NAME_cmp\n\nBased on a boringssl test contributed by David Benjamin\n\nReviewed-by: Tomas Mraz ", "target": 0, "func": "int setup_tests(void)\n{\n    ADD_ALL_TESTS(call_run_cert, OSSL_NELEM(name_fns));\n    ADD_TEST(test_GENERAL_NAME_cmp);\n    return 1;\n}", "func_hash": 300508003271249901349188890485879920788, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2020-1971", "cve_desc": "The X.509 GeneralName type is a generic type for representing different types of names. One of those name types is known as EDIPartyName. OpenSSL provides a function GENERAL_NAME_cmp which compares different instances of a GENERAL_NAME to see if they are equal or not. This function behaves incorrectly when both GENERAL_NAMEs contain an EDIPARTYNAME. A NULL pointer dereference and a crash may occur leading to a possible denial of service attack. OpenSSL itself uses the GENERAL_NAME_cmp function for two purposes: 1) Comparing CRL distribution point names between an available CRL and a CRL distribution point embedded in an X509 certificate 2) When verifying that a timestamp response token signer matches the timestamp authority name (exposed via the API functions TS_RESP_verify_response and TS_RESP_verify_token) If an attacker can control both items being compared then that attacker could trigger a crash. For example if the attacker can trick a client or server into checking a malicious certificate against a malicious CRL then this may occur. Note that some applications automatically download CRLs based on a URL embedded in a certificate. This checking happens prior to the signatures on the certificate and CRL being verified. OpenSSL's s_server, s_client and verify tools have support for the \"-crl_download\" option which implements automatic CRL downloading and this attack has been demonstrated to work against those tools. Note that an unrelated bug means that affected versions of OpenSSL cannot parse or construct correct encodings of EDIPARTYNAME. However it is possible to construct a malformed EDIPARTYNAME that OpenSSL's parser will accept and hence trigger this attack. All OpenSSL 1.1.1 and 1.0.2 versions are affected by this issue. Other OpenSSL releases are out of support and have not been checked. Fixed in OpenSSL 1.1.1i (Affected 1.1.1-1.1.1h). Fixed in OpenSSL 1.0.2x (Affected 1.0.2-1.0.2w).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2020-1971"}
{"idx": 216861, "project": "openssl", "commit_id": "94d23fcff9b2a7a8368dfe52214d5c2569882c11", "project_url": "https://github.com/openssl/openssl", "commit_url": "https://github.com/openssl/openssl/commit/94d23fcff9b2a7a8368dfe52214d5c2569882c11", "commit_message": "Fix EC_GROUP_new_from_ecparameters to check the base length\n\nCheck that there's at least one byte in params->base before trying to\nread it.\n\nCVE-2021-3712\n\nReviewed-by: Viktor Dukhovni \nReviewed-by: Paul Dale ", "target": 1, "func": "EC_GROUP *EC_GROUP_new_from_ecparameters(const ECPARAMETERS *params)\n{\n    int ok = 0, tmp;\n    EC_GROUP *ret = NULL, *dup = NULL;\n    BIGNUM *p = NULL, *a = NULL, *b = NULL;\n    EC_POINT *point = NULL;\n    long field_bits;\n    int curve_name = NID_undef;\n    BN_CTX *ctx = NULL;\n\n    if (!params->fieldID || !params->fieldID->fieldType ||\n        !params->fieldID->p.ptr) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n        goto err;\n    }\n\n    /*\n     * Now extract the curve parameters a and b. Note that, although SEC 1\n     * specifies the length of their encodings, historical versions of OpenSSL\n     * encoded them incorrectly, so we must accept any length for backwards\n     * compatibility.\n     */\n    if (!params->curve || !params->curve->a ||\n        !params->curve->a->data || !params->curve->b ||\n        !params->curve->b->data) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n        goto err;\n    }\n    a = BN_bin2bn(params->curve->a->data, params->curve->a->length, NULL);\n    if (a == NULL) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_BN_LIB);\n        goto err;\n    }\n    b = BN_bin2bn(params->curve->b->data, params->curve->b->length, NULL);\n    if (b == NULL) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_BN_LIB);\n        goto err;\n    }\n\n    /* get the field parameters */\n    tmp = OBJ_obj2nid(params->fieldID->fieldType);\n    if (tmp == NID_X9_62_characteristic_two_field)\n#ifdef OPENSSL_NO_EC2M\n    {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_GF2M_NOT_SUPPORTED);\n        goto err;\n    }\n#else\n    {\n        X9_62_CHARACTERISTIC_TWO *char_two;\n\n        char_two = params->fieldID->p.char_two;\n\n        field_bits = char_two->m;\n        if (field_bits > OPENSSL_ECC_MAX_FIELD_BITS) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_FIELD_TOO_LARGE);\n            goto err;\n        }\n\n        if ((p = BN_new()) == NULL) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_MALLOC_FAILURE);\n            goto err;\n        }\n\n        /* get the base type */\n        tmp = OBJ_obj2nid(char_two->type);\n\n        if (tmp == NID_X9_62_tpBasis) {\n            long tmp_long;\n\n            if (!char_two->p.tpBasis) {\n                ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n                goto err;\n            }\n\n            tmp_long = ASN1_INTEGER_get(char_two->p.tpBasis);\n\n            if (!(char_two->m > tmp_long && tmp_long > 0)) {\n                ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS,\n                      EC_R_INVALID_TRINOMIAL_BASIS);\n                goto err;\n            }\n\n            /* create the polynomial */\n            if (!BN_set_bit(p, (int)char_two->m))\n                goto err;\n            if (!BN_set_bit(p, (int)tmp_long))\n                goto err;\n            if (!BN_set_bit(p, 0))\n                goto err;\n        } else if (tmp == NID_X9_62_ppBasis) {\n            X9_62_PENTANOMIAL *penta;\n\n            penta = char_two->p.ppBasis;\n            if (!penta) {\n                ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n                goto err;\n            }\n\n            if (!\n                (char_two->m > penta->k3 && penta->k3 > penta->k2\n                 && penta->k2 > penta->k1 && penta->k1 > 0)) {\n                ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS,\n                      EC_R_INVALID_PENTANOMIAL_BASIS);\n                goto err;\n            }\n\n            /* create the polynomial */\n            if (!BN_set_bit(p, (int)char_two->m))\n                goto err;\n            if (!BN_set_bit(p, (int)penta->k1))\n                goto err;\n            if (!BN_set_bit(p, (int)penta->k2))\n                goto err;\n            if (!BN_set_bit(p, (int)penta->k3))\n                goto err;\n            if (!BN_set_bit(p, 0))\n                goto err;\n        } else if (tmp == NID_X9_62_onBasis) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_NOT_IMPLEMENTED);\n            goto err;\n        } else {                /* error */\n\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n            goto err;\n        }\n\n        /* create the EC_GROUP structure */\n        ret = EC_GROUP_new_curve_GF2m(p, a, b, NULL);\n    }\n#endif\n    else if (tmp == NID_X9_62_prime_field) {\n        /* we have a curve over a prime field */\n        /* extract the prime number */\n        if (!params->fieldID->p.prime) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n            goto err;\n        }\n        p = ASN1_INTEGER_to_BN(params->fieldID->p.prime, NULL);\n        if (p == NULL) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_ASN1_LIB);\n            goto err;\n        }\n\n        if (BN_is_negative(p) || BN_is_zero(p)) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_INVALID_FIELD);\n            goto err;\n        }\n\n        field_bits = BN_num_bits(p);\n        if (field_bits > OPENSSL_ECC_MAX_FIELD_BITS) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_FIELD_TOO_LARGE);\n            goto err;\n        }\n\n        /* create the EC_GROUP structure */\n        ret = EC_GROUP_new_curve_GFp(p, a, b, NULL);\n    } else {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_INVALID_FIELD);\n        goto err;\n    }\n\n    if (ret == NULL) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);\n        goto err;\n    }\n\n    /* extract seed (optional) */\n    if (params->curve->seed != NULL) {\n        OPENSSL_free(ret->seed);\n        if ((ret->seed = OPENSSL_malloc(params->curve->seed->length)) == NULL) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_MALLOC_FAILURE);\n            goto err;\n        }\n        memcpy(ret->seed, params->curve->seed->data,\n               params->curve->seed->length);\n        ret->seed_len = params->curve->seed->length;\n    }\n\n    if (!params->order || !params->base || !params->base->data) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n        goto err;\n    }\n\n    if ((point = EC_POINT_new(ret)) == NULL)\n        goto err;\n\n    /* set the point conversion form */\n    EC_GROUP_set_point_conversion_form(ret, (point_conversion_form_t)\n                                       (params->base->data[0] & ~0x01));\n\n    /* extract the ec point */\n    if (!EC_POINT_oct2point(ret, point, params->base->data,\n                            params->base->length, NULL)) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);\n        goto err;\n    }\n\n    /* extract the order */\n    if ((a = ASN1_INTEGER_to_BN(params->order, a)) == NULL) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_ASN1_LIB);\n        goto err;\n    }\n    if (BN_is_negative(a) || BN_is_zero(a)) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_INVALID_GROUP_ORDER);\n        goto err;\n    }\n    if (BN_num_bits(a) > (int)field_bits + 1) { /* Hasse bound */\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_INVALID_GROUP_ORDER);\n        goto err;\n    }\n\n    /* extract the cofactor (optional) */\n    if (params->cofactor == NULL) {\n        BN_free(b);\n        b = NULL;\n    } else if ((b = ASN1_INTEGER_to_BN(params->cofactor, b)) == NULL) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_ASN1_LIB);\n        goto err;\n    }\n    /* set the generator, order and cofactor (if present) */\n    if (!EC_GROUP_set_generator(ret, point, a, b)) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);\n        goto err;\n    }\n\n    /*\n     * Check if the explicit parameters group just created matches one of the\n     * built-in curves.\n     *\n     * We create a copy of the group just built, so that we can remove optional\n     * fields for the lookup: we do this to avoid the possibility that one of\n     * the optional parameters is used to force the library into using a less\n     * performant and less secure EC_METHOD instead of the specialized one.\n     * In any case, `seed` is not really used in any computation, while a\n     * cofactor different from the one in the built-in table is just\n     * mathematically wrong anyway and should not be used.\n     */\n    if ((ctx = BN_CTX_new()) == NULL) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_BN_LIB);\n        goto err;\n    }\n    if ((dup = EC_GROUP_dup(ret)) == NULL\n            || EC_GROUP_set_seed(dup, NULL, 0) != 1\n            || !EC_GROUP_set_generator(dup, point, a, NULL)) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);\n        goto err;\n    }\n    if ((curve_name = ec_curve_nid_from_params(dup, ctx)) != NID_undef) {\n        /*\n         * The input explicit parameters successfully matched one of the\n         * built-in curves: often for built-in curves we have specialized\n         * methods with better performance and hardening.\n         *\n         * In this case we replace the `EC_GROUP` created through explicit\n         * parameters with one created from a named group.\n         */\n        EC_GROUP *named_group = NULL;\n\n#ifndef OPENSSL_NO_EC_NISTP_64_GCC_128\n        /*\n         * NID_wap_wsg_idm_ecid_wtls12 and NID_secp224r1 are both aliases for\n         * the same curve, we prefer the SECP nid when matching explicit\n         * parameters as that is associated with a specialized EC_METHOD.\n         */\n        if (curve_name == NID_wap_wsg_idm_ecid_wtls12)\n            curve_name = NID_secp224r1;\n#endif /* !def(OPENSSL_NO_EC_NISTP_64_GCC_128) */\n\n        if ((named_group = EC_GROUP_new_by_curve_name(curve_name)) == NULL) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);\n            goto err;\n        }\n        EC_GROUP_free(ret);\n        ret = named_group;\n\n        /*\n         * Set the flag so that EC_GROUPs created from explicit parameters are\n         * serialized using explicit parameters by default.\n         */\n        EC_GROUP_set_asn1_flag(ret, OPENSSL_EC_EXPLICIT_CURVE);\n\n        /*\n         * If the input params do not contain the optional seed field we make\n         * sure it is not added to the returned group.\n         *\n         * The seed field is not really used inside libcrypto anyway, and\n         * adding it to parsed explicit parameter keys would alter their DER\n         * encoding output (because of the extra field) which could impact\n         * applications fingerprinting keys by their DER encoding.\n         */\n        if (params->curve->seed == NULL) {\n            if (EC_GROUP_set_seed(ret, NULL, 0) != 1)\n                goto err;\n        }\n    }\n\n    ok = 1;\n\n err:\n    if (!ok) {\n        EC_GROUP_free(ret);\n        ret = NULL;\n    }\n    EC_GROUP_free(dup);\n\n    BN_free(p);\n    BN_free(a);\n    BN_free(b);\n    EC_POINT_free(point);\n\n    BN_CTX_free(ctx);\n\n    return ret;\n}", "func_hash": 80540639516178112864890741931948685257, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2021-3712", "cve_desc": "ASN.1 strings are represented internally within OpenSSL as an ASN1_STRING structure which contains a buffer holding the string data and a field holding the buffer length. This contrasts with normal C strings which are repesented as a buffer for the string data which is terminated with a NUL (0) byte. Although not a strict requirement, ASN.1 strings that are parsed using OpenSSL's own \"d2i\" functions (and other similar parsing functions) as well as any string whose value has been set with the ASN1_STRING_set() function will additionally NUL terminate the byte array in the ASN1_STRING structure. However, it is possible for applications to directly construct valid ASN1_STRING structures which do not NUL terminate the byte array by directly setting the \"data\" and \"length\" fields in the ASN1_STRING array. This can also happen by using the ASN1_STRING_set0() function. Numerous OpenSSL functions that print ASN.1 data have been found to assume that the ASN1_STRING byte array will be NUL terminated, even though this is not guaranteed for strings that have been directly constructed. Where an application requests an ASN.1 structure to be printed, and where that ASN.1 structure contains ASN1_STRINGs that have been directly constructed by the application without NUL terminating the \"data\" field, then a read buffer overrun can occur. The same thing can also occur during name constraints processing of certificates (for example if a certificate has been directly constructed by the application instead of loading it via the OpenSSL parsing functions, and the certificate contains non NUL terminated ASN1_STRING structures). It can also occur in the X509_get1_email(), X509_REQ_get1_email() and X509_get1_ocsp() functions. If a malicious actor can cause an application to directly construct an ASN1_STRING and then process it through one of the affected OpenSSL functions then this issue could be hit. This might result in a crash (causing a Denial of Service attack). It could also result in the disclosure of private memory contents (such as private keys, or sensitive plaintext). Fixed in OpenSSL 1.1.1l (Affected 1.1.1-1.1.1k). Fixed in OpenSSL 1.0.2za (Affected 1.0.2-1.0.2y).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3712"}
{"idx": 507778, "project": "openssl", "commit_id": "94d23fcff9b2a7a8368dfe52214d5c2569882c11", "project_url": "https://github.com/openssl/openssl", "commit_url": "https://github.com/openssl/openssl/commit/94d23fcff9b2a7a8368dfe52214d5c2569882c11", "commit_message": "Fix EC_GROUP_new_from_ecparameters to check the base length\n\nCheck that there's at least one byte in params->base before trying to\nread it.\n\nCVE-2021-3712\n\nReviewed-by: Viktor Dukhovni \nReviewed-by: Paul Dale ", "target": 0, "func": "EC_GROUP *EC_GROUP_new_from_ecparameters(const ECPARAMETERS *params)\n{\n    int ok = 0, tmp;\n    EC_GROUP *ret = NULL, *dup = NULL;\n    BIGNUM *p = NULL, *a = NULL, *b = NULL;\n    EC_POINT *point = NULL;\n    long field_bits;\n    int curve_name = NID_undef;\n    BN_CTX *ctx = NULL;\n\n    if (!params->fieldID || !params->fieldID->fieldType ||\n        !params->fieldID->p.ptr) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n        goto err;\n    }\n\n    /*\n     * Now extract the curve parameters a and b. Note that, although SEC 1\n     * specifies the length of their encodings, historical versions of OpenSSL\n     * encoded them incorrectly, so we must accept any length for backwards\n     * compatibility.\n     */\n    if (!params->curve || !params->curve->a ||\n        !params->curve->a->data || !params->curve->b ||\n        !params->curve->b->data) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n        goto err;\n    }\n    a = BN_bin2bn(params->curve->a->data, params->curve->a->length, NULL);\n    if (a == NULL) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_BN_LIB);\n        goto err;\n    }\n    b = BN_bin2bn(params->curve->b->data, params->curve->b->length, NULL);\n    if (b == NULL) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_BN_LIB);\n        goto err;\n    }\n\n    /* get the field parameters */\n    tmp = OBJ_obj2nid(params->fieldID->fieldType);\n    if (tmp == NID_X9_62_characteristic_two_field)\n#ifdef OPENSSL_NO_EC2M\n    {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_GF2M_NOT_SUPPORTED);\n        goto err;\n    }\n#else\n    {\n        X9_62_CHARACTERISTIC_TWO *char_two;\n\n        char_two = params->fieldID->p.char_two;\n\n        field_bits = char_two->m;\n        if (field_bits > OPENSSL_ECC_MAX_FIELD_BITS) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_FIELD_TOO_LARGE);\n            goto err;\n        }\n\n        if ((p = BN_new()) == NULL) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_MALLOC_FAILURE);\n            goto err;\n        }\n\n        /* get the base type */\n        tmp = OBJ_obj2nid(char_two->type);\n\n        if (tmp == NID_X9_62_tpBasis) {\n            long tmp_long;\n\n            if (!char_two->p.tpBasis) {\n                ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n                goto err;\n            }\n\n            tmp_long = ASN1_INTEGER_get(char_two->p.tpBasis);\n\n            if (!(char_two->m > tmp_long && tmp_long > 0)) {\n                ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS,\n                      EC_R_INVALID_TRINOMIAL_BASIS);\n                goto err;\n            }\n\n            /* create the polynomial */\n            if (!BN_set_bit(p, (int)char_two->m))\n                goto err;\n            if (!BN_set_bit(p, (int)tmp_long))\n                goto err;\n            if (!BN_set_bit(p, 0))\n                goto err;\n        } else if (tmp == NID_X9_62_ppBasis) {\n            X9_62_PENTANOMIAL *penta;\n\n            penta = char_two->p.ppBasis;\n            if (!penta) {\n                ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n                goto err;\n            }\n\n            if (!\n                (char_two->m > penta->k3 && penta->k3 > penta->k2\n                 && penta->k2 > penta->k1 && penta->k1 > 0)) {\n                ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS,\n                      EC_R_INVALID_PENTANOMIAL_BASIS);\n                goto err;\n            }\n\n            /* create the polynomial */\n            if (!BN_set_bit(p, (int)char_two->m))\n                goto err;\n            if (!BN_set_bit(p, (int)penta->k1))\n                goto err;\n            if (!BN_set_bit(p, (int)penta->k2))\n                goto err;\n            if (!BN_set_bit(p, (int)penta->k3))\n                goto err;\n            if (!BN_set_bit(p, 0))\n                goto err;\n        } else if (tmp == NID_X9_62_onBasis) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_NOT_IMPLEMENTED);\n            goto err;\n        } else {                /* error */\n\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n            goto err;\n        }\n\n        /* create the EC_GROUP structure */\n        ret = EC_GROUP_new_curve_GF2m(p, a, b, NULL);\n    }\n#endif\n    else if (tmp == NID_X9_62_prime_field) {\n        /* we have a curve over a prime field */\n        /* extract the prime number */\n        if (!params->fieldID->p.prime) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n            goto err;\n        }\n        p = ASN1_INTEGER_to_BN(params->fieldID->p.prime, NULL);\n        if (p == NULL) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_ASN1_LIB);\n            goto err;\n        }\n\n        if (BN_is_negative(p) || BN_is_zero(p)) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_INVALID_FIELD);\n            goto err;\n        }\n\n        field_bits = BN_num_bits(p);\n        if (field_bits > OPENSSL_ECC_MAX_FIELD_BITS) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_FIELD_TOO_LARGE);\n            goto err;\n        }\n\n        /* create the EC_GROUP structure */\n        ret = EC_GROUP_new_curve_GFp(p, a, b, NULL);\n    } else {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_INVALID_FIELD);\n        goto err;\n    }\n\n    if (ret == NULL) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);\n        goto err;\n    }\n\n    /* extract seed (optional) */\n    if (params->curve->seed != NULL) {\n        OPENSSL_free(ret->seed);\n        if ((ret->seed = OPENSSL_malloc(params->curve->seed->length)) == NULL) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_MALLOC_FAILURE);\n            goto err;\n        }\n        memcpy(ret->seed, params->curve->seed->data,\n               params->curve->seed->length);\n        ret->seed_len = params->curve->seed->length;\n    }\n\n    if (params->order == NULL\n            || params->base == NULL\n            || params->base->data == NULL\n            || params->base->length == 0) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);\n        goto err;\n    }\n\n    if ((point = EC_POINT_new(ret)) == NULL)\n        goto err;\n\n    /* set the point conversion form */\n    EC_GROUP_set_point_conversion_form(ret, (point_conversion_form_t)\n                                       (params->base->data[0] & ~0x01));\n\n    /* extract the ec point */\n    if (!EC_POINT_oct2point(ret, point, params->base->data,\n                            params->base->length, NULL)) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);\n        goto err;\n    }\n\n    /* extract the order */\n    if ((a = ASN1_INTEGER_to_BN(params->order, a)) == NULL) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_ASN1_LIB);\n        goto err;\n    }\n    if (BN_is_negative(a) || BN_is_zero(a)) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_INVALID_GROUP_ORDER);\n        goto err;\n    }\n    if (BN_num_bits(a) > (int)field_bits + 1) { /* Hasse bound */\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_INVALID_GROUP_ORDER);\n        goto err;\n    }\n\n    /* extract the cofactor (optional) */\n    if (params->cofactor == NULL) {\n        BN_free(b);\n        b = NULL;\n    } else if ((b = ASN1_INTEGER_to_BN(params->cofactor, b)) == NULL) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_ASN1_LIB);\n        goto err;\n    }\n    /* set the generator, order and cofactor (if present) */\n    if (!EC_GROUP_set_generator(ret, point, a, b)) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);\n        goto err;\n    }\n\n    /*\n     * Check if the explicit parameters group just created matches one of the\n     * built-in curves.\n     *\n     * We create a copy of the group just built, so that we can remove optional\n     * fields for the lookup: we do this to avoid the possibility that one of\n     * the optional parameters is used to force the library into using a less\n     * performant and less secure EC_METHOD instead of the specialized one.\n     * In any case, `seed` is not really used in any computation, while a\n     * cofactor different from the one in the built-in table is just\n     * mathematically wrong anyway and should not be used.\n     */\n    if ((ctx = BN_CTX_new()) == NULL) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_BN_LIB);\n        goto err;\n    }\n    if ((dup = EC_GROUP_dup(ret)) == NULL\n            || EC_GROUP_set_seed(dup, NULL, 0) != 1\n            || !EC_GROUP_set_generator(dup, point, a, NULL)) {\n        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);\n        goto err;\n    }\n    if ((curve_name = ec_curve_nid_from_params(dup, ctx)) != NID_undef) {\n        /*\n         * The input explicit parameters successfully matched one of the\n         * built-in curves: often for built-in curves we have specialized\n         * methods with better performance and hardening.\n         *\n         * In this case we replace the `EC_GROUP` created through explicit\n         * parameters with one created from a named group.\n         */\n        EC_GROUP *named_group = NULL;\n\n#ifndef OPENSSL_NO_EC_NISTP_64_GCC_128\n        /*\n         * NID_wap_wsg_idm_ecid_wtls12 and NID_secp224r1 are both aliases for\n         * the same curve, we prefer the SECP nid when matching explicit\n         * parameters as that is associated with a specialized EC_METHOD.\n         */\n        if (curve_name == NID_wap_wsg_idm_ecid_wtls12)\n            curve_name = NID_secp224r1;\n#endif /* !def(OPENSSL_NO_EC_NISTP_64_GCC_128) */\n\n        if ((named_group = EC_GROUP_new_by_curve_name(curve_name)) == NULL) {\n            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);\n            goto err;\n        }\n        EC_GROUP_free(ret);\n        ret = named_group;\n\n        /*\n         * Set the flag so that EC_GROUPs created from explicit parameters are\n         * serialized using explicit parameters by default.\n         */\n        EC_GROUP_set_asn1_flag(ret, OPENSSL_EC_EXPLICIT_CURVE);\n\n        /*\n         * If the input params do not contain the optional seed field we make\n         * sure it is not added to the returned group.\n         *\n         * The seed field is not really used inside libcrypto anyway, and\n         * adding it to parsed explicit parameter keys would alter their DER\n         * encoding output (because of the extra field) which could impact\n         * applications fingerprinting keys by their DER encoding.\n         */\n        if (params->curve->seed == NULL) {\n            if (EC_GROUP_set_seed(ret, NULL, 0) != 1)\n                goto err;\n        }\n    }\n\n    ok = 1;\n\n err:\n    if (!ok) {\n        EC_GROUP_free(ret);\n        ret = NULL;\n    }\n    EC_GROUP_free(dup);\n\n    BN_free(p);\n    BN_free(a);\n    BN_free(b);\n    EC_POINT_free(point);\n\n    BN_CTX_free(ctx);\n\n    return ret;\n}", "func_hash": 230738893451780669362858497865794698672, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2021-3712", "cve_desc": "ASN.1 strings are represented internally within OpenSSL as an ASN1_STRING structure which contains a buffer holding the string data and a field holding the buffer length. This contrasts with normal C strings which are repesented as a buffer for the string data which is terminated with a NUL (0) byte. Although not a strict requirement, ASN.1 strings that are parsed using OpenSSL's own \"d2i\" functions (and other similar parsing functions) as well as any string whose value has been set with the ASN1_STRING_set() function will additionally NUL terminate the byte array in the ASN1_STRING structure. However, it is possible for applications to directly construct valid ASN1_STRING structures which do not NUL terminate the byte array by directly setting the \"data\" and \"length\" fields in the ASN1_STRING array. This can also happen by using the ASN1_STRING_set0() function. Numerous OpenSSL functions that print ASN.1 data have been found to assume that the ASN1_STRING byte array will be NUL terminated, even though this is not guaranteed for strings that have been directly constructed. Where an application requests an ASN.1 structure to be printed, and where that ASN.1 structure contains ASN1_STRINGs that have been directly constructed by the application without NUL terminating the \"data\" field, then a read buffer overrun can occur. The same thing can also occur during name constraints processing of certificates (for example if a certificate has been directly constructed by the application instead of loading it via the OpenSSL parsing functions, and the certificate contains non NUL terminated ASN1_STRING structures). It can also occur in the X509_get1_email(), X509_REQ_get1_email() and X509_get1_ocsp() functions. If a malicious actor can cause an application to directly construct an ASN1_STRING and then process it through one of the affected OpenSSL functions then this issue could be hit. This might result in a crash (causing a Denial of Service attack). It could also result in the disclosure of private memory contents (such as private keys, or sensitive plaintext). Fixed in OpenSSL 1.1.1l (Affected 1.1.1-1.1.1k). Fixed in OpenSSL 1.0.2za (Affected 1.0.2-1.0.2y).", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-3712"}
{"idx": 216903, "project": "server", "commit_id": "3a52569499e2f0c4d1f25db1e81617a9d9755400", "project_url": "https://github.com/MariaDB/server", "commit_url": "https://github.com/MariaDB/server/commit/3a52569499e2f0c4d1f25db1e81617a9d9755400", "commit_message": "MDEV-25636: Bug report: abortion in sql/sql_parse.cc:6294\n\nThe asserion failure was caused by this query\n\n  select /*id=1*/ from t1\n  where\n   col= ( select /*id=2*/ from ... where corr_cond1\n          union\n          select /*id=4*/ from ... where corr_cond2)\n\nHere,\n- select with id=2 was correlated due to corr_cond1.\n- select with id=4 was initially correlated due to corr_cond2, but then\n  the optimizer optimized away the correlation, making the select with id=4\n  uncorrelated.\n\nHowever, since select with id=2 remained correlated, the execution had to\nre-compute the whole UNION. When it tried to execute select with id=4, it\nhit an assertion  (join buffer already free'd).\n\nThis is because select with id=4 has freed its execution structures after\nit has been executed once. The select is uncorrelated, so it did not expect\nit would need to be executed for the second time.\n\nFixed this by adding this logic in\nst_select_lex::optimize_unflattened_subqueries():\n\n  If a member of a UNION is correlated, mark all its members as\n  correlated, so that they are prepared to be executed multiple times.", "target": 1, "func": "bool st_select_lex::optimize_unflattened_subqueries(bool const_only)\n{\n  SELECT_LEX_UNIT *next_unit= NULL;\n  for (SELECT_LEX_UNIT *un= first_inner_unit();\n       un;\n       un= next_unit ? next_unit : un->next_unit())\n  {\n    Item_subselect *subquery_predicate= un->item;\n    next_unit= NULL;\n\n    if (subquery_predicate)\n    {\n      if (!subquery_predicate->fixed)\n      {\n\t/*\n\t This subquery was excluded as part of some expression so it is\n\t invisible from all prepared expression.\n       */\n\tnext_unit= un->next_unit();\n\tun->exclude_level();\n\tif (next_unit)\n\t  continue;\n\tbreak;\n      }\n      if (subquery_predicate->substype() == Item_subselect::IN_SUBS)\n      {\n        Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;\n        if (in_subs->is_jtbm_merged)\n          continue;\n      }\n\n      if (const_only && !subquery_predicate->const_item())\n      {\n        /* Skip non-constant subqueries if the caller asked so. */\n        continue;\n      }\n\n      bool empty_union_result= true;\n      bool is_correlated_unit= false;\n      bool first= true;\n      bool union_plan_saved= false;\n      /*\n        If the subquery is a UNION, optimize all the subqueries in the UNION. If\n        there is no UNION, then the loop will execute once for the subquery.\n      */\n      for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())\n      {\n        JOIN *inner_join= sl->join;\n        if (first)\n          first= false;\n        else\n        {\n          if (!union_plan_saved)\n          {\n            union_plan_saved= true;\n            if (un->save_union_explain(un->thd->lex->explain))\n              return true; /* Failure */\n          }\n        }\n        if (!inner_join)\n          continue;\n        SELECT_LEX *save_select= un->thd->lex->current_select;\n        ulonglong save_options;\n        int res;\n        /* We need only 1 row to determine existence */\n        un->set_limit(un->global_parameters());\n        un->thd->lex->current_select= sl;\n        save_options= inner_join->select_options;\n        if (options & SELECT_DESCRIBE)\n        {\n          /* Optimize the subquery in the context of EXPLAIN. */\n          sl->set_explain_type(FALSE);\n          sl->options|= SELECT_DESCRIBE;\n          inner_join->select_options|= SELECT_DESCRIBE;\n        }\n        if ((res= inner_join->optimize()))\n          return TRUE;\n        if (!inner_join->cleaned)\n          sl->update_used_tables();\n        sl->update_correlated_cache();\n        is_correlated_unit|= sl->is_correlated;\n        inner_join->select_options= save_options;\n        un->thd->lex->current_select= save_select;\n\n        Explain_query *eq;\n        if ((eq= inner_join->thd->lex->explain))\n        {\n          Explain_select *expl_sel;\n          if ((expl_sel= eq->get_select(inner_join->select_lex->select_number)))\n          {\n            sl->set_explain_type(TRUE);\n            expl_sel->select_type= sl->type;\n          }\n        }\n\n        if (empty_union_result)\n        {\n          /*\n            If at least one subquery in a union is non-empty, the UNION result\n            is non-empty. If there is no UNION, the only subquery is non-empy.\n          */\n          empty_union_result= inner_join->empty_result();\n        }\n        if (res)\n          return TRUE;\n      }\n      if (empty_union_result)\n        subquery_predicate->no_rows_in_result();\n      if (!is_correlated_unit)\n        un->uncacheable&= ~UNCACHEABLE_DEPENDENT;\n      subquery_predicate->is_correlated= is_correlated_unit;\n    }\n  }\n  return FALSE;\n}", "func_hash": 170977446789514176182113064369700449502, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2021-46664", "cve_desc": "MariaDB through 10.5.9 allows an application crash in sub_select_postjoin_aggr for a NULL value of aggr.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46664"}
{"idx": 508874, "project": "server", "commit_id": "3a52569499e2f0c4d1f25db1e81617a9d9755400", "project_url": "https://github.com/MariaDB/server", "commit_url": "https://github.com/MariaDB/server/commit/3a52569499e2f0c4d1f25db1e81617a9d9755400", "commit_message": "MDEV-25636: Bug report: abortion in sql/sql_parse.cc:6294\n\nThe asserion failure was caused by this query\n\n  select /*id=1*/ from t1\n  where\n   col= ( select /*id=2*/ from ... where corr_cond1\n          union\n          select /*id=4*/ from ... where corr_cond2)\n\nHere,\n- select with id=2 was correlated due to corr_cond1.\n- select with id=4 was initially correlated due to corr_cond2, but then\n  the optimizer optimized away the correlation, making the select with id=4\n  uncorrelated.\n\nHowever, since select with id=2 remained correlated, the execution had to\nre-compute the whole UNION. When it tried to execute select with id=4, it\nhit an assertion  (join buffer already free'd).\n\nThis is because select with id=4 has freed its execution structures after\nit has been executed once. The select is uncorrelated, so it did not expect\nit would need to be executed for the second time.\n\nFixed this by adding this logic in\nst_select_lex::optimize_unflattened_subqueries():\n\n  If a member of a UNION is correlated, mark all its members as\n  correlated, so that they are prepared to be executed multiple times.", "target": 0, "func": "bool st_select_lex::optimize_unflattened_subqueries(bool const_only)\n{\n  SELECT_LEX_UNIT *next_unit= NULL;\n  for (SELECT_LEX_UNIT *un= first_inner_unit();\n       un;\n       un= next_unit ? next_unit : un->next_unit())\n  {\n    Item_subselect *subquery_predicate= un->item;\n    next_unit= NULL;\n\n    if (subquery_predicate)\n    {\n      if (!subquery_predicate->fixed)\n      {\n\t/*\n\t This subquery was excluded as part of some expression so it is\n\t invisible from all prepared expression.\n       */\n\tnext_unit= un->next_unit();\n\tun->exclude_level();\n\tif (next_unit)\n\t  continue;\n\tbreak;\n      }\n      if (subquery_predicate->substype() == Item_subselect::IN_SUBS)\n      {\n        Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;\n        if (in_subs->is_jtbm_merged)\n          continue;\n      }\n\n      if (const_only && !subquery_predicate->const_item())\n      {\n        /* Skip non-constant subqueries if the caller asked so. */\n        continue;\n      }\n\n      bool empty_union_result= true;\n      bool is_correlated_unit= false;\n      bool first= true;\n      bool union_plan_saved= false;\n      /*\n        If the subquery is a UNION, optimize all the subqueries in the UNION. If\n        there is no UNION, then the loop will execute once for the subquery.\n      */\n      for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())\n      {\n        JOIN *inner_join= sl->join;\n        if (first)\n          first= false;\n        else\n        {\n          if (!union_plan_saved)\n          {\n            union_plan_saved= true;\n            if (un->save_union_explain(un->thd->lex->explain))\n              return true; /* Failure */\n          }\n        }\n        if (!inner_join)\n          continue;\n        SELECT_LEX *save_select= un->thd->lex->current_select;\n        ulonglong save_options;\n        int res;\n        /* We need only 1 row to determine existence */\n        un->set_limit(un->global_parameters());\n        un->thd->lex->current_select= sl;\n        save_options= inner_join->select_options;\n        if (options & SELECT_DESCRIBE)\n        {\n          /* Optimize the subquery in the context of EXPLAIN. */\n          sl->set_explain_type(FALSE);\n          sl->options|= SELECT_DESCRIBE;\n          inner_join->select_options|= SELECT_DESCRIBE;\n        }\n        if ((res= inner_join->optimize()))\n          return TRUE;\n        if (!inner_join->cleaned)\n          sl->update_used_tables();\n        sl->update_correlated_cache();\n        is_correlated_unit|= sl->is_correlated;\n        inner_join->select_options= save_options;\n        un->thd->lex->current_select= save_select;\n\n        Explain_query *eq;\n        if ((eq= inner_join->thd->lex->explain))\n        {\n          Explain_select *expl_sel;\n          if ((expl_sel= eq->get_select(inner_join->select_lex->select_number)))\n          {\n            sl->set_explain_type(TRUE);\n            expl_sel->select_type= sl->type;\n          }\n        }\n\n        if (empty_union_result)\n        {\n          /*\n            If at least one subquery in a union is non-empty, the UNION result\n            is non-empty. If there is no UNION, the only subquery is non-empy.\n          */\n          empty_union_result= inner_join->empty_result();\n        }\n        if (res)\n          return TRUE;\n      }\n      if (empty_union_result)\n        subquery_predicate->no_rows_in_result();\n\n      if (is_correlated_unit)\n      {\n        /*\n          Some parts of UNION are not correlated. This means we will need to\n          re-execute the whole UNION every time. Mark all parts of the UNION\n          as correlated so that they are prepared to be executed multiple\n          times (if we don't do that, some part of the UNION may free its\n          execution data at the end of first execution and crash on the second\n          execution)\n        */\n        for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())\n          sl->uncacheable |= UNCACHEABLE_DEPENDENT;\n      }\n      else\n        un->uncacheable&= ~UNCACHEABLE_DEPENDENT;\n      subquery_predicate->is_correlated= is_correlated_unit;\n    }\n  }\n  return FALSE;\n}", "func_hash": 335655854636733648424487878771712666992, "file_name": "None", "file_hash": null, "cwe": ["CWE-476"], "cve": "CVE-2021-46664", "cve_desc": "MariaDB through 10.5.9 allows an application crash in sub_select_postjoin_aggr for a NULL value of aggr.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46664"}
{"idx": 216906, "project": "server", "commit_id": "9e39d0ae44595dbd1570805d97c9c874778a6be8", "project_url": "https://github.com/MariaDB/server", "commit_url": "https://github.com/MariaDB/server/commit/9e39d0ae44595dbd1570805d97c9c874778a6be8", "commit_message": "MDEV-25787 Bug report: crash on SELECT DISTINCT thousands_blob_fields\n\nfix a debug assert to account for not opened temp tables", "target": 1, "func": "void ha_maria::drop_table(const char *name)\n{\n  DBUG_ASSERT(file->s->temporary);\n  (void) ha_close();\n  (void) maria_delete_table_files(name, 1, MY_WME);\n}", "func_hash": 85612271673629964630565572694774133988, "file_name": "None", "file_hash": null, "cwe": ["CWE-400"], "cve": "CVE-2021-46668", "cve_desc": "MariaDB through 10.5.9 allows an application crash via certain long SELECT DISTINCT statements that improperly interact with storage-engine resource limitations for temporary data structures.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46668"}
{"idx": 509510, "project": "server", "commit_id": "9e39d0ae44595dbd1570805d97c9c874778a6be8", "project_url": "https://github.com/MariaDB/server", "commit_url": "https://github.com/MariaDB/server/commit/9e39d0ae44595dbd1570805d97c9c874778a6be8", "commit_message": "MDEV-25787 Bug report: crash on SELECT DISTINCT thousands_blob_fields\n\nfix a debug assert to account for not opened temp tables", "target": 0, "func": "void ha_maria::drop_table(const char *name)\n{\n  DBUG_ASSERT(!file || file->s->temporary);\n  (void) ha_close();\n  (void) maria_delete_table_files(name, 1, MY_WME);\n}", "func_hash": 36457166293746144750064590645990572247, "file_name": "None", "file_hash": null, "cwe": ["CWE-400"], "cve": "CVE-2021-46668", "cve_desc": "MariaDB through 10.5.9 allows an application crash via certain long SELECT DISTINCT statements that improperly interact with storage-engine resource limitations for temporary data structures.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46668"}
{"idx": 216938, "project": "server", "commit_id": "b3c3291f0b7c1623cb20663f7cf31b7f749768bc", "project_url": "https://github.com/MariaDB/server", "commit_url": "https://github.com/MariaDB/server/commit/b3c3291f0b7c1623cb20663f7cf31b7f749768bc", "commit_message": "MDEV-24176 fixup: GCC -Wmaybe-uninitialized", "target": 1, "func": "bool open_table(THD *thd, TABLE_LIST *table_list, Open_table_context *ot_ctx)\n{\n  TABLE *table;\n  const char *key;\n  uint\tkey_length;\n  const char *alias= table_list->alias.str;\n  uint flags= ot_ctx->get_flags();\n  MDL_ticket *mdl_ticket;\n  TABLE_SHARE *share;\n  uint gts_flags;\n  bool from_share= false;\n#ifdef WITH_PARTITION_STORAGE_ENGINE\n  int part_names_error=0;\n#endif\n  DBUG_ENTER(\"open_table\");\n\n  /*\n    The table must not be opened already. The table can be pre-opened for\n    some statements if it is a temporary table.\n\n    open_temporary_table() must be used to open temporary tables.\n  */\n  DBUG_ASSERT(!table_list->table);\n\n  /* an open table operation needs a lot of the stack space */\n  if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (uchar *)&alias))\n    DBUG_RETURN(TRUE);\n\n  if (!(flags & MYSQL_OPEN_IGNORE_KILLED) && thd->killed)\n  {\n    thd->send_kill_message();\n    DBUG_RETURN(TRUE);\n  }\n\n  /*\n    Check if we're trying to take a write lock in a read only transaction.\n\n    Note that we allow write locks on log tables as otherwise logging\n    to general/slow log would be disabled in read only transactions.\n  */\n  if (table_list->mdl_request.is_write_lock_request() &&\n      thd->tx_read_only &&\n      !(flags & (MYSQL_LOCK_LOG_TABLE | MYSQL_OPEN_HAS_MDL_LOCK)))\n  {\n    my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0));\n    DBUG_RETURN(true);\n  }\n\n  if (!table_list->db.str)\n  {\n    my_error(ER_NO_DB_ERROR, MYF(0));\n    DBUG_RETURN(true);\n  }\n\n  key_length= get_table_def_key(table_list, &key);\n\n  /*\n    If we're in pre-locked or LOCK TABLES mode, let's try to find the\n    requested table in the list of pre-opened and locked tables. If the\n    table is not there, return an error - we can't open not pre-opened\n    tables in pre-locked/LOCK TABLES mode.\n    TODO: move this block into a separate function.\n  */\n  if (thd->locked_tables_mode &&\n      ! (flags & MYSQL_OPEN_GET_NEW_TABLE))\n  {\t\t\t\t\t\t// Using table locks\n    TABLE *best_table= 0;\n    int best_distance= INT_MIN;\n    for (table=thd->open_tables; table ; table=table->next)\n    {\n      if (table->s->table_cache_key.length == key_length &&\n\t  !memcmp(table->s->table_cache_key.str, key, key_length))\n      {\n        if (!my_strcasecmp(system_charset_info, table->alias.c_ptr(), alias) &&\n            table->query_id != thd->query_id && /* skip tables already used */\n            (thd->locked_tables_mode == LTM_LOCK_TABLES ||\n             table->query_id == 0))\n        {\n          int distance= ((int) table->reginfo.lock_type -\n                         (int) table_list->lock_type);\n\n          /*\n            Find a table that either has the exact lock type requested,\n            or has the best suitable lock. In case there is no locked\n            table that has an equal or higher lock than requested,\n            we us the closest matching lock to be able to produce an error\n            message about wrong lock mode on the table. The best_table\n            is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.\n\n            distance <  0 - No suitable lock found\n            distance >  0 - we have lock mode higher then we require\n            distance == 0 - we have lock mode exactly which we need\n          */\n          if ((best_distance < 0 && distance > best_distance) ||\n              (distance >= 0 && distance < best_distance))\n          {\n            best_distance= distance;\n            best_table= table;\n            if (best_distance == 0)\n            {\n              /*\n                We have found a perfect match and can finish iterating\n                through open tables list. Check for table use conflict\n                between calling statement and SP/trigger is done in\n                lock_tables().\n              */\n              break;\n            }\n          }\n        }\n      }\n    }\n    if (best_table)\n    {\n      table= best_table;\n      table->query_id= thd->query_id;\n      table->init(thd, table_list);\n      DBUG_PRINT(\"info\",(\"Using locked table\"));\n#ifdef WITH_PARTITION_STORAGE_ENGINE\n      part_names_error= set_partitions_as_used(table_list, table);\n#endif\n      goto reset;\n    }\n\n    if (is_locked_view(thd, table_list))\n    {\n      if (table_list->sequence)\n      {\n        my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str, table_list->alias.str);\n        DBUG_RETURN(true);\n      }\n      DBUG_RETURN(FALSE); // VIEW\n    }\n\n    /*\n      No table in the locked tables list. In case of explicit LOCK TABLES\n      this can happen if a user did not include the table into the list.\n      In case of pre-locked mode locked tables list is generated automatically,\n      so we may only end up here if the table did not exist when\n      locked tables list was created.\n    */\n    if (thd->locked_tables_mode == LTM_PRELOCKED)\n      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db.str, table_list->alias.str);\n    else\n      my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);\n    DBUG_RETURN(TRUE);\n  }\n\n  /*\n    Non pre-locked/LOCK TABLES mode, and the table is not temporary.\n    This is the normal use case.\n  */\n\n  if (! (flags & MYSQL_OPEN_HAS_MDL_LOCK))\n  {\n    /*\n      We are not under LOCK TABLES and going to acquire write-lock/\n      modify the base table. We need to acquire protection against\n      global read lock until end of this statement in order to have\n      this statement blocked by active FLUSH TABLES WITH READ LOCK.\n\n      We don't need to acquire this protection under LOCK TABLES as\n      such protection already acquired at LOCK TABLES time and\n      not released until UNLOCK TABLES.\n\n      We don't block statements which modify only temporary tables\n      as these tables are not preserved by any form of\n      backup which uses FLUSH TABLES WITH READ LOCK.\n\n      TODO: The fact that we sometimes acquire protection against\n            GRL only when we encounter table to be write-locked\n            slightly increases probability of deadlock.\n            This problem will be solved once Alik pushes his\n            temporary table refactoring patch and we can start\n            pre-acquiring metadata locks at the beggining of\n            open_tables() call.\n    */\n    if (table_list->mdl_request.is_write_lock_request() &&\n        ! (flags & (MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK |\n                    MYSQL_OPEN_FORCE_SHARED_MDL |\n                    MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL |\n                    MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK)) &&\n        ! ot_ctx->has_protection_against_grl())\n    {\n      MDL_request protection_request;\n      MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);\n\n      if (thd->global_read_lock.can_acquire_protection())\n        DBUG_RETURN(TRUE);\n\n      protection_request.init(MDL_key::GLOBAL, \"\", \"\", MDL_INTENTION_EXCLUSIVE,\n                              MDL_STATEMENT);\n\n      /*\n        Install error handler which if possible will convert deadlock error\n        into request to back-off and restart process of opening tables.\n      */\n      thd->push_internal_handler(&mdl_deadlock_handler);\n      bool result= thd->mdl_context.acquire_lock(&protection_request,\n                                                 ot_ctx->get_timeout());\n      thd->pop_internal_handler();\n\n      if (result)\n        DBUG_RETURN(TRUE);\n\n      ot_ctx->set_has_protection_against_grl();\n    }\n\n    if (open_table_get_mdl_lock(thd, ot_ctx, &table_list->mdl_request,\n                                flags, &mdl_ticket) ||\n        mdl_ticket == NULL)\n    {\n      DEBUG_SYNC(thd, \"before_open_table_wait_refresh\");\n      DBUG_RETURN(TRUE);\n    }\n    DEBUG_SYNC(thd, \"after_open_table_mdl_shared\");\n  }\n  else\n  {\n    /*\n      Grab reference to the MDL lock ticket that was acquired\n      by the caller.\n    */\n    mdl_ticket= table_list->mdl_request.ticket;\n  }\n\n  if (table_list->open_strategy == TABLE_LIST::OPEN_IF_EXISTS)\n  {\n    if (!ha_table_exists(thd, &table_list->db, &table_list->table_name))\n      DBUG_RETURN(FALSE);\n  }\n  else if (table_list->open_strategy == TABLE_LIST::OPEN_STUB)\n    DBUG_RETURN(FALSE);\n\n  /* Table exists. Let us try to open it. */\n\n  if (table_list->i_s_requested_object & OPEN_TABLE_ONLY)\n    gts_flags= GTS_TABLE;\n  else if (table_list->i_s_requested_object &  OPEN_VIEW_ONLY)\n    gts_flags= GTS_VIEW;\n  else\n    gts_flags= GTS_TABLE | GTS_VIEW;\n\nretry_share:\n\n  share= tdc_acquire_share(thd, table_list, gts_flags, &table);\n\n  if (unlikely(!share))\n  {\n    /*\n      Hide \"Table doesn't exist\" errors if the table belongs to a view.\n      The check for thd->is_error() is necessary to not push an\n      unwanted error in case the error was already silenced.\n      @todo Rework the alternative ways to deal with ER_NO_SUCH TABLE.\n    */\n    if (thd->is_error())\n    {\n      if (table_list->parent_l)\n      {\n        thd->clear_error();\n        my_error(ER_WRONG_MRG_TABLE, MYF(0));\n      }\n      else if (table_list->belong_to_view)\n      {\n        TABLE_LIST *view= table_list->belong_to_view;\n        thd->clear_error();\n        my_error(ER_VIEW_INVALID, MYF(0),\n                 view->view_db.str, view->view_name.str);\n      }\n    }\n    DBUG_RETURN(TRUE);\n  }\n\n  /*\n    Check if this TABLE_SHARE-object corresponds to a view. Note, that there is\n    no need to check TABLE_SHARE::tdc.flushed as we do for regular tables,\n    because view shares are always up to date.\n  */\n  if (share->is_view)\n  {\n    /*\n      If parent_l of the table_list is non null then a merge table\n      has this view as child table, which is not supported.\n    */\n    if (table_list->parent_l)\n    {\n      my_error(ER_WRONG_MRG_TABLE, MYF(0));\n      goto err_lock;\n    }\n    if (table_list->sequence)\n    {\n      my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str,\n               table_list->alias.str);\n      goto err_lock;\n    }\n    /*\n      This table is a view. Validate its metadata version: in particular,\n      that it was a view when the statement was prepared.\n    */\n    if (check_and_update_table_version(thd, table_list, share))\n      goto err_lock;\n\n    /* Open view */\n    if (mysql_make_view(thd, share, table_list, false))\n      goto err_lock;\n\n\n    /* TODO: Don't free this */\n    tdc_release_share(share);\n\n    DBUG_ASSERT(table_list->view);\n\n    DBUG_RETURN(FALSE);\n  }\n\n#ifdef WITH_WSREP\n  if (!((flags & MYSQL_OPEN_IGNORE_FLUSH) ||\n        (thd->wsrep_applier)))\n#else\n  if (!(flags & MYSQL_OPEN_IGNORE_FLUSH))\n#endif\n  {\n    if (share->tdc->flushed)\n    {\n      DBUG_PRINT(\"info\", (\"Found old share version: %lld  current: %lld\",\n                          share->tdc->version, tdc_refresh_version()));\n      /*\n        We already have an MDL lock. But we have encountered an old\n        version of table in the table definition cache which is possible\n        when someone changes the table version directly in the cache\n        without acquiring a metadata lock (e.g. this can happen during\n        \"rolling\" FLUSH TABLE(S)).\n        Release our reference to share, wait until old version of\n        share goes away and then try to get new version of table share.\n      */\n      if (table)\n        tc_release_table(table);\n      else\n        tdc_release_share(share);\n\n      MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);\n      bool wait_result;\n\n      thd->push_internal_handler(&mdl_deadlock_handler);\n      wait_result= tdc_wait_for_old_version(thd, table_list->db.str,\n                                            table_list->table_name.str,\n                                            ot_ctx->get_timeout(),\n                                            mdl_ticket->get_deadlock_weight());\n      thd->pop_internal_handler();\n\n      if (wait_result)\n        DBUG_RETURN(TRUE);\n\n      goto retry_share;\n    }\n\n    if (thd->open_tables && thd->open_tables->s->tdc->flushed)\n    {\n      /*\n        If the version changes while we're opening the tables,\n        we have to back off, close all the tables opened-so-far,\n        and try to reopen them. Note: refresh_version is currently\n        changed only during FLUSH TABLES.\n      */\n      if (table)\n        tc_release_table(table);\n      else\n        tdc_release_share(share);\n      (void)ot_ctx->request_backoff_action(Open_table_context::OT_REOPEN_TABLES,\n                                           NULL);\n      DBUG_RETURN(TRUE);\n    }\n  }\n\n  if (table)\n  {\n    DBUG_ASSERT(table->file != NULL);\n    MYSQL_REBIND_TABLE(table->file);\n#ifdef WITH_PARTITION_STORAGE_ENGINE\n    part_names_error= set_partitions_as_used(table_list, table);\n#endif\n  }\n  else\n  {\n    enum open_frm_error error;\n\n    /* make a new table */\n    if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME))))\n      goto err_lock;\n\n    error= open_table_from_share(thd, share, &table_list->alias,\n                                 HA_OPEN_KEYFILE | HA_TRY_READ_ONLY,\n                                 EXTRA_RECORD,\n                                 thd->open_options, table, FALSE,\n                                 IF_PARTITIONING(table_list->partition_names,0));\n\n    if (unlikely(error))\n    {\n      my_free(table);\n\n      if (error == OPEN_FRM_DISCOVER)\n        (void) ot_ctx->request_backoff_action(Open_table_context::OT_DISCOVER,\n                                              table_list);\n      else if (share->crashed)\n      {\n        if (!(flags & MYSQL_OPEN_IGNORE_REPAIR))\n          (void) ot_ctx->request_backoff_action(Open_table_context::OT_REPAIR,\n                                                table_list);\n        else\n          table_list->crashed= 1;  /* Mark that table was crashed */\n      }\n      goto err_lock;\n    }\n    if (open_table_entry_fini(thd, share, table))\n    {\n      closefrm(table);\n      my_free(table);\n      goto err_lock;\n    }\n\n    /* Add table to the share's used tables list. */\n    tc_add_table(thd, table);\n    from_share= true;\n  }\n\n  table->mdl_ticket= mdl_ticket;\n  table->reginfo.lock_type=TL_READ;\t\t/* Assume read */\n\n  table->init(thd, table_list);\n\n  table->next= thd->open_tables;\t\t/* Link into simple list */\n  thd->set_open_tables(table);\n\n reset:\n  /*\n    Check that there is no reference to a condition from an earlier query\n    (cf. Bug#58553). \n  */\n  DBUG_ASSERT(table->file->pushed_cond == NULL);\n  table_list->updatable= 1; // It is not derived table nor non-updatable VIEW\n  table_list->table= table;\n\n  if (!from_share && table->vcol_fix_expr(thd))\n    goto err_lock;\n\n#ifdef WITH_PARTITION_STORAGE_ENGINE\n  if (unlikely(table->part_info))\n  {\n    /* Partitions specified were incorrect.*/\n    if (part_names_error)\n    {\n      table->file->print_error(part_names_error, MYF(0));\n      DBUG_RETURN(true);\n    }\n  }\n  else if (table_list->partition_names)\n  {\n    /* Don't allow PARTITION () clause on a nonpartitioned table */\n    my_error(ER_PARTITION_CLAUSE_ON_NONPARTITIONED, MYF(0));\n    DBUG_RETURN(true);\n  }\n#endif\n  if (table_list->sequence && table->s->table_type != TABLE_TYPE_SEQUENCE)\n  {\n    my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str, table_list->alias.str);\n    DBUG_RETURN(true);\n  }\n\n  DBUG_RETURN(FALSE);\n\nerr_lock:\n  tdc_release_share(share);\n\n  DBUG_PRINT(\"exit\", (\"failed\"));\n  DBUG_RETURN(TRUE);\n}", "func_hash": 336982129080685152460431545851496461461, "file_name": "None", "file_hash": null, "cwe": ["CWE-416"], "cve": "CVE-2022-27376", "cve_desc": "MariaDB Server v10.6.5 and below was discovered to contain an use-after-free in the component Item_args::walk_arg, which is exploited via specially crafted SQL statements.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27376"}
{"idx": 511472, "project": "server", "commit_id": "b3c3291f0b7c1623cb20663f7cf31b7f749768bc", "project_url": "https://github.com/MariaDB/server", "commit_url": "https://github.com/MariaDB/server/commit/b3c3291f0b7c1623cb20663f7cf31b7f749768bc", "commit_message": "MDEV-24176 fixup: GCC -Wmaybe-uninitialized", "target": 0, "func": "bool open_table(THD *thd, TABLE_LIST *table_list, Open_table_context *ot_ctx)\n{\n  TABLE *table;\n  const char *key;\n  uint\tkey_length;\n  const char *alias= table_list->alias.str;\n  uint flags= ot_ctx->get_flags();\n  MDL_ticket *mdl_ticket;\n  TABLE_SHARE *share;\n  uint gts_flags;\n  bool from_share= false;\n#ifdef WITH_PARTITION_STORAGE_ENGINE\n  int part_names_error=0;\n#endif\n  DBUG_ENTER(\"open_table\");\n\n  /*\n    The table must not be opened already. The table can be pre-opened for\n    some statements if it is a temporary table.\n\n    open_temporary_table() must be used to open temporary tables.\n  */\n  DBUG_ASSERT(!table_list->table);\n\n  /* an open table operation needs a lot of the stack space */\n  if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (uchar *)&alias))\n    DBUG_RETURN(TRUE);\n\n  if (!(flags & MYSQL_OPEN_IGNORE_KILLED) && thd->killed)\n  {\n    thd->send_kill_message();\n    DBUG_RETURN(TRUE);\n  }\n\n  /*\n    Check if we're trying to take a write lock in a read only transaction.\n\n    Note that we allow write locks on log tables as otherwise logging\n    to general/slow log would be disabled in read only transactions.\n  */\n  if (table_list->mdl_request.is_write_lock_request() &&\n      thd->tx_read_only &&\n      !(flags & (MYSQL_LOCK_LOG_TABLE | MYSQL_OPEN_HAS_MDL_LOCK)))\n  {\n    my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0));\n    DBUG_RETURN(true);\n  }\n\n  if (!table_list->db.str)\n  {\n    my_error(ER_NO_DB_ERROR, MYF(0));\n    DBUG_RETURN(true);\n  }\n\n  key_length= get_table_def_key(table_list, &key);\n\n  /*\n    If we're in pre-locked or LOCK TABLES mode, let's try to find the\n    requested table in the list of pre-opened and locked tables. If the\n    table is not there, return an error - we can't open not pre-opened\n    tables in pre-locked/LOCK TABLES mode.\n    TODO: move this block into a separate function.\n  */\n  if (thd->locked_tables_mode &&\n      ! (flags & MYSQL_OPEN_GET_NEW_TABLE))\n  {\t\t\t\t\t\t// Using table locks\n    TABLE *best_table= 0;\n    int best_distance= INT_MIN;\n    for (table=thd->open_tables; table ; table=table->next)\n    {\n      if (table->s->table_cache_key.length == key_length &&\n\t  !memcmp(table->s->table_cache_key.str, key, key_length))\n      {\n        if (!my_strcasecmp(system_charset_info, table->alias.c_ptr(), alias) &&\n            table->query_id != thd->query_id && /* skip tables already used */\n            (thd->locked_tables_mode == LTM_LOCK_TABLES ||\n             table->query_id == 0))\n        {\n          int distance= ((int) table->reginfo.lock_type -\n                         (int) table_list->lock_type);\n\n          /*\n            Find a table that either has the exact lock type requested,\n            or has the best suitable lock. In case there is no locked\n            table that has an equal or higher lock than requested,\n            we us the closest matching lock to be able to produce an error\n            message about wrong lock mode on the table. The best_table\n            is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.\n\n            distance <  0 - No suitable lock found\n            distance >  0 - we have lock mode higher then we require\n            distance == 0 - we have lock mode exactly which we need\n          */\n          if ((best_distance < 0 && distance > best_distance) ||\n              (distance >= 0 && distance < best_distance))\n          {\n            best_distance= distance;\n            best_table= table;\n            if (best_distance == 0)\n            {\n              /*\n                We have found a perfect match and can finish iterating\n                through open tables list. Check for table use conflict\n                between calling statement and SP/trigger is done in\n                lock_tables().\n              */\n              break;\n            }\n          }\n        }\n      }\n    }\n    if (best_table)\n    {\n      table= best_table;\n      table->query_id= thd->query_id;\n      table->init(thd, table_list);\n      DBUG_PRINT(\"info\",(\"Using locked table\"));\n#ifdef WITH_PARTITION_STORAGE_ENGINE\n      part_names_error= set_partitions_as_used(table_list, table);\n#endif\n      goto reset;\n    }\n\n    if (is_locked_view(thd, table_list))\n    {\n      if (table_list->sequence)\n      {\n        my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str, table_list->alias.str);\n        DBUG_RETURN(true);\n      }\n      DBUG_RETURN(FALSE); // VIEW\n    }\n\n    /*\n      No table in the locked tables list. In case of explicit LOCK TABLES\n      this can happen if a user did not include the table into the list.\n      In case of pre-locked mode locked tables list is generated automatically,\n      so we may only end up here if the table did not exist when\n      locked tables list was created.\n    */\n    if (thd->locked_tables_mode == LTM_PRELOCKED)\n      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db.str, table_list->alias.str);\n    else\n      my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);\n    DBUG_RETURN(TRUE);\n  }\n\n  /*\n    Non pre-locked/LOCK TABLES mode, and the table is not temporary.\n    This is the normal use case.\n  */\n\n  if (! (flags & MYSQL_OPEN_HAS_MDL_LOCK))\n  {\n    /*\n      We are not under LOCK TABLES and going to acquire write-lock/\n      modify the base table. We need to acquire protection against\n      global read lock until end of this statement in order to have\n      this statement blocked by active FLUSH TABLES WITH READ LOCK.\n\n      We don't need to acquire this protection under LOCK TABLES as\n      such protection already acquired at LOCK TABLES time and\n      not released until UNLOCK TABLES.\n\n      We don't block statements which modify only temporary tables\n      as these tables are not preserved by any form of\n      backup which uses FLUSH TABLES WITH READ LOCK.\n\n      TODO: The fact that we sometimes acquire protection against\n            GRL only when we encounter table to be write-locked\n            slightly increases probability of deadlock.\n            This problem will be solved once Alik pushes his\n            temporary table refactoring patch and we can start\n            pre-acquiring metadata locks at the beggining of\n            open_tables() call.\n    */\n    if (table_list->mdl_request.is_write_lock_request() &&\n        ! (flags & (MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK |\n                    MYSQL_OPEN_FORCE_SHARED_MDL |\n                    MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL |\n                    MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK)) &&\n        ! ot_ctx->has_protection_against_grl())\n    {\n      MDL_request protection_request;\n      MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);\n\n      if (thd->global_read_lock.can_acquire_protection())\n        DBUG_RETURN(TRUE);\n\n      protection_request.init(MDL_key::GLOBAL, \"\", \"\", MDL_INTENTION_EXCLUSIVE,\n                              MDL_STATEMENT);\n\n      /*\n        Install error handler which if possible will convert deadlock error\n        into request to back-off and restart process of opening tables.\n      */\n      thd->push_internal_handler(&mdl_deadlock_handler);\n      bool result= thd->mdl_context.acquire_lock(&protection_request,\n                                                 ot_ctx->get_timeout());\n      thd->pop_internal_handler();\n\n      if (result)\n        DBUG_RETURN(TRUE);\n\n      ot_ctx->set_has_protection_against_grl();\n    }\n\n    if (open_table_get_mdl_lock(thd, ot_ctx, &table_list->mdl_request,\n                                flags, &mdl_ticket) ||\n        mdl_ticket == NULL)\n    {\n      DEBUG_SYNC(thd, \"before_open_table_wait_refresh\");\n      DBUG_RETURN(TRUE);\n    }\n    DEBUG_SYNC(thd, \"after_open_table_mdl_shared\");\n  }\n  else\n  {\n    /*\n      Grab reference to the MDL lock ticket that was acquired\n      by the caller.\n    */\n    mdl_ticket= table_list->mdl_request.ticket;\n  }\n\n  if (table_list->open_strategy == TABLE_LIST::OPEN_IF_EXISTS)\n  {\n    if (!ha_table_exists(thd, &table_list->db, &table_list->table_name))\n      DBUG_RETURN(FALSE);\n  }\n  else if (table_list->open_strategy == TABLE_LIST::OPEN_STUB)\n    DBUG_RETURN(FALSE);\n\n  /* Table exists. Let us try to open it. */\n\n  if (table_list->i_s_requested_object & OPEN_TABLE_ONLY)\n    gts_flags= GTS_TABLE;\n  else if (table_list->i_s_requested_object &  OPEN_VIEW_ONLY)\n    gts_flags= GTS_VIEW;\n  else\n    gts_flags= GTS_TABLE | GTS_VIEW;\n\nretry_share:\n\n  share= tdc_acquire_share(thd, table_list, gts_flags, &table);\n\n  if (unlikely(!share))\n  {\n    /*\n      Hide \"Table doesn't exist\" errors if the table belongs to a view.\n      The check for thd->is_error() is necessary to not push an\n      unwanted error in case the error was already silenced.\n      @todo Rework the alternative ways to deal with ER_NO_SUCH TABLE.\n    */\n    if (thd->is_error())\n    {\n      if (table_list->parent_l)\n      {\n        thd->clear_error();\n        my_error(ER_WRONG_MRG_TABLE, MYF(0));\n      }\n      else if (table_list->belong_to_view)\n      {\n        TABLE_LIST *view= table_list->belong_to_view;\n        thd->clear_error();\n        my_error(ER_VIEW_INVALID, MYF(0),\n                 view->view_db.str, view->view_name.str);\n      }\n    }\n    DBUG_RETURN(TRUE);\n  }\n\n  /*\n    Check if this TABLE_SHARE-object corresponds to a view. Note, that there is\n    no need to check TABLE_SHARE::tdc.flushed as we do for regular tables,\n    because view shares are always up to date.\n  */\n  if (share->is_view)\n  {\n    /*\n      If parent_l of the table_list is non null then a merge table\n      has this view as child table, which is not supported.\n    */\n    if (table_list->parent_l)\n    {\n      my_error(ER_WRONG_MRG_TABLE, MYF(0));\n      goto err_lock;\n    }\n    if (table_list->sequence)\n    {\n      my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str,\n               table_list->alias.str);\n      goto err_lock;\n    }\n    /*\n      This table is a view. Validate its metadata version: in particular,\n      that it was a view when the statement was prepared.\n    */\n    if (check_and_update_table_version(thd, table_list, share))\n      goto err_lock;\n\n    /* Open view */\n    if (mysql_make_view(thd, share, table_list, false))\n      goto err_lock;\n\n\n    /* TODO: Don't free this */\n    tdc_release_share(share);\n\n    DBUG_ASSERT(table_list->view);\n\n    DBUG_RETURN(FALSE);\n  }\n\n#ifdef WITH_WSREP\n  if (!((flags & MYSQL_OPEN_IGNORE_FLUSH) ||\n        (thd->wsrep_applier)))\n#else\n  if (!(flags & MYSQL_OPEN_IGNORE_FLUSH))\n#endif\n  {\n    if (share->tdc->flushed)\n    {\n      DBUG_PRINT(\"info\", (\"Found old share version: %lld  current: %lld\",\n                          share->tdc->version, tdc_refresh_version()));\n      /*\n        We already have an MDL lock. But we have encountered an old\n        version of table in the table definition cache which is possible\n        when someone changes the table version directly in the cache\n        without acquiring a metadata lock (e.g. this can happen during\n        \"rolling\" FLUSH TABLE(S)).\n        Release our reference to share, wait until old version of\n        share goes away and then try to get new version of table share.\n      */\n      if (table)\n        tc_release_table(table);\n      else\n        tdc_release_share(share);\n\n      MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);\n      bool wait_result;\n\n      thd->push_internal_handler(&mdl_deadlock_handler);\n      wait_result= tdc_wait_for_old_version(thd, table_list->db.str,\n                                            table_list->table_name.str,\n                                            ot_ctx->get_timeout(),\n                                            mdl_ticket->get_deadlock_weight());\n      thd->pop_internal_handler();\n\n      if (wait_result)\n        DBUG_RETURN(TRUE);\n\n      goto retry_share;\n    }\n\n    if (thd->open_tables && thd->open_tables->s->tdc->flushed)\n    {\n      /*\n        If the version changes while we're opening the tables,\n        we have to back off, close all the tables opened-so-far,\n        and try to reopen them. Note: refresh_version is currently\n        changed only during FLUSH TABLES.\n      */\n      if (table)\n        tc_release_table(table);\n      else\n        tdc_release_share(share);\n      (void)ot_ctx->request_backoff_action(Open_table_context::OT_REOPEN_TABLES,\n                                           NULL);\n      DBUG_RETURN(TRUE);\n    }\n  }\n\n  if (table)\n  {\n    DBUG_ASSERT(table->file != NULL);\n    MYSQL_REBIND_TABLE(table->file);\n#ifdef WITH_PARTITION_STORAGE_ENGINE\n    part_names_error= set_partitions_as_used(table_list, table);\n#endif\n  }\n  else\n  {\n    enum open_frm_error error;\n\n    /* make a new table */\n    if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME))))\n      goto err_lock;\n\n    error= open_table_from_share(thd, share, &table_list->alias,\n                                 HA_OPEN_KEYFILE | HA_TRY_READ_ONLY,\n                                 EXTRA_RECORD,\n                                 thd->open_options, table, FALSE,\n                                 IF_PARTITIONING(table_list->partition_names,0));\n\n    if (unlikely(error))\n    {\n      my_free(table);\n\n      if (error == OPEN_FRM_DISCOVER)\n        (void) ot_ctx->request_backoff_action(Open_table_context::OT_DISCOVER,\n                                              table_list);\n      else if (share->crashed)\n      {\n        if (!(flags & MYSQL_OPEN_IGNORE_REPAIR))\n          (void) ot_ctx->request_backoff_action(Open_table_context::OT_REPAIR,\n                                                table_list);\n        else\n          table_list->crashed= 1;  /* Mark that table was crashed */\n      }\n      goto err_lock;\n    }\n    if (open_table_entry_fini(thd, share, table))\n    {\n      closefrm(table);\n      my_free(table);\n      goto err_lock;\n    }\n\n    /* Add table to the share's used tables list. */\n    tc_add_table(thd, table);\n    from_share= true;\n  }\n\n  table->mdl_ticket= mdl_ticket;\n  table->reginfo.lock_type=TL_READ;\t\t/* Assume read */\n\n  table->init(thd, table_list);\n\n  table->next= thd->open_tables;\t\t/* Link into simple list */\n  thd->set_open_tables(table);\n\n reset:\n  /*\n    Check that there is no reference to a condition from an earlier query\n    (cf. Bug#58553). \n  */\n  DBUG_ASSERT(table->file->pushed_cond == NULL);\n  table_list->updatable= 1; // It is not derived table nor non-updatable VIEW\n  table_list->table= table;\n\n  if (!from_share && table->vcol_fix_expr(thd))\n    DBUG_RETURN(true);\n\n#ifdef WITH_PARTITION_STORAGE_ENGINE\n  if (unlikely(table->part_info))\n  {\n    /* Partitions specified were incorrect.*/\n    if (part_names_error)\n    {\n      table->file->print_error(part_names_error, MYF(0));\n      DBUG_RETURN(true);\n    }\n  }\n  else if (table_list->partition_names)\n  {\n    /* Don't allow PARTITION () clause on a nonpartitioned table */\n    my_error(ER_PARTITION_CLAUSE_ON_NONPARTITIONED, MYF(0));\n    DBUG_RETURN(true);\n  }\n#endif\n  if (table_list->sequence && table->s->table_type != TABLE_TYPE_SEQUENCE)\n  {\n    my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str, table_list->alias.str);\n    DBUG_RETURN(true);\n  }\n\n  DBUG_RETURN(FALSE);\n\nerr_lock:\n  tdc_release_share(share);\n\n  DBUG_PRINT(\"exit\", (\"failed\"));\n  DBUG_RETURN(TRUE);\n}", "func_hash": 83128391821270233968176562120215675650, "file_name": "None", "file_hash": null, "cwe": ["CWE-416"], "cve": "CVE-2022-27376", "cve_desc": "MariaDB Server v10.6.5 and below was discovered to contain an use-after-free in the component Item_args::walk_arg, which is exploited via specially crafted SQL statements.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27376"}
{"idx": 216945, "project": "server", "commit_id": "807945f2eb5fa22e6f233cc17b85a2e141efe2c8", "project_url": "https://github.com/MariaDB/server", "commit_url": "https://github.com/MariaDB/server/commit/807945f2eb5fa22e6f233cc17b85a2e141efe2c8", "commit_message": "MDEV-26402: A SEGV in Item_field::used_tables/update_depend_map_for_order...\n\nWhen doing condition pushdown from HAVING into WHERE,\nItem_equal::create_pushable_equalities() calls\nitem->set_extraction_flag(IMMUTABLE_FL) for constant items.\nThen, Item::cleanup_excluding_immutables_processor() checks for this flag\nto see if it should call item->cleanup() or leave the item as-is.\n\nThe failure happens when a constant item has a non-constant one inside it,\nlike:\n\n   (tbl.col=0 AND impossible_cond)\n\nitem->walk(cleanup_excluding_immutables_processor) works in a bottom-up\nway so it\n1. will call Item_func_eq(tbl.col=0)->cleanup()\n2. will not call Item_cond_and->cleanup (as the AND is constant)\n\nThis creates an item tree where a fixed Item has an un-fixed Item inside\nit which eventually causes an assertion failure.\n\nFixed by introducing this rule: instead of just calling\n\n  item->set_extraction_flag(IMMUTABLE_FL);\n\nwe call Item::walk() to set the flag for all sub-items of the item.", "target": 1, "func": "bool Item_equal::create_pushable_equalities(THD *thd,\n                                            List *equalities,\n                                            Pushdown_checker checker,\n                                            uchar *arg,\n                                            bool clone_const)\n{\n  Item *item;\n  Item *left_item= NULL;\n  Item *right_item = get_const();\n  Item_equal_fields_iterator it(*this);\n\n  while ((item=it++))\n  {\n    left_item= item;\n    if (checker && !((item->*checker) (arg)))\n      continue;\n    break;\n  }\n\n  if (!left_item)\n    return false;\n\n  if (right_item)\n  {\n    Item_func_eq *eq= 0;\n    Item *left_item_clone= left_item->build_clone(thd);\n    Item *right_item_clone= !clone_const ?\n                            right_item : right_item->build_clone(thd);\n    if (!left_item_clone || !right_item_clone)\n      return true;\n    eq= new (thd->mem_root) Item_func_eq(thd,\n                                         left_item_clone,\n                                         right_item_clone);\n    if (!eq ||  equalities->push_back(eq, thd->mem_root))\n      return true;\n    if (!clone_const)\n      right_item->set_extraction_flag(IMMUTABLE_FL);\n  }\n\n  while ((item=it++))\n  {\n    if (checker && !((item->*checker) (arg)))\n      continue;\n    Item_func_eq *eq= 0;\n    Item *left_item_clone= left_item->build_clone(thd);\n    Item *right_item_clone= item->build_clone(thd);\n    if (!(left_item_clone && right_item_clone))\n      return true;\n    left_item_clone->set_item_equal(NULL);\n    right_item_clone->set_item_equal(NULL);\n    eq= new (thd->mem_root) Item_func_eq(thd,\n                                         right_item_clone,\n                                         left_item_clone);\n    if (!eq || equalities->push_back(eq, thd->mem_root))\n      return true;\n  }\n  return false;\n}", "func_hash": 310506936609045112273577090786370872524, "file_name": "None", "file_hash": null, "cwe": ["CWE-617"], "cve": "CVE-2022-27382", "cve_desc": "MariaDB Server v10.7 and below was discovered to contain a segmentation fault via the component Item_field::used_tables/update_depend_map_for_order.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27382"}
{"idx": 512825, "project": "server", "commit_id": "807945f2eb5fa22e6f233cc17b85a2e141efe2c8", "project_url": "https://github.com/MariaDB/server", "commit_url": "https://github.com/MariaDB/server/commit/807945f2eb5fa22e6f233cc17b85a2e141efe2c8", "commit_message": "MDEV-26402: A SEGV in Item_field::used_tables/update_depend_map_for_order...\n\nWhen doing condition pushdown from HAVING into WHERE,\nItem_equal::create_pushable_equalities() calls\nitem->set_extraction_flag(IMMUTABLE_FL) for constant items.\nThen, Item::cleanup_excluding_immutables_processor() checks for this flag\nto see if it should call item->cleanup() or leave the item as-is.\n\nThe failure happens when a constant item has a non-constant one inside it,\nlike:\n\n   (tbl.col=0 AND impossible_cond)\n\nitem->walk(cleanup_excluding_immutables_processor) works in a bottom-up\nway so it\n1. will call Item_func_eq(tbl.col=0)->cleanup()\n2. will not call Item_cond_and->cleanup (as the AND is constant)\n\nThis creates an item tree where a fixed Item has an un-fixed Item inside\nit which eventually causes an assertion failure.\n\nFixed by introducing this rule: instead of just calling\n\n  item->set_extraction_flag(IMMUTABLE_FL);\n\nwe call Item::walk() to set the flag for all sub-items of the item.", "target": 0, "func": "bool Item_equal::create_pushable_equalities(THD *thd,\n                                            List *equalities,\n                                            Pushdown_checker checker,\n                                            uchar *arg,\n                                            bool clone_const)\n{\n  Item *item;\n  Item *left_item= NULL;\n  Item *right_item = get_const();\n  Item_equal_fields_iterator it(*this);\n\n  while ((item=it++))\n  {\n    left_item= item;\n    if (checker && !((item->*checker) (arg)))\n      continue;\n    break;\n  }\n\n  if (!left_item)\n    return false;\n\n  if (right_item)\n  {\n    Item_func_eq *eq= 0;\n    Item *left_item_clone= left_item->build_clone(thd);\n    Item *right_item_clone= !clone_const ?\n                            right_item : right_item->build_clone(thd);\n    if (!left_item_clone || !right_item_clone)\n      return true;\n    eq= new (thd->mem_root) Item_func_eq(thd,\n                                         left_item_clone,\n                                         right_item_clone);\n    if (!eq ||  equalities->push_back(eq, thd->mem_root))\n      return true;\n    if (!clone_const)\n    {\n      /*\n        Also set IMMUTABLE_FL for any sub-items of the right_item.\n        This is needed to prevent Item::cleanup_excluding_immutables_processor\n        from peforming cleanup of the sub-items and so creating an item tree\n        where a fixed item has non-fixed items inside it.\n      */\n      int new_flag= IMMUTABLE_FL;\n      right_item->walk(&Item::set_extraction_flag_processor, false,\n                       (void*)&new_flag);\n    }\n  }\n\n  while ((item=it++))\n  {\n    if (checker && !((item->*checker) (arg)))\n      continue;\n    Item_func_eq *eq= 0;\n    Item *left_item_clone= left_item->build_clone(thd);\n    Item *right_item_clone= item->build_clone(thd);\n    if (!(left_item_clone && right_item_clone))\n      return true;\n    left_item_clone->set_item_equal(NULL);\n    right_item_clone->set_item_equal(NULL);\n    eq= new (thd->mem_root) Item_func_eq(thd,\n                                         right_item_clone,\n                                         left_item_clone);\n    if (!eq || equalities->push_back(eq, thd->mem_root))\n      return true;\n  }\n  return false;\n}", "func_hash": 247600252359942672774915786547473250797, "file_name": "None", "file_hash": null, "cwe": ["CWE-617"], "cve": "CVE-2022-27382", "cve_desc": "MariaDB Server v10.7 and below was discovered to contain a segmentation fault via the component Item_field::used_tables/update_depend_map_for_order.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27382"}
{"idx": 216946, "project": "server", "commit_id": "c05fd700970ad45735caed3a6f9930d4ce19a3bd", "project_url": "https://github.com/MariaDB/server", "commit_url": "https://github.com/MariaDB/server/commit/c05fd700970ad45735caed3a6f9930d4ce19a3bd", "commit_message": "MDEV-26323 use-after-poison issue of MariaDB server", "target": 1, "func": "static void fix_dl_name(MEM_ROOT *root, LEX_STRING *dl)\n{\n  const size_t so_ext_len= sizeof(SO_EXT) - 1;\n  if (my_strcasecmp(&my_charset_latin1, dl->str + dl->length - so_ext_len,\n                    SO_EXT))\n  {\n    char *s= (char*)alloc_root(root, dl->length + so_ext_len + 1);\n    memcpy(s, dl->str, dl->length);\n    strcpy(s + dl->length, SO_EXT);\n    dl->str= s;\n    dl->length+= so_ext_len;\n  }\n}", "func_hash": 339917125862392009139749816960654857347, "file_name": "None", "file_hash": null, "cwe": ["CWE-416"], "cve": "CVE-2022-27383", "cve_desc": "MariaDB Server v10.6 and below was discovered to contain an use-after-free in the component my_strcasecmp_8bit, which is exploited via specially crafted SQL statements.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27383"}
{"idx": 513202, "project": "server", "commit_id": "c05fd700970ad45735caed3a6f9930d4ce19a3bd", "project_url": "https://github.com/MariaDB/server", "commit_url": "https://github.com/MariaDB/server/commit/c05fd700970ad45735caed3a6f9930d4ce19a3bd", "commit_message": "MDEV-26323 use-after-poison issue of MariaDB server", "target": 0, "func": "static void fix_dl_name(MEM_ROOT *root, LEX_STRING *dl)\n{\n  const size_t so_ext_len= sizeof(SO_EXT) - 1;\n  if (dl->length < so_ext_len ||\n      my_strcasecmp(&my_charset_latin1, dl->str + dl->length - so_ext_len,\n                    SO_EXT))\n  {\n    char *s= (char*)alloc_root(root, dl->length + so_ext_len + 1);\n    memcpy(s, dl->str, dl->length);\n    strcpy(s + dl->length, SO_EXT);\n    dl->str= s;\n    dl->length+= so_ext_len;\n  }\n}", "func_hash": 98463444639733543200591125506342217809, "file_name": "None", "file_hash": null, "cwe": ["CWE-416"], "cve": "CVE-2022-27383", "cve_desc": "MariaDB Server v10.6 and below was discovered to contain an use-after-free in the component my_strcasecmp_8bit, which is exploited via specially crafted SQL statements.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27383"}
{"idx": 216965, "project": "server", "commit_id": "ecb6f9c894d3ebafeff1c6eb3b65cd248062296f", "project_url": "https://github.com/MariaDB/server", "commit_url": "https://github.com/MariaDB/server/commit/ecb6f9c894d3ebafeff1c6eb3b65cd248062296f", "commit_message": "MDEV-28095 crash in multi-update and implicit grouping\n\ndisallow implicit grouping in multi-update.\nexplicit GROUP BY is not allowed by the grammar.", "target": 1, "func": "multi_update::initialize_tables(JOIN *join)\n{\n  TABLE_LIST *table_ref;\n  DBUG_ENTER(\"initialize_tables\");\n\n  if (unlikely((thd->variables.option_bits & OPTION_SAFE_UPDATES) &&\n               error_if_full_join(join)))\n    DBUG_RETURN(1);\n  main_table=join->join_tab->table;\n  table_to_update= 0;\n\n  /* Any update has at least one pair (field, value) */\n  DBUG_ASSERT(fields->elements);\n  /*\n   Only one table may be modified by UPDATE of an updatable view.\n   For an updatable view first_table_for_update indicates this\n   table.\n   For a regular multi-update it refers to some updated table.\n  */ \n  TABLE *first_table_for_update= ((Item_field *) fields->head())->field->table;\n\n  /* Create a temporary table for keys to all tables, except main table */\n  for (table_ref= update_tables; table_ref; table_ref= table_ref->next_local)\n  {\n    TABLE *table=table_ref->table;\n    uint cnt= table_ref->shared;\n    List temp_fields;\n    ORDER     group;\n    TMP_TABLE_PARAM *tmp_param;\n\n    if (ignore)\n      table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);\n    if (table == main_table)\t\t\t// First table in join\n    {\n      if (safe_update_on_fly(thd, join->join_tab, table_ref, all_tables))\n      {\n\ttable_to_update= table;\t\t\t// Update table on the fly\n        has_vers_fields= table->vers_check_update(*fields);\n\tcontinue;\n      }\n    }\n    table->prepare_for_position();\n    join->map2table[table->tablenr]->keep_current_rowid= true;\n\n    /*\n      enable uncacheable flag if we update a view with check option\n      and check option has a subselect, otherwise, the check option\n      can be evaluated after the subselect was freed as independent\n      (See full_local in JOIN::join_free()).\n    */\n    if (table_ref->check_option && !join->select_lex->uncacheable)\n    {\n      SELECT_LEX_UNIT *tmp_unit;\n      SELECT_LEX *sl;\n      for (tmp_unit= join->select_lex->first_inner_unit();\n           tmp_unit;\n           tmp_unit= tmp_unit->next_unit())\n      {\n        for (sl= tmp_unit->first_select(); sl; sl= sl->next_select())\n        {\n          if (sl->master_unit()->item)\n          {\n            join->select_lex->uncacheable|= UNCACHEABLE_CHECKOPTION;\n            goto loop_end;\n          }\n        }\n      }\n    }\nloop_end:\n\n    if (table == first_table_for_update && table_ref->check_option)\n    {\n      table_map unupdated_tables= table_ref->check_option->used_tables() &\n                                  ~first_table_for_update->map;\n      List_iterator ti(*leaves);\n      TABLE_LIST *tbl_ref;\n      while ((tbl_ref= ti++) && unupdated_tables)\n      {\n        if (unupdated_tables & tbl_ref->table->map)\n          unupdated_tables&= ~tbl_ref->table->map;\n        else\n          continue;\n        if (unupdated_check_opt_tables.push_back(tbl_ref->table))\n          DBUG_RETURN(1);\n      }\n    }\n\n    tmp_param= tmp_table_param+cnt;\n\n    /*\n      Create a temporary table to store all fields that are changed for this\n      table. The first field in the temporary table is a pointer to the\n      original row so that we can find and update it. For the updatable\n      VIEW a few following fields are rowids of tables used in the CHECK\n      OPTION condition.\n    */\n\n    List_iterator_fast tbl_it(unupdated_check_opt_tables);\n    TABLE *tbl= table;\n    do\n    {\n      LEX_CSTRING field_name;\n      field_name.str= tbl->alias.c_ptr();\n      field_name.length= strlen(field_name.str);\n      /*\n        Signal each table (including tables referenced by WITH CHECK OPTION\n        clause) for which we will store row position in the temporary table\n        that we need a position to be read first.\n      */\n      tbl->prepare_for_position();\n      join->map2table[tbl->tablenr]->keep_current_rowid= true;\n\n      Item_temptable_rowid *item=\n        new (thd->mem_root) Item_temptable_rowid(tbl);\n      if (!item)\n         DBUG_RETURN(1);\n      item->fix_fields(thd, 0);\n      if (temp_fields.push_back(item, thd->mem_root))\n        DBUG_RETURN(1);\n    } while ((tbl= tbl_it++));\n\n    temp_fields.append(fields_for_table[cnt]);\n\n    /* Make an unique key over the first field to avoid duplicated updates */\n    bzero((char*) &group, sizeof(group));\n    group.direction= ORDER::ORDER_ASC;\n    group.item= (Item**) temp_fields.head_ref();\n\n    tmp_param->quick_group= 1;\n    tmp_param->field_count= temp_fields.elements;\n    tmp_param->func_count=  temp_fields.elements - 1;\n    calc_group_buffer(tmp_param, &group);\n    /* small table, ignore SQL_BIG_TABLES */\n    my_bool save_big_tables= thd->variables.big_tables; \n    thd->variables.big_tables= FALSE;\n    tmp_tables[cnt]=create_tmp_table(thd, tmp_param, temp_fields,\n                                     (ORDER*) &group, 0, 0,\n                                     TMP_TABLE_ALL_COLUMNS, HA_POS_ERROR, &empty_clex_str);\n    thd->variables.big_tables= save_big_tables;\n    if (!tmp_tables[cnt])\n      DBUG_RETURN(1);\n    tmp_tables[cnt]->file->extra(HA_EXTRA_WRITE_CACHE);\n  }\n  join->tmp_table_keep_current_rowid= TRUE;\n  DBUG_RETURN(0);\n}", "func_hash": 133589877756276645137859301197732446596, "file_name": "None", "file_hash": null, "cwe": ["CWE-617"], "cve": "CVE-2022-27448", "cve_desc": "There is an Assertion failure in MariaDB Server v10.9 and below via 'node->pcur->rel_pos == BTR_PCUR_ON' at /row/row0mysql.cc.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27448"}
{"idx": 514292, "project": "server", "commit_id": "ecb6f9c894d3ebafeff1c6eb3b65cd248062296f", "project_url": "https://github.com/MariaDB/server", "commit_url": "https://github.com/MariaDB/server/commit/ecb6f9c894d3ebafeff1c6eb3b65cd248062296f", "commit_message": "MDEV-28095 crash in multi-update and implicit grouping\n\ndisallow implicit grouping in multi-update.\nexplicit GROUP BY is not allowed by the grammar.", "target": 0, "func": "multi_update::initialize_tables(JOIN *join)\n{\n  TABLE_LIST *table_ref;\n  DBUG_ENTER(\"initialize_tables\");\n\n  if (unlikely((thd->variables.option_bits & OPTION_SAFE_UPDATES) &&\n               error_if_full_join(join)))\n    DBUG_RETURN(1);\n  if (join->implicit_grouping)\n  {\n    my_error(ER_INVALID_GROUP_FUNC_USE, MYF(0));\n    DBUG_RETURN(1);\n  }\n  main_table=join->join_tab->table;\n  table_to_update= 0;\n\n  /* Any update has at least one pair (field, value) */\n  DBUG_ASSERT(fields->elements);\n  /*\n   Only one table may be modified by UPDATE of an updatable view.\n   For an updatable view first_table_for_update indicates this\n   table.\n   For a regular multi-update it refers to some updated table.\n  */ \n  TABLE *first_table_for_update= ((Item_field *) fields->head())->field->table;\n\n  /* Create a temporary table for keys to all tables, except main table */\n  for (table_ref= update_tables; table_ref; table_ref= table_ref->next_local)\n  {\n    TABLE *table=table_ref->table;\n    uint cnt= table_ref->shared;\n    List temp_fields;\n    ORDER     group;\n    TMP_TABLE_PARAM *tmp_param;\n\n    if (ignore)\n      table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);\n    if (table == main_table)\t\t\t// First table in join\n    {\n      if (safe_update_on_fly(thd, join->join_tab, table_ref, all_tables))\n      {\n\ttable_to_update= table;\t\t\t// Update table on the fly\n        has_vers_fields= table->vers_check_update(*fields);\n\tcontinue;\n      }\n    }\n    table->prepare_for_position();\n    join->map2table[table->tablenr]->keep_current_rowid= true;\n\n    /*\n      enable uncacheable flag if we update a view with check option\n      and check option has a subselect, otherwise, the check option\n      can be evaluated after the subselect was freed as independent\n      (See full_local in JOIN::join_free()).\n    */\n    if (table_ref->check_option && !join->select_lex->uncacheable)\n    {\n      SELECT_LEX_UNIT *tmp_unit;\n      SELECT_LEX *sl;\n      for (tmp_unit= join->select_lex->first_inner_unit();\n           tmp_unit;\n           tmp_unit= tmp_unit->next_unit())\n      {\n        for (sl= tmp_unit->first_select(); sl; sl= sl->next_select())\n        {\n          if (sl->master_unit()->item)\n          {\n            join->select_lex->uncacheable|= UNCACHEABLE_CHECKOPTION;\n            goto loop_end;\n          }\n        }\n      }\n    }\nloop_end:\n\n    if (table == first_table_for_update && table_ref->check_option)\n    {\n      table_map unupdated_tables= table_ref->check_option->used_tables() &\n                                  ~first_table_for_update->map;\n      List_iterator ti(*leaves);\n      TABLE_LIST *tbl_ref;\n      while ((tbl_ref= ti++) && unupdated_tables)\n      {\n        if (unupdated_tables & tbl_ref->table->map)\n          unupdated_tables&= ~tbl_ref->table->map;\n        else\n          continue;\n        if (unupdated_check_opt_tables.push_back(tbl_ref->table))\n          DBUG_RETURN(1);\n      }\n    }\n\n    tmp_param= tmp_table_param+cnt;\n\n    /*\n      Create a temporary table to store all fields that are changed for this\n      table. The first field in the temporary table is a pointer to the\n      original row so that we can find and update it. For the updatable\n      VIEW a few following fields are rowids of tables used in the CHECK\n      OPTION condition.\n    */\n\n    List_iterator_fast
tbl_it(unupdated_check_opt_tables);\n TABLE *tbl= table;\n do\n {\n LEX_CSTRING field_name;\n field_name.str= tbl->alias.c_ptr();\n field_name.length= strlen(field_name.str);\n /*\n Signal each table (including tables referenced by WITH CHECK OPTION\n clause) for which we will store row position in the temporary table\n that we need a position to be read first.\n */\n tbl->prepare_for_position();\n join->map2table[tbl->tablenr]->keep_current_rowid= true;\n\n Item_temptable_rowid *item=\n new (thd->mem_root) Item_temptable_rowid(tbl);\n if (!item)\n DBUG_RETURN(1);\n item->fix_fields(thd, 0);\n if (temp_fields.push_back(item, thd->mem_root))\n DBUG_RETURN(1);\n } while ((tbl= tbl_it++));\n\n temp_fields.append(fields_for_table[cnt]);\n\n /* Make an unique key over the first field to avoid duplicated updates */\n bzero((char*) &group, sizeof(group));\n group.direction= ORDER::ORDER_ASC;\n group.item= (Item**) temp_fields.head_ref();\n\n tmp_param->quick_group= 1;\n tmp_param->field_count= temp_fields.elements;\n tmp_param->func_count= temp_fields.elements - 1;\n calc_group_buffer(tmp_param, &group);\n /* small table, ignore SQL_BIG_TABLES */\n my_bool save_big_tables= thd->variables.big_tables; \n thd->variables.big_tables= FALSE;\n tmp_tables[cnt]=create_tmp_table(thd, tmp_param, temp_fields,\n (ORDER*) &group, 0, 0,\n TMP_TABLE_ALL_COLUMNS, HA_POS_ERROR, &empty_clex_str);\n thd->variables.big_tables= save_big_tables;\n if (!tmp_tables[cnt])\n DBUG_RETURN(1);\n tmp_tables[cnt]->file->extra(HA_EXTRA_WRITE_CACHE);\n }\n join->tmp_table_keep_current_rowid= TRUE;\n DBUG_RETURN(0);\n}", "func_hash": 64239982738333152415398593981285799300, "file_name": "None", "file_hash": null, "cwe": ["CWE-617"], "cve": "CVE-2022-27448", "cve_desc": "There is an Assertion failure in MariaDB Server v10.9 and below via 'node->pcur->rel_pos == BTR_PCUR_ON' at /row/row0mysql.cc.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-27448"} {"idx": 217176, "project": "monit", "commit_id": "328f60773057641c4b2075fab9820145e95b728c", "project_url": "https://bitbucket.org/tildeslash/monit", "commit_url": "https://bitbucket.org/tildeslash/monit/commits/328f60773057641c4b2075fab9820145e95b728c", "commit_message": "Fixed: HTML escape the log file content when viewed via Monit GUI.", "target": 1, "func": "static void do_viewlog(HttpRequest req, HttpResponse res) {\n if (is_readonly(req)) {\n send_error(req, res, SC_FORBIDDEN, \"You do not have sufficient privileges to access this page\");\n return;\n }\n do_head(res, \"_viewlog\", \"View log\", 100);\n if ((Run.flags & Run_Log) && ! (Run.flags & Run_UseSyslog)) {\n FILE *f = fopen(Run.files.log, \"r\");\n if (f) {\n size_t n;\n char buf[512];\n StringBuffer_append(res->outputbuffer, \"

\");\n } else {\n StringBuffer_append(res->outputbuffer, \"Error opening logfile: %s\", STRERROR);\n }\n } else {\n StringBuffer_append(res->outputbuffer,\n \"Cannot view logfile:
\");\n if (! (Run.flags & Run_Log))\n StringBuffer_append(res->outputbuffer, \"Monit was started without logging\");\n else\n StringBuffer_append(res->outputbuffer, \"Monit uses syslog\");\n }\n do_foot(res);\n}", "func_hash": 11066915327345888296428446172682700897, "file_name": "None", "file_hash": null, "cwe": ["CWE-79"], "cve": "CVE-2019-11454", "cve_desc": "Persistent cross-site scripting (XSS) in http/cervlet.c in Tildeslash Monit before 5.25.3 allows a remote unauthenticated attacker to introduce arbitrary JavaScript via manipulation of an unsanitized user field of the Authorization header for HTTP Basic Authentication, which is mishandled during an _viewlog operation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-11454"} {"idx": 517437, "project": "monit", "commit_id": "328f60773057641c4b2075fab9820145e95b728c", "project_url": "https://bitbucket.org/tildeslash/monit", "commit_url": "https://bitbucket.org/tildeslash/monit/commits/328f60773057641c4b2075fab9820145e95b728c", "commit_message": "Fixed: HTML escape the log file content when viewed via Monit GUI.", "target": 0, "func": "static void do_viewlog(HttpRequest req, HttpResponse res) {\n if (is_readonly(req)) {\n send_error(req, res, SC_FORBIDDEN, \"You do not have sufficient privileges to access this page\");\n return;\n }\n do_head(res, \"_viewlog\", \"View log\", 100);\n if ((Run.flags & Run_Log) && ! (Run.flags & Run_UseSyslog)) {\n FILE *f = fopen(Run.files.log, \"r\");\n if (f) {\n size_t n;\n char buf[512];\n StringBuffer_append(res->outputbuffer, \"

\");\n } else {\n StringBuffer_append(res->outputbuffer, \"Error opening logfile: %s\", STRERROR);\n }\n } else {\n StringBuffer_append(res->outputbuffer,\n \"Cannot view logfile:
\");\n if (! (Run.flags & Run_Log))\n StringBuffer_append(res->outputbuffer, \"Monit was started without logging\");\n else\n StringBuffer_append(res->outputbuffer, \"Monit uses syslog\");\n }\n do_foot(res);\n}", "func_hash": 289779635859944473579386698211739203129, "file_name": "None", "file_hash": null, "cwe": ["CWE-79"], "cve": "CVE-2019-11454", "cve_desc": "Persistent cross-site scripting (XSS) in http/cervlet.c in Tildeslash Monit before 5.25.3 allows a remote unauthenticated attacker to introduce arbitrary JavaScript via manipulation of an unsanitized user field of the Authorization header for HTTP Basic Authentication, which is mishandled during an _viewlog operation.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2019-11454"} {"idx": 217459, "project": "JUCE", "commit_id": "2e874e80cba0152201aff6a4d0dc407997d10a7f", "project_url": "https://github.com/juce-framework/JUCE", "commit_url": "https://github.com/juce-framework/JUCE/commit/2e874e80cba0152201aff6a4d0dc407997d10a7f", "commit_message": "ZipFile: Add path checks to uncompressEntry()", "target": 1, "func": "Result ZipFile::uncompressEntry (int index, const File& targetDirectory, bool shouldOverwriteFiles)\r\n{\r\n auto* zei = entries.getUnchecked (index);\r\n\r\n #if JUCE_WINDOWS\r\n auto entryPath = zei->entry.filename;\r\n #else\r\n auto entryPath = zei->entry.filename.replaceCharacter ('\\\\', '/');\r\n #endif\r\n\r\n if (entryPath.isEmpty())\r\n return Result::ok();\r\n\r\n auto targetFile = targetDirectory.getChildFile (entryPath);\r\n\r\n if (entryPath.endsWithChar ('/') || entryPath.endsWithChar ('\\\\'))\r\n return targetFile.createDirectory(); // (entry is a directory, not a file)\r\n\r\n std::unique_ptr in (createStreamForEntry (index));\r\n\r\n if (in == nullptr)\r\n return Result::fail (\"Failed to open the zip file for reading\");\r\n\r\n if (targetFile.exists())\r\n {\r\n if (! shouldOverwriteFiles)\r\n return Result::ok();\r\n\r\n if (! targetFile.deleteFile())\r\n return Result::fail (\"Failed to write to target file: \" + targetFile.getFullPathName());\r\n }\r\n\r\n if (! targetFile.getParentDirectory().createDirectory())\r\n return Result::fail (\"Failed to create target folder: \" + targetFile.getParentDirectory().getFullPathName());\r\n\r\n if (zei->entry.isSymbolicLink)\r\n {\r\n String originalFilePath (in->readEntireStreamAsString()\r\n .replaceCharacter (L'/', File::getSeparatorChar()));\r\n\r\n if (! File::createSymbolicLink (targetFile, originalFilePath, true))\r\n return Result::fail (\"Failed to create symbolic link: \" + originalFilePath);\r\n }\r\n else\r\n {\r\n FileOutputStream out (targetFile);\r\n\r\n if (out.failedToOpen())\r\n return Result::fail (\"Failed to write to target file: \" + targetFile.getFullPathName());\r\n\r\n out << *in;\r\n }\r\n\r\n targetFile.setCreationTime (zei->entry.fileTime);\r\n targetFile.setLastModificationTime (zei->entry.fileTime);\r\n targetFile.setLastAccessTime (zei->entry.fileTime);\r\n\r\n return Result::ok();\r\n}\r", "func_hash": 147242935972698231254697341250203186621, "file_name": "None", "file_hash": null, "cwe": ["CWE-59"], "cve": "CVE-2021-23521", "cve_desc": "This affects the package juce-framework/JUCE before 6.1.5. This vulnerability is triggered when a malicious archive is crafted with an entry containing a symbolic link. When extracted, the symbolic link is followed outside of the target dir allowing writing arbitrary files on the target host. In some cases, this can allow an attacker to execute arbitrary code. The vulnerable code is in the ZipFile::uncompressEntry function in juce_ZipFile.cpp and is executed when the archive is extracted upon calling uncompressTo() on a ZipFile object.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-23521"} {"idx": 521488, "project": "JUCE", "commit_id": "2e874e80cba0152201aff6a4d0dc407997d10a7f", "project_url": "https://github.com/juce-framework/JUCE", "commit_url": "https://github.com/juce-framework/JUCE/commit/2e874e80cba0152201aff6a4d0dc407997d10a7f", "commit_message": "ZipFile: Add path checks to uncompressEntry()", "target": 0, "func": "Result ZipFile::uncompressEntry (int index, const File& targetDirectory, OverwriteFiles overwriteFiles, FollowSymlinks followSymlinks)\r\n{\r\n auto* zei = entries.getUnchecked (index);\r\n\r\n #if JUCE_WINDOWS\r\n auto entryPath = zei->entry.filename;\r\n #else\r\n auto entryPath = zei->entry.filename.replaceCharacter ('\\\\', '/');\r\n #endif\r\n\r\n if (entryPath.isEmpty())\r\n return Result::ok();\r\n\r\n auto targetFile = targetDirectory.getChildFile (entryPath);\r\n\r\n if (! targetFile.isAChildOf (targetDirectory))\r\n return Result::fail (\"Entry \" + entryPath + \" is outside the target directory\");\r\n\r\n if (entryPath.endsWithChar ('/') || entryPath.endsWithChar ('\\\\'))\r\n return targetFile.createDirectory(); // (entry is a directory, not a file)\r\n\r\n std::unique_ptr in (createStreamForEntry (index));\r\n\r\n if (in == nullptr)\r\n return Result::fail (\"Failed to open the zip file for reading\");\r\n\r\n if (targetFile.exists())\r\n {\r\n if (overwriteFiles == OverwriteFiles::no)\r\n return Result::ok();\r\n\r\n if (! targetFile.deleteFile())\r\n return Result::fail (\"Failed to write to target file: \" + targetFile.getFullPathName());\r\n }\r\n\r\n if (followSymlinks == FollowSymlinks::no && hasSymbolicPart (targetDirectory, targetFile.getParentDirectory()))\r\n return Result::fail (\"Parent directory leads through symlink for target file: \" + targetFile.getFullPathName());\r\n\r\n if (! targetFile.getParentDirectory().createDirectory())\r\n return Result::fail (\"Failed to create target folder: \" + targetFile.getParentDirectory().getFullPathName());\r\n\r\n if (zei->entry.isSymbolicLink)\r\n {\r\n String originalFilePath (in->readEntireStreamAsString()\r\n .replaceCharacter (L'/', File::getSeparatorChar()));\r\n\r\n if (! File::createSymbolicLink (targetFile, originalFilePath, true))\r\n return Result::fail (\"Failed to create symbolic link: \" + originalFilePath);\r\n }\r\n else\r\n {\r\n FileOutputStream out (targetFile);\r\n\r\n if (out.failedToOpen())\r\n return Result::fail (\"Failed to write to target file: \" + targetFile.getFullPathName());\r\n\r\n out << *in;\r\n }\r\n\r\n targetFile.setCreationTime (zei->entry.fileTime);\r\n targetFile.setLastModificationTime (zei->entry.fileTime);\r\n targetFile.setLastAccessTime (zei->entry.fileTime);\r\n\r\n return Result::ok();\r\n}\r", "func_hash": 31848199774747663184028918368749536503, "file_name": "None", "file_hash": null, "cwe": ["CWE-59"], "cve": "CVE-2021-23521", "cve_desc": "This affects the package juce-framework/JUCE before 6.1.5. This vulnerability is triggered when a malicious archive is crafted with an entry containing a symbolic link. When extracted, the symbolic link is followed outside of the target dir allowing writing arbitrary files on the target host. In some cases, this can allow an attacker to execute arbitrary code. The vulnerable code is in the ZipFile::uncompressEntry function in juce_ZipFile.cpp and is executed when the archive is extracted upon calling uncompressTo() on a ZipFile object.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-23521"} {"idx": 217547, "project": "libMeshb", "commit_id": "8cd68c54e0647c0030ae4506a225ad4a2655c316", "project_url": "https://github.com/LoicMarechal/libMeshb", "commit_url": "https://github.com/LoicMarechal/libMeshb/commit/8cd68c54e0647c0030ae4506a225ad4a2655c316", "commit_message": "Removed a potential buffer overflow crash in GmfOpenMesh and debugged the test_libmeshb_block_pipeline.f that crashed", "target": 1, "func": "int64_t GmfOpenMesh(const char *FilNam, int mod, ...)\n{\n int KwdCod, res, *PtrVer, *PtrDim, err;\n int64_t MshIdx;\n char str[ GmfStrSiz ];\n va_list VarArg;\n GmfMshSct *msh;\n\n /*---------------------*/\n /* MESH STRUCTURE INIT */\n /*---------------------*/\n\n if(!(msh = calloc(1, sizeof(GmfMshSct))))\n return(0);\n\n MshIdx = (int64_t)msh;\n\n // Save the current stack environment for longjmp\n if( (err = setjmp(msh->err)) != 0)\n {\n#ifdef GMFDEBUG\n printf(\"libMeshb : mesh %p : error %d\\n\", msh, err);\n#endif\n if(msh->hdl != NULL)\n fclose(msh->hdl);\n\n if(msh->FilDes != 0)\n#ifdef GMF_WINDOWS\n _close(msh->FilDes);\n#else\n close(msh->FilDes);\n#endif\n\n free(msh);\n return(0);\n }\n\n // Copy the FilNam into the structure\n if(strlen(FilNam) + 7 >= GmfStrSiz)\n longjmp(msh->err, -4);\n\n strcpy(msh->FilNam, FilNam);\n\n // Store the opening mod (read or write) and guess\n // the filetype (binary or ascii) depending on the extension\n msh->mod = mod;\n msh->buf = (void *)msh->DblBuf;\n msh->FltBuf = (void *)msh->DblBuf;\n msh->IntBuf = (void *)msh->DblBuf;\n\n if(strstr(msh->FilNam, \".meshb\"))\n msh->typ |= (Bin | MshFil);\n else if(strstr(msh->FilNam, \".mesh\"))\n msh->typ |= (Asc | MshFil);\n else if(strstr(msh->FilNam, \".solb\"))\n msh->typ |= (Bin | SolFil);\n else if(strstr(msh->FilNam, \".sol\"))\n msh->typ |= (Asc | SolFil);\n else\n longjmp(msh->err, -5);\n\n // Open the file in the required mod and initialize the mesh structure\n if(msh->mod == GmfRead)\n {\n\n /*-----------------------*/\n /* OPEN FILE FOR READING */\n /*-----------------------*/\n\n va_start(VarArg, mod);\n PtrVer = va_arg(VarArg, int *);\n PtrDim = va_arg(VarArg, int *);\n va_end(VarArg);\n\n // Read the endian coding tag, the mesh version\n // and the mesh dimension (mandatory kwd)\n if(msh->typ & Bin)\n {\n // Create the name string and open the file\n#ifdef WITH_GMF_AIO\n // [Bruno] added binary flag (necessary under Windows)\n msh->FilDes = open(msh->FilNam, OPEN_READ_FLAGS, OPEN_READ_MODE);\n\n if(msh->FilDes <= 0)\n longjmp(msh->err, -6);\n\n // Read the endian coding tag\n if(read(msh->FilDes, &msh->cod, WrdSiz) != WrdSiz)\n longjmp(msh->err, -7);\n#else\n // [Bruno] added binary flag (necessary under Windows)\n if(!(msh->hdl = fopen(msh->FilNam, \"rb\")))\n longjmp(msh->err, -8);\n\n // Read the endian coding tag\n safe_fread(&msh->cod, WrdSiz, 1, msh->hdl, msh->err);\n#endif\n\n // Read the mesh version and the mesh dimension (mandatory kwd)\n if( (msh->cod != 1) && (msh->cod != 16777216) )\n longjmp(msh->err, -9);\n\n ScaWrd(msh, (unsigned char *)&msh->ver);\n\n if( (msh->ver < 1) || (msh->ver > 4) )\n longjmp(msh->err, -10);\n\n if( (msh->ver >= 3) && (sizeof(int64_t) != 8) )\n longjmp(msh->err, -11);\n\n ScaWrd(msh, (unsigned char *)&KwdCod);\n\n if(KwdCod != GmfDimension)\n longjmp(msh->err, -12);\n\n GetPos(msh);\n ScaWrd(msh, (unsigned char *)&msh->dim);\n }\n else\n {\n // Create the name string and open the file\n if(!(msh->hdl = fopen(msh->FilNam, \"rb\")))\n longjmp(msh->err, -13);\n\n do\n {\n res = fscanf(msh->hdl, \"%s\", str);\n }while( (res != EOF) && strcmp(str, \"MeshVersionFormatted\") );\n\n if(res == EOF)\n longjmp(msh->err, -14);\n\n safe_fscanf(msh->hdl, \"%d\", &msh->ver, msh->err);\n\n if( (msh->ver < 1) || (msh->ver > 4) )\n longjmp(msh->err, -15);\n\n do\n {\n res = fscanf(msh->hdl, \"%s\", str);\n }while( (res != EOF) && strcmp(str, \"Dimension\") );\n\n if(res == EOF)\n longjmp(msh->err, -16);\n\n safe_fscanf(msh->hdl, \"%d\", &msh->dim, msh->err);\n }\n\n if( (msh->dim != 2) && (msh->dim != 3) )\n longjmp(msh->err, -17);\n\n (*PtrVer) = msh->ver;\n (*PtrDim) = msh->dim;\n\n // Set default real numbers size\n if(msh->ver == 1)\n msh->FltSiz = 32;\n else\n msh->FltSiz = 64;\n\n /*------------*/\n /* KW READING */\n /*------------*/\n\n // Read the list of kw present in the file\n if(!ScaKwdTab(msh))\n return(0);\n\n return(MshIdx);\n }\n else if(msh->mod == GmfWrite)\n {\n\n /*-----------------------*/\n /* OPEN FILE FOR WRITING */\n /*-----------------------*/\n\n msh->cod = 1;\n\n // Check if the user provided a valid version number and dimension\n va_start(VarArg, mod);\n msh->ver = va_arg(VarArg, int);\n msh->dim = va_arg(VarArg, int);\n va_end(VarArg);\n\n if( (msh->ver < 1) || (msh->ver > 4) )\n longjmp(msh->err, -18);\n\n if( (msh->ver >= 3) && (sizeof(int64_t) != 8) )\n longjmp(msh->err, -19);\n\n if( (msh->dim != 2) && (msh->dim != 3) )\n longjmp(msh->err, -20);\n\n // Set default real numbers size\n if(msh->ver == 1)\n msh->FltSiz = 32;\n else\n msh->FltSiz = 64;\n\n // Create the mesh file\n if(msh->typ & Bin) \n {\n /* \n * [Bruno] replaced previous call to creat():\n * with a call to open(), because Windows needs the\n * binary flag to be specified.\n */\n#ifdef WITH_GMF_AIO\n msh->FilDes = open(msh->FilNam, OPEN_WRITE_FLAGS, OPEN_WRITE_MODE);\n\n if(msh->FilDes <= 0)\n longjmp(msh->err, -21);\n#else\n if(!(msh->hdl = fopen(msh->FilNam, \"wb\")))\n longjmp(msh->err, -22);\n#endif\n }\n else if(!(msh->hdl = fopen(msh->FilNam, \"wb\")))\n longjmp(msh->err, -23);\n\n\n /*------------*/\n /* KW WRITING */\n /*------------*/\n\n // Write the mesh version and dimension\n if(msh->typ & Asc)\n {\n fprintf(msh->hdl, \"%s %d\\n\\n\",\n GmfKwdFmt[ GmfVersionFormatted ][0], msh->ver);\n fprintf(msh->hdl, \"%s %d\\n\",\n GmfKwdFmt[ GmfDimension ][0], msh->dim);\n }\n else\n {\n RecWrd(msh, (unsigned char *)&msh->cod);\n RecWrd(msh, (unsigned char *)&msh->ver);\n GmfSetKwd(MshIdx, GmfDimension, 0);\n RecWrd(msh, (unsigned char *)&msh->dim);\n }\n\n return(MshIdx);\n }\n else\n {\n free(msh);\n return(0);\n }\n}", "func_hash": 15680638155848863443525622432898430696, "file_name": "None", "file_hash": null, "cwe": ["CWE-120"], "cve": "CVE-2021-46225", "cve_desc": "A buffer overflow in the GmfOpenMesh() function of libMeshb v7.61 allows attackers to cause a Denial of Service (DoS) via a crafted MESH file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46225"} {"idx": 522329, "project": "libMeshb", "commit_id": "8cd68c54e0647c0030ae4506a225ad4a2655c316", "project_url": "https://github.com/LoicMarechal/libMeshb", "commit_url": "https://github.com/LoicMarechal/libMeshb/commit/8cd68c54e0647c0030ae4506a225ad4a2655c316", "commit_message": "Removed a potential buffer overflow crash in GmfOpenMesh and debugged the test_libmeshb_block_pipeline.f that crashed", "target": 0, "func": "int64_t GmfOpenMesh(const char *FilNam, int mod, ...)\n{\n int KwdCod, res, *PtrVer, *PtrDim, err;\n int64_t MshIdx;\n char str[ GmfStrSiz ];\n va_list VarArg;\n GmfMshSct *msh;\n\n /*---------------------*/\n /* MESH STRUCTURE INIT */\n /*---------------------*/\n\n if(!(msh = calloc(1, sizeof(GmfMshSct))))\n return(0);\n\n MshIdx = (int64_t)msh;\n\n // Save the current stack environment for longjmp\n if( (err = setjmp(msh->err)) != 0)\n {\n#ifdef GMFDEBUG\n printf(\"libMeshb : mesh %p : error %d\\n\", msh, err);\n#endif\n if(msh->hdl != NULL)\n fclose(msh->hdl);\n\n if(msh->FilDes != 0)\n#ifdef GMF_WINDOWS\n _close(msh->FilDes);\n#else\n close(msh->FilDes);\n#endif\n\n free(msh);\n return(0);\n }\n\n // Copy the FilNam into the structure\n if(strlen(FilNam) + 7 >= GmfStrSiz)\n longjmp(msh->err, -4);\n\n strcpy(msh->FilNam, FilNam);\n\n // Store the opening mod (read or write) and guess\n // the filetype (binary or ascii) depending on the extension\n msh->mod = mod;\n msh->buf = (void *)msh->DblBuf;\n msh->FltBuf = (void *)msh->DblBuf;\n msh->IntBuf = (void *)msh->DblBuf;\n\n if(strstr(msh->FilNam, \".meshb\"))\n msh->typ |= (Bin | MshFil);\n else if(strstr(msh->FilNam, \".mesh\"))\n msh->typ |= (Asc | MshFil);\n else if(strstr(msh->FilNam, \".solb\"))\n msh->typ |= (Bin | SolFil);\n else if(strstr(msh->FilNam, \".sol\"))\n msh->typ |= (Asc | SolFil);\n else\n longjmp(msh->err, -5);\n\n // Open the file in the required mod and initialize the mesh structure\n if(msh->mod == GmfRead)\n {\n\n /*-----------------------*/\n /* OPEN FILE FOR READING */\n /*-----------------------*/\n\n va_start(VarArg, mod);\n PtrVer = va_arg(VarArg, int *);\n PtrDim = va_arg(VarArg, int *);\n va_end(VarArg);\n\n // Read the endian coding tag, the mesh version\n // and the mesh dimension (mandatory kwd)\n if(msh->typ & Bin)\n {\n // Create the name string and open the file\n#ifdef WITH_GMF_AIO\n // [Bruno] added binary flag (necessary under Windows)\n msh->FilDes = open(msh->FilNam, OPEN_READ_FLAGS, OPEN_READ_MODE);\n\n if(msh->FilDes <= 0)\n longjmp(msh->err, -6);\n\n // Read the endian coding tag\n if(read(msh->FilDes, &msh->cod, WrdSiz) != WrdSiz)\n longjmp(msh->err, -7);\n#else\n // [Bruno] added binary flag (necessary under Windows)\n if(!(msh->hdl = fopen(msh->FilNam, \"rb\")))\n longjmp(msh->err, -8);\n\n // Read the endian coding tag\n safe_fread(&msh->cod, WrdSiz, 1, msh->hdl, msh->err);\n#endif\n\n // Read the mesh version and the mesh dimension (mandatory kwd)\n if( (msh->cod != 1) && (msh->cod != 16777216) )\n longjmp(msh->err, -9);\n\n ScaWrd(msh, (unsigned char *)&msh->ver);\n\n if( (msh->ver < 1) || (msh->ver > 4) )\n longjmp(msh->err, -10);\n\n if( (msh->ver >= 3) && (sizeof(int64_t) != 8) )\n longjmp(msh->err, -11);\n\n ScaWrd(msh, (unsigned char *)&KwdCod);\n\n if(KwdCod != GmfDimension)\n longjmp(msh->err, -12);\n\n GetPos(msh);\n ScaWrd(msh, (unsigned char *)&msh->dim);\n }\n else\n {\n // Create the name string and open the file\n if(!(msh->hdl = fopen(msh->FilNam, \"rb\")))\n longjmp(msh->err, -13);\n\n do\n {\n res = fscanf(msh->hdl, \"%100s\", str);\n }while( (res != EOF) && strcmp(str, \"MeshVersionFormatted\") );\n\n if(res == EOF)\n longjmp(msh->err, -14);\n\n safe_fscanf(msh->hdl, \"%d\", &msh->ver, msh->err);\n\n if( (msh->ver < 1) || (msh->ver > 4) )\n longjmp(msh->err, -15);\n\n do\n {\n res = fscanf(msh->hdl, \"%100s\", str);\n }while( (res != EOF) && strcmp(str, \"Dimension\") );\n\n if(res == EOF)\n longjmp(msh->err, -16);\n\n safe_fscanf(msh->hdl, \"%d\", &msh->dim, msh->err);\n }\n\n if( (msh->dim != 2) && (msh->dim != 3) )\n longjmp(msh->err, -17);\n\n (*PtrVer) = msh->ver;\n (*PtrDim) = msh->dim;\n\n // Set default real numbers size\n if(msh->ver == 1)\n msh->FltSiz = 32;\n else\n msh->FltSiz = 64;\n\n /*------------*/\n /* KW READING */\n /*------------*/\n\n // Read the list of kw present in the file\n if(!ScaKwdTab(msh))\n return(0);\n\n return(MshIdx);\n }\n else if(msh->mod == GmfWrite)\n {\n\n /*-----------------------*/\n /* OPEN FILE FOR WRITING */\n /*-----------------------*/\n\n msh->cod = 1;\n\n // Check if the user provided a valid version number and dimension\n va_start(VarArg, mod);\n msh->ver = va_arg(VarArg, int);\n msh->dim = va_arg(VarArg, int);\n va_end(VarArg);\n\n if( (msh->ver < 1) || (msh->ver > 4) )\n longjmp(msh->err, -18);\n\n if( (msh->ver >= 3) && (sizeof(int64_t) != 8) )\n longjmp(msh->err, -19);\n\n if( (msh->dim != 2) && (msh->dim != 3) )\n longjmp(msh->err, -20);\n\n // Set default real numbers size\n if(msh->ver == 1)\n msh->FltSiz = 32;\n else\n msh->FltSiz = 64;\n\n // Create the mesh file\n if(msh->typ & Bin) \n {\n /* \n * [Bruno] replaced previous call to creat():\n * with a call to open(), because Windows needs the\n * binary flag to be specified.\n */\n#ifdef WITH_GMF_AIO\n msh->FilDes = open(msh->FilNam, OPEN_WRITE_FLAGS, OPEN_WRITE_MODE);\n\n if(msh->FilDes <= 0)\n longjmp(msh->err, -21);\n#else\n if(!(msh->hdl = fopen(msh->FilNam, \"wb\")))\n longjmp(msh->err, -22);\n#endif\n }\n else if(!(msh->hdl = fopen(msh->FilNam, \"wb\")))\n longjmp(msh->err, -23);\n\n\n /*------------*/\n /* KW WRITING */\n /*------------*/\n\n // Write the mesh version and dimension\n if(msh->typ & Asc)\n {\n fprintf(msh->hdl, \"%s %d\\n\\n\",\n GmfKwdFmt[ GmfVersionFormatted ][0], msh->ver);\n fprintf(msh->hdl, \"%s %d\\n\",\n GmfKwdFmt[ GmfDimension ][0], msh->dim);\n }\n else\n {\n RecWrd(msh, (unsigned char *)&msh->cod);\n RecWrd(msh, (unsigned char *)&msh->ver);\n GmfSetKwd(MshIdx, GmfDimension, 0);\n RecWrd(msh, (unsigned char *)&msh->dim);\n }\n\n return(MshIdx);\n }\n else\n {\n free(msh);\n return(0);\n }\n}", "func_hash": 94702895651186711005755032541348695201, "file_name": "None", "file_hash": null, "cwe": ["CWE-120"], "cve": "CVE-2021-46225", "cve_desc": "A buffer overflow in the GmfOpenMesh() function of libMeshb v7.61 allows attackers to cause a Denial of Service (DoS) via a crafted MESH file.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46225"} {"idx": 217551, "project": "elfspirit", "commit_id": "c5b0f5a9a24f2451bbeda4751d67633bc375e608", "project_url": "https://github.com/liyansong2018/elfspirit", "commit_url": "https://github.com/liyansong2018/elfspirit/commit/c5b0f5a9a24f2451bbeda4751d67633bc375e608", "commit_message": "Fix #1 about out-of-bounds", "target": 1, "func": "int parse(char *elf) {\n int fd;\n struct stat st;\n uint8_t *elf_map;\n int count;\n char *tmp;\n char *name;\n char flag[4];\n\n MODE = get_elf_class(elf);\n\n fd = open(elf, O_RDONLY);\n if (fd < 0) {\n perror(\"open\");\n return -1;\n }\n\n if (fstat(fd, &st) < 0) {\n perror(\"fstat\");\n return -1;\n }\n\n elf_map = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);\n if (elf_map == MAP_FAILED) {\n perror(\"mmap\");\n return -1;\n }\n\n /* 32bit */\n if (MODE == ELFCLASS32) {\n /* ELF Header Information */\n Elf32_Ehdr *ehdr;\n ehdr = (Elf32_Ehdr *)elf_map;\n\n INFO(\"ELF Header\\n\"); \n switch (ehdr->e_type) {\n case ET_NONE:\n tmp = \"An unknown type\";\n break;\n\n case ET_REL:\n tmp = \"A relocatable file\";\n break;\n\n case ET_EXEC:\n tmp = \"An executable file\";\n break;\n\n case ET_DYN:\n tmp = \"A shared object\";\n break;\n\n case ET_CORE:\n tmp = \"A core file\";\n break;\n \n default:\n tmp = \"An unknown type\";\n break;\n }\n PRINT_HEADER_EXP(\"e_type:\", ehdr->e_type, tmp);\n\n switch (ehdr->e_type) {\n case EM_NONE:\n tmp = \"An unknown machine\";\n break;\n\n case EM_M32:\n tmp = \"AT&T WE 32100\";\n break;\n\n case EM_SPARC:\n tmp = \"Sun Microsystems SPARC\";\n break;\n\n case EM_386:\n tmp = \"Intel 80386\";\n break;\n\n case EM_68K:\n tmp = \"Motorola 68000\";\n break;\n \n case EM_88K:\n tmp = \"Motorola 88000\";\n break;\n\n case EM_860:\n tmp = \"Intel 80860\";\n break;\n\n case EM_MIPS:\n tmp = \"MIPS RS3000 (big-endian only)\";\n break;\n\n case EM_PARISC:\n tmp = \"HP/PA\";\n break;\n\n case EM_SPARC32PLUS:\n tmp = \"SPARC with enhanced instruction set\";\n break;\n \n case EM_PPC:\n tmp = \"PowerPC\";\n break;\n\n case EM_PPC64:\n tmp = \"PowerPC 64-bit\";\n break;\n\n case EM_S390:\n tmp = \"IBM S/390\";\n break;\n\n case EM_ARM:\n tmp = \"Advanced RISC Machines\";\n break;\n\n case EM_SH:\n tmp = \"Renesas SuperH\";\n break;\n \n case EM_SPARCV9:\n tmp = \"SPARC v9 64-bit\";\n break;\n\n case EM_IA_64:\n tmp = \"Intel Itanium\";\n break;\n\n case EM_X86_64:\n tmp = \"AMD x86-64\";\n break;\n\n case EM_VAX:\n tmp = \"DEC Vax\";\n break;\n \n default:\n tmp = \"An unknown machine\";\n break;\n }\n PRINT_HEADER_EXP(\"e_machine:\", ehdr->e_machine, tmp);\n\n switch (ehdr->e_version) {\n case EV_NONE:\n tmp = \"Invalid version\";\n break;\n\n case EV_CURRENT:\n tmp = \"Current version\";\n break;\n\n default:\n tmp = \"Known version\";\n break;\n }\n PRINT_HEADER_EXP(\"e_version:\", ehdr->e_version, tmp);\n PRINT_HEADER(\"e_entry:\", ehdr->e_entry);\n PRINT_HEADER(\"e_phoff:\", ehdr->e_phoff);\n PRINT_HEADER(\"e_shoff:\", ehdr->e_shoff);\n PRINT_HEADER(\"e_flags:\", ehdr->e_flags);\n PRINT_HEADER(\"e_ehsize:\", ehdr->e_ehsize);\n PRINT_HEADER(\"e_phentsize:\", ehdr->e_phentsize);\n PRINT_HEADER(\"e_phnum:\", ehdr->e_phnum);\n PRINT_HEADER(\"e_shentsize:\", ehdr->e_shentsize);\n PRINT_HEADER(\"e_shentsize:\", ehdr->e_shentsize);\n PRINT_HEADER(\"e_shstrndx:\", ehdr->e_shstrndx);\n\n /* Section Information */\n Elf32_Shdr *shdr;\n Elf32_Phdr *phdr;\n Elf32_Shdr shstrtab;\n\n shdr = (Elf32_Shdr *)&elf_map[ehdr->e_shoff];\n phdr = (Elf32_Phdr *)&elf_map[ehdr->e_phoff];\n shstrtab = shdr[ehdr->e_shstrndx];\n\n INFO(\"Section Header Table\\n\");\n PRINT_SECTION_TITLE(\"Nr\", \"Name\", \"Type\", \"Addr\", \"Off\", \"Size\", \"Es\", \"Flg\", \"Lk\", \"Inf\", \"Al\");\n for (int i = 0; i < ehdr->e_shnum; i++) {\n name = elf_map + shstrtab.sh_offset + shdr[i].sh_name;\n\n switch (shdr[i].sh_type) {\n case SHT_NULL:\n tmp = \"SHT_NULL\";\n break;\n \n case SHT_PROGBITS:\n tmp = \"SHT_PROGBITS\";\n break;\n\n case SHT_SYMTAB:\n tmp = \"SHT_SYMTAB\";\n break;\n\n case SHT_STRTAB:\n tmp = \"SHT_STRTAB\";\n break;\n\n case SHT_RELA:\n tmp = \"SHT_RELA\";\n break;\n\n case SHT_HASH:\n tmp = \"SHT_HASH\";\n break;\n\n case SHT_DYNAMIC:\n tmp = \"SHT_DYNAMIC\";\n break;\n\n case SHT_NOTE:\n tmp = \"SHT_NOTE\";\n break;\n\n case SHT_NOBITS:\n tmp = \"SHT_NOBITS\";\n break;\n\n case SHT_REL:\n tmp = \"SHT_REL\";\n break;\n\n case SHT_SHLIB:\n tmp = \"SHT_SHLIB\";\n break;\n\n case SHT_DYNSYM:\n tmp = \"SHT_DYNSYM\";\n break;\n\n case SHT_LOPROC:\n tmp = \"SHT_LOPROC\";\n break;\n\n case SHT_HIPROC:\n tmp = \"SHT_HIPROC\";\n break;\n\n case SHT_LOUSER:\n tmp = \"SHT_LOUSER\";\n break;\n\n case SHT_HIUSER:\n tmp = \"SHT_HIUSER\";\n break;\n \n default:\n break;\n }\n\n if (strlen(name) > 15) {\n strcpy(&name[15 - 6], \"[...]\");\n }\n strcpy(flag, \" \");\n flag2str_sh(shdr[i].sh_flags, flag);\n PRINT_SECTION(i, name, tmp, shdr[i].sh_addr, shdr[i].sh_offset, shdr[i].sh_size, shdr[i].sh_entsize, \\\n flag, shdr[i].sh_link, shdr[i].sh_info, shdr[i].sh_addralign);\n }\n\n INFO(\"Program Header Table\\n\");\n PRINT_PROGRAM_TITLE(\"Nr\", \"Type\", \"Offset\", \"Virtaddr\", \"Physaddr\", \"Filesiz\", \"Memsiz\", \"Flg\", \"Align\");\n for (int i = 0; i < ehdr->e_phnum; i++) {\n switch (phdr[i].p_type) {\n case PT_NULL:\n tmp = \"PT_NULL\";\n break;\n \n case PT_LOAD:\n tmp = \"PT_LOAD\";\n break;\n\n case PT_DYNAMIC:\n tmp = \"PT_DYNAMIC\";\n break;\n\n case PT_INTERP:\n tmp = \"PT_INTERP\";\n break;\n\n case PT_NOTE:\n tmp = \"PT_NOTE\";\n break;\n\n case PT_SHLIB:\n tmp = \"PT_SHLIB\";\n break;\n\n case PT_PHDR:\n tmp = \"PT_PHDR\";\n break;\n\n case PT_LOPROC:\n tmp = \"PT_LOPROC\";\n break;\n\n case PT_HIPROC:\n tmp = \"PT_HIPROC\";\n break;\n\n case PT_GNU_STACK:\n tmp = \"PT_GNU_STACK\";\n break;\n \n default:\n break;\n }\n strcpy(flag, \" \");\n flag2str(phdr[i].p_flags, flag);\n PRINT_PROGRAM(i, tmp, phdr[i].p_offset, phdr[i].p_vaddr, phdr[i].p_paddr, phdr[i].p_filesz, phdr[i].p_memsz, flag, phdr[i].p_align); \n }\n\n INFO(\"Section to segment mapping\\n\");\n for (int i = 0; i < ehdr->e_phnum; i++) {\n printf(\" [%2d]\", i);\n for (int j = 0; j < ehdr->e_shnum; j++) {\n name = elf_map + shstrtab.sh_offset + shdr[j].sh_name;\n if (shdr[j].sh_addr >= phdr[i].p_vaddr && shdr[j].sh_addr + shdr[j].sh_size <= phdr[i].p_vaddr + phdr[i].p_memsz && shdr[j].sh_type != SHT_NULL) {\n if (shdr[j].sh_flags >> 1 & 0x1) {\n printf(\" %s\", name);\n }\n } \n }\n printf(\"\\n\");\n }\n\n INFO(\"Dynamic link information\\n\");\n int dynstr;\n int dynamic;\n Elf32_Dyn *dyn;\n for (int i = 0; i < ehdr->e_shnum; i++) {\n name = elf_map + shstrtab.sh_offset + shdr[i].sh_name;\n if (!strcmp(name, \".dynstr\")) {\n dynstr = i;\n }\n if (!strcmp(name, \".dynamic\")) {\n dynamic = i;\n }\n }\n\n char value[50];\n name = \"\";\n dyn = (Elf32_Dyn *)&elf_map[shdr[dynamic].sh_offset];\n count = shdr[dynamic].sh_size / sizeof(Elf32_Dyn);\n INFO(\"Dynamic section at offset 0x%x contains %d entries\\n\", shdr[dynamic].sh_offset, count);\n PRINT_DYN_TITLE(\"Tag\", \"Type\", \"Name/Value\");\n \n for(int i = 0; i < count; i++) {\n tmp = \"\";\n memset(value, 0, 50);\n snprintf(value, 50, \"0x%x\", dyn[i].d_un.d_val);\n switch (dyn[i].d_tag) {\n /* Legal values for d_tag (dynamic entry type). */\n case DT_NULL:\n tmp = \"DT_NULL\";\n break;\n\n case DT_NEEDED:\n tmp = \"DT_NEEDED\";\n name = elf_map + shdr[dynstr].sh_offset + dyn[i].d_un.d_val;\n snprintf(value, 50, \"Shared library: [%s]\", name);\n break;\n \n case DT_PLTRELSZ:\n tmp = \"DT_PLTRELSZ\";\n break;\n\n case DT_PLTGOT:\n tmp = \"DT_PLTGOT\";\n break;\n\n case DT_HASH:\n tmp = \"DT_HASH\";\n break;\n\n case DT_STRTAB:\n tmp = \"DT_STRTAB\";\n break;\n\n case DT_SYMTAB:\n tmp = \"DT_SYMTAB\";\n break;\n\n case DT_RELA:\n tmp = \"DT_RELA\";\n break;\n\n case DT_RELASZ:\n tmp = \"DT_RELASZ\";\n break;\n\n case DT_RELAENT:\n tmp = \"DT_RELAENT\";\n break;\n\n case DT_STRSZ:\n tmp = \"DT_STRSZ\";\n break;\n\n case DT_SYMENT:\n tmp = \"DT_SYMENT\";\n break;\n\n case DT_INIT:\n tmp = \"DT_INIT\";\n break;\n\n case DT_FINI:\n tmp = \"DT_FINI\";\n break;\n\n case DT_SONAME:\n tmp = \"DT_SONAME\";\n break;\n\n case DT_RPATH:\n tmp = \"DT_RPATH\";\n break;\n\n case DT_SYMBOLIC:\n tmp = \"DT_SYMBOLIC\";\n break;\n\n case DT_REL:\n tmp = \"DT_REL\";\n break;\n\n case DT_RELSZ:\n tmp = \"DT_RELSZ\";\n break;\n\n case DT_RELENT:\n tmp = \"DT_RELENT\";\n break;\n \n case DT_PLTREL:\n tmp = \"DT_PLTREL\";\n break;\n\n case DT_DEBUG:\n tmp = \"DT_DEBUG\";\n break;\n\n case DT_TEXTREL:\n tmp = \"DT_TEXTREL\";\n break;\n\n case DT_JMPREL:\n tmp = \"DT_JMPREL\";\n break;\n\n case DT_BIND_NOW:\n tmp = \"DT_BIND_NOW\";\n break;\n\n case DT_INIT_ARRAY:\n tmp = \"DT_INIT_ARRAY\";\n break;\n\n case DT_FINI_ARRAY:\n tmp = \"DT_FINI_ARRAY\";\n break;\n\n case DT_INIT_ARRAYSZ:\n tmp = \"DT_INIT_ARRAYSZ\";\n break;\n \n case DT_FINI_ARRAYSZ:\n tmp = \"DT_FINI_ARRAYSZ\";\n break;\n\n case DT_RUNPATH:\n tmp = \"DT_RUNPATH\";\n break;\n\n case DT_FLAGS:\n tmp = \"DT_FLAGS\";\n snprintf(value, 50, \"Flags: %d\", dyn[i].d_un.d_val);\n break;\n \n case DT_ENCODING:\n tmp = \"DT_ENCODING\";\n break;\n\n case DT_PREINIT_ARRAYSZ:\n tmp = \"DT_PREINIT_ARRAYSZ\";\n break;\n\n case DT_SYMTAB_SHNDX:\n tmp = \"DT_SYMTAB_SHNDX\";\n break;\n \n case DT_NUM:\n tmp = \"DT_NUM\";\n break;\n\n case DT_LOOS:\n tmp = \"DT_LOOS\";\n break;\n\n case DT_HIOS:\n tmp = \"DT_HIOS\";\n break;\n\n case DT_LOPROC:\n tmp = \"DT_LOPROC\";\n break;\n\n case DT_HIPROC:\n tmp = \"DT_HIPROC\";\n break;\n\n case DT_PROCNUM:\n tmp = \"DT_LOPROC\";\n break;\n\n /* DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the\n * Dyn.d_un.d_val field of the Elf*_Dyn structure. This follows Sun's\n * approach. */\n\n case DT_VALRNGLO:\n tmp = \"DT_VALRNGLO\";\n break;\n\n case DT_GNU_PRELINKED:\n tmp = \"DT_GNU_PRELINKED\";\n break;\n \n case DT_GNU_CONFLICTSZ:\n tmp = \"DT_GNU_CONFLICTSZ\";\n break;\n\n case DT_GNU_LIBLISTSZ:\n tmp = \"DT_GNU_LIBLISTSZ\";\n break;\n\n case DT_CHECKSUM:\n tmp = \"DT_CHECKSUM\";\n break;\n\n case DT_PLTPADSZ:\n tmp = \"DT_PLTPADSZ\";\n break;\n\n case DT_MOVEENT:\n tmp = \"DT_MOVEENT\";\n break;\n\n case DT_MOVESZ:\n tmp = \"DT_MOVESZ\";\n break;\n\n case DT_FEATURE_1:\n tmp = \"DT_FEATURE_1\";\n break;\n\n case DT_POSFLAG_1:\n tmp = \"DT_POSFLAG_1\";\n break;\n\n case DT_SYMINSZ:\n tmp = \"DT_SYMINSZ\";\n break;\n\n case DT_SYMINENT:\n tmp = \"DT_SYMINENT\";\n break;\n\n /* DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the\n * Dyn.d_un.d_ptr field of the Elf*_Dyn structure.\n * If any adjustment is made to the ELF object after it has been\n * built these entries will need to be adjusted. */\n case DT_ADDRRNGLO:\n tmp = \"DT_ADDRRNGLO\";\n break;\n\n case DT_GNU_HASH:\n tmp = \"DT_GNU_HASH\";\n break;\n\n case DT_TLSDESC_PLT:\n tmp = \"DT_TLSDESC_PLT\";\n break;\n\n case DT_TLSDESC_GOT:\n tmp = \"DT_TLSDESC_GOT\";\n break;\n\n case DT_GNU_CONFLICT:\n tmp = \"DT_GNU_CONFLICT\";\n break;\n\n case DT_GNU_LIBLIST:\n tmp = \"DT_GNU_LIBLIST\";\n break;\n\n case DT_CONFIG:\n tmp = \"DT_CONFIG\";\n break;\n\n case DT_DEPAUDIT:\n tmp = \"DT_DEPAUDIT\";\n break;\n\n case DT_AUDIT:\n tmp = \"DT_AUDIT\";\n break;\n\n case DT_PLTPAD:\n tmp = \"DT_PLTPAD\";\n break;\n\n case DT_MOVETAB:\n tmp = \"DT_MOVETAB\";\n break;\n\n case DT_SYMINFO:\n tmp = \"DT_SYMINFO\";\n break;\n \n /* The versioning entry types. The next are defined as part of the\n * GNU extension. */\n case DT_VERSYM:\n tmp = \"DT_VERSYM\";\n break;\n\n case DT_RELACOUNT:\n tmp = \"DT_RELACOUNT\";\n break;\n\n case DT_RELCOUNT:\n tmp = \"DT_RELCOUNT\";\n break;\n \n /* These were chosen by Sun. */\n case DT_FLAGS_1:\n tmp = \"DT_FLAGS_1\";\n switch (dyn[i].d_un.d_val) {\n case DF_1_PIE:\n snprintf(value, 50, \"Flags: %s\", \"PIE\");\n break;\n \n default:\n snprintf(value, 50, \"Flags: %d\", dyn[i].d_un.d_val);\n break;\n }\n \n break;\n\n case DT_VERDEF:\n tmp = \"DT_VERDEF\";\n break;\n\n case DT_VERDEFNUM:\n tmp = \"DT_VERDEFNUM\";\n break;\n\n case DT_VERNEED:\n tmp = \"DT_VERNEED\";\n break;\n\n case DT_VERNEEDNUM:\n tmp = \"DT_VERNEEDNUM\";\n break;\n \n default:\n break;\n }\n PRINT_DYN(dyn[i].d_tag, tmp, value);\n } \n }\n\n /* 64bit */\n if (MODE == ELFCLASS64) {\n /* ELF Header Information */\n Elf64_Ehdr *ehdr;\n ehdr = (Elf64_Ehdr *)elf_map;\n\n INFO(\"ELF Header\\n\"); \n switch (ehdr->e_type) {\n case ET_NONE:\n tmp = \"An unknown type\";\n break;\n\n case ET_REL:\n tmp = \"A relocatable file\";\n break;\n\n case ET_EXEC:\n tmp = \"An executable file\";\n break;\n\n case ET_DYN:\n tmp = \"A shared object\";\n break;\n\n case ET_CORE:\n tmp = \"A core file\";\n break;\n \n default:\n tmp = \"An unknown type\";\n break;\n }\n PRINT_HEADER_EXP(\"e_type:\", ehdr->e_type, tmp);\n\n switch (ehdr->e_type) {\n case EM_NONE:\n tmp = \"An unknown machine\";\n break;\n\n case EM_M32:\n tmp = \"AT&T WE 32100\";\n break;\n\n case EM_SPARC:\n tmp = \"Sun Microsystems SPARC\";\n break;\n\n case EM_386:\n tmp = \"Intel 80386\";\n break;\n\n case EM_68K:\n tmp = \"Motorola 68000\";\n break;\n \n case EM_88K:\n tmp = \"Motorola 88000\";\n break;\n\n case EM_860:\n tmp = \"Intel 80860\";\n break;\n\n case EM_MIPS:\n tmp = \"MIPS RS3000 (big-endian only)\";\n break;\n\n case EM_PARISC:\n tmp = \"HP/PA\";\n break;\n\n case EM_SPARC32PLUS:\n tmp = \"SPARC with enhanced instruction set\";\n break;\n \n case EM_PPC:\n tmp = \"PowerPC\";\n break;\n\n case EM_PPC64:\n tmp = \"PowerPC 64-bit\";\n break;\n\n case EM_S390:\n tmp = \"IBM S/390\";\n break;\n\n case EM_ARM:\n tmp = \"Advanced RISC Machines\";\n break;\n\n case EM_SH:\n tmp = \"Renesas SuperH\";\n break;\n \n case EM_SPARCV9:\n tmp = \"SPARC v9 64-bit\";\n break;\n\n case EM_IA_64:\n tmp = \"Intel Itanium\";\n break;\n\n case EM_X86_64:\n tmp = \"AMD x86-64\";\n break;\n\n case EM_VAX:\n tmp = \"DEC Vax\";\n break;\n \n default:\n tmp = \"An unknown machine\";\n break;\n }\n PRINT_HEADER_EXP(\"e_machine:\", ehdr->e_machine, tmp);\n\n switch (ehdr->e_version) {\n case EV_NONE:\n tmp = \"Invalid version\";\n break;\n\n case EV_CURRENT:\n tmp = \"Current version\";\n break;\n\n default:\n tmp = \"Known version\";\n break;\n }\n PRINT_HEADER_EXP(\"e_version:\", ehdr->e_version, tmp);\n PRINT_HEADER(\"e_entry:\", ehdr->e_entry);\n PRINT_HEADER(\"e_phoff:\", ehdr->e_phoff);\n PRINT_HEADER(\"e_shoff:\", ehdr->e_shoff);\n PRINT_HEADER(\"e_flags:\", ehdr->e_flags);\n PRINT_HEADER(\"e_ehsize:\", ehdr->e_ehsize);\n PRINT_HEADER(\"e_phentsize:\", ehdr->e_phentsize);\n PRINT_HEADER(\"e_phnum:\", ehdr->e_phnum);\n PRINT_HEADER(\"e_shentsize:\", ehdr->e_shentsize);\n PRINT_HEADER(\"e_shentsize:\", ehdr->e_shentsize);\n PRINT_HEADER(\"e_shstrndx:\", ehdr->e_shstrndx);\n\n /* Section Information */\n Elf64_Shdr *shdr;\n Elf64_Phdr *phdr;\n Elf64_Shdr shstrtab;\n\n shdr = (Elf64_Shdr *)&elf_map[ehdr->e_shoff];\n phdr = (Elf64_Phdr *)&elf_map[ehdr->e_phoff];\n shstrtab = shdr[ehdr->e_shstrndx];\n\n INFO(\"Section Header Table\\n\");\n PRINT_SECTION_TITLE(\"Nr\", \"Name\", \"Type\", \"Addr\", \"Off\", \"Size\", \"Es\", \"Flg\", \"Lk\", \"Inf\", \"Al\");\n for (int i = 0; i < ehdr->e_shnum; i++) {\n name = elf_map + shstrtab.sh_offset + shdr[i].sh_name;\n\n switch (shdr[i].sh_type) {\n case SHT_NULL:\n tmp = \"SHT_NULL\";\n break;\n \n case SHT_PROGBITS:\n tmp = \"SHT_PROGBITS\";\n break;\n\n case SHT_SYMTAB:\n tmp = \"SHT_SYMTAB\";\n break;\n\n case SHT_STRTAB:\n tmp = \"SHT_STRTAB\";\n break;\n\n case SHT_RELA:\n tmp = \"SHT_RELA\";\n break;\n\n case SHT_HASH:\n tmp = \"SHT_HASH\";\n break;\n\n case SHT_DYNAMIC:\n tmp = \"SHT_DYNAMIC\";\n break;\n\n case SHT_NOTE:\n tmp = \"SHT_NOTE\";\n break;\n\n case SHT_NOBITS:\n tmp = \"SHT_NOBITS\";\n break;\n\n case SHT_REL:\n tmp = \"SHT_REL\";\n break;\n\n case SHT_SHLIB:\n tmp = \"SHT_SHLIB\";\n break;\n\n case SHT_DYNSYM:\n tmp = \"SHT_DYNSYM\";\n break;\n\n case SHT_LOPROC:\n tmp = \"SHT_LOPROC\";\n break;\n\n case SHT_HIPROC:\n tmp = \"SHT_HIPROC\";\n break;\n\n case SHT_LOUSER:\n tmp = \"SHT_LOUSER\";\n break;\n\n case SHT_HIUSER:\n tmp = \"SHT_HIUSER\";\n break;\n \n default:\n break;\n }\n\n if (strlen(name) > 15) {\n strcpy(&name[15 - 6], \"[...]\");\n }\n strcpy(flag, \" \");\n flag2str_sh(shdr[i].sh_flags, flag);\n PRINT_SECTION(i, name, tmp, shdr[i].sh_addr, shdr[i].sh_offset, shdr[i].sh_size, shdr[i].sh_entsize, \\\n flag, shdr[i].sh_link, shdr[i].sh_info, shdr[i].sh_addralign);\n }\n\n INFO(\"Program Header Table\\n\");\n PRINT_PROGRAM_TITLE(\"Nr\", \"Type\", \"Offset\", \"Virtaddr\", \"Physaddr\", \"Filesiz\", \"Memsiz\", \"Flg\", \"Align\");\n for (int i = 0; i < ehdr->e_phnum; i++) {\n switch (phdr[i].p_type) {\n case PT_NULL:\n tmp = \"PT_NULL\";\n break;\n \n case PT_LOAD:\n tmp = \"PT_LOAD\";\n break;\n\n case PT_DYNAMIC:\n tmp = \"PT_DYNAMIC\";\n break;\n\n case PT_INTERP:\n tmp = \"PT_INTERP\";\n break;\n\n case PT_NOTE:\n tmp = \"PT_NOTE\";\n break;\n\n case PT_SHLIB:\n tmp = \"PT_SHLIB\";\n break;\n\n case PT_PHDR:\n tmp = \"PT_PHDR\";\n break;\n\n case PT_LOPROC:\n tmp = \"PT_LOPROC\";\n break;\n\n case PT_HIPROC:\n tmp = \"PT_HIPROC\";\n break;\n\n case PT_GNU_STACK:\n tmp = \"PT_GNU_STACK\";\n break;\n \n default:\n break;\n }\n strcpy(flag, \" \");\n flag2str(phdr[i].p_flags, flag);\n PRINT_PROGRAM(i, tmp, phdr[i].p_offset, phdr[i].p_vaddr, phdr[i].p_paddr, phdr[i].p_filesz, phdr[i].p_memsz, flag, phdr[i].p_align); \n }\n\n INFO(\"Section to segment mapping\\n\");\n for (int i = 0; i < ehdr->e_phnum; i++) {\n printf(\" [%2d]\", i);\n for (int j = 0; j < ehdr->e_shnum; j++) {\n name = elf_map + shstrtab.sh_offset + shdr[j].sh_name;\n if (shdr[j].sh_addr >= phdr[i].p_vaddr && shdr[j].sh_addr + shdr[j].sh_size <= phdr[i].p_vaddr + phdr[i].p_memsz && shdr[j].sh_type != SHT_NULL) {\n if (shdr[j].sh_flags >> 1 & 0x1) {\n printf(\" %s\", name);\n }\n } \n }\n printf(\"\\n\");\n }\n\n INFO(\"Dynamic link information\\n\");\n int dynstr;\n int dynamic;\n Elf64_Dyn *dyn;\n for (int i = 0; i < ehdr->e_shnum; i++) {\n name = elf_map + shstrtab.sh_offset + shdr[i].sh_name;\n if (!strcmp(name, \".dynstr\")) {\n dynstr = i;\n }\n if (!strcmp(name, \".dynamic\")) {\n dynamic = i;\n }\n }\n\n char value[50];\n name = \"\";\n dyn = (Elf64_Dyn *)&elf_map[shdr[dynamic].sh_offset];\n count = shdr[dynamic].sh_size / sizeof(Elf64_Dyn);\n INFO(\"Dynamic section at offset 0x%x contains %d entries\\n\", shdr[dynamic].sh_offset, count);\n PRINT_DYN_TITLE(\"Tag\", \"Type\", \"Name/Value\");\n \n for(int i = 0; i < count; i++) {\n tmp = \"\";\n memset(value, 0, 50);\n snprintf(value, 50, \"0x%x\", dyn[i].d_un.d_val);\n switch (dyn[i].d_tag) {\n /* Legal values for d_tag (dynamic entry type). */\n case DT_NULL:\n tmp = \"DT_NULL\";\n break;\n\n case DT_NEEDED:\n tmp = \"DT_NEEDED\";\n name = elf_map + shdr[dynstr].sh_offset + dyn[i].d_un.d_val;\n snprintf(value, 50, \"Shared library: [%s]\", name);\n break;\n \n case DT_PLTRELSZ:\n tmp = \"DT_PLTRELSZ\";\n break;\n\n case DT_PLTGOT:\n tmp = \"DT_PLTGOT\";\n break;\n\n case DT_HASH:\n tmp = \"DT_HASH\";\n break;\n\n case DT_STRTAB:\n tmp = \"DT_STRTAB\";\n break;\n\n case DT_SYMTAB:\n tmp = \"DT_SYMTAB\";\n break;\n\n case DT_RELA:\n tmp = \"DT_RELA\";\n break;\n\n case DT_RELASZ:\n tmp = \"DT_RELASZ\";\n break;\n\n case DT_RELAENT:\n tmp = \"DT_RELAENT\";\n break;\n\n case DT_STRSZ:\n tmp = \"DT_STRSZ\";\n break;\n\n case DT_SYMENT:\n tmp = \"DT_SYMENT\";\n break;\n\n case DT_INIT:\n tmp = \"DT_INIT\";\n break;\n\n case DT_FINI:\n tmp = \"DT_FINI\";\n break;\n\n case DT_SONAME:\n tmp = \"DT_SONAME\";\n break;\n\n case DT_RPATH:\n tmp = \"DT_RPATH\";\n break;\n\n case DT_SYMBOLIC:\n tmp = \"DT_SYMBOLIC\";\n break;\n\n case DT_REL:\n tmp = \"DT_REL\";\n break;\n\n case DT_RELSZ:\n tmp = \"DT_RELSZ\";\n break;\n\n case DT_RELENT:\n tmp = \"DT_RELENT\";\n break;\n \n case DT_PLTREL:\n tmp = \"DT_PLTREL\";\n break;\n\n case DT_DEBUG:\n tmp = \"DT_DEBUG\";\n break;\n\n case DT_TEXTREL:\n tmp = \"DT_TEXTREL\";\n break;\n\n case DT_JMPREL:\n tmp = \"DT_JMPREL\";\n break;\n\n case DT_BIND_NOW:\n tmp = \"DT_BIND_NOW\";\n break;\n\n case DT_INIT_ARRAY:\n tmp = \"DT_INIT_ARRAY\";\n break;\n\n case DT_FINI_ARRAY:\n tmp = \"DT_FINI_ARRAY\";\n break;\n\n case DT_INIT_ARRAYSZ:\n tmp = \"DT_INIT_ARRAYSZ\";\n break;\n \n case DT_FINI_ARRAYSZ:\n tmp = \"DT_FINI_ARRAYSZ\";\n break;\n\n case DT_RUNPATH:\n tmp = \"DT_RUNPATH\";\n break;\n\n case DT_FLAGS:\n tmp = \"DT_FLAGS\";\n snprintf(value, 50, \"Flags: %d\", dyn[i].d_un.d_val);\n break;\n \n case DT_ENCODING:\n tmp = \"DT_ENCODING\";\n break;\n\n case DT_PREINIT_ARRAYSZ:\n tmp = \"DT_PREINIT_ARRAYSZ\";\n break;\n\n case DT_SYMTAB_SHNDX:\n tmp = \"DT_SYMTAB_SHNDX\";\n break;\n \n case DT_NUM:\n tmp = \"DT_NUM\";\n break;\n\n case DT_LOOS:\n tmp = \"DT_LOOS\";\n break;\n\n case DT_HIOS:\n tmp = \"DT_HIOS\";\n break;\n\n case DT_LOPROC:\n tmp = \"DT_LOPROC\";\n break;\n\n case DT_HIPROC:\n tmp = \"DT_HIPROC\";\n break;\n\n case DT_PROCNUM:\n tmp = \"DT_LOPROC\";\n break;\n\n /* DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the\n * Dyn.d_un.d_val field of the Elf*_Dyn structure. This follows Sun's\n * approach. */\n\n case DT_VALRNGLO:\n tmp = \"DT_VALRNGLO\";\n break;\n\n case DT_GNU_PRELINKED:\n tmp = \"DT_GNU_PRELINKED\";\n break;\n \n case DT_GNU_CONFLICTSZ:\n tmp = \"DT_GNU_CONFLICTSZ\";\n break;\n\n case DT_GNU_LIBLISTSZ:\n tmp = \"DT_GNU_LIBLISTSZ\";\n break;\n\n case DT_CHECKSUM:\n tmp = \"DT_CHECKSUM\";\n break;\n\n case DT_PLTPADSZ:\n tmp = \"DT_PLTPADSZ\";\n break;\n\n case DT_MOVEENT:\n tmp = \"DT_MOVEENT\";\n break;\n\n case DT_MOVESZ:\n tmp = \"DT_MOVESZ\";\n break;\n\n case DT_FEATURE_1:\n tmp = \"DT_FEATURE_1\";\n break;\n\n case DT_POSFLAG_1:\n tmp = \"DT_POSFLAG_1\";\n break;\n\n case DT_SYMINSZ:\n tmp = \"DT_SYMINSZ\";\n break;\n\n case DT_SYMINENT:\n tmp = \"DT_SYMINENT\";\n break;\n\n /* DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the\n * Dyn.d_un.d_ptr field of the Elf*_Dyn structure.\n * If any adjustment is made to the ELF object after it has been\n * built these entries will need to be adjusted. */\n case DT_ADDRRNGLO:\n tmp = \"DT_ADDRRNGLO\";\n break;\n\n case DT_GNU_HASH:\n tmp = \"DT_GNU_HASH\";\n break;\n\n case DT_TLSDESC_PLT:\n tmp = \"DT_TLSDESC_PLT\";\n break;\n\n case DT_TLSDESC_GOT:\n tmp = \"DT_TLSDESC_GOT\";\n break;\n\n case DT_GNU_CONFLICT:\n tmp = \"DT_GNU_CONFLICT\";\n break;\n\n case DT_GNU_LIBLIST:\n tmp = \"DT_GNU_LIBLIST\";\n break;\n\n case DT_CONFIG:\n tmp = \"DT_CONFIG\";\n break;\n\n case DT_DEPAUDIT:\n tmp = \"DT_DEPAUDIT\";\n break;\n\n case DT_AUDIT:\n tmp = \"DT_AUDIT\";\n break;\n\n case DT_PLTPAD:\n tmp = \"DT_PLTPAD\";\n break;\n\n case DT_MOVETAB:\n tmp = \"DT_MOVETAB\";\n break;\n\n case DT_SYMINFO:\n tmp = \"DT_SYMINFO\";\n break;\n \n /* The versioning entry types. The next are defined as part of the\n * GNU extension. */\n case DT_VERSYM:\n tmp = \"DT_VERSYM\";\n break;\n\n case DT_RELACOUNT:\n tmp = \"DT_RELACOUNT\";\n break;\n\n case DT_RELCOUNT:\n tmp = \"DT_RELCOUNT\";\n break;\n \n /* These were chosen by Sun. */\n case DT_FLAGS_1:\n tmp = \"DT_FLAGS_1\";\n switch (dyn[i].d_un.d_val) {\n case DF_1_PIE:\n snprintf(value, 50, \"Flags: %s\", \"PIE\");\n break;\n \n default:\n snprintf(value, 50, \"Flags: %d\", dyn[i].d_un.d_val);\n break;\n }\n \n break;\n\n case DT_VERDEF:\n tmp = \"DT_VERDEF\";\n break;\n\n case DT_VERDEFNUM:\n tmp = \"DT_VERDEFNUM\";\n break;\n\n case DT_VERNEED:\n tmp = \"DT_VERNEED\";\n break;\n\n case DT_VERNEEDNUM:\n tmp = \"DT_VERNEEDNUM\";\n break;\n \n default:\n break;\n }\n PRINT_DYN(dyn[i].d_tag, tmp, value);\n } \n }\n\n return 0;\n}", "func_hash": 10492118832219739041814229234332696880, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2022-21711", "cve_desc": "elfspirit is an ELF static analysis and injection framework that parses, manipulates, and camouflages ELF files. When analyzing the ELF file format in versions prior to 1.1, there is an out-of-bounds read bug, which can lead to application crashes or information leakage. By constructing a special format ELF file, the information of any address can be leaked. elfspirit version 1.1 contains a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21711"} {"idx": 522438, "project": "elfspirit", "commit_id": "c5b0f5a9a24f2451bbeda4751d67633bc375e608", "project_url": "https://github.com/liyansong2018/elfspirit", "commit_url": "https://github.com/liyansong2018/elfspirit/commit/c5b0f5a9a24f2451bbeda4751d67633bc375e608", "commit_message": "Fix #1 about out-of-bounds", "target": 0, "func": "int parse(char *elf) {\n int fd;\n struct stat st;\n uint8_t *elf_map;\n int count;\n char *tmp;\n char *name;\n char flag[4];\n\n MODE = get_elf_class(elf);\n\n fd = open(elf, O_RDONLY);\n if (fd < 0) {\n perror(\"open\");\n return -1;\n }\n\n if (fstat(fd, &st) < 0) {\n perror(\"fstat\");\n return -1;\n }\n\n elf_map = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);\n if (elf_map == MAP_FAILED) {\n perror(\"mmap\");\n return -1;\n }\n\n /* 32bit */\n if (MODE == ELFCLASS32) {\n /* ELF Header Information */\n Elf32_Ehdr *ehdr;\n ehdr = (Elf32_Ehdr *)elf_map;\n\n INFO(\"ELF Header\\n\"); \n switch (ehdr->e_type) {\n case ET_NONE:\n tmp = \"An unknown type\";\n break;\n\n case ET_REL:\n tmp = \"A relocatable file\";\n break;\n\n case ET_EXEC:\n tmp = \"An executable file\";\n break;\n\n case ET_DYN:\n tmp = \"A shared object\";\n break;\n\n case ET_CORE:\n tmp = \"A core file\";\n break;\n \n default:\n tmp = \"An unknown type\";\n break;\n }\n PRINT_HEADER_EXP(\"e_type:\", ehdr->e_type, tmp);\n\n switch (ehdr->e_type) {\n case EM_NONE:\n tmp = \"An unknown machine\";\n break;\n\n case EM_M32:\n tmp = \"AT&T WE 32100\";\n break;\n\n case EM_SPARC:\n tmp = \"Sun Microsystems SPARC\";\n break;\n\n case EM_386:\n tmp = \"Intel 80386\";\n break;\n\n case EM_68K:\n tmp = \"Motorola 68000\";\n break;\n \n case EM_88K:\n tmp = \"Motorola 88000\";\n break;\n\n case EM_860:\n tmp = \"Intel 80860\";\n break;\n\n case EM_MIPS:\n tmp = \"MIPS RS3000 (big-endian only)\";\n break;\n\n case EM_PARISC:\n tmp = \"HP/PA\";\n break;\n\n case EM_SPARC32PLUS:\n tmp = \"SPARC with enhanced instruction set\";\n break;\n \n case EM_PPC:\n tmp = \"PowerPC\";\n break;\n\n case EM_PPC64:\n tmp = \"PowerPC 64-bit\";\n break;\n\n case EM_S390:\n tmp = \"IBM S/390\";\n break;\n\n case EM_ARM:\n tmp = \"Advanced RISC Machines\";\n break;\n\n case EM_SH:\n tmp = \"Renesas SuperH\";\n break;\n \n case EM_SPARCV9:\n tmp = \"SPARC v9 64-bit\";\n break;\n\n case EM_IA_64:\n tmp = \"Intel Itanium\";\n break;\n\n case EM_X86_64:\n tmp = \"AMD x86-64\";\n break;\n\n case EM_VAX:\n tmp = \"DEC Vax\";\n break;\n \n default:\n tmp = \"An unknown machine\";\n break;\n }\n PRINT_HEADER_EXP(\"e_machine:\", ehdr->e_machine, tmp);\n\n switch (ehdr->e_version) {\n case EV_NONE:\n tmp = \"Invalid version\";\n break;\n\n case EV_CURRENT:\n tmp = \"Current version\";\n break;\n\n default:\n tmp = \"Known version\";\n break;\n }\n PRINT_HEADER_EXP(\"e_version:\", ehdr->e_version, tmp);\n PRINT_HEADER(\"e_entry:\", ehdr->e_entry);\n PRINT_HEADER(\"e_phoff:\", ehdr->e_phoff);\n PRINT_HEADER(\"e_shoff:\", ehdr->e_shoff);\n PRINT_HEADER(\"e_flags:\", ehdr->e_flags);\n PRINT_HEADER(\"e_ehsize:\", ehdr->e_ehsize);\n PRINT_HEADER(\"e_phentsize:\", ehdr->e_phentsize);\n PRINT_HEADER(\"e_phnum:\", ehdr->e_phnum);\n PRINT_HEADER(\"e_shentsize:\", ehdr->e_shentsize);\n PRINT_HEADER(\"e_shentsize:\", ehdr->e_shentsize);\n PRINT_HEADER(\"e_shstrndx:\", ehdr->e_shstrndx);\n\n /* Section Information */\n Elf32_Shdr *shdr;\n Elf32_Phdr *phdr;\n Elf32_Shdr shstrtab;\n\n shdr = (Elf32_Shdr *)&elf_map[ehdr->e_shoff];\n phdr = (Elf32_Phdr *)&elf_map[ehdr->e_phoff];\n shstrtab = shdr[ehdr->e_shstrndx];\n\n INFO(\"Section Header Table\\n\");\n PRINT_SECTION_TITLE(\"Nr\", \"Name\", \"Type\", \"Addr\", \"Off\", \"Size\", \"Es\", \"Flg\", \"Lk\", \"Inf\", \"Al\");\n for (int i = 0; i < ehdr->e_shnum; i++) {\n name = elf_map + shstrtab.sh_offset + shdr[i].sh_name;\n if (validated_offset(name, elf_map, elf_map + st.st_size)) {\n ERROR(\"Corrupt file format\\n\");\n return -1;\n }\n\n switch (shdr[i].sh_type) {\n case SHT_NULL:\n tmp = \"SHT_NULL\";\n break;\n \n case SHT_PROGBITS:\n tmp = \"SHT_PROGBITS\";\n break;\n\n case SHT_SYMTAB:\n tmp = \"SHT_SYMTAB\";\n break;\n\n case SHT_STRTAB:\n tmp = \"SHT_STRTAB\";\n break;\n\n case SHT_RELA:\n tmp = \"SHT_RELA\";\n break;\n\n case SHT_HASH:\n tmp = \"SHT_HASH\";\n break;\n\n case SHT_DYNAMIC:\n tmp = \"SHT_DYNAMIC\";\n break;\n\n case SHT_NOTE:\n tmp = \"SHT_NOTE\";\n break;\n\n case SHT_NOBITS:\n tmp = \"SHT_NOBITS\";\n break;\n\n case SHT_REL:\n tmp = \"SHT_REL\";\n break;\n\n case SHT_SHLIB:\n tmp = \"SHT_SHLIB\";\n break;\n\n case SHT_DYNSYM:\n tmp = \"SHT_DYNSYM\";\n break;\n\n case SHT_LOPROC:\n tmp = \"SHT_LOPROC\";\n break;\n\n case SHT_HIPROC:\n tmp = \"SHT_HIPROC\";\n break;\n\n case SHT_LOUSER:\n tmp = \"SHT_LOUSER\";\n break;\n\n case SHT_HIUSER:\n tmp = \"SHT_HIUSER\";\n break;\n \n default:\n break;\n }\n\n if (strlen(name) > 15) {\n strcpy(&name[15 - 6], \"[...]\");\n }\n strcpy(flag, \" \");\n flag2str_sh(shdr[i].sh_flags, flag);\n PRINT_SECTION(i, name, tmp, shdr[i].sh_addr, shdr[i].sh_offset, shdr[i].sh_size, shdr[i].sh_entsize, \\\n flag, shdr[i].sh_link, shdr[i].sh_info, shdr[i].sh_addralign);\n }\n\n INFO(\"Program Header Table\\n\");\n PRINT_PROGRAM_TITLE(\"Nr\", \"Type\", \"Offset\", \"Virtaddr\", \"Physaddr\", \"Filesiz\", \"Memsiz\", \"Flg\", \"Align\");\n for (int i = 0; i < ehdr->e_phnum; i++) {\n switch (phdr[i].p_type) {\n case PT_NULL:\n tmp = \"PT_NULL\";\n break;\n \n case PT_LOAD:\n tmp = \"PT_LOAD\";\n break;\n\n case PT_DYNAMIC:\n tmp = \"PT_DYNAMIC\";\n break;\n\n case PT_INTERP:\n tmp = \"PT_INTERP\";\n break;\n\n case PT_NOTE:\n tmp = \"PT_NOTE\";\n break;\n\n case PT_SHLIB:\n tmp = \"PT_SHLIB\";\n break;\n\n case PT_PHDR:\n tmp = \"PT_PHDR\";\n break;\n\n case PT_LOPROC:\n tmp = \"PT_LOPROC\";\n break;\n\n case PT_HIPROC:\n tmp = \"PT_HIPROC\";\n break;\n\n case PT_GNU_STACK:\n tmp = \"PT_GNU_STACK\";\n break;\n \n default:\n break;\n }\n strcpy(flag, \" \");\n flag2str(phdr[i].p_flags, flag);\n PRINT_PROGRAM(i, tmp, phdr[i].p_offset, phdr[i].p_vaddr, phdr[i].p_paddr, phdr[i].p_filesz, phdr[i].p_memsz, flag, phdr[i].p_align); \n }\n\n INFO(\"Section to segment mapping\\n\");\n for (int i = 0; i < ehdr->e_phnum; i++) {\n printf(\" [%2d]\", i);\n for (int j = 0; j < ehdr->e_shnum; j++) {\n name = elf_map + shstrtab.sh_offset + shdr[j].sh_name;\n if (shdr[j].sh_addr >= phdr[i].p_vaddr && shdr[j].sh_addr + shdr[j].sh_size <= phdr[i].p_vaddr + phdr[i].p_memsz && shdr[j].sh_type != SHT_NULL) {\n if (shdr[j].sh_flags >> 1 & 0x1) {\n printf(\" %s\", name);\n }\n } \n }\n printf(\"\\n\");\n }\n\n INFO(\"Dynamic link information\\n\");\n int dynstr;\n int dynamic;\n Elf32_Dyn *dyn;\n for (int i = 0; i < ehdr->e_shnum; i++) {\n name = elf_map + shstrtab.sh_offset + shdr[i].sh_name;\n if (!strcmp(name, \".dynstr\")) {\n dynstr = i;\n }\n if (!strcmp(name, \".dynamic\")) {\n dynamic = i;\n }\n }\n\n char value[50];\n name = \"\";\n dyn = (Elf32_Dyn *)&elf_map[shdr[dynamic].sh_offset];\n count = shdr[dynamic].sh_size / sizeof(Elf32_Dyn);\n INFO(\"Dynamic section at offset 0x%x contains %d entries\\n\", shdr[dynamic].sh_offset, count);\n PRINT_DYN_TITLE(\"Tag\", \"Type\", \"Name/Value\");\n \n for(int i = 0; i < count; i++) {\n tmp = \"\";\n memset(value, 0, 50);\n snprintf(value, 50, \"0x%x\", dyn[i].d_un.d_val);\n switch (dyn[i].d_tag) {\n /* Legal values for d_tag (dynamic entry type). */\n case DT_NULL:\n tmp = \"DT_NULL\";\n break;\n\n case DT_NEEDED:\n tmp = \"DT_NEEDED\";\n name = elf_map + shdr[dynstr].sh_offset + dyn[i].d_un.d_val;\n snprintf(value, 50, \"Shared library: [%s]\", name);\n break;\n \n case DT_PLTRELSZ:\n tmp = \"DT_PLTRELSZ\";\n break;\n\n case DT_PLTGOT:\n tmp = \"DT_PLTGOT\";\n break;\n\n case DT_HASH:\n tmp = \"DT_HASH\";\n break;\n\n case DT_STRTAB:\n tmp = \"DT_STRTAB\";\n break;\n\n case DT_SYMTAB:\n tmp = \"DT_SYMTAB\";\n break;\n\n case DT_RELA:\n tmp = \"DT_RELA\";\n break;\n\n case DT_RELASZ:\n tmp = \"DT_RELASZ\";\n break;\n\n case DT_RELAENT:\n tmp = \"DT_RELAENT\";\n break;\n\n case DT_STRSZ:\n tmp = \"DT_STRSZ\";\n break;\n\n case DT_SYMENT:\n tmp = \"DT_SYMENT\";\n break;\n\n case DT_INIT:\n tmp = \"DT_INIT\";\n break;\n\n case DT_FINI:\n tmp = \"DT_FINI\";\n break;\n\n case DT_SONAME:\n tmp = \"DT_SONAME\";\n break;\n\n case DT_RPATH:\n tmp = \"DT_RPATH\";\n break;\n\n case DT_SYMBOLIC:\n tmp = \"DT_SYMBOLIC\";\n break;\n\n case DT_REL:\n tmp = \"DT_REL\";\n break;\n\n case DT_RELSZ:\n tmp = \"DT_RELSZ\";\n break;\n\n case DT_RELENT:\n tmp = \"DT_RELENT\";\n break;\n \n case DT_PLTREL:\n tmp = \"DT_PLTREL\";\n break;\n\n case DT_DEBUG:\n tmp = \"DT_DEBUG\";\n break;\n\n case DT_TEXTREL:\n tmp = \"DT_TEXTREL\";\n break;\n\n case DT_JMPREL:\n tmp = \"DT_JMPREL\";\n break;\n\n case DT_BIND_NOW:\n tmp = \"DT_BIND_NOW\";\n break;\n\n case DT_INIT_ARRAY:\n tmp = \"DT_INIT_ARRAY\";\n break;\n\n case DT_FINI_ARRAY:\n tmp = \"DT_FINI_ARRAY\";\n break;\n\n case DT_INIT_ARRAYSZ:\n tmp = \"DT_INIT_ARRAYSZ\";\n break;\n \n case DT_FINI_ARRAYSZ:\n tmp = \"DT_FINI_ARRAYSZ\";\n break;\n\n case DT_RUNPATH:\n tmp = \"DT_RUNPATH\";\n break;\n\n case DT_FLAGS:\n tmp = \"DT_FLAGS\";\n snprintf(value, 50, \"Flags: %d\", dyn[i].d_un.d_val);\n break;\n \n case DT_ENCODING:\n tmp = \"DT_ENCODING\";\n break;\n\n case DT_PREINIT_ARRAYSZ:\n tmp = \"DT_PREINIT_ARRAYSZ\";\n break;\n\n case DT_SYMTAB_SHNDX:\n tmp = \"DT_SYMTAB_SHNDX\";\n break;\n \n case DT_NUM:\n tmp = \"DT_NUM\";\n break;\n\n case DT_LOOS:\n tmp = \"DT_LOOS\";\n break;\n\n case DT_HIOS:\n tmp = \"DT_HIOS\";\n break;\n\n case DT_LOPROC:\n tmp = \"DT_LOPROC\";\n break;\n\n case DT_HIPROC:\n tmp = \"DT_HIPROC\";\n break;\n\n case DT_PROCNUM:\n tmp = \"DT_LOPROC\";\n break;\n\n /* DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the\n * Dyn.d_un.d_val field of the Elf*_Dyn structure. This follows Sun's\n * approach. */\n\n case DT_VALRNGLO:\n tmp = \"DT_VALRNGLO\";\n break;\n\n case DT_GNU_PRELINKED:\n tmp = \"DT_GNU_PRELINKED\";\n break;\n \n case DT_GNU_CONFLICTSZ:\n tmp = \"DT_GNU_CONFLICTSZ\";\n break;\n\n case DT_GNU_LIBLISTSZ:\n tmp = \"DT_GNU_LIBLISTSZ\";\n break;\n\n case DT_CHECKSUM:\n tmp = \"DT_CHECKSUM\";\n break;\n\n case DT_PLTPADSZ:\n tmp = \"DT_PLTPADSZ\";\n break;\n\n case DT_MOVEENT:\n tmp = \"DT_MOVEENT\";\n break;\n\n case DT_MOVESZ:\n tmp = \"DT_MOVESZ\";\n break;\n\n case DT_FEATURE_1:\n tmp = \"DT_FEATURE_1\";\n break;\n\n case DT_POSFLAG_1:\n tmp = \"DT_POSFLAG_1\";\n break;\n\n case DT_SYMINSZ:\n tmp = \"DT_SYMINSZ\";\n break;\n\n case DT_SYMINENT:\n tmp = \"DT_SYMINENT\";\n break;\n\n /* DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the\n * Dyn.d_un.d_ptr field of the Elf*_Dyn structure.\n * If any adjustment is made to the ELF object after it has been\n * built these entries will need to be adjusted. */\n case DT_ADDRRNGLO:\n tmp = \"DT_ADDRRNGLO\";\n break;\n\n case DT_GNU_HASH:\n tmp = \"DT_GNU_HASH\";\n break;\n\n case DT_TLSDESC_PLT:\n tmp = \"DT_TLSDESC_PLT\";\n break;\n\n case DT_TLSDESC_GOT:\n tmp = \"DT_TLSDESC_GOT\";\n break;\n\n case DT_GNU_CONFLICT:\n tmp = \"DT_GNU_CONFLICT\";\n break;\n\n case DT_GNU_LIBLIST:\n tmp = \"DT_GNU_LIBLIST\";\n break;\n\n case DT_CONFIG:\n tmp = \"DT_CONFIG\";\n break;\n\n case DT_DEPAUDIT:\n tmp = \"DT_DEPAUDIT\";\n break;\n\n case DT_AUDIT:\n tmp = \"DT_AUDIT\";\n break;\n\n case DT_PLTPAD:\n tmp = \"DT_PLTPAD\";\n break;\n\n case DT_MOVETAB:\n tmp = \"DT_MOVETAB\";\n break;\n\n case DT_SYMINFO:\n tmp = \"DT_SYMINFO\";\n break;\n \n /* The versioning entry types. The next are defined as part of the\n * GNU extension. */\n case DT_VERSYM:\n tmp = \"DT_VERSYM\";\n break;\n\n case DT_RELACOUNT:\n tmp = \"DT_RELACOUNT\";\n break;\n\n case DT_RELCOUNT:\n tmp = \"DT_RELCOUNT\";\n break;\n \n /* These were chosen by Sun. */\n case DT_FLAGS_1:\n tmp = \"DT_FLAGS_1\";\n switch (dyn[i].d_un.d_val) {\n case DF_1_PIE:\n snprintf(value, 50, \"Flags: %s\", \"PIE\");\n break;\n \n default:\n snprintf(value, 50, \"Flags: %d\", dyn[i].d_un.d_val);\n break;\n }\n \n break;\n\n case DT_VERDEF:\n tmp = \"DT_VERDEF\";\n break;\n\n case DT_VERDEFNUM:\n tmp = \"DT_VERDEFNUM\";\n break;\n\n case DT_VERNEED:\n tmp = \"DT_VERNEED\";\n break;\n\n case DT_VERNEEDNUM:\n tmp = \"DT_VERNEEDNUM\";\n break;\n \n default:\n break;\n }\n PRINT_DYN(dyn[i].d_tag, tmp, value);\n } \n }\n\n /* 64bit */\n if (MODE == ELFCLASS64) {\n /* ELF Header Information */\n Elf64_Ehdr *ehdr;\n ehdr = (Elf64_Ehdr *)elf_map;\n\n INFO(\"ELF Header\\n\"); \n switch (ehdr->e_type) {\n case ET_NONE:\n tmp = \"An unknown type\";\n break;\n\n case ET_REL:\n tmp = \"A relocatable file\";\n break;\n\n case ET_EXEC:\n tmp = \"An executable file\";\n break;\n\n case ET_DYN:\n tmp = \"A shared object\";\n break;\n\n case ET_CORE:\n tmp = \"A core file\";\n break;\n \n default:\n tmp = \"An unknown type\";\n break;\n }\n PRINT_HEADER_EXP(\"e_type:\", ehdr->e_type, tmp);\n\n switch (ehdr->e_type) {\n case EM_NONE:\n tmp = \"An unknown machine\";\n break;\n\n case EM_M32:\n tmp = \"AT&T WE 32100\";\n break;\n\n case EM_SPARC:\n tmp = \"Sun Microsystems SPARC\";\n break;\n\n case EM_386:\n tmp = \"Intel 80386\";\n break;\n\n case EM_68K:\n tmp = \"Motorola 68000\";\n break;\n \n case EM_88K:\n tmp = \"Motorola 88000\";\n break;\n\n case EM_860:\n tmp = \"Intel 80860\";\n break;\n\n case EM_MIPS:\n tmp = \"MIPS RS3000 (big-endian only)\";\n break;\n\n case EM_PARISC:\n tmp = \"HP/PA\";\n break;\n\n case EM_SPARC32PLUS:\n tmp = \"SPARC with enhanced instruction set\";\n break;\n \n case EM_PPC:\n tmp = \"PowerPC\";\n break;\n\n case EM_PPC64:\n tmp = \"PowerPC 64-bit\";\n break;\n\n case EM_S390:\n tmp = \"IBM S/390\";\n break;\n\n case EM_ARM:\n tmp = \"Advanced RISC Machines\";\n break;\n\n case EM_SH:\n tmp = \"Renesas SuperH\";\n break;\n \n case EM_SPARCV9:\n tmp = \"SPARC v9 64-bit\";\n break;\n\n case EM_IA_64:\n tmp = \"Intel Itanium\";\n break;\n\n case EM_X86_64:\n tmp = \"AMD x86-64\";\n break;\n\n case EM_VAX:\n tmp = \"DEC Vax\";\n break;\n \n default:\n tmp = \"An unknown machine\";\n break;\n }\n PRINT_HEADER_EXP(\"e_machine:\", ehdr->e_machine, tmp);\n\n switch (ehdr->e_version) {\n case EV_NONE:\n tmp = \"Invalid version\";\n break;\n\n case EV_CURRENT:\n tmp = \"Current version\";\n break;\n\n default:\n tmp = \"Known version\";\n break;\n }\n PRINT_HEADER_EXP(\"e_version:\", ehdr->e_version, tmp);\n PRINT_HEADER(\"e_entry:\", ehdr->e_entry);\n PRINT_HEADER(\"e_phoff:\", ehdr->e_phoff);\n PRINT_HEADER(\"e_shoff:\", ehdr->e_shoff);\n PRINT_HEADER(\"e_flags:\", ehdr->e_flags);\n PRINT_HEADER(\"e_ehsize:\", ehdr->e_ehsize);\n PRINT_HEADER(\"e_phentsize:\", ehdr->e_phentsize);\n PRINT_HEADER(\"e_phnum:\", ehdr->e_phnum);\n PRINT_HEADER(\"e_shentsize:\", ehdr->e_shentsize);\n PRINT_HEADER(\"e_shentsize:\", ehdr->e_shentsize);\n PRINT_HEADER(\"e_shstrndx:\", ehdr->e_shstrndx);\n\n /* Section Information */\n Elf64_Shdr *shdr;\n Elf64_Phdr *phdr;\n Elf64_Shdr shstrtab;\n\n shdr = (Elf64_Shdr *)&elf_map[ehdr->e_shoff];\n phdr = (Elf64_Phdr *)&elf_map[ehdr->e_phoff];\n shstrtab = shdr[ehdr->e_shstrndx];\n\n INFO(\"Section Header Table\\n\");\n PRINT_SECTION_TITLE(\"Nr\", \"Name\", \"Type\", \"Addr\", \"Off\", \"Size\", \"Es\", \"Flg\", \"Lk\", \"Inf\", \"Al\");\n for (int i = 0; i < ehdr->e_shnum; i++) {\n name = elf_map + shstrtab.sh_offset + shdr[i].sh_name;\n if (validated_offset(name, elf_map, elf_map + st.st_size)) {\n ERROR(\"Corrupt file format\\n\");\n return -1;\n }\n\n switch (shdr[i].sh_type) {\n case SHT_NULL:\n tmp = \"SHT_NULL\";\n break;\n \n case SHT_PROGBITS:\n tmp = \"SHT_PROGBITS\";\n break;\n\n case SHT_SYMTAB:\n tmp = \"SHT_SYMTAB\";\n break;\n\n case SHT_STRTAB:\n tmp = \"SHT_STRTAB\";\n break;\n\n case SHT_RELA:\n tmp = \"SHT_RELA\";\n break;\n\n case SHT_HASH:\n tmp = \"SHT_HASH\";\n break;\n\n case SHT_DYNAMIC:\n tmp = \"SHT_DYNAMIC\";\n break;\n\n case SHT_NOTE:\n tmp = \"SHT_NOTE\";\n break;\n\n case SHT_NOBITS:\n tmp = \"SHT_NOBITS\";\n break;\n\n case SHT_REL:\n tmp = \"SHT_REL\";\n break;\n\n case SHT_SHLIB:\n tmp = \"SHT_SHLIB\";\n break;\n\n case SHT_DYNSYM:\n tmp = \"SHT_DYNSYM\";\n break;\n\n case SHT_LOPROC:\n tmp = \"SHT_LOPROC\";\n break;\n\n case SHT_HIPROC:\n tmp = \"SHT_HIPROC\";\n break;\n\n case SHT_LOUSER:\n tmp = \"SHT_LOUSER\";\n break;\n\n case SHT_HIUSER:\n tmp = \"SHT_HIUSER\";\n break;\n \n default:\n break;\n }\n\n if (strlen(name) > 15) {\n strcpy(&name[15 - 6], \"[...]\");\n }\n strcpy(flag, \" \");\n flag2str_sh(shdr[i].sh_flags, flag);\n PRINT_SECTION(i, name, tmp, shdr[i].sh_addr, shdr[i].sh_offset, shdr[i].sh_size, shdr[i].sh_entsize, \\\n flag, shdr[i].sh_link, shdr[i].sh_info, shdr[i].sh_addralign);\n }\n\n INFO(\"Program Header Table\\n\");\n PRINT_PROGRAM_TITLE(\"Nr\", \"Type\", \"Offset\", \"Virtaddr\", \"Physaddr\", \"Filesiz\", \"Memsiz\", \"Flg\", \"Align\");\n for (int i = 0; i < ehdr->e_phnum; i++) {\n switch (phdr[i].p_type) {\n case PT_NULL:\n tmp = \"PT_NULL\";\n break;\n \n case PT_LOAD:\n tmp = \"PT_LOAD\";\n break;\n\n case PT_DYNAMIC:\n tmp = \"PT_DYNAMIC\";\n break;\n\n case PT_INTERP:\n tmp = \"PT_INTERP\";\n break;\n\n case PT_NOTE:\n tmp = \"PT_NOTE\";\n break;\n\n case PT_SHLIB:\n tmp = \"PT_SHLIB\";\n break;\n\n case PT_PHDR:\n tmp = \"PT_PHDR\";\n break;\n\n case PT_LOPROC:\n tmp = \"PT_LOPROC\";\n break;\n\n case PT_HIPROC:\n tmp = \"PT_HIPROC\";\n break;\n\n case PT_GNU_STACK:\n tmp = \"PT_GNU_STACK\";\n break;\n \n default:\n break;\n }\n strcpy(flag, \" \");\n flag2str(phdr[i].p_flags, flag);\n PRINT_PROGRAM(i, tmp, phdr[i].p_offset, phdr[i].p_vaddr, phdr[i].p_paddr, phdr[i].p_filesz, phdr[i].p_memsz, flag, phdr[i].p_align); \n }\n\n INFO(\"Section to segment mapping\\n\");\n for (int i = 0; i < ehdr->e_phnum; i++) {\n printf(\" [%2d]\", i);\n for (int j = 0; j < ehdr->e_shnum; j++) {\n name = elf_map + shstrtab.sh_offset + shdr[j].sh_name;\n if (shdr[j].sh_addr >= phdr[i].p_vaddr && shdr[j].sh_addr + shdr[j].sh_size <= phdr[i].p_vaddr + phdr[i].p_memsz && shdr[j].sh_type != SHT_NULL) {\n if (shdr[j].sh_flags >> 1 & 0x1) {\n printf(\" %s\", name);\n }\n } \n }\n printf(\"\\n\");\n }\n\n INFO(\"Dynamic link information\\n\");\n int dynstr;\n int dynamic;\n Elf64_Dyn *dyn;\n for (int i = 0; i < ehdr->e_shnum; i++) {\n name = elf_map + shstrtab.sh_offset + shdr[i].sh_name;\n if (!strcmp(name, \".dynstr\")) {\n dynstr = i;\n }\n if (!strcmp(name, \".dynamic\")) {\n dynamic = i;\n }\n }\n\n char value[50];\n name = \"\";\n dyn = (Elf64_Dyn *)&elf_map[shdr[dynamic].sh_offset];\n count = shdr[dynamic].sh_size / sizeof(Elf64_Dyn);\n INFO(\"Dynamic section at offset 0x%x contains %d entries\\n\", shdr[dynamic].sh_offset, count);\n PRINT_DYN_TITLE(\"Tag\", \"Type\", \"Name/Value\");\n \n for(int i = 0; i < count; i++) {\n tmp = \"\";\n memset(value, 0, 50);\n snprintf(value, 50, \"0x%x\", dyn[i].d_un.d_val);\n switch (dyn[i].d_tag) {\n /* Legal values for d_tag (dynamic entry type). */\n case DT_NULL:\n tmp = \"DT_NULL\";\n break;\n\n case DT_NEEDED:\n tmp = \"DT_NEEDED\";\n name = elf_map + shdr[dynstr].sh_offset + dyn[i].d_un.d_val;\n snprintf(value, 50, \"Shared library: [%s]\", name);\n break;\n \n case DT_PLTRELSZ:\n tmp = \"DT_PLTRELSZ\";\n break;\n\n case DT_PLTGOT:\n tmp = \"DT_PLTGOT\";\n break;\n\n case DT_HASH:\n tmp = \"DT_HASH\";\n break;\n\n case DT_STRTAB:\n tmp = \"DT_STRTAB\";\n break;\n\n case DT_SYMTAB:\n tmp = \"DT_SYMTAB\";\n break;\n\n case DT_RELA:\n tmp = \"DT_RELA\";\n break;\n\n case DT_RELASZ:\n tmp = \"DT_RELASZ\";\n break;\n\n case DT_RELAENT:\n tmp = \"DT_RELAENT\";\n break;\n\n case DT_STRSZ:\n tmp = \"DT_STRSZ\";\n break;\n\n case DT_SYMENT:\n tmp = \"DT_SYMENT\";\n break;\n\n case DT_INIT:\n tmp = \"DT_INIT\";\n break;\n\n case DT_FINI:\n tmp = \"DT_FINI\";\n break;\n\n case DT_SONAME:\n tmp = \"DT_SONAME\";\n break;\n\n case DT_RPATH:\n tmp = \"DT_RPATH\";\n break;\n\n case DT_SYMBOLIC:\n tmp = \"DT_SYMBOLIC\";\n break;\n\n case DT_REL:\n tmp = \"DT_REL\";\n break;\n\n case DT_RELSZ:\n tmp = \"DT_RELSZ\";\n break;\n\n case DT_RELENT:\n tmp = \"DT_RELENT\";\n break;\n \n case DT_PLTREL:\n tmp = \"DT_PLTREL\";\n break;\n\n case DT_DEBUG:\n tmp = \"DT_DEBUG\";\n break;\n\n case DT_TEXTREL:\n tmp = \"DT_TEXTREL\";\n break;\n\n case DT_JMPREL:\n tmp = \"DT_JMPREL\";\n break;\n\n case DT_BIND_NOW:\n tmp = \"DT_BIND_NOW\";\n break;\n\n case DT_INIT_ARRAY:\n tmp = \"DT_INIT_ARRAY\";\n break;\n\n case DT_FINI_ARRAY:\n tmp = \"DT_FINI_ARRAY\";\n break;\n\n case DT_INIT_ARRAYSZ:\n tmp = \"DT_INIT_ARRAYSZ\";\n break;\n \n case DT_FINI_ARRAYSZ:\n tmp = \"DT_FINI_ARRAYSZ\";\n break;\n\n case DT_RUNPATH:\n tmp = \"DT_RUNPATH\";\n break;\n\n case DT_FLAGS:\n tmp = \"DT_FLAGS\";\n snprintf(value, 50, \"Flags: %d\", dyn[i].d_un.d_val);\n break;\n \n case DT_ENCODING:\n tmp = \"DT_ENCODING\";\n break;\n\n case DT_PREINIT_ARRAYSZ:\n tmp = \"DT_PREINIT_ARRAYSZ\";\n break;\n\n case DT_SYMTAB_SHNDX:\n tmp = \"DT_SYMTAB_SHNDX\";\n break;\n \n case DT_NUM:\n tmp = \"DT_NUM\";\n break;\n\n case DT_LOOS:\n tmp = \"DT_LOOS\";\n break;\n\n case DT_HIOS:\n tmp = \"DT_HIOS\";\n break;\n\n case DT_LOPROC:\n tmp = \"DT_LOPROC\";\n break;\n\n case DT_HIPROC:\n tmp = \"DT_HIPROC\";\n break;\n\n case DT_PROCNUM:\n tmp = \"DT_LOPROC\";\n break;\n\n /* DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the\n * Dyn.d_un.d_val field of the Elf*_Dyn structure. This follows Sun's\n * approach. */\n\n case DT_VALRNGLO:\n tmp = \"DT_VALRNGLO\";\n break;\n\n case DT_GNU_PRELINKED:\n tmp = \"DT_GNU_PRELINKED\";\n break;\n \n case DT_GNU_CONFLICTSZ:\n tmp = \"DT_GNU_CONFLICTSZ\";\n break;\n\n case DT_GNU_LIBLISTSZ:\n tmp = \"DT_GNU_LIBLISTSZ\";\n break;\n\n case DT_CHECKSUM:\n tmp = \"DT_CHECKSUM\";\n break;\n\n case DT_PLTPADSZ:\n tmp = \"DT_PLTPADSZ\";\n break;\n\n case DT_MOVEENT:\n tmp = \"DT_MOVEENT\";\n break;\n\n case DT_MOVESZ:\n tmp = \"DT_MOVESZ\";\n break;\n\n case DT_FEATURE_1:\n tmp = \"DT_FEATURE_1\";\n break;\n\n case DT_POSFLAG_1:\n tmp = \"DT_POSFLAG_1\";\n break;\n\n case DT_SYMINSZ:\n tmp = \"DT_SYMINSZ\";\n break;\n\n case DT_SYMINENT:\n tmp = \"DT_SYMINENT\";\n break;\n\n /* DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the\n * Dyn.d_un.d_ptr field of the Elf*_Dyn structure.\n * If any adjustment is made to the ELF object after it has been\n * built these entries will need to be adjusted. */\n case DT_ADDRRNGLO:\n tmp = \"DT_ADDRRNGLO\";\n break;\n\n case DT_GNU_HASH:\n tmp = \"DT_GNU_HASH\";\n break;\n\n case DT_TLSDESC_PLT:\n tmp = \"DT_TLSDESC_PLT\";\n break;\n\n case DT_TLSDESC_GOT:\n tmp = \"DT_TLSDESC_GOT\";\n break;\n\n case DT_GNU_CONFLICT:\n tmp = \"DT_GNU_CONFLICT\";\n break;\n\n case DT_GNU_LIBLIST:\n tmp = \"DT_GNU_LIBLIST\";\n break;\n\n case DT_CONFIG:\n tmp = \"DT_CONFIG\";\n break;\n\n case DT_DEPAUDIT:\n tmp = \"DT_DEPAUDIT\";\n break;\n\n case DT_AUDIT:\n tmp = \"DT_AUDIT\";\n break;\n\n case DT_PLTPAD:\n tmp = \"DT_PLTPAD\";\n break;\n\n case DT_MOVETAB:\n tmp = \"DT_MOVETAB\";\n break;\n\n case DT_SYMINFO:\n tmp = \"DT_SYMINFO\";\n break;\n \n /* The versioning entry types. The next are defined as part of the\n * GNU extension. */\n case DT_VERSYM:\n tmp = \"DT_VERSYM\";\n break;\n\n case DT_RELACOUNT:\n tmp = \"DT_RELACOUNT\";\n break;\n\n case DT_RELCOUNT:\n tmp = \"DT_RELCOUNT\";\n break;\n \n /* These were chosen by Sun. */\n case DT_FLAGS_1:\n tmp = \"DT_FLAGS_1\";\n switch (dyn[i].d_un.d_val) {\n case DF_1_PIE:\n snprintf(value, 50, \"Flags: %s\", \"PIE\");\n break;\n \n default:\n snprintf(value, 50, \"Flags: %d\", dyn[i].d_un.d_val);\n break;\n }\n \n break;\n\n case DT_VERDEF:\n tmp = \"DT_VERDEF\";\n break;\n\n case DT_VERDEFNUM:\n tmp = \"DT_VERDEFNUM\";\n break;\n\n case DT_VERNEED:\n tmp = \"DT_VERNEED\";\n break;\n\n case DT_VERNEEDNUM:\n tmp = \"DT_VERNEEDNUM\";\n break;\n \n default:\n break;\n }\n PRINT_DYN(dyn[i].d_tag, tmp, value);\n } \n }\n\n return 0;\n}", "func_hash": 212625338852409612714470845997465821390, "file_name": "None", "file_hash": null, "cwe": ["CWE-125"], "cve": "CVE-2022-21711", "cve_desc": "elfspirit is an ELF static analysis and injection framework that parses, manipulates, and camouflages ELF files. When analyzing the ELF file format in versions prior to 1.1, there is an out-of-bounds read bug, which can lead to application crashes or information leakage. By constructing a special format ELF file, the information of any address can be leaked. elfspirit version 1.1 contains a patch for this issue.", "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21711"}