diff --git "a/test_split.csv" "b/test_split.csv" new file mode 100644--- /dev/null +++ "b/test_split.csv" @@ -0,0 +1,16063 @@ +cwe,func_name,func_src_before,func_src_after,line_changes,char_changes,commit_link,file_name,vul_type,num_tokens +cwe-022,getKey,"def getKey(client): + """"""Retrieves the specified key for the specified client + Returns an error if the key doesn't exist, obviously. + """""" + global SERVER_JWT_PRIVATE_KEY + global BAD_REQUEST + + validateClient(client) + + client_pub_key = loadClientRSAKey(client) + token_data = decodeRequestToken(request.data, client_pub_key) + + # Keys may only have alpha-numeric names + try: + if re.search('[^a-zA-Z0-9]', token_data['key']): + raise FoxlockError(BAD_REQUEST, 'Invalid key requested') + requested_key = open('keys/%s/%s.key' % (client, token_data['key']), 'r').read() + except KeyError: + raise FoxlockError(BAD_REQUEST, ""JWT did not contain attribute 'key'"") + except IOError: + raise FoxlockError(BAD_REQUEST, ""Key '%s' not found"" % token_data['key']) + + # Key is returned in a JWT encrypted with the client's public key, so only they can decrypt it + keytoken = packJWT({'key': requested_key}, SERVER_JWT_PRIVATE_KEY, client_pub_key) + + return keytoken","def getKey(client): + """"""Retrieves the specified key for the specified client + Returns an error if the key doesn't exist, obviously. + """""" + global SERVER_JWT_PRIVATE_KEY + global BAD_REQUEST + + validateClient(client) + client_pub_key = loadClientRSAKey(client) + token_data = decodeRequestToken(request.data, client_pub_key) + validateKeyName(token_data['key']) + + # Keys may only have alpha-numeric names + try: + requested_key = open('keys/%s/%s.key' % (client, token_data['key']), 'r').read() + except KeyError: + raise FoxlockError(BAD_REQUEST, ""JWT did not contain attribute 'key'"") + except IOError: + raise FoxlockError(BAD_REQUEST, ""Key '%s' not found"" % token_data['key']) + + # Key is returned in a JWT encrypted with the client's public key, so only they can decrypt it + keytoken = packJWT({'key': requested_key}, SERVER_JWT_PRIVATE_KEY, client_pub_key) + + return keytoken","{'deleted': [{'line_no': 9, 'char_start': 213, 'char_end': 214, 'line': '\n'}, {'line_no': 15, 'char_start': 369, 'char_end': 420, 'line': ""\t\tif re.search('[^a-zA-Z0-9]', token_data['key']):\n""}, {'line_no': 16, 'char_start': 420, 'char_end': 480, 'line': ""\t\t\traise FoxlockError(BAD_REQUEST, 'Invalid key requested')\n""}], 'added': [{'line_no': 11, 'char_start': 319, 'char_end': 355, 'line': ""\tvalidateKeyName(token_data['key'])\n""}]}","{'deleted': [{'char_start': 213, 'char_end': 214, 'chars': '\n'}, {'char_start': 368, 'char_end': 479, 'chars': ""\n\t\tif re.search('[^a-zA-Z0-9]', token_data['key']):\n\t\t\traise FoxlockError(BAD_REQUEST, 'Invalid key requested')""}], 'added': [{'char_start': 318, 'char_end': 354, 'chars': ""\n\tvalidateKeyName(token_data['key'])""}, {'char_start': 398, 'char_end': 398, 'chars': ''}]}",github.com/Mimickal/FoxLock/commit/7c665e556987f4e2c1a75e143a1e80ae066ad833,impl.py,cwe-022, +cwe-022,ImportEPUB::ExtractContainer,"void ImportEPUB::ExtractContainer() +{ + int res = 0; + if (!cp437) { + cp437 = new QCodePage437Codec(); + } +#ifdef Q_OS_WIN32 + zlib_filefunc64_def ffunc; + fill_win32_filefunc64W(&ffunc); + unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(m_FullFilePath)).c_str(), &ffunc); +#else + unzFile zfile = unzOpen64(QDir::toNativeSeparators(m_FullFilePath).toUtf8().constData()); +#endif + + if (zfile == NULL) { + throw (EPUBLoadParseError(QString(QObject::tr(""Cannot unzip EPUB: %1"")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString())); + } + + res = unzGoToFirstFile(zfile); + + if (res == UNZ_OK) { + do { + // Get the name of the file in the archive. + char file_name[MAX_PATH] = {0}; + unz_file_info64 file_info; + unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0); + QString qfile_name; + QString cp437_file_name; + qfile_name = QString::fromUtf8(file_name); + if (!(file_info.flag & (1<<11))) { + // General purpose bit 11 says the filename is utf-8 encoded. If not set then + // IBM 437 encoding might be used. + cp437_file_name = cp437->toUnicode(file_name); + } + + // If there is no file name then we can't do anything with it. + if (!qfile_name.isEmpty()) { + // We use the dir object to create the path in the temporary directory. + // Unfortunately, we need a dir ojbect to do this as it's not a static function. + QDir dir(m_ExtractedFolderPath); + // Full file path in the temporary directory. + QString file_path = m_ExtractedFolderPath + ""/"" + qfile_name; + QFileInfo qfile_info(file_path); + + // Is this entry a directory? + if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) { + dir.mkpath(qfile_name); + continue; + } else { + dir.mkpath(qfile_info.path()); + // add it to the list of files found inside the zip + if (cp437_file_name.isEmpty()) { + m_ZipFilePaths << qfile_name; + } else { + m_ZipFilePaths << cp437_file_name; + } + } + + // Open the file entry in the archive for reading. + if (unzOpenCurrentFile(zfile) != UNZ_OK) { + unzClose(zfile); + throw (EPUBLoadParseError(QString(QObject::tr(""Cannot extract file: %1"")).arg(qfile_name).toStdString())); + } + + // Open the file on disk to write the entry in the archive to. + QFile entry(file_path); + + if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) { + unzCloseCurrentFile(zfile); + unzClose(zfile); + throw (EPUBLoadParseError(QString(QObject::tr(""Cannot extract file: %1"")).arg(qfile_name).toStdString())); + } + + // Buffered reading and writing. + char buff[BUFF_SIZE] = {0}; + int read = 0; + + while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) { + entry.write(buff, read); + } + + entry.close(); + + // Read errors are marked by a negative read amount. + if (read < 0) { + unzCloseCurrentFile(zfile); + unzClose(zfile); + throw (EPUBLoadParseError(QString(QObject::tr(""Cannot extract file: %1"")).arg(qfile_name).toStdString())); + } + + // The file was read but the CRC did not match. + // We don't check the read file size vs the uncompressed file size + // because if they're different there should be a CRC error. + if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) { + unzClose(zfile); + throw (EPUBLoadParseError(QString(QObject::tr(""Cannot extract file: %1"")).arg(qfile_name).toStdString())); + } + if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) { + QString cp437_file_path = m_ExtractedFolderPath + ""/"" + cp437_file_name; + QFile::copy(file_path, cp437_file_path); + } + } + } while ((res = unzGoToNextFile(zfile)) == UNZ_OK); + } + + if (res != UNZ_END_OF_LIST_OF_FILE) { + unzClose(zfile); + throw (EPUBLoadParseError(QString(QObject::tr(""Cannot open EPUB: %1"")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString())); + } + + unzClose(zfile); +}","void ImportEPUB::ExtractContainer() +{ + int res = 0; + if (!cp437) { + cp437 = new QCodePage437Codec(); + } +#ifdef Q_OS_WIN32 + zlib_filefunc64_def ffunc; + fill_win32_filefunc64W(&ffunc); + unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(m_FullFilePath)).c_str(), &ffunc); +#else + unzFile zfile = unzOpen64(QDir::toNativeSeparators(m_FullFilePath).toUtf8().constData()); +#endif + + if (zfile == NULL) { + throw (EPUBLoadParseError(QString(QObject::tr(""Cannot unzip EPUB: %1"")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString())); + } + + res = unzGoToFirstFile(zfile); + + if (res == UNZ_OK) { + do { + // Get the name of the file in the archive. + char file_name[MAX_PATH] = {0}; + unz_file_info64 file_info; + unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0); + QString qfile_name; + QString cp437_file_name; + qfile_name = QString::fromUtf8(file_name); + if (!(file_info.flag & (1<<11))) { + // General purpose bit 11 says the filename is utf-8 encoded. If not set then + // IBM 437 encoding might be used. + cp437_file_name = cp437->toUnicode(file_name); + } + + // If there is no file name then we can't do anything with it. + if (!qfile_name.isEmpty()) { + + // for security reasons we need the file path to always be inside the + // target folder and not outside, so we will remove all relative upward + // paths segments "".."" from the file path before prepending the target + // folder to create the final target path + qfile_name = qfile_name.replace(""../"",""""); + cp437_file_name = cp437_file_name.replace(""../"",""""); + + // We use the dir object to create the path in the temporary directory. + // Unfortunately, we need a dir ojbect to do this as it's not a static function. + QDir dir(m_ExtractedFolderPath); + // Full file path in the temporary directory. + QString file_path = m_ExtractedFolderPath + ""/"" + qfile_name; + QFileInfo qfile_info(file_path); + + // Is this entry a directory? + if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) { + dir.mkpath(qfile_name); + continue; + } else { + dir.mkpath(qfile_info.path()); + // add it to the list of files found inside the zip + if (cp437_file_name.isEmpty()) { + m_ZipFilePaths << qfile_name; + } else { + m_ZipFilePaths << cp437_file_name; + } + } + + // Open the file entry in the archive for reading. + if (unzOpenCurrentFile(zfile) != UNZ_OK) { + unzClose(zfile); + throw (EPUBLoadParseError(QString(QObject::tr(""Cannot extract file: %1"")).arg(qfile_name).toStdString())); + } + + // Open the file on disk to write the entry in the archive to. + QFile entry(file_path); + + if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) { + unzCloseCurrentFile(zfile); + unzClose(zfile); + throw (EPUBLoadParseError(QString(QObject::tr(""Cannot extract file: %1"")).arg(qfile_name).toStdString())); + } + + // Buffered reading and writing. + char buff[BUFF_SIZE] = {0}; + int read = 0; + + while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) { + entry.write(buff, read); + } + + entry.close(); + + // Read errors are marked by a negative read amount. + if (read < 0) { + unzCloseCurrentFile(zfile); + unzClose(zfile); + throw (EPUBLoadParseError(QString(QObject::tr(""Cannot extract file: %1"")).arg(qfile_name).toStdString())); + } + + // The file was read but the CRC did not match. + // We don't check the read file size vs the uncompressed file size + // because if they're different there should be a CRC error. + if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) { + unzClose(zfile); + throw (EPUBLoadParseError(QString(QObject::tr(""Cannot extract file: %1"")).arg(qfile_name).toStdString())); + } + if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) { + QString cp437_file_path = m_ExtractedFolderPath + ""/"" + cp437_file_name; + QFile::copy(file_path, cp437_file_path); + } + } + } while ((res = unzGoToNextFile(zfile)) == UNZ_OK); + } + + if (res != UNZ_END_OF_LIST_OF_FILE) { + unzClose(zfile); + throw (EPUBLoadParseError(QString(QObject::tr(""Cannot open EPUB: %1"")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString())); + } + + unzClose(zfile); +}","{'deleted': [], 'added': [{'line_no': 38, 'char_start': 1427, 'char_end': 1428, 'line': '\n'}, {'line_no': 43, 'char_start': 1743, 'char_end': 1795, 'line': '\t qfile_name = qfile_name.replace(""../"","""");\n'}, {'line_no': 44, 'char_start': 1795, 'char_end': 1864, 'line': ' cp437_file_name = cp437_file_name.replace(""../"","""");\n'}, {'line_no': 45, 'char_start': 1864, 'char_end': 1865, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 1427, 'char_end': 1865, 'chars': '\n\t // for security reasons we need the file path to always be inside the \n // target folder and not outside, so we will remove all relative upward \n // paths segments "".."" from the file path before prepending the target \n // folder to create the final target path\n\t qfile_name = qfile_name.replace(""../"","""");\n cp437_file_name = cp437_file_name.replace(""../"","""");\n\n'}]}",github.com/Sigil-Ebook/Sigil/commit/369eebe936e4a8c83cc54662a3412ce8bef189e4,src/Importers/ImportEPUB.cpp,cwe-022, +cwe-022,GetMagickModulePath,"static MagickBooleanType GetMagickModulePath(const char *filename, + MagickModuleType module_type,char *path,ExceptionInfo *exception) +{ + char + *module_path; + + assert(filename != (const char *) NULL); + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",filename); + assert(path != (char *) NULL); + assert(exception != (ExceptionInfo *) NULL); + (void) CopyMagickString(path,filename,MaxTextExtent); + module_path=(char *) NULL; + switch (module_type) + { + case MagickImageCoderModule: + default: + { + (void) LogMagickEvent(ModuleEvent,GetMagickModule(), + ""Searching for coder module file \""%s\"" ..."",filename); + module_path=GetEnvironmentValue(""MAGICK_CODER_MODULE_PATH""); +#if defined(MAGICKCORE_CODER_PATH) + if (module_path == (char *) NULL) + module_path=AcquireString(MAGICKCORE_CODER_PATH); +#endif + break; + } + case MagickImageFilterModule: + { + (void) LogMagickEvent(ModuleEvent,GetMagickModule(), + ""Searching for filter module file \""%s\"" ..."",filename); + module_path=GetEnvironmentValue(""MAGICK_CODER_FILTER_PATH""); +#if defined(MAGICKCORE_FILTER_PATH) + if (module_path == (char *) NULL) + module_path=AcquireString(MAGICKCORE_FILTER_PATH); +#endif + break; + } + } + if (module_path != (char *) NULL) + { + register char + *p, + *q; + + for (p=module_path-1; p != (char *) NULL; ) + { + (void) CopyMagickString(path,p+1,MaxTextExtent); + q=strchr(path,DirectoryListSeparator); + if (q != (char *) NULL) + *q='\0'; + q=path+strlen(path)-1; + if ((q >= path) && (*q != *DirectorySeparator)) + (void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent); + (void) ConcatenateMagickString(path,filename,MaxTextExtent); + if (IsPathAccessible(path) != MagickFalse) + { + module_path=DestroyString(module_path); + return(MagickTrue); + } + p=strchr(p+1,DirectoryListSeparator); + } + module_path=DestroyString(module_path); + } +#if defined(MAGICKCORE_INSTALLED_SUPPORT) + else +#if defined(MAGICKCORE_CODER_PATH) + { + const char + *directory; + + /* + Search hard coded paths. + */ + switch (module_type) + { + case MagickImageCoderModule: + default: + { + directory=MAGICKCORE_CODER_PATH; + break; + } + case MagickImageFilterModule: + { + directory=MAGICKCORE_FILTER_PATH; + break; + } + } + (void) FormatLocaleString(path,MaxTextExtent,""%s%s"",directory,filename); + if (IsPathAccessible(path) == MagickFalse) + { + ThrowFileException(exception,ConfigureWarning, + ""UnableToOpenModuleFile"",path); + return(MagickFalse); + } + return(MagickTrue); + } +#else +#if defined(MAGICKCORE_WINDOWS_SUPPORT) + { + const char + *registery_key; + + unsigned char + *key_value; + + /* + Locate path via registry key. + */ + switch (module_type) + { + case MagickImageCoderModule: + default: + { + registery_key=""CoderModulesPath""; + break; + } + case MagickImageFilterModule: + { + registery_key=""FilterModulesPath""; + break; + } + } + key_value=NTRegistryKeyLookup(registery_key); + if (key_value == (unsigned char *) NULL) + { + ThrowMagickException(exception,GetMagickModule(),ConfigureError, + ""RegistryKeyLookupFailed"",""`%s'"",registery_key); + return(MagickFalse); + } + (void) FormatLocaleString(path,MaxTextExtent,""%s%s%s"",(char *) key_value, + DirectorySeparator,filename); + key_value=(unsigned char *) RelinquishMagickMemory(key_value); + if (IsPathAccessible(path) == MagickFalse) + { + ThrowFileException(exception,ConfigureWarning, + ""UnableToOpenModuleFile"",path); + return(MagickFalse); + } + return(MagickTrue); + } +#endif +#endif +#if !defined(MAGICKCORE_CODER_PATH) && !defined(MAGICKCORE_WINDOWS_SUPPORT) +# error MAGICKCORE_CODER_PATH or MAGICKCORE_WINDOWS_SUPPORT must be defined when MAGICKCORE_INSTALLED_SUPPORT is defined +#endif +#else + { + char + *home; + + home=GetEnvironmentValue(""MAGICK_HOME""); + if (home != (char *) NULL) + { + /* + Search MAGICK_HOME. + */ +#if !defined(MAGICKCORE_POSIX_SUPPORT) + (void) FormatLocaleString(path,MaxTextExtent,""%s%s%s"",home, + DirectorySeparator,filename); +#else + const char + *directory; + + switch (module_type) + { + case MagickImageCoderModule: + default: + { + directory=MAGICKCORE_CODER_RELATIVE_PATH; + break; + } + case MagickImageFilterModule: + { + directory=MAGICKCORE_FILTER_RELATIVE_PATH; + break; + } + } + (void) FormatLocaleString(path,MaxTextExtent,""%s/lib/%s/%s"",home, + directory,filename); +#endif + home=DestroyString(home); + if (IsPathAccessible(path) != MagickFalse) + return(MagickTrue); + } + } + if (*GetClientPath() != '\0') + { + /* + Search based on executable directory. + */ +#if !defined(MAGICKCORE_POSIX_SUPPORT) + (void) FormatLocaleString(path,MaxTextExtent,""%s%s%s"",GetClientPath(), + DirectorySeparator,filename); +#else + char + prefix[MaxTextExtent]; + + const char + *directory; + + switch (module_type) + { + case MagickImageCoderModule: + default: + { + directory=""coders""; + break; + } + case MagickImageFilterModule: + { + directory=""filters""; + break; + } + } + (void) CopyMagickString(prefix,GetClientPath(),MaxTextExtent); + ChopPathComponents(prefix,1); + (void) FormatLocaleString(path,MaxTextExtent,""%s/lib/%s/%s/%s"",prefix, + MAGICKCORE_MODULES_RELATIVE_PATH,directory,filename); +#endif + if (IsPathAccessible(path) != MagickFalse) + return(MagickTrue); + } +#if defined(MAGICKCORE_WINDOWS_SUPPORT) + { + /* + Search module path. + */ + if ((NTGetModulePath(""CORE_RL_magick_.dll"",path) != MagickFalse) || + (NTGetModulePath(""CORE_DB_magick_.dll"",path) != MagickFalse) || + (NTGetModulePath(""Magick.dll"",path) != MagickFalse)) + { + (void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent); + (void) ConcatenateMagickString(path,filename,MaxTextExtent); + if (IsPathAccessible(path) != MagickFalse) + return(MagickTrue); + } + } +#endif + { + char + *home; + + home=GetEnvironmentValue(""XDG_CONFIG_HOME""); + if (home == (char *) NULL) + home=GetEnvironmentValue(""LOCALAPPDATA""); + if (home == (char *) NULL) + home=GetEnvironmentValue(""APPDATA""); + if (home == (char *) NULL) + home=GetEnvironmentValue(""USERPROFILE""); + if (home != (char *) NULL) + { + /* + Search $XDG_CONFIG_HOME/ImageMagick. + */ + (void) FormatLocaleString(path,MaxTextExtent,""%s%sImageMagick%s%s"", + home,DirectorySeparator,DirectorySeparator,filename); + home=DestroyString(home); + if (IsPathAccessible(path) != MagickFalse) + return(MagickTrue); + } + home=GetEnvironmentValue(""HOME""); + if (home != (char *) NULL) + { + /* + Search $HOME/.config/ImageMagick. + */ + (void) FormatLocaleString(path,MaxTextExtent, + ""%s%s.config%sImageMagick%s%s"",home,DirectorySeparator, + DirectorySeparator,DirectorySeparator,filename); + if (IsPathAccessible(path) != MagickFalse) + { + home=DestroyString(home); + return(MagickTrue); + } + /* + Search $HOME/.magick. + */ + (void) FormatLocaleString(path,MaxTextExtent,""%s%s.magick%s%s"",home, + DirectorySeparator,DirectorySeparator,filename); + home=DestroyString(home); + if (IsPathAccessible(path) != MagickFalse) + return(MagickTrue); + } + } + /* + Search current directory. + */ + if (IsPathAccessible(path) != MagickFalse) + return(MagickTrue); + if (exception->severity < ConfigureError) + ThrowFileException(exception,ConfigureWarning,""UnableToOpenModuleFile"", + path); +#endif + return(MagickFalse); +}","static MagickBooleanType GetMagickModulePath(const char *filename, + MagickModuleType module_type,char *path,ExceptionInfo *exception) +{ + char + *module_path; + + assert(filename != (const char *) NULL); + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",filename); + assert(path != (char *) NULL); + assert(exception != (ExceptionInfo *) NULL); + (void) CopyMagickString(path,filename,MaxTextExtent); +#if defined(MAGICKCORE_INSTALLED_SUPPORT) + if (strstr(path,""../"") != (char *) NULL) + { + errno=EPERM; + (void) ThrowMagickException(exception,GetMagickModule(),PolicyError, + ""NotAuthorized"",""`%s'"",path); + return(MagickFalse); + } +#endif + module_path=(char *) NULL; + switch (module_type) + { + case MagickImageCoderModule: + default: + { + (void) LogMagickEvent(ModuleEvent,GetMagickModule(), + ""Searching for coder module file \""%s\"" ..."",filename); + module_path=GetEnvironmentValue(""MAGICK_CODER_MODULE_PATH""); +#if defined(MAGICKCORE_CODER_PATH) + if (module_path == (char *) NULL) + module_path=AcquireString(MAGICKCORE_CODER_PATH); +#endif + break; + } + case MagickImageFilterModule: + { + (void) LogMagickEvent(ModuleEvent,GetMagickModule(), + ""Searching for filter module file \""%s\"" ..."",filename); + module_path=GetEnvironmentValue(""MAGICK_CODER_FILTER_PATH""); +#if defined(MAGICKCORE_FILTER_PATH) + if (module_path == (char *) NULL) + module_path=AcquireString(MAGICKCORE_FILTER_PATH); +#endif + break; + } + } + if (module_path != (char *) NULL) + { + register char + *p, + *q; + + for (p=module_path-1; p != (char *) NULL; ) + { + (void) CopyMagickString(path,p+1,MaxTextExtent); + q=strchr(path,DirectoryListSeparator); + if (q != (char *) NULL) + *q='\0'; + q=path+strlen(path)-1; + if ((q >= path) && (*q != *DirectorySeparator)) + (void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent); + (void) ConcatenateMagickString(path,filename,MaxTextExtent); + if (IsPathAccessible(path) != MagickFalse) + { + module_path=DestroyString(module_path); + return(MagickTrue); + } + p=strchr(p+1,DirectoryListSeparator); + } + module_path=DestroyString(module_path); + } +#if defined(MAGICKCORE_INSTALLED_SUPPORT) + else +#if defined(MAGICKCORE_CODER_PATH) + { + const char + *directory; + + /* + Search hard coded paths. + */ + switch (module_type) + { + case MagickImageCoderModule: + default: + { + directory=MAGICKCORE_CODER_PATH; + break; + } + case MagickImageFilterModule: + { + directory=MAGICKCORE_FILTER_PATH; + break; + } + } + (void) FormatLocaleString(path,MaxTextExtent,""%s%s"",directory,filename); + if (IsPathAccessible(path) == MagickFalse) + { + ThrowFileException(exception,ConfigureWarning, + ""UnableToOpenModuleFile"",path); + return(MagickFalse); + } + return(MagickTrue); + } +#else +#if defined(MAGICKCORE_WINDOWS_SUPPORT) + { + const char + *registery_key; + + unsigned char + *key_value; + + /* + Locate path via registry key. + */ + switch (module_type) + { + case MagickImageCoderModule: + default: + { + registery_key=""CoderModulesPath""; + break; + } + case MagickImageFilterModule: + { + registery_key=""FilterModulesPath""; + break; + } + } + key_value=NTRegistryKeyLookup(registery_key); + if (key_value == (unsigned char *) NULL) + { + ThrowMagickException(exception,GetMagickModule(),ConfigureError, + ""RegistryKeyLookupFailed"",""`%s'"",registery_key); + return(MagickFalse); + } + (void) FormatLocaleString(path,MaxTextExtent,""%s%s%s"",(char *) key_value, + DirectorySeparator,filename); + key_value=(unsigned char *) RelinquishMagickMemory(key_value); + if (IsPathAccessible(path) == MagickFalse) + { + ThrowFileException(exception,ConfigureWarning, + ""UnableToOpenModuleFile"",path); + return(MagickFalse); + } + return(MagickTrue); + } +#endif +#endif +#if !defined(MAGICKCORE_CODER_PATH) && !defined(MAGICKCORE_WINDOWS_SUPPORT) +# error MAGICKCORE_CODER_PATH or MAGICKCORE_WINDOWS_SUPPORT must be defined when MAGICKCORE_INSTALLED_SUPPORT is defined +#endif +#else + { + char + *home; + + home=GetEnvironmentValue(""MAGICK_HOME""); + if (home != (char *) NULL) + { + /* + Search MAGICK_HOME. + */ +#if !defined(MAGICKCORE_POSIX_SUPPORT) + (void) FormatLocaleString(path,MaxTextExtent,""%s%s%s"",home, + DirectorySeparator,filename); +#else + const char + *directory; + + switch (module_type) + { + case MagickImageCoderModule: + default: + { + directory=MAGICKCORE_CODER_RELATIVE_PATH; + break; + } + case MagickImageFilterModule: + { + directory=MAGICKCORE_FILTER_RELATIVE_PATH; + break; + } + } + (void) FormatLocaleString(path,MaxTextExtent,""%s/lib/%s/%s"",home, + directory,filename); +#endif + home=DestroyString(home); + if (IsPathAccessible(path) != MagickFalse) + return(MagickTrue); + } + } + if (*GetClientPath() != '\0') + { + /* + Search based on executable directory. + */ +#if !defined(MAGICKCORE_POSIX_SUPPORT) + (void) FormatLocaleString(path,MaxTextExtent,""%s%s%s"",GetClientPath(), + DirectorySeparator,filename); +#else + char + prefix[MaxTextExtent]; + + const char + *directory; + + switch (module_type) + { + case MagickImageCoderModule: + default: + { + directory=""coders""; + break; + } + case MagickImageFilterModule: + { + directory=""filters""; + break; + } + } + (void) CopyMagickString(prefix,GetClientPath(),MaxTextExtent); + ChopPathComponents(prefix,1); + (void) FormatLocaleString(path,MaxTextExtent,""%s/lib/%s/%s/%s"",prefix, + MAGICKCORE_MODULES_RELATIVE_PATH,directory,filename); +#endif + if (IsPathAccessible(path) != MagickFalse) + return(MagickTrue); + } +#if defined(MAGICKCORE_WINDOWS_SUPPORT) + { + /* + Search module path. + */ + if ((NTGetModulePath(""CORE_RL_magick_.dll"",path) != MagickFalse) || + (NTGetModulePath(""CORE_DB_magick_.dll"",path) != MagickFalse) || + (NTGetModulePath(""Magick.dll"",path) != MagickFalse)) + { + (void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent); + (void) ConcatenateMagickString(path,filename,MaxTextExtent); + if (IsPathAccessible(path) != MagickFalse) + return(MagickTrue); + } + } +#endif + { + char + *home; + + home=GetEnvironmentValue(""XDG_CONFIG_HOME""); + if (home == (char *) NULL) + home=GetEnvironmentValue(""LOCALAPPDATA""); + if (home == (char *) NULL) + home=GetEnvironmentValue(""APPDATA""); + if (home == (char *) NULL) + home=GetEnvironmentValue(""USERPROFILE""); + if (home != (char *) NULL) + { + /* + Search $XDG_CONFIG_HOME/ImageMagick. + */ + (void) FormatLocaleString(path,MaxTextExtent,""%s%sImageMagick%s%s"", + home,DirectorySeparator,DirectorySeparator,filename); + home=DestroyString(home); + if (IsPathAccessible(path) != MagickFalse) + return(MagickTrue); + } + home=GetEnvironmentValue(""HOME""); + if (home != (char *) NULL) + { + /* + Search $HOME/.config/ImageMagick. + */ + (void) FormatLocaleString(path,MaxTextExtent, + ""%s%s.config%sImageMagick%s%s"",home,DirectorySeparator, + DirectorySeparator,DirectorySeparator,filename); + if (IsPathAccessible(path) != MagickFalse) + { + home=DestroyString(home); + return(MagickTrue); + } + /* + Search $HOME/.magick. + */ + (void) FormatLocaleString(path,MaxTextExtent,""%s%s.magick%s%s"",home, + DirectorySeparator,DirectorySeparator,filename); + home=DestroyString(home); + if (IsPathAccessible(path) != MagickFalse) + return(MagickTrue); + } + } + /* + Search current directory. + */ + if (IsPathAccessible(path) != MagickFalse) + return(MagickTrue); + if (exception->severity < ConfigureError) + ThrowFileException(exception,ConfigureWarning,""UnableToOpenModuleFile"", + path); +#endif + return(MagickFalse); +}","{'deleted': [], 'added': [{'line_no': 13, 'char_start': 453, 'char_end': 496, 'line': ' if (strstr(path,""../"") != (char *) NULL)\n'}, {'line_no': 14, 'char_start': 496, 'char_end': 502, 'line': ' {\n'}, {'line_no': 15, 'char_start': 502, 'char_end': 521, 'line': ' errno=EPERM;\n'}, {'line_no': 16, 'char_start': 521, 'char_end': 596, 'line': ' (void) ThrowMagickException(exception,GetMagickModule(),PolicyError,\n'}, {'line_no': 17, 'char_start': 596, 'char_end': 634, 'line': ' ""NotAuthorized"",""`%s\'"",path);\n'}, {'line_no': 18, 'char_start': 634, 'char_end': 661, 'line': ' return(MagickFalse);\n'}, {'line_no': 19, 'char_start': 661, 'char_end': 667, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 411, 'char_end': 674, 'chars': '#if defined(MAGICKCORE_INSTALLED_SUPPORT)\n if (strstr(path,""../"") != (char *) NULL)\n {\n errno=EPERM;\n (void) ThrowMagickException(exception,GetMagickModule(),PolicyError,\n ""NotAuthorized"",""`%s\'"",path);\n return(MagickFalse);\n }\n#endif\n'}]}",github.com/ImageMagick/ImageMagick/commit/fc6080f1321fd21e86ef916195cc110b05d9effb,magick/module.c,cwe-022, +cwe-022,estimate_size," @staticmethod + def estimate_size(task_id, taken_dirs, taken_files): + report = AnalysisController.get_report(task_id) + report = report[""analysis""] + path = report[""info""][""analysis_path""] + + size_total = 0 + + for directory in taken_dirs: + destination = ""%s/%s"" % (path, directory) + if os.path.isdir(destination): + size_total += get_directory_size(destination) + + for filename in taken_files: + destination = ""%s/%s"" % (path, filename) + if os.path.isfile(destination): + size_total += os.path.getsize(destination) + + # estimate file size after zipping; 60% compression rate typically + size_estimated = size_total / 6.5 + + return { + ""size"": int(size_estimated), + ""size_human"": filesizeformat(size_estimated) + }"," @staticmethod + def estimate_size(task_id, taken_dirs, taken_files): + report = AnalysisController.get_report(task_id) + report = report[""analysis""] + path = report[""info""][""analysis_path""] + + size_total = 0 + + for directory in taken_dirs: + destination = ""%s/%s"" % (path, os.path.basename(directory)) + if os.path.isdir(destination): + size_total += get_directory_size(destination) + + for filename in taken_files: + destination = ""%s/%s"" % (path, os.path.basename(filename)) + if os.path.isfile(destination): + size_total += os.path.getsize(destination) + + # estimate file size after zipping; 60% compression rate typically + size_estimated = size_total / 6.5 + + return { + ""size"": int(size_estimated), + ""size_human"": filesizeformat(size_estimated) + }","{'deleted': [{'line_no': 10, 'char_start': 276, 'char_end': 330, 'line': ' destination = ""%s/%s"" % (path, directory)\n'}, {'line_no': 15, 'char_start': 473, 'char_end': 526, 'line': ' destination = ""%s/%s"" % (path, filename)\n'}], 'added': [{'line_no': 10, 'char_start': 276, 'char_end': 348, 'line': ' destination = ""%s/%s"" % (path, os.path.basename(directory))\n'}, {'line_no': 15, 'char_start': 491, 'char_end': 562, 'line': ' destination = ""%s/%s"" % (path, os.path.basename(filename))\n'}]}","{'deleted': [], 'added': [{'char_start': 319, 'char_end': 336, 'chars': 'os.path.basename('}, {'char_start': 345, 'char_end': 346, 'chars': ')'}, {'char_start': 534, 'char_end': 551, 'chars': 'os.path.basename('}, {'char_start': 559, 'char_end': 560, 'chars': ')'}]}",github.com/cuckoosandbox/cuckoo/commit/b90267fe4e5ee266ec3d4310a7b5c92c805b7ea3,cuckoo/web/controllers/analysis/export/export.py,cwe-022, +cwe-022,span," def span(self, key): + path = os.path.join(self.namespace, key) + try: + self.etcd.write(path, None, dir=True, prevExist=False) + except etcd.EtcdAlreadyExist as err: + raise CSStoreExists(str(err)) + except etcd.EtcdException as err: + log_error(""Error storing key %s: [%r]"" % (key, repr(err))) + raise CSStoreError('Error occurred while trying to store key')"," def span(self, key): + path = self._absolute_key(key) + try: + self.etcd.write(path, None, dir=True, prevExist=False) + except etcd.EtcdAlreadyExist as err: + raise CSStoreExists(str(err)) + except etcd.EtcdException as err: + log_error(""Error storing key %s: [%r]"" % (key, repr(err))) + raise CSStoreError('Error occurred while trying to store key')","{'deleted': [{'line_no': 2, 'char_start': 25, 'char_end': 74, 'line': ' path = os.path.join(self.namespace, key)\n'}], 'added': [{'line_no': 2, 'char_start': 25, 'char_end': 64, 'line': ' path = self._absolute_key(key)\n'}]}","{'deleted': [{'char_start': 40, 'char_end': 53, 'chars': 'os.path.join('}, {'char_start': 58, 'char_end': 59, 'chars': 'n'}, {'char_start': 60, 'char_end': 62, 'chars': 'me'}, {'char_start': 63, 'char_end': 66, 'chars': 'pac'}, {'char_start': 67, 'char_end': 69, 'chars': ', '}], 'added': [{'char_start': 45, 'char_end': 46, 'chars': '_'}, {'char_start': 47, 'char_end': 53, 'chars': 'bsolut'}, {'char_start': 54, 'char_end': 56, 'chars': '_k'}, {'char_start': 57, 'char_end': 59, 'chars': 'y('}]}",github.com/latchset/custodia/commit/785fc87f38b4811bc4ce43a0a9b2267ee7d500b4,custodia/store/etcdstore.py,cwe-022, +cwe-022,_get_settings,"def _get_settings(view): + return { + 'linters': get_settings(view, 'anaconda_go_linters', []), + 'lint_test': get_settings( + view, 'anaconda_go_lint_test', False), + 'exclude_regexps': get_settings( + view, 'anaconda_go_exclude_regexps', []), + 'max_line_length': get_settings( + view, 'anaconda_go_max_line_length', 120), + 'gocyclo_threshold': get_settings( + view, 'anaconda_go_gocyclo_threshold', 10), + 'golint_min_confidence': get_settings( + view, 'anaconda_go_golint_min_confidence', 0.80), + 'goconst_min_occurrences': get_settings( + view, 'anaconda_go_goconst_min_occurrences', 3), + 'min_const_length': get_settings( + view, 'anaconda_go_min_const_length', 3), + 'dupl_threshold': get_settings( + view, 'anaconda_go_dupl_threshold', 50), + 'path': get_working_directory(view) + }","def _get_settings(view): + return { + 'linters': get_settings(view, 'anaconda_go_linters', []), + 'lint_test': get_settings( + view, 'anaconda_go_lint_test', False), + 'exclude_regexps': get_settings( + view, 'anaconda_go_exclude_regexps', []), + 'max_line_length': get_settings( + view, 'anaconda_go_max_line_length', 120), + 'gocyclo_threshold': get_settings( + view, 'anaconda_go_gocyclo_threshold', 10), + 'golint_min_confidence': get_settings( + view, 'anaconda_go_golint_min_confidence', 0.80), + 'goconst_min_occurrences': get_settings( + view, 'anaconda_go_goconst_min_occurrences', 3), + 'min_const_length': get_settings( + view, 'anaconda_go_min_const_length', 3), + 'dupl_threshold': get_settings( + view, 'anaconda_go_dupl_threshold', 50), + 'path': os.path.dirname(view.file_name()) + }","{'deleted': [{'line_no': 20, 'char_start': 888, 'char_end': 932, 'line': "" 'path': get_working_directory(view)\n""}], 'added': [{'line_no': 20, 'char_start': 888, 'char_end': 938, 'line': "" 'path': os.path.dirname(view.file_name())\n""}]}","{'deleted': [{'char_start': 904, 'char_end': 906, 'chars': 'ge'}, {'char_start': 907, 'char_end': 916, 'chars': '_working_'}, {'char_start': 920, 'char_end': 925, 'chars': 'ctory'}], 'added': [{'char_start': 905, 'char_end': 912, 'chars': 's.path.'}, {'char_start': 915, 'char_end': 918, 'chars': 'nam'}, {'char_start': 924, 'char_end': 936, 'chars': '.file_name()'}]}",github.com/DamnWidget/anaconda_go/commit/d3db90bb8853d832927818699591b91f56f6413c,lib/_sublime.py,cwe-022, +cwe-078,_get_3par_host," def _get_3par_host(self, hostname): + out = self._cli_run('showhost -verbose %s' % (hostname), None) + LOG.debug(""OUTPUT = \n%s"" % (pprint.pformat(out))) + host = {'id': None, 'name': None, + 'domain': None, + 'descriptors': {}, + 'iSCSIPaths': [], + 'FCPaths': []} + + if out: + err = out[0] + if err == 'no hosts listed': + msg = {'code': 'NON_EXISTENT_HOST', + 'desc': ""HOST '%s' was not found"" % hostname} + raise hpexceptions.HTTPNotFound(msg) + + # start parsing the lines after the header line + for line in out[1:]: + if line == '': + break + tmp = line.split(',') + paths = {} + + LOG.debug(""line = %s"" % (pprint.pformat(tmp))) + host['id'] = tmp[0] + host['name'] = tmp[1] + + portPos = tmp[4] + LOG.debug(""portPos = %s"" % (pprint.pformat(portPos))) + if portPos == '---': + portPos = None + else: + port = portPos.split(':') + portPos = {'node': int(port[0]), 'slot': int(port[1]), + 'cardPort': int(port[2])} + + paths['portPos'] = portPos + + # If FC entry + if tmp[5] == 'n/a': + paths['wwn'] = tmp[3] + host['FCPaths'].append(paths) + # else iSCSI entry + else: + paths['name'] = tmp[3] + paths['ipAddr'] = tmp[5] + host['iSCSIPaths'].append(paths) + + # find the offset to the description stuff + offset = 0 + for line in out: + if line[:15] == '---------- Host': + break + else: + offset += 1 + + info = out[offset + 2] + tmp = info.split(':') + host['domain'] = tmp[1] + + info = out[offset + 4] + tmp = info.split(':') + host['descriptors']['location'] = tmp[1] + + info = out[offset + 5] + tmp = info.split(':') + host['descriptors']['ipAddr'] = tmp[1] + + info = out[offset + 6] + tmp = info.split(':') + host['descriptors']['os'] = tmp[1] + + info = out[offset + 7] + tmp = info.split(':') + host['descriptors']['model'] = tmp[1] + + info = out[offset + 8] + tmp = info.split(':') + host['descriptors']['contact'] = tmp[1] + + info = out[offset + 9] + tmp = info.split(':') + host['descriptors']['comment'] = tmp[1] + + return host"," def _get_3par_host(self, hostname): + out = self._cli_run(['showhost', '-verbose', hostname]) + LOG.debug(""OUTPUT = \n%s"" % (pprint.pformat(out))) + host = {'id': None, 'name': None, + 'domain': None, + 'descriptors': {}, + 'iSCSIPaths': [], + 'FCPaths': []} + + if out: + err = out[0] + if err == 'no hosts listed': + msg = {'code': 'NON_EXISTENT_HOST', + 'desc': ""HOST '%s' was not found"" % hostname} + raise hpexceptions.HTTPNotFound(msg) + + # start parsing the lines after the header line + for line in out[1:]: + if line == '': + break + tmp = line.split(',') + paths = {} + + LOG.debug(""line = %s"" % (pprint.pformat(tmp))) + host['id'] = tmp[0] + host['name'] = tmp[1] + + portPos = tmp[4] + LOG.debug(""portPos = %s"" % (pprint.pformat(portPos))) + if portPos == '---': + portPos = None + else: + port = portPos.split(':') + portPos = {'node': int(port[0]), 'slot': int(port[1]), + 'cardPort': int(port[2])} + + paths['portPos'] = portPos + + # If FC entry + if tmp[5] == 'n/a': + paths['wwn'] = tmp[3] + host['FCPaths'].append(paths) + # else iSCSI entry + else: + paths['name'] = tmp[3] + paths['ipAddr'] = tmp[5] + host['iSCSIPaths'].append(paths) + + # find the offset to the description stuff + offset = 0 + for line in out: + if line[:15] == '---------- Host': + break + else: + offset += 1 + + info = out[offset + 2] + tmp = info.split(':') + host['domain'] = tmp[1] + + info = out[offset + 4] + tmp = info.split(':') + host['descriptors']['location'] = tmp[1] + + info = out[offset + 5] + tmp = info.split(':') + host['descriptors']['ipAddr'] = tmp[1] + + info = out[offset + 6] + tmp = info.split(':') + host['descriptors']['os'] = tmp[1] + + info = out[offset + 7] + tmp = info.split(':') + host['descriptors']['model'] = tmp[1] + + info = out[offset + 8] + tmp = info.split(':') + host['descriptors']['contact'] = tmp[1] + + info = out[offset + 9] + tmp = info.split(':') + host['descriptors']['comment'] = tmp[1] + + return host","{'deleted': [{'line_no': 2, 'char_start': 40, 'char_end': 111, 'line': "" out = self._cli_run('showhost -verbose %s' % (hostname), None)\n""}], 'added': [{'line_no': 2, 'char_start': 40, 'char_end': 104, 'line': "" out = self._cli_run(['showhost', '-verbose', hostname])\n""}]}","{'deleted': [{'char_start': 86, 'char_end': 89, 'chars': ' %s'}, {'char_start': 90, 'char_end': 92, 'chars': ' %'}, {'char_start': 93, 'char_end': 94, 'chars': '('}, {'char_start': 102, 'char_end': 109, 'chars': '), None'}], 'added': [{'char_start': 68, 'char_end': 69, 'chars': '['}, {'char_start': 78, 'char_end': 80, 'chars': ""',""}, {'char_start': 81, 'char_end': 82, 'chars': ""'""}, {'char_start': 91, 'char_end': 92, 'chars': ','}, {'char_start': 101, 'char_end': 102, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078, +cwe-078,_get_vdisk_attributes," def _get_vdisk_attributes(self, vdisk_name): + """"""Return vdisk attributes, or None if vdisk does not exist + + Exception is raised if the information from system can not be + parsed/matched to a single vdisk. + """""" + + ssh_cmd = 'svcinfo lsvdisk -bytes -delim ! %s ' % vdisk_name + return self._execute_command_and_parse_attributes(ssh_cmd)"," def _get_vdisk_attributes(self, vdisk_name): + """"""Return vdisk attributes, or None if vdisk does not exist + + Exception is raised if the information from system can not be + parsed/matched to a single vdisk. + """""" + + ssh_cmd = ['svcinfo', 'lsvdisk', '-bytes', '-delim', '!', vdisk_name] + return self._execute_command_and_parse_attributes(ssh_cmd)","{'deleted': [{'line_no': 8, 'char_start': 243, 'char_end': 312, 'line': "" ssh_cmd = 'svcinfo lsvdisk -bytes -delim ! %s ' % vdisk_name\n""}], 'added': [{'line_no': 8, 'char_start': 243, 'char_end': 321, 'line': "" ssh_cmd = ['svcinfo', 'lsvdisk', '-bytes', '-delim', '!', vdisk_name]\n""}]}","{'deleted': [{'char_start': 293, 'char_end': 297, 'chars': ' %s '}, {'char_start': 298, 'char_end': 300, 'chars': ' %'}], 'added': [{'char_start': 261, 'char_end': 262, 'chars': '['}, {'char_start': 270, 'char_end': 272, 'chars': ""',""}, {'char_start': 273, 'char_end': 274, 'chars': ""'""}, {'char_start': 281, 'char_end': 283, 'chars': ""',""}, {'char_start': 284, 'char_end': 285, 'chars': ""'""}, {'char_start': 291, 'char_end': 293, 'chars': ""',""}, {'char_start': 294, 'char_end': 295, 'chars': ""'""}, {'char_start': 301, 'char_end': 303, 'chars': ""',""}, {'char_start': 304, 'char_end': 305, 'chars': ""'""}, {'char_start': 307, 'char_end': 308, 'chars': ','}, {'char_start': 319, 'char_end': 320, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078, +cwe-078,git_hook,"def git_hook(strict=False, modify=False): + """""" + Git pre-commit hook to check staged files for isort errors + + :param bool strict - if True, return number of errors on exit, + causing the hook to fail. If False, return zero so it will + just act as a warning. + :param bool modify - if True, fix the sources if they are not + sorted properly. If False, only report result without + modifying anything. + + :return number of errors if in strict mode, 0 otherwise. + """""" + + # Get list of files modified and staged + diff_cmd = ""git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD"" + files_modified = get_lines(diff_cmd) + + errors = 0 + for filename in files_modified: + if filename.endswith('.py'): + # Get the staged contents of the file + staged_cmd = ""git show :%s"" % filename + staged_contents = get_output(staged_cmd) + + sort = SortImports( + file_path=filename, + file_contents=staged_contents.decode(), + check=True + ) + + if sort.incorrectly_sorted: + errors += 1 + if modify: + SortImports( + file_path=filename, + file_contents=staged_contents.decode(), + check=False, + ) + + return errors if strict else 0","def git_hook(strict=False, modify=False): + """""" + Git pre-commit hook to check staged files for isort errors + + :param bool strict - if True, return number of errors on exit, + causing the hook to fail. If False, return zero so it will + just act as a warning. + :param bool modify - if True, fix the sources if they are not + sorted properly. If False, only report result without + modifying anything. + + :return number of errors if in strict mode, 0 otherwise. + """""" + + # Get list of files modified and staged + diff_cmd = [""git"", ""diff-index"", ""--cached"", ""--name-only"", ""--diff-filter=ACMRTUXB HEAD""] + files_modified = get_lines(diff_cmd) + + errors = 0 + for filename in files_modified: + if filename.endswith('.py'): + # Get the staged contents of the file + staged_cmd = [""git"", ""show"", "":%s"" % filename] + staged_contents = get_output(staged_cmd) + + sort = SortImports( + file_path=filename, + file_contents=staged_contents, + check=True + ) + + if sort.incorrectly_sorted: + errors += 1 + if modify: + SortImports( + file_path=filename, + file_contents=staged_contents, + check=False, + ) + + return errors if strict else 0","{'deleted': [{'line_no': 16, 'char_start': 550, 'char_end': 631, 'line': ' diff_cmd = ""git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD""\n'}, {'line_no': 23, 'char_start': 811, 'char_end': 862, 'line': ' staged_cmd = ""git show :%s"" % filename\n'}, {'line_no': 28, 'char_start': 984, 'char_end': 1040, 'line': ' file_contents=staged_contents.decode(),\n'}, {'line_no': 37, 'char_start': 1254, 'char_end': 1318, 'line': ' file_contents=staged_contents.decode(),\n'}], 'added': [{'line_no': 16, 'char_start': 550, 'char_end': 645, 'line': ' diff_cmd = [""git"", ""diff-index"", ""--cached"", ""--name-only"", ""--diff-filter=ACMRTUXB HEAD""]\n'}, {'line_no': 23, 'char_start': 825, 'char_end': 884, 'line': ' staged_cmd = [""git"", ""show"", "":%s"" % filename]\n'}, {'line_no': 28, 'char_start': 1006, 'char_end': 1053, 'line': ' file_contents=staged_contents,\n'}, {'line_no': 37, 'char_start': 1267, 'char_end': 1322, 'line': ' file_contents=staged_contents,\n'}]}","{'deleted': [{'char_start': 1029, 'char_end': 1038, 'chars': '.decode()'}, {'char_start': 1307, 'char_end': 1316, 'chars': '.decode()'}], 'added': [{'char_start': 565, 'char_end': 566, 'chars': '['}, {'char_start': 570, 'char_end': 572, 'chars': '"",'}, {'char_start': 573, 'char_end': 574, 'chars': '""'}, {'char_start': 584, 'char_end': 586, 'chars': '"",'}, {'char_start': 587, 'char_end': 588, 'chars': '""'}, {'char_start': 596, 'char_end': 598, 'chars': '"",'}, {'char_start': 599, 'char_end': 600, 'chars': '""'}, {'char_start': 611, 'char_end': 613, 'chars': '"",'}, {'char_start': 614, 'char_end': 615, 'chars': '""'}, {'char_start': 643, 'char_end': 644, 'chars': ']'}, {'char_start': 850, 'char_end': 851, 'chars': '['}, {'char_start': 855, 'char_end': 857, 'chars': '"",'}, {'char_start': 858, 'char_end': 859, 'chars': '""'}, {'char_start': 863, 'char_end': 865, 'chars': '"",'}, {'char_start': 866, 'char_end': 867, 'chars': '""'}, {'char_start': 882, 'char_end': 883, 'chars': ']'}, {'char_start': 1267, 'char_end': 1267, 'chars': ''}]}",github.com/timothycrosley/isort/commit/1ab38f4f7840a3c19bf961a24630a992a8373a76,isort/hooks.py,cwe-078, +cwe-078,test_create_modify_host," def test_create_modify_host(self): + self.flags(lock_path=self.tempdir) + + #record + self.clear_mox() + self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_cpg"", + self.fake_get_cpg) + self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_domain"", + self.fake_get_domain) + _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) + self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) + + show_host_cmd = 'showhost -verbose fakehost' + _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_NO_HOST_RET), '']) + + create_host_cmd = ('createhost -iscsi -add fakehost ' + 'iqn.1993-08.org.debian:01:222') + _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, '']) + _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_HOST_RET), '']) + self.mox.ReplayAll() + + host = self.driver._create_host(self.volume, self.connector) + self.assertEqual(host['name'], self.FAKE_HOST)"," def test_create_modify_host(self): + self.flags(lock_path=self.tempdir) + + #record + self.clear_mox() + self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_cpg"", + self.fake_get_cpg) + self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_domain"", + self.fake_get_domain) + _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) + self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) + + show_host_cmd = ['showhost', '-verbose', 'fakehost'] + _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_NO_HOST_RET), '']) + + create_host_cmd = ['createhost', '-iscsi', '-add', 'fakehost', + 'iqn.1993-08.org.debian:01:222'] + _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, '']) + _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_HOST_RET), '']) + self.mox.ReplayAll() + + host = self.driver._create_host(self.volume, self.connector) + self.assertEqual(host['name'], self.FAKE_HOST)","{'deleted': [{'line_no': 13, 'char_start': 504, 'char_end': 557, 'line': "" show_host_cmd = 'showhost -verbose fakehost'\n""}, {'line_no': 16, 'char_start': 638, 'char_end': 700, 'line': "" create_host_cmd = ('createhost -iscsi -add fakehost '\n""}, {'line_no': 17, 'char_start': 700, 'char_end': 760, 'line': "" 'iqn.1993-08.org.debian:01:222')\n""}], 'added': [{'line_no': 13, 'char_start': 504, 'char_end': 565, 'line': "" show_host_cmd = ['showhost', '-verbose', 'fakehost']\n""}, {'line_no': 16, 'char_start': 646, 'char_end': 717, 'line': "" create_host_cmd = ['createhost', '-iscsi', '-add', 'fakehost',\n""}, {'line_no': 17, 'char_start': 717, 'char_end': 777, 'line': "" 'iqn.1993-08.org.debian:01:222']\n""}]}","{'deleted': [{'char_start': 664, 'char_end': 665, 'chars': '('}, {'char_start': 697, 'char_end': 698, 'chars': ' '}, {'char_start': 758, 'char_end': 759, 'chars': ')'}], 'added': [{'char_start': 528, 'char_end': 529, 'chars': '['}, {'char_start': 538, 'char_end': 540, 'chars': ""',""}, {'char_start': 541, 'char_end': 542, 'chars': ""'""}, {'char_start': 550, 'char_end': 552, 'chars': ""',""}, {'char_start': 553, 'char_end': 554, 'chars': ""'""}, {'char_start': 563, 'char_end': 564, 'chars': ']'}, {'char_start': 672, 'char_end': 673, 'chars': '['}, {'char_start': 684, 'char_end': 686, 'chars': ""',""}, {'char_start': 687, 'char_end': 688, 'chars': ""'""}, {'char_start': 694, 'char_end': 696, 'chars': ""',""}, {'char_start': 697, 'char_end': 698, 'chars': ""'""}, {'char_start': 702, 'char_end': 704, 'chars': ""',""}, {'char_start': 705, 'char_end': 706, 'chars': ""'""}, {'char_start': 715, 'char_end': 716, 'chars': ','}, {'char_start': 775, 'char_end': 776, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/tests/test_hp3par.py,cwe-078, +cwe-078,_run_ssh," def _run_ssh(self, command, check_exit_code=True, attempts=1): + if not self.sshpool: + password = self.configuration.san_password + privatekey = self.configuration.san_private_key + min_size = self.configuration.ssh_min_pool_conn + max_size = self.configuration.ssh_max_pool_conn + self.sshpool = utils.SSHPool(self.configuration.san_ip, + self.configuration.san_ssh_port, + self.configuration.ssh_conn_timeout, + self.configuration.san_login, + password=password, + privatekey=privatekey, + min_size=min_size, + max_size=max_size) + last_exception = None + try: + total_attempts = attempts + with self.sshpool.item() as ssh: + while attempts > 0: + attempts -= 1 + try: + return utils.ssh_execute( + ssh, + command, + check_exit_code=check_exit_code) + except Exception as e: + LOG.error(e) + last_exception = e + greenthread.sleep(random.randint(20, 500) / 100.0) + try: + raise exception.ProcessExecutionError( + exit_code=last_exception.exit_code, + stdout=last_exception.stdout, + stderr=last_exception.stderr, + cmd=last_exception.cmd) + except AttributeError: + raise exception.ProcessExecutionError( + exit_code=-1, + stdout="""", + stderr=""Error running SSH command"", + cmd=command) + + except Exception: + with excutils.save_and_reraise_exception(): + LOG.error(_(""Error running SSH command: %s"") % command)"," def _run_ssh(self, cmd_list, check_exit_code=True, attempts=1): + utils.check_ssh_injection(cmd_list) + command = ' '. join(cmd_list) + + if not self.sshpool: + password = self.configuration.san_password + privatekey = self.configuration.san_private_key + min_size = self.configuration.ssh_min_pool_conn + max_size = self.configuration.ssh_max_pool_conn + self.sshpool = utils.SSHPool(self.configuration.san_ip, + self.configuration.san_ssh_port, + self.configuration.ssh_conn_timeout, + self.configuration.san_login, + password=password, + privatekey=privatekey, + min_size=min_size, + max_size=max_size) + last_exception = None + try: + total_attempts = attempts + with self.sshpool.item() as ssh: + while attempts > 0: + attempts -= 1 + try: + return utils.ssh_execute( + ssh, + command, + check_exit_code=check_exit_code) + except Exception as e: + LOG.error(e) + last_exception = e + greenthread.sleep(random.randint(20, 500) / 100.0) + try: + raise exception.ProcessExecutionError( + exit_code=last_exception.exit_code, + stdout=last_exception.stdout, + stderr=last_exception.stderr, + cmd=last_exception.cmd) + except AttributeError: + raise exception.ProcessExecutionError( + exit_code=-1, + stdout="""", + stderr=""Error running SSH command"", + cmd=command) + + except Exception: + with excutils.save_and_reraise_exception(): + LOG.error(_(""Error running SSH command: %s"") % command)","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 67, 'line': ' def _run_ssh(self, command, check_exit_code=True, attempts=1):\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 68, 'line': ' def _run_ssh(self, cmd_list, check_exit_code=True, attempts=1):\n'}, {'line_no': 2, 'char_start': 68, 'char_end': 112, 'line': ' utils.check_ssh_injection(cmd_list)\n'}, {'line_no': 3, 'char_start': 112, 'char_end': 150, 'line': "" command = ' '. join(cmd_list)\n""}, {'line_no': 4, 'char_start': 150, 'char_end': 151, 'line': '\n'}]}","{'deleted': [{'char_start': 24, 'char_end': 25, 'chars': 'o'}, {'char_start': 26, 'char_end': 29, 'chars': 'man'}], 'added': [{'char_start': 26, 'char_end': 31, 'chars': '_list'}, {'char_start': 67, 'char_end': 150, 'chars': ""\n utils.check_ssh_injection(cmd_list)\n command = ' '. join(cmd_list)\n""}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/san/san.py,cwe-078, +cwe-078,view,"@app.route('/view/') +def view(sid): + if '/' not in sid: + path = os.path.join(app.config['UPLOAD_FOLDER'], sid) + if os.path.isdir(path): + using_firebase = 'true' if app.config['FIREBASE'] else 'false' + return render_template('view.html', + sid=sid, title=""Progress for %s"" % sid, using_firebase=using_firebase) + else: + abort(404) + else: + abort(403)","@app.route('/view/') +def view(sid): + if utils.sid_is_valid(sid): + path = join(app.config['UPLOAD_FOLDER'], sid) + if os.path.isdir(path): + using_firebase = 'true' if app.config['FIREBASE'] else 'false' + return render_template('view.html', sid=sid, + title=""Progress for %s"" % sid, + using_firebase=using_firebase) + else: + abort(404) + else: + abort(403)","{'deleted': [{'line_no': 3, 'char_start': 41, 'char_end': 64, 'line': "" if '/' not in sid:\n""}, {'line_no': 4, 'char_start': 64, 'char_end': 126, 'line': "" path = os.path.join(app.config['UPLOAD_FOLDER'], sid)\n""}, {'line_no': 7, 'char_start': 233, 'char_end': 281, 'line': "" return render_template('view.html',\n""}, {'line_no': 8, 'char_start': 281, 'char_end': 364, 'line': ' sid=sid, title=""Progress for %s"" % sid, using_firebase=using_firebase)\n'}], 'added': [{'line_no': 3, 'char_start': 41, 'char_end': 73, 'line': ' if utils.sid_is_valid(sid):\n'}, {'line_no': 4, 'char_start': 73, 'char_end': 127, 'line': "" path = join(app.config['UPLOAD_FOLDER'], sid)\n""}, {'line_no': 7, 'char_start': 234, 'char_end': 291, 'line': "" return render_template('view.html', sid=sid,\n""}, {'line_no': 8, 'char_start': 291, 'char_end': 358, 'line': ' title=""Progress for %s"" % sid,\n'}, {'line_no': 9, 'char_start': 358, 'char_end': 425, 'line': ' using_firebase=using_firebase)\n'}]}","{'deleted': [{'char_start': 48, 'char_end': 54, 'chars': ""'/' no""}, {'char_start': 55, 'char_end': 56, 'chars': ' '}, {'char_start': 57, 'char_end': 59, 'chars': 'n '}, {'char_start': 79, 'char_end': 87, 'chars': 'os.path.'}, {'char_start': 293, 'char_end': 301, 'chars': 'sid=sid,'}], 'added': [{'char_start': 48, 'char_end': 49, 'chars': 'u'}, {'char_start': 51, 'char_end': 54, 'chars': 'ls.'}, {'char_start': 57, 'char_end': 71, 'chars': '_is_valid(sid)'}, {'char_start': 281, 'char_end': 290, 'chars': ' sid=sid,'}, {'char_start': 291, 'char_end': 301, 'chars': ' '}, {'char_start': 313, 'char_end': 326, 'chars': ' '}, {'char_start': 357, 'char_end': 393, 'chars': '\n '}]}",github.com/cheukyin699/genset-demo-site/commit/abb55b1a6786b0a995c2cdf77a7977a1d51cfc0d,app/views.py,cwe-078, +cwe-078,get_title_from_youtube_url,"def get_title_from_youtube_url(url): + try: + output = str(subprocess.check_output('youtube-dl --get-title %s --no-warnings' % url, stderr=subprocess.STDOUT, + shell=True)).strip() + except subprocess.CalledProcessError as ex: + output = str(ex.output).strip() + except OSError as ex: + output = 'youtube-dl not found: %s' % ex + except Exception as ex: + output = 'Something bad happened: %s' % ex + return remove_commas_from_string(output)","def get_title_from_youtube_url(url): + try: + output = str(subprocess.check_output(['youtube-dl', '--get-title', url, '--no-warnings'], + stderr=subprocess.STDOUT)).strip() + except subprocess.CalledProcessError as ex: + output = str(ex.output).strip() + except OSError as ex: + output = 'youtube-dl not found: %s' % ex + except Exception as ex: + output = 'Something bad happened: %s' % ex + return remove_commas_from_string(output)","{'deleted': [{'line_no': 3, 'char_start': 46, 'char_end': 166, 'line': "" output = str(subprocess.check_output('youtube-dl --get-title %s --no-warnings' % url, stderr=subprocess.STDOUT,\n""}, {'line_no': 4, 'char_start': 166, 'char_end': 232, 'line': ' shell=True)).strip()\n'}], 'added': [{'line_no': 3, 'char_start': 46, 'char_end': 144, 'line': "" output = str(subprocess.check_output(['youtube-dl', '--get-title', url, '--no-warnings'],\n""}, {'line_no': 4, 'char_start': 144, 'char_end': 224, 'line': ' stderr=subprocess.STDOUT)).strip()\n'}]}","{'deleted': [{'char_start': 115, 'char_end': 117, 'chars': '%s'}, {'char_start': 132, 'char_end': 164, 'chars': ' % url, stderr=subprocess.STDOUT'}, {'char_start': 212, 'char_end': 213, 'chars': 'h'}, {'char_start': 214, 'char_end': 218, 'chars': 'll=T'}], 'added': [{'char_start': 91, 'char_end': 92, 'chars': '['}, {'char_start': 103, 'char_end': 105, 'chars': ""',""}, {'char_start': 106, 'char_end': 107, 'chars': ""'""}, {'char_start': 118, 'char_end': 120, 'chars': ""',""}, {'char_start': 121, 'char_end': 125, 'chars': 'url,'}, {'char_start': 126, 'char_end': 127, 'chars': ""'""}, {'char_start': 141, 'char_end': 142, 'chars': ']'}, {'char_start': 190, 'char_end': 192, 'chars': 'td'}, {'char_start': 193, 'char_end': 195, 'chars': 'rr'}, {'char_start': 196, 'char_end': 200, 'chars': 'subp'}, {'char_start': 201, 'char_end': 203, 'chars': 'oc'}, {'char_start': 204, 'char_end': 213, 'chars': 'ss.STDOUT'}]}",github.com/w-martin/mindfulness/commit/62e1d5ce9deb57468cf917ce0ce838120ec84c46,src/util.py,cwe-078, +cwe-078,test_get_ports," def test_get_ports(self): + self.flags(lock_path=self.tempdir) + + #record + self.clear_mox() + _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) + self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) + + show_port_cmd = 'showport' + _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), '']) + + show_port_i_cmd = 'showport -iscsi' + _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET), + '']) + + show_port_i_cmd = 'showport -iscsiname' + _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), + '']) + self.mox.ReplayAll() + + ports = self.driver.common.get_ports() + self.assertEqual(ports['FC'][0], '20210002AC00383D') + self.assertEqual(ports['iSCSI']['10.10.120.252']['nsp'], '0:8:2')"," def test_get_ports(self): + self.flags(lock_path=self.tempdir) + + #record + self.clear_mox() + _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) + self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) + + show_port_cmd = ['showport'] + _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), '']) + + show_port_i_cmd = ['showport', '-iscsi'] + _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET), + '']) + + show_port_i_cmd = ['showport', '-iscsiname'] + _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), + '']) + self.mox.ReplayAll() + + ports = self.driver.common.get_ports() + self.assertEqual(ports['FC'][0], '20210002AC00383D') + self.assertEqual(ports['iSCSI']['10.10.120.252']['nsp'], '0:8:2')","{'deleted': [{'line_no': 9, 'char_start': 273, 'char_end': 308, 'line': "" show_port_cmd = 'showport'\n""}, {'line_no': 12, 'char_start': 380, 'char_end': 424, 'line': "" show_port_i_cmd = 'showport -iscsi'\n""}, {'line_no': 16, 'char_start': 562, 'char_end': 610, 'line': "" show_port_i_cmd = 'showport -iscsiname'\n""}], 'added': [{'line_no': 9, 'char_start': 273, 'char_end': 310, 'line': "" show_port_cmd = ['showport']\n""}, {'line_no': 12, 'char_start': 382, 'char_end': 431, 'line': "" show_port_i_cmd = ['showport', '-iscsi']\n""}, {'line_no': 16, 'char_start': 569, 'char_end': 622, 'line': "" show_port_i_cmd = ['showport', '-iscsiname']\n""}]}","{'deleted': [], 'added': [{'char_start': 297, 'char_end': 298, 'chars': '['}, {'char_start': 308, 'char_end': 309, 'chars': ']'}, {'char_start': 408, 'char_end': 409, 'chars': '['}, {'char_start': 418, 'char_end': 420, 'chars': ""',""}, {'char_start': 421, 'char_end': 422, 'chars': ""'""}, {'char_start': 429, 'char_end': 430, 'chars': ']'}, {'char_start': 595, 'char_end': 596, 'chars': '['}, {'char_start': 605, 'char_end': 607, 'chars': ""',""}, {'char_start': 608, 'char_end': 609, 'chars': ""'""}, {'char_start': 620, 'char_end': 621, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/tests/test_hp3par.py,cwe-078, +cwe-078,_create_3par_vlun," def _create_3par_vlun(self, volume, hostname): + out = self._cli_run('createvlun %s auto %s' % (volume, hostname), None) + if out and len(out) > 1: + if ""must be in the same domain"" in out[0]: + err = out[0].strip() + err = err + "" "" + out[1].strip() + raise exception.Invalid3PARDomain(err=err)"," def _create_3par_vlun(self, volume, hostname): + out = self._cli_run(['createvlun', volume, 'auto', hostname]) + if out and len(out) > 1: + if ""must be in the same domain"" in out[0]: + err = out[0].strip() + err = err + "" "" + out[1].strip() + raise exception.Invalid3PARDomain(err=err)","{'deleted': [{'line_no': 2, 'char_start': 51, 'char_end': 131, 'line': "" out = self._cli_run('createvlun %s auto %s' % (volume, hostname), None)\n""}], 'added': [{'line_no': 2, 'char_start': 51, 'char_end': 121, 'line': "" out = self._cli_run(['createvlun', volume, 'auto', hostname])\n""}]}","{'deleted': [{'char_start': 90, 'char_end': 101, 'chars': ' %s auto %s'}, {'char_start': 102, 'char_end': 104, 'chars': ' %'}, {'char_start': 105, 'char_end': 106, 'chars': '('}, {'char_start': 122, 'char_end': 129, 'chars': '), None'}], 'added': [{'char_start': 79, 'char_end': 80, 'chars': '['}, {'char_start': 92, 'char_end': 93, 'chars': ','}, {'char_start': 102, 'char_end': 110, 'chars': ""'auto', ""}, {'char_start': 118, 'char_end': 119, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078, +cwe-078,_set_connections," def _set_connections(self): + """"""Set the number of concurrent connections. + + The 3PAR WS API server has a limit of concurrent connections. + This is setting the number to the highest allowed, 15 connections. + """""" + self._cli_run(""setwsapi -sru high"", None)"," def _set_connections(self): + """"""Set the number of concurrent connections. + + The 3PAR WS API server has a limit of concurrent connections. + This is setting the number to the highest allowed, 15 connections. + """""" + self._cli_run(['setwsapi', '-sru', 'high'])","{'deleted': [{'line_no': 7, 'char_start': 243, 'char_end': 292, 'line': ' self._cli_run(""setwsapi -sru high"", None)\n'}], 'added': [{'line_no': 7, 'char_start': 243, 'char_end': 294, 'line': "" self._cli_run(['setwsapi', '-sru', 'high'])\n""}]}","{'deleted': [{'char_start': 265, 'char_end': 266, 'chars': '""'}, {'char_start': 284, 'char_end': 291, 'chars': '"", None'}], 'added': [{'char_start': 265, 'char_end': 267, 'chars': ""['""}, {'char_start': 275, 'char_end': 277, 'chars': ""',""}, {'char_start': 278, 'char_end': 279, 'chars': ""'""}, {'char_start': 283, 'char_end': 285, 'chars': ""',""}, {'char_start': 286, 'char_end': 287, 'chars': ""'""}, {'char_start': 291, 'char_end': 293, 'chars': ""']""}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078, +cwe-078,_get_chap_secret_for_host," def _get_chap_secret_for_host(self, host_name): + """"""Return the CHAP secret for the given host."""""" + + LOG.debug(_('enter: _get_chap_secret_for_host: host name %s') + % host_name) + + ssh_cmd = 'svcinfo lsiscsiauth -delim !' + out, err = self._run_ssh(ssh_cmd) + + if not len(out.strip()): + return None + + host_lines = out.strip().split('\n') + self._assert_ssh_return(len(host_lines), '_get_chap_secret_for_host', + ssh_cmd, out, err) + + header = host_lines.pop(0).split('!') + self._assert_ssh_return('name' in header, '_get_chap_secret_for_host', + ssh_cmd, out, err) + self._assert_ssh_return('iscsi_auth_method' in header, + '_get_chap_secret_for_host', ssh_cmd, out, err) + self._assert_ssh_return('iscsi_chap_secret' in header, + '_get_chap_secret_for_host', ssh_cmd, out, err) + name_index = header.index('name') + method_index = header.index('iscsi_auth_method') + secret_index = header.index('iscsi_chap_secret') + + chap_secret = None + host_found = False + for line in host_lines: + info = line.split('!') + if info[name_index] == host_name: + host_found = True + if info[method_index] == 'chap': + chap_secret = info[secret_index] + + self._assert_ssh_return(host_found, '_get_chap_secret_for_host', + ssh_cmd, out, err) + + LOG.debug(_('leave: _get_chap_secret_for_host: host name ' + '%(host_name)s with secret %(chap_secret)s') + % {'host_name': host_name, 'chap_secret': chap_secret}) + + return chap_secret"," def _get_chap_secret_for_host(self, host_name): + """"""Return the CHAP secret for the given host."""""" + + LOG.debug(_('enter: _get_chap_secret_for_host: host name %s') + % host_name) + + ssh_cmd = ['svcinfo', 'lsiscsiauth', '-delim', '!'] + out, err = self._run_ssh(ssh_cmd) + + if not len(out.strip()): + return None + + host_lines = out.strip().split('\n') + self._assert_ssh_return(len(host_lines), '_get_chap_secret_for_host', + ssh_cmd, out, err) + + header = host_lines.pop(0).split('!') + self._assert_ssh_return('name' in header, '_get_chap_secret_for_host', + ssh_cmd, out, err) + self._assert_ssh_return('iscsi_auth_method' in header, + '_get_chap_secret_for_host', ssh_cmd, out, err) + self._assert_ssh_return('iscsi_chap_secret' in header, + '_get_chap_secret_for_host', ssh_cmd, out, err) + name_index = header.index('name') + method_index = header.index('iscsi_auth_method') + secret_index = header.index('iscsi_chap_secret') + + chap_secret = None + host_found = False + for line in host_lines: + info = line.split('!') + if info[name_index] == host_name: + host_found = True + if info[method_index] == 'chap': + chap_secret = info[secret_index] + + self._assert_ssh_return(host_found, '_get_chap_secret_for_host', + ssh_cmd, out, err) + + LOG.debug(_('leave: _get_chap_secret_for_host: host name ' + '%(host_name)s with secret %(chap_secret)s') + % {'host_name': host_name, 'chap_secret': chap_secret}) + + return chap_secret","{'deleted': [{'line_no': 7, 'char_start': 212, 'char_end': 261, 'line': "" ssh_cmd = 'svcinfo lsiscsiauth -delim !'\n""}], 'added': [{'line_no': 7, 'char_start': 212, 'char_end': 272, 'line': "" ssh_cmd = ['svcinfo', 'lsiscsiauth', '-delim', '!']\n""}]}","{'deleted': [], 'added': [{'char_start': 230, 'char_end': 231, 'chars': '['}, {'char_start': 239, 'char_end': 241, 'chars': ""',""}, {'char_start': 242, 'char_end': 243, 'chars': ""'""}, {'char_start': 254, 'char_end': 256, 'chars': ""',""}, {'char_start': 257, 'char_end': 258, 'chars': ""'""}, {'char_start': 264, 'char_end': 266, 'chars': ""',""}, {'char_start': 267, 'char_end': 268, 'chars': ""'""}, {'char_start': 270, 'char_end': 271, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078, +cwe-079,PeerListWidget::updatePeer,"void PeerListWidget::updatePeer(const QString &ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer) +{ + QStandardItem *item = m_peerItems.value(ip); + int row = item->row(); + if (m_resolveCountries) { + const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country()); + if (!ico.isNull()) { + m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole); + const QString countryName = Net::GeoIPManager::CountryName(peer.country()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole); + m_missingFlags.remove(ip); + } + } + m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), peer.client()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance()); + QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex())); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String("";""))); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(""\n"")), Qt::ToolTipRole); +}","void PeerListWidget::updatePeer(const QString &ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer) +{ + QStandardItem *item = m_peerItems.value(ip); + int row = item->row(); + if (m_resolveCountries) { + const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country()); + if (!ico.isNull()) { + m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole); + const QString countryName = Net::GeoIPManager::CountryName(peer.country()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole); + m_missingFlags.remove(ip); + } + } + m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), Utils::String::toHtmlEscaped(peer.client())); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload()); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance()); + QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex())); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String("";""))); + m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(""\n"")), Qt::ToolTipRole); +}","{'deleted': [{'line_no': 18, 'char_start': 1126, 'char_end': 1218, 'line': ' m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), peer.client());\n'}], 'added': [{'line_no': 18, 'char_start': 1126, 'char_end': 1248, 'line': ' m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), Utils::String::toHtmlEscaped(peer.client()));\n'}]}","{'deleted': [], 'added': [{'char_start': 1202, 'char_end': 1231, 'chars': 'Utils::String::toHtmlEscaped('}, {'char_start': 1243, 'char_end': 1244, 'chars': ')'}]}",github.com/qbittorrent/qBittorrent/commit/6ca3e4f094da0a0017cb2d483ec1db6176bb0b16,src/gui/properties/peerlistwidget.cpp,cwe-079, +cwe-079,redirect," def redirect(self, url, **kwargs): + """"""Explicitly converts url to 'str', because webapp2.RequestHandler.redirect + strongly requires 'str' but url might be an unicode string."""""" + super(Handler, self).redirect(str(url), **kwargs)"," def redirect(self, url, **kwargs): + """"""Explicitly converts url to 'str', because webapp2.RequestHandler.redirect + strongly requires 'str' but url might be an unicode string."""""" + url = str(url) + check_redirect_url(url) + super(Handler, self).redirect(url, **kwargs)","{'deleted': [{'line_no': 4, 'char_start': 185, 'char_end': 238, 'line': ' super(Handler, self).redirect(str(url), **kwargs)\n'}], 'added': [{'line_no': 4, 'char_start': 185, 'char_end': 204, 'line': ' url = str(url)\n'}, {'line_no': 5, 'char_start': 204, 'char_end': 232, 'line': ' check_redirect_url(url)\n'}, {'line_no': 6, 'char_start': 232, 'char_end': 280, 'line': ' super(Handler, self).redirect(url, **kwargs)\n'}]}","{'deleted': [{'char_start': 219, 'char_end': 223, 'chars': 'str('}, {'char_start': 226, 'char_end': 227, 'chars': ')'}], 'added': [{'char_start': 189, 'char_end': 236, 'chars': 'url = str(url)\n check_redirect_url(url)\n '}]}",github.com/google/clusterfuzz/commit/3d66c1146550eecd4e34d47332a8616b435a21fe,src/appengine/handlers/base_handler.py,cwe-079, +cwe-079,get_value," def get_value(self): + if self.column.render_function: + # We don't want to escape our html + return self.column.render_function(self.object) + + field = getattr(self.object, self.column.field_name) if self.column.field_name else None + if type(self.object) == dict: + value = self.object.get(self.column.field_name) + elif callable(field): + value = field() if getattr(field, 'do_not_call_in_templates', False) else field + else: + display_function = getattr(self.object, 'get_%s_display' % self.column.field_name, False) + value = display_function() if display_function else field + + return escape(value)"," def get_value(self): + field = getattr(self.object, self.column.field_name) if self.column.field_name else None + if self.column.render_function: + template = self.column.render_function(self.object) + if not self.is_template_instance(template): + raise SmartListException( + 'Your render_function {} should return django.template.Template or django.template.backends.django.Template object instead of {}'.format( + self.column.render_function.__name__, + type(template), + ) + ) + value = template.render() + elif type(self.object) == dict: + value = self.object.get(self.column.field_name) + elif callable(field): + value = field() if getattr(field, 'do_not_call_in_templates', False) else field + else: + display_function = getattr(self.object, 'get_%s_display' % self.column.field_name, False) + value = display_function() if display_function else field + + return value","{'deleted': [{'line_no': 2, 'char_start': 25, 'char_end': 65, 'line': ' if self.column.render_function:\n'}, {'line_no': 4, 'char_start': 112, 'char_end': 172, 'line': ' return self.column.render_function(self.object)\n'}, {'line_no': 5, 'char_start': 172, 'char_end': 173, 'line': '\n'}, {'line_no': 7, 'char_start': 270, 'char_end': 308, 'line': ' if type(self.object) == dict:\n'}, {'line_no': 15, 'char_start': 677, 'char_end': 705, 'line': ' return escape(value)\n'}], 'added': [{'line_no': 3, 'char_start': 122, 'char_end': 162, 'line': ' if self.column.render_function:\n'}, {'line_no': 4, 'char_start': 162, 'char_end': 226, 'line': ' template = self.column.render_function(self.object)\n'}, {'line_no': 5, 'char_start': 226, 'char_end': 282, 'line': ' if not self.is_template_instance(template):\n'}, {'line_no': 6, 'char_start': 282, 'char_end': 324, 'line': ' raise SmartListException(\n'}, {'line_no': 7, 'char_start': 324, 'char_end': 482, 'line': "" 'Your render_function {} should return django.template.Template or django.template.backends.django.Template object instead of {}'.format(\n""}, {'line_no': 8, 'char_start': 482, 'char_end': 544, 'line': ' self.column.render_function.__name__,\n'}, {'line_no': 9, 'char_start': 544, 'char_end': 584, 'line': ' type(template),\n'}, {'line_no': 10, 'char_start': 584, 'char_end': 606, 'line': ' )\n'}, {'line_no': 11, 'char_start': 606, 'char_end': 624, 'line': ' )\n'}, {'line_no': 12, 'char_start': 624, 'char_end': 662, 'line': ' value = template.render()\n'}, {'line_no': 13, 'char_start': 662, 'char_end': 702, 'line': ' elif type(self.object) == dict:\n'}, {'line_no': 21, 'char_start': 1071, 'char_end': 1091, 'line': ' return value\n'}]}","{'deleted': [{'char_start': 48, 'char_end': 49, 'chars': 'r'}, {'char_start': 51, 'char_end': 52, 'chars': 'd'}, {'char_start': 53, 'char_end': 55, 'chars': 'r_'}, {'char_start': 58, 'char_end': 60, 'chars': 'ct'}, {'char_start': 61, 'char_end': 62, 'chars': 'o'}, {'char_start': 63, 'char_end': 67, 'chars': ':\n '}, {'char_start': 77, 'char_end': 78, 'chars': '#'}, {'char_start': 79, 'char_end': 80, 'chars': 'W'}, {'char_start': 81, 'char_end': 83, 'chars': ' d'}, {'char_start': 85, 'char_end': 90, 'chars': ""'t wa""}, {'char_start': 91, 'char_end': 96, 'chars': 't to '}, {'char_start': 97, 'char_end': 98, 'chars': 's'}, {'char_start': 99, 'char_end': 103, 'chars': 'ape '}, {'char_start': 104, 'char_end': 111, 'chars': 'ur html'}, {'char_start': 124, 'char_end': 125, 'chars': 'r'}, {'char_start': 127, 'char_end': 130, 'chars': 'urn'}, {'char_start': 172, 'char_end': 173, 'chars': '\n'}, {'char_start': 185, 'char_end': 190, 'chars': 'd = g'}, {'char_start': 196, 'char_end': 197, 'chars': '('}, {'char_start': 199, 'char_end': 205, 'chars': 'lf.obj'}, {'char_start': 206, 'char_end': 207, 'chars': 'c'}, {'char_start': 208, 'char_end': 209, 'chars': ','}, {'char_start': 210, 'char_end': 211, 'chars': 's'}, {'char_start': 212, 'char_end': 213, 'chars': 'l'}, {'char_start': 214, 'char_end': 215, 'chars': '.'}, {'char_start': 219, 'char_end': 220, 'chars': 'm'}, {'char_start': 222, 'char_end': 224, 'chars': 'fi'}, {'char_start': 227, 'char_end': 228, 'chars': '_'}, {'char_start': 232, 'char_end': 233, 'chars': ')'}, {'char_start': 251, 'char_end': 254, 'chars': 'eld'}, {'char_start': 262, 'char_end': 263, 'chars': 's'}, {'char_start': 265, 'char_end': 267, 'chars': 'No'}, {'char_start': 692, 'char_end': 699, 'chars': 'escape('}, {'char_start': 704, 'char_end': 705, 'chars': ')'}], 'added': [{'char_start': 33, 'char_end': 34, 'chars': 'f'}, {'char_start': 35, 'char_end': 52, 'chars': 'eld = getattr(sel'}, {'char_start': 53, 'char_end': 61, 'chars': '.object,'}, {'char_start': 74, 'char_end': 76, 'chars': 'fi'}, {'char_start': 77, 'char_end': 78, 'chars': 'l'}, {'char_start': 80, 'char_end': 87, 'chars': 'name) i'}, {'char_start': 88, 'char_end': 97, 'chars': ' self.col'}, {'char_start': 98, 'char_end': 99, 'chars': 'm'}, {'char_start': 100, 'char_end': 102, 'chars': '.f'}, {'char_start': 103, 'char_end': 118, 'chars': 'eld_name else N'}, {'char_start': 120, 'char_end': 121, 'chars': 'e'}, {'char_start': 130, 'char_end': 132, 'chars': 'if'}, {'char_start': 133, 'char_end': 134, 'chars': 's'}, {'char_start': 135, 'char_end': 139, 'chars': 'lf.c'}, {'char_start': 140, 'char_end': 143, 'chars': 'lum'}, {'char_start': 144, 'char_end': 146, 'chars': '.r'}, {'char_start': 147, 'char_end': 149, 'chars': 'nd'}, {'char_start': 150, 'char_end': 153, 'chars': 'r_f'}, {'char_start': 154, 'char_end': 156, 'chars': 'nc'}, {'char_start': 157, 'char_end': 161, 'chars': 'ion:'}, {'char_start': 174, 'char_end': 175, 'chars': 't'}, {'char_start': 176, 'char_end': 180, 'chars': 'mpla'}, {'char_start': 181, 'char_end': 184, 'chars': 'e ='}, {'char_start': 226, 'char_end': 230, 'chars': ' '}, {'char_start': 238, 'char_end': 239, 'chars': 'i'}, {'char_start': 240, 'char_end': 250, 'chars': ' not self.'}, {'char_start': 251, 'char_end': 254, 'chars': 's_t'}, {'char_start': 255, 'char_end': 257, 'chars': 'mp'}, {'char_start': 258, 'char_end': 260, 'chars': 'at'}, {'char_start': 261, 'char_end': 265, 'chars': '_ins'}, {'char_start': 267, 'char_end': 271, 'chars': 'nce('}, {'char_start': 272, 'char_end': 277, 'chars': 'empla'}, {'char_start': 278, 'char_end': 298, 'chars': 'e):\n '}, {'char_start': 299, 'char_end': 301, 'chars': 'ai'}, {'char_start': 303, 'char_end': 346, 'chars': "" SmartListException(\n 'Y""}, {'char_start': 347, 'char_end': 351, 'chars': 'ur r'}, {'char_start': 352, 'char_end': 360, 'chars': 'nder_fun'}, {'char_start': 362, 'char_end': 368, 'chars': 'ion {}'}, {'char_start': 370, 'char_end': 377, 'chars': 'hould r'}, {'char_start': 378, 'char_end': 388, 'chars': 'turn djang'}, {'char_start': 389, 'char_end': 394, 'chars': '.temp'}, {'char_start': 395, 'char_end': 401, 'chars': 'ate.Te'}, {'char_start': 402, 'char_end': 414, 'chars': 'plate or dja'}, {'char_start': 415, 'char_end': 417, 'chars': 'go'}, {'char_start': 418, 'char_end': 419, 'chars': 't'}, {'char_start': 420, 'char_end': 422, 'chars': 'mp'}, {'char_start': 423, 'char_end': 433, 'chars': 'ate.backen'}, {'char_start': 434, 'char_end': 439, 'chars': 's.dja'}, {'char_start': 440, 'char_end': 445, 'chars': 'go.Te'}, {'char_start': 446, 'char_end': 450, 'chars': 'plat'}, {'char_start': 451, 'char_end': 458, 'chars': ' object'}, {'char_start': 460, 'char_end': 468, 'chars': 'nstead o'}, {'char_start': 470, 'char_end': 506, 'chars': ""{}'.format(\n ""}, {'char_start': 518, 'char_end': 519, 'chars': 'r'}, {'char_start': 520, 'char_end': 521, 'chars': 'n'}, {'char_start': 522, 'char_end': 535, 'chars': 'er_function._'}, {'char_start': 540, 'char_end': 560, 'chars': '__,\n '}, {'char_start': 561, 'char_end': 574, 'chars': ' type(t'}, {'char_start': 575, 'char_end': 577, 'chars': 'mp'}, {'char_start': 578, 'char_end': 580, 'chars': 'at'}, {'char_start': 581, 'char_end': 588, 'chars': '),\n '}, {'char_start': 589, 'char_end': 655, 'chars': ' )\n )\n value = template.re'}, {'char_start': 656, 'char_end': 657, 'chars': 'd'}, {'char_start': 658, 'char_end': 661, 'chars': 'r()'}, {'char_start': 670, 'char_end': 672, 'chars': 'el'}]}",github.com/plecto/django-smart-lists/commit/44314e51b371e01cd9bceb2e0ed6c8d75d7f87c3,smart_lists/helpers.py,cwe-079, +cwe-079,http_error_t::make_body,"http_error_t::make_body (int n, const str &si, const str &aux) +{ + strbuf b; + str ldesc; + const str sdesc = http_status.get_desc (n, &ldesc); + b << ""\n"" + << "" \n"" + << "" "" << n << "" "" << sdesc << ""\n"" + << "" \n"" + << "" \n"" + << ""

Error "" << n << "" "" << sdesc << ""



\n"" + ; + if (n == HTTP_NOT_FOUND && aux) { + b << ""The file "" << aux + << "" was not found on this server.

\n\n""; + } + b << ""
\n"" + << "" "" << si << ""\n"" + << ""
\n"" + << "" \n"" + << ""\n"" + ; + return b; +}","http_error_t::make_body (int n, const str &si, const str &aux) +{ + strbuf b; + str ldesc; + const str sdesc = xss_escape (http_status.get_desc (n, &ldesc)); + b << ""\n"" + << "" \n"" + << "" "" << n << "" "" << sdesc << ""\n"" + << "" \n"" + << "" \n"" + << ""

Error "" << n << "" "" << sdesc << ""



\n"" + ; + if (n == HTTP_NOT_FOUND && aux) { + b << ""The file "" << xss_escape (aux) + << "" was not found on this server.

\n\n""; + } + b << ""
\n"" + << "" "" << xss_escape (si) << ""\n"" + << ""
\n"" + << "" \n"" + << ""\n"" + ; + return b; +}","{'deleted': [{'line_no': 5, 'char_start': 90, 'char_end': 144, 'line': ' const str sdesc = http_status.get_desc (n, &ldesc);\n'}, {'line_no': 14, 'char_start': 381, 'char_end': 414, 'line': ' b << ""The file "" << aux \n'}, {'line_no': 18, 'char_start': 496, 'char_end': 529, 'line': ' << "" "" << si << ""\\n""\n'}], 'added': [{'line_no': 5, 'char_start': 90, 'char_end': 157, 'line': ' const str sdesc = xss_escape (http_status.get_desc (n, &ldesc));\n'}, {'line_no': 14, 'char_start': 394, 'char_end': 439, 'line': ' b << ""The file "" << xss_escape (aux)\n'}, {'line_no': 18, 'char_start': 521, 'char_end': 567, 'line': ' << "" "" << xss_escape (si) << ""\\n""\n'}]}","{'deleted': [{'char_start': 412, 'char_end': 413, 'chars': ' '}], 'added': [{'char_start': 110, 'char_end': 122, 'chars': 'xss_escape ('}, {'char_start': 153, 'char_end': 154, 'chars': ')'}, {'char_start': 422, 'char_end': 434, 'chars': 'xss_escape ('}, {'char_start': 437, 'char_end': 438, 'chars': ')'}, {'char_start': 539, 'char_end': 551, 'chars': 'xss_escape ('}, {'char_start': 553, 'char_end': 554, 'chars': ')'}]}",github.com/okws/okws/commit/e9bedb644d106a043e33e1058bedd1c2c0b2e2e0,libahttp/err.C,cwe-079, +cwe-079,list_editor_workflows,"def list_editor_workflows(request): + workflows = [d.content_object.to_dict() for d in Document.objects.get_docs(request.user, Document2, extra='workflow2')] + + return render('editor/list_editor_workflows.mako', request, { + 'workflows_json': json.dumps(workflows) + })","def list_editor_workflows(request): + workflows = [d.content_object.to_dict() for d in Document.objects.get_docs(request.user, Document2, extra='workflow2')] + + return render('editor/list_editor_workflows.mako', request, { + 'workflows_json': json.dumps(workflows, cls=JSONEncoderForHTML) + })","{'deleted': [{'line_no': 5, 'char_start': 225, 'char_end': 271, 'line': "" 'workflows_json': json.dumps(workflows)\n""}], 'added': [{'line_no': 5, 'char_start': 225, 'char_end': 295, 'line': "" 'workflows_json': json.dumps(workflows, cls=JSONEncoderForHTML)\n""}]}","{'deleted': [], 'added': [{'char_start': 269, 'char_end': 293, 'chars': ', cls=JSONEncoderForHTML'}]}",github.com/gethue/hue/commit/6641c62beaa1468082e47d82da5ed758d11c7735,apps/oozie/src/oozie/views/editor2.py,cwe-079, +cwe-089,likeComments," def likeComments(self,commentid,userid): + sqlText=""insert into comment_like values(%d,%d);""%(userid,commentid) + result=sql.insertDB(self.conn,sqlText) + return result;"," def likeComments(self,commentid,userid): + sqlText=""insert into comment_like values(%s,%s);"" + params=[userid,commentid] + result=sql.insertDB(self.conn,sqlText,params) + return result;","{'deleted': [{'line_no': 2, 'char_start': 45, 'char_end': 122, 'line': ' sqlText=""insert into comment_like values(%d,%d);""%(userid,commentid)\n'}, {'line_no': 3, 'char_start': 122, 'char_end': 169, 'line': ' result=sql.insertDB(self.conn,sqlText)\n'}], 'added': [{'line_no': 2, 'char_start': 45, 'char_end': 103, 'line': ' sqlText=""insert into comment_like values(%s,%s);""\n'}, {'line_no': 3, 'char_start': 103, 'char_end': 137, 'line': ' params=[userid,commentid]\n'}, {'line_no': 4, 'char_start': 137, 'char_end': 191, 'line': ' result=sql.insertDB(self.conn,sqlText,params)\n'}]}","{'deleted': [{'char_start': 95, 'char_end': 96, 'chars': 'd'}, {'char_start': 98, 'char_end': 99, 'chars': 'd'}, {'char_start': 102, 'char_end': 104, 'chars': '%('}, {'char_start': 120, 'char_end': 121, 'chars': ')'}], 'added': [{'char_start': 95, 'char_end': 96, 'chars': 's'}, {'char_start': 98, 'char_end': 99, 'chars': 's'}, {'char_start': 102, 'char_end': 119, 'chars': '\n params=['}, {'char_start': 135, 'char_end': 136, 'chars': ']'}, {'char_start': 182, 'char_end': 189, 'chars': ',params'}]}",github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9,modules/comment.py,cwe-089, +cwe-089,add_inverters," def add_inverters(self): + interfaces = self.config.get_connection_interfaces() + for source in interfaces: + if source[""type""] == ""inverter"": + + query = ''' + INSERT OR IGNORE INTO Inverters ( + Serial, + EToday, + ETotal + ) VALUES ( + %s, + %s, + %s + ); + ''' % (source[""serial_id""], 0, source[""prev_etotal""]) + self.c.execute(query) + + query = ''' + UPDATE Inverters + SET + Name='%s', + Type='%s', + SW_Version='%s', + Status='%s', + TimeStamp='%s' + WHERE Serial='%s'; + ''' % (source[""name""], source[""inverter_type""], ""s0-bridge v0"", ""OK"", int(datetime.now().timestamp()), source[""serial_id""] ) + self.c.execute(query) + + self.db.commit()"," def add_inverters(self): + interfaces = self.config.get_connection_interfaces() + for source in interfaces: + if source[""type""] == ""inverter"": + + query = ''' + INSERT OR IGNORE INTO Inverters ( + Serial, + EToday, + ETotal + ) VALUES ( + ?, + ?, + ? + ); + ''' + self.c.execute(query, (source[""serial_id""], 0, source[""prev_etotal""])) + + query = ''' + UPDATE Inverters + SET + Name=?, + Type=?, + SW_Version=?, + Status=?, + TimeStamp=? + WHERE Serial=?; + ''' + self.c.execute(query, (source[""name""], source[""inverter_type""], ""s0-bridge v0"", ""OK"", int(datetime.now().timestamp()), source[""serial_id""] )) + + self.db.commit()","{'deleted': [{'line_no': 12, 'char_start': 378, 'char_end': 406, 'line': ' %s,\n'}, {'line_no': 13, 'char_start': 406, 'char_end': 434, 'line': ' %s,\n'}, {'line_no': 14, 'char_start': 434, 'char_end': 461, 'line': ' %s\n'}, {'line_no': 16, 'char_start': 484, 'char_end': 554, 'line': ' \'\'\' % (source[""serial_id""], 0, source[""prev_etotal""])\n'}, {'line_no': 17, 'char_start': 554, 'char_end': 592, 'line': ' self.c.execute(query)\n'}, {'line_no': 22, 'char_start': 687, 'char_end': 723, 'line': "" Name='%s', \n""}, {'line_no': 23, 'char_start': 723, 'char_end': 759, 'line': "" Type='%s', \n""}, {'line_no': 24, 'char_start': 759, 'char_end': 801, 'line': "" SW_Version='%s', \n""}, {'line_no': 25, 'char_start': 801, 'char_end': 838, 'line': "" Status='%s',\n""}, {'line_no': 26, 'char_start': 838, 'char_end': 877, 'line': "" TimeStamp='%s'\n""}, {'line_no': 27, 'char_start': 877, 'char_end': 916, 'line': "" WHERE Serial='%s';\n""}, {'line_no': 28, 'char_start': 916, 'char_end': 1057, 'line': ' \'\'\' % (source[""name""], source[""inverter_type""], ""s0-bridge v0"", ""OK"", int(datetime.now().timestamp()), source[""serial_id""] )\n'}, {'line_no': 29, 'char_start': 1057, 'char_end': 1095, 'line': ' self.c.execute(query)\n'}], 'added': [{'line_no': 12, 'char_start': 378, 'char_end': 405, 'line': ' ?,\n'}, {'line_no': 13, 'char_start': 405, 'char_end': 432, 'line': ' ?,\n'}, {'line_no': 14, 'char_start': 432, 'char_end': 458, 'line': ' ?\n'}, {'line_no': 16, 'char_start': 481, 'char_end': 501, 'line': "" '''\n""}, {'line_no': 17, 'char_start': 501, 'char_end': 588, 'line': ' self.c.execute(query, (source[""serial_id""], 0, source[""prev_etotal""]))\n'}, {'line_no': 22, 'char_start': 683, 'char_end': 716, 'line': ' Name=?, \n'}, {'line_no': 23, 'char_start': 716, 'char_end': 749, 'line': ' Type=?, \n'}, {'line_no': 24, 'char_start': 749, 'char_end': 788, 'line': ' SW_Version=?, \n'}, {'line_no': 25, 'char_start': 788, 'char_end': 822, 'line': ' Status=?,\n'}, {'line_no': 26, 'char_start': 822, 'char_end': 858, 'line': ' TimeStamp=?\n'}, {'line_no': 27, 'char_start': 858, 'char_end': 894, 'line': ' WHERE Serial=?;\n'}, {'line_no': 28, 'char_start': 894, 'char_end': 914, 'line': "" '''\n""}, {'line_no': 29, 'char_start': 914, 'char_end': 1072, 'line': ' self.c.execute(query, (source[""name""], source[""inverter_type""], ""s0-bridge v0"", ""OK"", int(datetime.now().timestamp()), source[""serial_id""] ))\n'}]}","{'deleted': [{'char_start': 402, 'char_end': 404, 'chars': '%s'}, {'char_start': 430, 'char_end': 432, 'chars': '%s'}, {'char_start': 458, 'char_end': 460, 'chars': '%s'}, {'char_start': 504, 'char_end': 505, 'chars': '%'}, {'char_start': 553, 'char_end': 590, 'chars': '\n self.c.execute(query'}, {'char_start': 716, 'char_end': 720, 'chars': ""'%s'""}, {'char_start': 752, 'char_end': 756, 'chars': ""'%s'""}, {'char_start': 794, 'char_end': 798, 'chars': ""'%s'""}, {'char_start': 832, 'char_end': 836, 'chars': ""'%s'""}, {'char_start': 872, 'char_end': 876, 'chars': ""'%s'""}, {'char_start': 910, 'char_end': 914, 'chars': ""'%s'""}, {'char_start': 936, 'char_end': 937, 'chars': '%'}, {'char_start': 1056, 'char_end': 1093, 'chars': '\n self.c.execute(query'}], 'added': [{'char_start': 402, 'char_end': 403, 'chars': '?'}, {'char_start': 429, 'char_end': 430, 'chars': '?'}, {'char_start': 456, 'char_end': 457, 'chars': '?'}, {'char_start': 500, 'char_end': 515, 'chars': '\n '}, {'char_start': 516, 'char_end': 538, 'chars': ' self.c.execute(query,'}, {'char_start': 712, 'char_end': 713, 'chars': '?'}, {'char_start': 745, 'char_end': 746, 'chars': '?'}, {'char_start': 784, 'char_end': 785, 'chars': '?'}, {'char_start': 819, 'char_end': 820, 'chars': '?'}, {'char_start': 856, 'char_end': 857, 'chars': '?'}, {'char_start': 891, 'char_end': 892, 'chars': '?'}, {'char_start': 913, 'char_end': 918, 'chars': '\n '}, {'char_start': 919, 'char_end': 951, 'chars': ' self.c.execute(query,'}]}",github.com/philipptrenz/s0-bridge/commit/269b48caa05377b7c58c3e6d1622a4429cb5ba65,util/database.py,cwe-089, +cwe-089,delete,"@mod.route('/delete/', methods=['GET', 'POST']) +def delete(msg_id): + if request.method == 'GET': + sql = ""DELETE FROM message where msg_id = '%d';"" % (msg_id) + cursor.execute(sql) + conn.commit() + flash('Delete Success!') + return redirect(url_for('show_entries'))","@mod.route('/delete/', methods=['GET', 'POST']) +def delete(msg_id): + if request.method == 'GET': + cursor.execute(""DELETE FROM message where msg_id = %s;"", (msg_id,)) + conn.commit() + flash('Delete Success!') + return redirect(url_for('show_entries'))","{'deleted': [{'line_no': 4, 'char_start': 112, 'char_end': 180, 'line': ' sql = ""DELETE FROM message where msg_id = \'%d\';"" % (msg_id)\n'}, {'line_no': 5, 'char_start': 180, 'char_end': 208, 'line': ' cursor.execute(sql)\n'}], 'added': [{'line_no': 4, 'char_start': 112, 'char_end': 188, 'line': ' cursor.execute(""DELETE FROM message where msg_id = %s;"", (msg_id,))\n'}]}","{'deleted': [{'char_start': 121, 'char_end': 126, 'chars': 'ql = '}, {'char_start': 162, 'char_end': 163, 'chars': ""'""}, {'char_start': 164, 'char_end': 166, 'chars': ""d'""}, {'char_start': 168, 'char_end': 170, 'chars': ' %'}, {'char_start': 179, 'char_end': 206, 'chars': '\n cursor.execute(sql'}], 'added': [{'char_start': 120, 'char_end': 123, 'chars': 'cur'}, {'char_start': 124, 'char_end': 135, 'chars': 'or.execute('}, {'char_start': 172, 'char_end': 173, 'chars': 's'}, {'char_start': 175, 'char_end': 176, 'chars': ','}, {'char_start': 184, 'char_end': 185, 'chars': ','}]}",github.com/ulyssetsd/bjtu-sql/commit/17d7b21864b72ba5666f15236474a93268b32ec9,flaskr/flaskr/views/message.py,cwe-089, +cwe-089,karma_rank,"def karma_rank(name): + db = db_connect() + cursor = db.cursor() + try: + cursor.execute(''' + SELECT (SELECT COUNT(*) FROM people AS t2 WHERE t2.karma > t1.karma) + AS row_Num FROM people AS t1 WHERE name='{}' + '''.format(name)) + rank = cursor.fetchone()[0] + 1 + logger.debug('Rank of {} found for name {}'.format(rank, name)) + db.close() + return rank + except Exception as e: + logger.error('Execution failed with error: {}'.format(e)) + raise","def karma_rank(name): + db = db_connect() + cursor = db.cursor() + try: + cursor.execute(''' + SELECT (SELECT COUNT(*) FROM people AS t2 WHERE t2.karma > t1.karma) + AS row_Num FROM people AS t1 WHERE name=%(name)s + ''', (name, )) + rank = cursor.fetchone()[0] + 1 + logger.debug('Rank of {} found for name {}'.format(rank, name)) + db.close() + return rank + except Exception as e: + logger.error('Execution failed with error: {}'.format(e)) + raise","{'deleted': [{'line_no': 7, 'char_start': 186, 'char_end': 243, 'line': "" AS row_Num FROM people AS t1 WHERE name='{}'\n""}, {'line_no': 8, 'char_start': 243, 'char_end': 269, 'line': "" '''.format(name))\n""}], 'added': [{'line_no': 7, 'char_start': 186, 'char_end': 247, 'line': ' AS row_Num FROM people AS t1 WHERE name=%(name)s\n'}, {'line_no': 8, 'char_start': 247, 'char_end': 270, 'line': "" ''', (name, ))\n""}]}","{'deleted': [{'char_start': 238, 'char_end': 242, 'chars': ""'{}'""}, {'char_start': 254, 'char_end': 261, 'chars': '.format'}], 'added': [{'char_start': 238, 'char_end': 246, 'chars': '%(name)s'}, {'char_start': 258, 'char_end': 260, 'chars': ', '}, {'char_start': 265, 'char_end': 267, 'chars': ', '}]}",github.com/tylarb/KarmaBoi-PCF/commit/c1d00a27d7f6b7eb6f15a3dacd4269654a32c10a,KarmaBoi/dbopts.py,cwe-089, +cwe-089,get_last_month,"def get_last_month(db, scene): + sql = ""select date from matches where scene='{}' order by date desc limit 1;"".format(scene) + res = db.exec(sql) + date = res[0][0] + + # If it has been more than 1 month since this last tournament, + # go ahead and round this date up by a 1 month + # eg, if the last tournament was 2015-01-15 (a long time ago) + # we can assume the scene won't have more tournaments + # So just round to 2015-02-01 + today = datetime.datetime.today().strftime('%Y-%m-%d') + y, m, d = today.split('-') + cy, cm, cd = date.split('-') + if y > cy or m > cm: + # Add 1 to the month before we return + # eg 2018-03-01 -> 2018-04-01 + date = get_next_month(date) + + return date","def get_last_month(db, scene): + sql = ""select date from matches where scene='{scene}' order by date desc limit 1;"" + args = {'scene': scene} + res = db.exec(sql, args) + date = res[0][0] + + # If it has been more than 1 month since this last tournament, + # go ahead and round this date up by a 1 month + # eg, if the last tournament was 2015-01-15 (a long time ago) + # we can assume the scene won't have more tournaments + # So just round to 2015-02-01 + today = datetime.datetime.today().strftime('%Y-%m-%d') + y, m, d = today.split('-') + cy, cm, cd = date.split('-') + if y > cy or m > cm: + # Add 1 to the month before we return + # eg 2018-03-01 -> 2018-04-01 + date = get_next_month(date) + + return date","{'deleted': [{'line_no': 2, 'char_start': 31, 'char_end': 127, 'line': ' sql = ""select date from matches where scene=\'{}\' order by date desc limit 1;"".format(scene)\n'}, {'line_no': 3, 'char_start': 127, 'char_end': 150, 'line': ' res = db.exec(sql)\n'}], 'added': [{'line_no': 2, 'char_start': 31, 'char_end': 118, 'line': ' sql = ""select date from matches where scene=\'{scene}\' order by date desc limit 1;""\n'}, {'line_no': 3, 'char_start': 118, 'char_end': 146, 'line': "" args = {'scene': scene}\n""}, {'line_no': 4, 'char_start': 146, 'char_end': 175, 'line': ' res = db.exec(sql, args)\n'}]}","{'deleted': [{'char_start': 112, 'char_end': 115, 'chars': '.fo'}, {'char_start': 116, 'char_end': 120, 'chars': 'mat('}, {'char_start': 125, 'char_end': 126, 'chars': ')'}], 'added': [{'char_start': 81, 'char_end': 86, 'chars': 'scene'}, {'char_start': 117, 'char_end': 123, 'chars': '\n a'}, {'char_start': 124, 'char_end': 131, 'chars': ""gs = {'""}, {'char_start': 136, 'char_end': 145, 'chars': ""': scene}""}, {'char_start': 167, 'char_end': 173, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,bracket_utils.py,cwe-089, +cwe-089,achievements_list_player,"@app.route('/players//achievements') +def achievements_list_player(player_id): + """"""Lists the progress of achievements for a player. + + :param player_id: ID of the player. + + :return: + If successful, this method returns a response body with the following structure:: + + { + ""items"": [ + { + ""achievement_id"": string, + ""state"": string, + ""current_steps"": integer, + ""create_time"": long, + ""update_time"": long + } + ] + } + """""" + with db.connection: + cursor = db.connection.cursor(db.pymysql.cursors.DictCursor) + cursor.execute(""""""SELECT + achievement_id, + current_steps, + state, + UNIX_TIMESTAMP(create_time) as create_time, + UNIX_TIMESTAMP(update_time) as update_time + FROM player_achievements + WHERE player_id = '%s'"""""" % player_id) + + return flask.jsonify(items=cursor.fetchall())","@app.route('/players//achievements') +def achievements_list_player(player_id): + """"""Lists the progress of achievements for a player. + + :param player_id: ID of the player. + + :return: + If successful, this method returns a response body with the following structure:: + + { + ""items"": [ + { + ""achievement_id"": string, + ""state"": string, + ""current_steps"": integer, + ""create_time"": long, + ""update_time"": long + } + ] + } + """""" + with db.connection: + cursor = db.connection.cursor(db.pymysql.cursors.DictCursor) + cursor.execute(""""""SELECT + achievement_id, + current_steps, + state, + UNIX_TIMESTAMP(create_time) as create_time, + UNIX_TIMESTAMP(update_time) as update_time + FROM player_achievements + WHERE player_id = %s"""""", player_id) + + return flask.jsonify(items=cursor.fetchall())","{'deleted': [{'line_no': 31, 'char_start': 1048, 'char_end': 1111, 'line': ' WHERE player_id = \'%s\'"""""" % player_id)\n'}], 'added': [{'line_no': 31, 'char_start': 1048, 'char_end': 1108, 'line': ' WHERE player_id = %s"""""", player_id)\n'}]}","{'deleted': [{'char_start': 1090, 'char_end': 1091, 'chars': ""'""}, {'char_start': 1093, 'char_end': 1094, 'chars': ""'""}, {'char_start': 1097, 'char_end': 1099, 'chars': ' %'}], 'added': [{'char_start': 1095, 'char_end': 1096, 'chars': ','}]}",github.com/FAForever/api/commit/5fe7f23868cd191616b088bdd5b24010f004dd5a,api/achievements.py,cwe-089, +cwe-089,check_if_this_project_is_in_database," def check_if_this_project_is_in_database(self, project_id): + self.cursor.execute(""SELECT count(id) FROM projects where id = %s"" % project_id) + return self.cursor.fetchall()[0][0] == 1"," def check_if_this_project_is_in_database(self, project_id): + self.cursor.execute(""SELECT count(id) FROM projects where id = %s"", (project_id,)) + return self.cursor.fetchall()[0][0] == 1","{'deleted': [{'line_no': 2, 'char_start': 64, 'char_end': 153, 'line': ' self.cursor.execute(""SELECT count(id) FROM projects where id = %s"" % project_id)\n'}], 'added': [{'line_no': 2, 'char_start': 64, 'char_end': 155, 'line': ' self.cursor.execute(""SELECT count(id) FROM projects where id = %s"", (project_id,))\n'}]}","{'deleted': [{'char_start': 138, 'char_end': 140, 'chars': ' %'}], 'added': [{'char_start': 138, 'char_end': 139, 'chars': ','}, {'char_start': 140, 'char_end': 141, 'chars': '('}, {'char_start': 151, 'char_end': 153, 'chars': ',)'}]}",github.com/JLucka/kickstarter-dev/commit/e2ffa062697e060fdfbd2eccbb89a8c53a569e0b,backend/transactions/TransactionConnector.py,cwe-089, +cwe-089,edit_page,"@app.route(""//edit"") +def edit_page(page_name): + query = db.query(""select * from page where title = '%s'"" % page_name).namedresult() + if len(query) == 0: + return render_template( + ""edit.html"", + page_name=page_name, + query=query + ) + else: + return render_template( + ""edit.html"", + page_name=page_name, + query=query[0] + )","@app.route(""//edit"") +def edit_page(page_name): + query = db.query(""select * from page where title = $1"", page_name).namedresult() + if len(query) == 0: + return render_template( + ""edit.html"", + page_name=page_name, + query=query + ) + else: + return render_template( + ""edit.html"", + page_name=page_name, + query=query[0] + )","{'deleted': [{'line_no': 3, 'char_start': 58, 'char_end': 146, 'line': ' query = db.query(""select * from page where title = \'%s\'"" % page_name).namedresult()\n'}], 'added': [{'line_no': 3, 'char_start': 58, 'char_end': 143, 'line': ' query = db.query(""select * from page where title = $1"", page_name).namedresult()\n'}]}","{'deleted': [{'char_start': 113, 'char_end': 117, 'chars': ""'%s'""}, {'char_start': 118, 'char_end': 120, 'chars': ' %'}], 'added': [{'char_start': 113, 'char_end': 115, 'chars': '$1'}, {'char_start': 116, 'char_end': 117, 'chars': ','}]}",github.com/jcortes0309/wiki_flask/commit/a6bf5316abe2eb528adf36c8241a013fd02c5ffa,server.py,cwe-089, +cwe-089,reportMatch,"def reportMatch(winner, loser): + """"""Records the outcome of a single match between two players. + + Args: + winner: the id number of the player who won + loser: the id number of the player who lost + """""" + conn = connect() + cursor = conn.cursor() + cursor.execute(""INSERT INTO playsRecord (winner, loser) VALUES ('%s', '%s')"" % (winner, loser)); + conn.commit() + conn.close()","def reportMatch(winner, loser): + """"""Records the outcome of a single match between two players. + + Args: + winner: the id number of the player who won + loser: the id number of the player who lost + """""" + conn = connect() + cursor = conn.cursor() + query = ""INSERT INTO playsRecord (winner, loser) VALUES (%s, %s);"" + cursor.execute(query, (winner, loser)); + conn.commit() + conn.close()","{'deleted': [{'line_no': 10, 'char_start': 267, 'char_end': 368, 'line': ' cursor.execute(""INSERT INTO playsRecord (winner, loser) VALUES (\'%s\', \'%s\')"" % (winner, loser));\n'}], 'added': [{'line_no': 10, 'char_start': 267, 'char_end': 338, 'line': ' query = ""INSERT INTO playsRecord (winner, loser) VALUES (%s, %s);""\n'}, {'line_no': 11, 'char_start': 338, 'char_end': 382, 'line': ' cursor.execute(query, (winner, loser));\n'}]}","{'deleted': [{'char_start': 271, 'char_end': 272, 'chars': 'c'}, {'char_start': 273, 'char_end': 276, 'chars': 'rso'}, {'char_start': 277, 'char_end': 286, 'chars': '.execute('}, {'char_start': 335, 'char_end': 336, 'chars': ""'""}, {'char_start': 338, 'char_end': 339, 'chars': ""'""}, {'char_start': 341, 'char_end': 342, 'chars': ""'""}, {'char_start': 344, 'char_end': 345, 'chars': ""'""}, {'char_start': 348, 'char_end': 349, 'chars': '%'}], 'added': [{'char_start': 271, 'char_end': 272, 'chars': 'q'}, {'char_start': 274, 'char_end': 279, 'chars': 'ry = '}, {'char_start': 335, 'char_end': 336, 'chars': ';'}, {'char_start': 337, 'char_end': 340, 'chars': '\n '}, {'char_start': 341, 'char_end': 363, 'chars': ' cursor.execute(query,'}]}",github.com/sarahkcaplan/tournament/commit/40aba5686059f5f398f6323b1483412c56140cc0,tournament.py,cwe-089, +cwe-089,get_game_info,"def get_game_info(conn, game): + # get the basic game properties + cursor = conn.cursor() + cursor.execute(""SELECT player1,player2,size,state FROM games WHERE id = %d;"" % game) + if cursor.rowcount != 1: + raise FormError(""Invalid game ID"") + + row = cursor.fetchall()[0] + players = [row[0],row[1]] + size = row[2] + state = row[3] + + if state is None: + state = ""Active"" + + cursor.close() + + return (players,size,state)","def get_game_info(conn, game): + # get the basic game properties + cursor = conn.cursor() + cursor.execute(""SELECT player1,player2,size,state FROM games WHERE id = %d;"", (game,)) + if cursor.rowcount != 1: + raise FormError(""Invalid game ID"") + + row = cursor.fetchall()[0] + players = [row[0],row[1]] + size = row[2] + state = row[3] + + if state is None: + state = ""Active"" + + cursor.close() + + return (players,size,state)","{'deleted': [{'line_no': 4, 'char_start': 94, 'char_end': 183, 'line': ' cursor.execute(""SELECT player1,player2,size,state FROM games WHERE id = %d;"" % game)\n'}], 'added': [{'line_no': 4, 'char_start': 94, 'char_end': 185, 'line': ' cursor.execute(""SELECT player1,player2,size,state FROM games WHERE id = %d;"", (game,))\n'}]}","{'deleted': [{'char_start': 174, 'char_end': 176, 'chars': ' %'}], 'added': [{'char_start': 174, 'char_end': 175, 'chars': ','}, {'char_start': 176, 'char_end': 177, 'chars': '('}, {'char_start': 181, 'char_end': 183, 'chars': ',)'}]}",github.com/russ-lewis/ttt_-_python_cgi/commit/6096f43fd4b2d91211eec4614b7960c0816900da,cgi/common.py,cwe-089, +cwe-089,process_as_reply,"def process_as_reply(email_obj): + job_number = email_obj['subject'].split(': #')[1] + feedback = re.findall(""^[\W]*([Oo\d]){1}(?=[\W]*)"", email_obj['content'].replace('#','').replace('link', ''))[0] + feedback = int(0 if feedback == ('O' or 'o') else feedback) + dcn_key = re.findall('\w{8}-\w{4}-\w{4}-\w{4}-\w{12}', email_obj['content'])[0] + logger.info(f""got feedback `{feedback}` for job #`{job_number}`"") + with create_connection() as conn: + was_prev_closed = pd.read_sql(f""SELECT * FROM df_dilfo WHERE job_number={job_number}"", conn).iloc[0].closed + if was_prev_closed: + logger.info(f""job was already matched successfully and logged as `closed`... skipping."") + return + if feedback == 1: + logger.info(f""got feeback that DCN key {dcn_key} was correct"") + update_status_query = ""UPDATE df_dilfo SET closed = 1 WHERE job_number = {}"" + with create_connection() as conn: + conn.cursor().execute(update_status_query.format(job_number)) + logger.info(f""updated df_dilfo to show `closed` status for job #{job_number}"") + with create_connection() as conn: + df = pd.read_sql(""SELECT * FROM df_matched"", conn) + match_dict_input = { + 'job_number': job_number, + 'dcn_key': dcn_key, + 'ground_truth': 1 if feedback == 1 else 0, + 'multi_phase': 1 if feedback == 2 else 0, + 'verifier': email_obj[""sender""], + 'source': 'feedback', + 'log_date': str(datetime.datetime.now().date()), + 'validate': 0, + } + df = df.append(match_dict_input, ignore_index=True) + df = df.drop_duplicates(subset=[""job_number"", ""dcn_key""], keep='last') + df.to_sql('df_matched', conn, if_exists='replace', index=False) + logger.info( + f""DCN key `{dcn_key}` was a "" + f""{'successful match' if feedback == 1 else 'mis-match'} for job "" + f""#{job_number}"" + )","def process_as_reply(email_obj): + job_number = email_obj['subject'].split(': #')[1] + feedback = re.findall(""^[\W]*([Oo\d]){1}(?=[\W]*)"", email_obj['content'].replace('#','').replace('link', ''))[0] + feedback = int(0 if feedback == ('O' or 'o') else feedback) + dcn_key = re.findall('\w{8}-\w{4}-\w{4}-\w{4}-\w{12}', email_obj['content'])[0] + logger.info(f""got feedback `{feedback}` for job #`{job_number}`"") + with create_connection() as conn: + was_prev_closed = pd.read_sql(""SELECT * FROM df_dilfo WHERE job_number=?"", conn, params=[job_number]).iloc[0].closed + if was_prev_closed: + logger.info(f""job was already matched successfully and logged as `closed`... skipping."") + return + if feedback == 1: + logger.info(f""got feeback that DCN key {dcn_key} was correct"") + update_status_query = ""UPDATE df_dilfo SET closed = 1 WHERE job_number = ?"" + with create_connection() as conn: + conn.cursor().execute(update_status_query, [job_number]) + logger.info(f""updated df_dilfo to show `closed` status for job #{job_number}"") + with create_connection() as conn: + df = pd.read_sql(""SELECT * FROM df_matched"", conn) + match_dict_input = { + 'job_number': job_number, + 'dcn_key': dcn_key, + 'ground_truth': 1 if feedback == 1 else 0, + 'multi_phase': 1 if feedback == 2 else 0, + 'verifier': email_obj[""sender""], + 'source': 'feedback', + 'log_date': str(datetime.datetime.now().date()), + 'validate': 0, + } + df = df.append(match_dict_input, ignore_index=True) + df = df.drop_duplicates(subset=[""job_number"", ""dcn_key""], keep='last') + df.to_sql('df_matched', conn, if_exists='replace', index=False) + logger.info( + f""DCN key `{dcn_key}` was a "" + f""{'successful match' if feedback == 1 else 'mis-match'} for job "" + f""#{job_number}"" + )","{'deleted': [{'line_no': 8, 'char_start': 460, 'char_end': 576, 'line': ' was_prev_closed = pd.read_sql(f""SELECT * FROM df_dilfo WHERE job_number={job_number}"", conn).iloc[0].closed\n'}, {'line_no': 14, 'char_start': 805, 'char_end': 890, 'line': ' update_status_query = ""UPDATE df_dilfo SET closed = 1 WHERE job_number = {}""\n'}, {'line_no': 16, 'char_start': 932, 'char_end': 1006, 'line': ' conn.cursor().execute(update_status_query.format(job_number))\n'}], 'added': [{'line_no': 8, 'char_start': 460, 'char_end': 585, 'line': ' was_prev_closed = pd.read_sql(""SELECT * FROM df_dilfo WHERE job_number=?"", conn, params=[job_number]).iloc[0].closed\n'}, {'line_no': 14, 'char_start': 814, 'char_end': 898, 'line': ' update_status_query = ""UPDATE df_dilfo SET closed = 1 WHERE job_number = ?""\n'}, {'line_no': 16, 'char_start': 940, 'char_end': 1009, 'line': ' conn.cursor().execute(update_status_query, [job_number])\n'}]}","{'deleted': [{'char_start': 498, 'char_end': 499, 'chars': 'f'}, {'char_start': 540, 'char_end': 541, 'chars': '{'}, {'char_start': 551, 'char_end': 559, 'chars': '}"", conn'}, {'char_start': 886, 'char_end': 888, 'chars': '{}'}, {'char_start': 985, 'char_end': 993, 'chars': '.format('}, {'char_start': 1003, 'char_end': 1004, 'chars': ')'}], 'added': [{'char_start': 539, 'char_end': 557, 'chars': '?"", conn, params=['}, {'char_start': 567, 'char_end': 568, 'chars': ']'}, {'char_start': 895, 'char_end': 896, 'chars': '?'}, {'char_start': 993, 'char_end': 996, 'chars': ', ['}, {'char_start': 1006, 'char_end': 1007, 'chars': ']'}]}",github.com/confirmationbias616/certificate_checker/commit/9e890b9613b627e3a5995d0e4a594c8e0831e2ce,inbox_scanner.py,cwe-089, +cwe-089,update_playlist,"def update_playlist(id, name, db): + db.execute( + ""UPDATE playlist SET name='{name}' WHERE id={id};"".format(name=name, id=id))","def update_playlist(id, name, db): + db.execute(""UPDATE playlist SET name=%s WHERE id=%s;"", (name, id,))","{'deleted': [{'line_no': 2, 'char_start': 35, 'char_end': 51, 'line': ' db.execute(\n'}, {'line_no': 3, 'char_start': 51, 'char_end': 135, 'line': ' ""UPDATE playlist SET name=\'{name}\' WHERE id={id};"".format(name=name, id=id))\n'}], 'added': [{'line_no': 2, 'char_start': 35, 'char_end': 106, 'line': ' db.execute(""UPDATE playlist SET name=%s WHERE id=%s;"", (name, id,))\n'}]}","{'deleted': [{'char_start': 50, 'char_end': 59, 'chars': '\n '}, {'char_start': 85, 'char_end': 93, 'chars': ""'{name}'""}, {'char_start': 103, 'char_end': 107, 'chars': '{id}'}, {'char_start': 109, 'char_end': 116, 'chars': '.format'}, {'char_start': 121, 'char_end': 126, 'chars': '=name'}, {'char_start': 130, 'char_end': 133, 'chars': '=id'}], 'added': [{'char_start': 76, 'char_end': 78, 'chars': '%s'}, {'char_start': 88, 'char_end': 90, 'chars': '%s'}, {'char_start': 92, 'char_end': 94, 'chars': ', '}, {'char_start': 103, 'char_end': 104, 'chars': ','}]}",github.com/Madmous/playlist/commit/666e52c5f0b8c1f4296e84471637033d9542a7a6,playlist/playlist_repository.py,cwe-089, +cwe-089,get_requested_month," def get_requested_month(self, date): + data = dict() + + month_start, month_end = self.get_epoch_month(date) + data['interval'] = {'from': self.convert_local_ts_to_utc(month_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(month_end, self.local_timezone)} + month_total = 0 + + query = ''' + SELECT TimeStamp, SUM(DayYield) AS Power + FROM MonthData + WHERE TimeStamp BETWEEN %s AND %s + GROUP BY TimeStamp + ''' + + data['data'] = list() + for row in self.c.execute(query % (month_start, month_end)): + data['data'].append({'time': self.convert_local_ts_to_utc(row[0], self.local_timezone), 'power': row[1]}) + month_total += row[1] + + data['total'] = month_total + + query = ''' + SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max + FROM ( SELECT TimeStamp FROM MonthData GROUP BY TimeStamp ); + ''' + + self.c.execute(query) + first_data, last_data = self.c.fetchone() + + if first_data: data['hasPrevious'] = (first_data < month_start) + else: data['hasPrevious'] = False + if last_data: data['hasNext'] = (last_data > month_end) + else: data['hasNext'] = False + + return data"," def get_requested_month(self, date): + data = dict() + + month_start, month_end = self.get_epoch_month(date) + data['interval'] = {'from': self.convert_local_ts_to_utc(month_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(month_end, self.local_timezone)} + month_total = 0 + + query = ''' + SELECT TimeStamp, SUM(DayYield) AS Power + FROM MonthData + WHERE TimeStamp BETWEEN ? AND ? + GROUP BY TimeStamp; + ''' + + data['data'] = list() + for row in self.c.execute(query, (month_start, month_end)): + data['data'].append({'time': self.convert_local_ts_to_utc(row[0], self.local_timezone), 'power': row[1]}) + month_total += row[1] + + data['total'] = month_total + + query = ''' + SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max + FROM ( SELECT TimeStamp FROM MonthData GROUP BY TimeStamp ); + ''' + + self.c.execute(query) + first_data, last_data = self.c.fetchone() + + if first_data: data['hasPrevious'] = (first_data < month_start) + else: data['hasPrevious'] = False + if last_data: data['hasNext'] = (last_data > month_end) + else: data['hasNext'] = False + + return data","{'deleted': [{'line_no': 11, 'char_start': 419, 'char_end': 465, 'line': ' WHERE TimeStamp BETWEEN %s AND %s\n'}, {'line_no': 12, 'char_start': 465, 'char_end': 496, 'line': ' GROUP BY TimeStamp\n'}, {'line_no': 16, 'char_start': 543, 'char_end': 612, 'line': ' for row in self.c.execute(query % (month_start, month_end)):\n'}], 'added': [{'line_no': 11, 'char_start': 419, 'char_end': 463, 'line': ' WHERE TimeStamp BETWEEN ? AND ?\n'}, {'line_no': 12, 'char_start': 463, 'char_end': 495, 'line': ' GROUP BY TimeStamp;\n'}, {'line_no': 16, 'char_start': 542, 'char_end': 610, 'line': ' for row in self.c.execute(query, (month_start, month_end)):\n'}]}","{'deleted': [{'char_start': 455, 'char_end': 457, 'chars': '%s'}, {'char_start': 462, 'char_end': 464, 'chars': '%s'}, {'char_start': 582, 'char_end': 584, 'chars': ' %'}], 'added': [{'char_start': 455, 'char_end': 456, 'chars': '?'}, {'char_start': 461, 'char_end': 462, 'chars': '?'}, {'char_start': 493, 'char_end': 494, 'chars': ';'}, {'char_start': 581, 'char_end': 582, 'chars': ','}]}",github.com/philipptrenz/sunportal/commit/7eef493a168ed4e6731ff800713bfb8aee99a506,util/database.py,cwe-089, +cwe-089,retrieve_videos_from_playlist,"def retrieve_videos_from_playlist(playlist_id, db): + db.execute(""SELECT id, title, thumbnail, position from video WHERE playlist_id={playlist_id} ORDER BY position ASC;"".format( + playlist_id=playlist_id)) + rows = db.fetchall() + return rows","def retrieve_videos_from_playlist(playlist_id, db): + db.execute(""SELECT id, title, thumbnail, position from video WHERE playlist_id=%s ORDER BY position ASC;"", (playlist_id,)) + rows = db.fetchall() + return rows","{'deleted': [{'line_no': 2, 'char_start': 52, 'char_end': 181, 'line': ' db.execute(""SELECT id, title, thumbnail, position from video WHERE playlist_id={playlist_id} ORDER BY position ASC;"".format(\n'}, {'line_no': 3, 'char_start': 181, 'char_end': 215, 'line': ' playlist_id=playlist_id))\n'}], 'added': [{'line_no': 2, 'char_start': 52, 'char_end': 179, 'line': ' db.execute(""SELECT id, title, thumbnail, position from video WHERE playlist_id=%s ORDER BY position ASC;"", (playlist_id,))\n'}]}","{'deleted': [{'char_start': 135, 'char_end': 142, 'chars': '{playli'}, {'char_start': 143, 'char_end': 148, 'chars': 't_id}'}, {'char_start': 172, 'char_end': 186, 'chars': '.format(\n '}, {'char_start': 187, 'char_end': 201, 'chars': ' playlist_id='}], 'added': [{'char_start': 135, 'char_end': 136, 'chars': '%'}, {'char_start': 161, 'char_end': 163, 'chars': ', '}, {'char_start': 175, 'char_end': 176, 'chars': ','}]}",github.com/Madmous/playlist/commit/666e52c5f0b8c1f4296e84471637033d9542a7a6,video/video_repository.py,cwe-089, +cwe-089,create_playlist,"def create_playlist(name): + db = connect_to_database() + cursor = db.cursor() + cursor.execute( + ""INSERT INTO playlist (name, video_position) VALUES('{name}', 0);"".format(name=name)) + db.commit() + db.close()","def create_playlist(name): + db = connect_to_database() + cursor = db.cursor() + cursor.execute( + ""INSERT INTO playlist (name, video_position) VALUES(%s, 0);"", (name,)) + db.commit() + db.close()","{'deleted': [{'line_no': 5, 'char_start': 103, 'char_end': 197, 'line': ' ""INSERT INTO playlist (name, video_position) VALUES(\'{name}\', 0);"".format(name=name))\n'}], 'added': [{'line_no': 5, 'char_start': 103, 'char_end': 182, 'line': ' ""INSERT INTO playlist (name, video_position) VALUES(%s, 0);"", (name,))\n'}]}","{'deleted': [{'char_start': 163, 'char_end': 171, 'chars': ""'{name}'""}, {'char_start': 177, 'char_end': 184, 'chars': '.format'}, {'char_start': 189, 'char_end': 194, 'chars': '=name'}], 'added': [{'char_start': 163, 'char_end': 165, 'chars': '%s'}, {'char_start': 171, 'char_end': 173, 'chars': ', '}, {'char_start': 178, 'char_end': 179, 'chars': ','}]}",github.com/Madmous/playlist/commit/666e52c5f0b8c1f4296e84471637033d9542a7a6,main_test.py,cwe-089, +cwe-089,update_video_positions,"def update_video_positions(removed_position, db): + db.execute(""UPDATE video SET position = position - 1 WHERE position > {removed_position}"".format( + removed_position=removed_position))","def update_video_positions(removed_position, db): + db.execute(""UPDATE video SET position = position - 1 WHERE position > %s"", (removed_position,))","{'deleted': [{'line_no': 2, 'char_start': 50, 'char_end': 152, 'line': ' db.execute(""UPDATE video SET position = position - 1 WHERE position > {removed_position}"".format(\n'}, {'line_no': 3, 'char_start': 152, 'char_end': 195, 'line': ' removed_position=removed_position))\n'}], 'added': [{'line_no': 2, 'char_start': 50, 'char_end': 149, 'line': ' db.execute(""UPDATE video SET position = position - 1 WHERE position > %s"", (removed_position,))\n'}]}","{'deleted': [{'char_start': 124, 'char_end': 135, 'chars': '{removed_po'}, {'char_start': 136, 'char_end': 142, 'chars': 'ition}'}, {'char_start': 143, 'char_end': 152, 'chars': '.format(\n'}, {'char_start': 153, 'char_end': 160, 'chars': ' '}, {'char_start': 176, 'char_end': 193, 'chars': '=removed_position'}], 'added': [{'char_start': 124, 'char_end': 125, 'chars': '%'}, {'char_start': 127, 'char_end': 129, 'chars': ', '}, {'char_start': 146, 'char_end': 147, 'chars': ','}]}",github.com/Madmous/playlist/commit/666e52c5f0b8c1f4296e84471637033d9542a7a6,video/video_repository.py,cwe-089, +cwe-089,_check_camera_tags," @staticmethod + def _check_camera_tags(tags): + """""" + Function that convert stupid code name of a smartphone or camera + from EXIF to meaningful one by looking a collation in a special MySQL + table For example instead of just Nikon there can be + NIKON CORPORATION in EXIF + + :param tags: name of a camera and lens from EXIF + :return: list with one or two strings which are name of + camera and/or lens. If there is not better name for the gadget + in database, function just returns name how it is + """""" + checked_tags = [] + + for tag in tags: + if tag: # If there was this information inside EXIF of the photo + tag = str(tag).strip() + log.info('Looking up collation for %s', tag) + query = ('SELECT right_tag ' + 'FROM tag_table ' + 'WHERE wrong_tag=""{}""'.format(tag)) + cursor = db.execute_query(query) + if not cursor: + log.error(""Can't check the tag because of the db error"") + log.warning(""Tag will stay as is."") + continue + if cursor.rowcount: + # Get appropriate tag from the table + tag = cursor.fetchone()[0] + log.info('Tag after looking up in tag_tables - %s.', tag) + + checked_tags.append(tag) + return checked_tags"," @staticmethod + def _check_camera_tags(tags): + """""" + Function that convert stupid code name of a smartphone or camera + from EXIF to meaningful one by looking a collation in a special MySQL + table For example instead of just Nikon there can be + NIKON CORPORATION in EXIF + + :param tags: name of a camera and lens from EXIF + :return: list with one or two strings which are name of + camera and/or lens. If there is not better name for the gadget + in database, function just returns name how it is + """""" + checked_tags = [] + + for tag in tags: + if tag: # If there was this information inside EXIF of the photo + tag = str(tag).strip() + log.info('Looking up collation for %s', tag) + query = ('SELECT right_tag ' + 'FROM tag_table ' + 'WHERE wrong_tag=%s') + parameters = tag, + cursor = db.execute_query(query, parameters) + if not cursor: + log.error(""Can't check the tag because of the db error"") + log.warning(""Tag will stay as is."") + continue + if cursor.rowcount: + # Get appropriate tag from the table + tag = cursor.fetchone()[0] + log.info('Tag after looking up in tag_tables - %s.', tag) + + checked_tags.append(tag) + return checked_tags","{'deleted': [{'line_no': 22, 'char_start': 891, 'char_end': 952, 'line': ' \'WHERE wrong_tag=""{}""\'.format(tag))\n'}, {'line_no': 23, 'char_start': 952, 'char_end': 1001, 'line': ' cursor = db.execute_query(query)\n'}], 'added': [{'line_no': 22, 'char_start': 891, 'char_end': 938, 'line': "" 'WHERE wrong_tag=%s')\n""}, {'line_no': 23, 'char_start': 938, 'char_end': 972, 'line': ' parameters = tag,\n'}, {'line_no': 24, 'char_start': 972, 'char_end': 1033, 'line': ' cursor = db.execute_query(query, parameters)\n'}]}","{'deleted': [{'char_start': 933, 'char_end': 937, 'chars': '""{}""'}, {'char_start': 938, 'char_end': 941, 'chars': '.fo'}, {'char_start': 942, 'char_end': 943, 'chars': 'm'}, {'char_start': 945, 'char_end': 946, 'chars': '('}, {'char_start': 949, 'char_end': 951, 'chars': '))'}], 'added': [{'char_start': 933, 'char_end': 935, 'chars': '%s'}, {'char_start': 936, 'char_end': 956, 'chars': ')\n pa'}, {'char_start': 957, 'char_end': 958, 'chars': 'a'}, {'char_start': 959, 'char_end': 960, 'chars': 'e'}, {'char_start': 961, 'char_end': 967, 'chars': 'ers = '}, {'char_start': 970, 'char_end': 971, 'chars': ','}, {'char_start': 1019, 'char_end': 1031, 'chars': ', parameters'}]}",github.com/RandyRomero/photoGPSbot/commit/0e9f57f13e61863b3672f5730e27f149da00786a,photogpsbot/process_image.py,cwe-089, +cwe-089,add_input," def add_input(self, data): + connection = self.connect() + try: + # The following introduces a deliberate security flaw.See section on SQL injection below + query = ""INSERT INTO crimes (description) VALUES('{}');"".format(data) + with connection.cursor() as cursor: + cursor.execute(query) + connection.commit() + finally: + connection.close()"," def add_input(self, data): + connection = self.connect() + try: + # The following introduces a deliberate security flaw.See section on SQL injection below + query = ""INSERT INTO crimes (description) VALUES (%s);"" + with connection.cursor() as cursor: + cursor.execute(query, data) + connection.commit() + finally: + connection.close()","{'deleted': [{'line_no': 5, 'char_start': 157, 'char_end': 230, 'line': '\t\t\tquery = ""INSERT INTO crimes (description) VALUES(\'{}\');"".format(data)\n'}, {'line_no': 7, 'char_start': 269, 'char_end': 295, 'line': '\t\t\t\tcursor.execute(query)\n'}], 'added': [{'line_no': 5, 'char_start': 157, 'char_end': 216, 'line': '\t\t\tquery = ""INSERT INTO crimes (description) VALUES (%s);""\n'}, {'line_no': 7, 'char_start': 255, 'char_end': 287, 'line': '\t\t\t\tcursor.execute(query, data)\n'}]}","{'deleted': [{'char_start': 209, 'char_end': 213, 'chars': ""'{}'""}, {'char_start': 216, 'char_end': 229, 'chars': '.format(data)'}], 'added': [{'char_start': 208, 'char_end': 209, 'chars': ' '}, {'char_start': 210, 'char_end': 212, 'chars': '%s'}, {'char_start': 279, 'char_end': 285, 'chars': ', data'}]}",github.com/fangyansun/crimemap/commit/a3ab652c214f801c2910e2f96e4de18848de58ae,dbhelper.py,cwe-089, +cwe-089,getResults,"def getResults(poll_name): + conn, c = connectDB() + req = ""SELECT options from {} where name = '{}'"".format(CFG(""poll_table_name""), poll_name) + options_str = queryOne(c, req) + + if not options_str: + raise LookupError(""Poll '{}' not found in DB"".format(poll_name)) + + total = 0 + options = options_str.split("","") + results = dict() + for opt in options: + count = getOptionCount(c, poll_name, opt) + total += int(count) + results.update({opt:count}) + + conn.close() + return (results, total)","def getResults(poll_name): + conn, c = connectDB() + req = ""SELECT options from {} where name=?"".format(CFG(""poll_table_name"")) + options_str = queryOne(c, req, (poll_name,)) + + if not options_str: + raise LookupError(""Poll '{}' not found in DB"".format(poll_name)) + + total = 0 + options = options_str.split("","") + results = dict() + for opt in options: + count = getOptionCount(c, poll_name, opt) + total += int(count) + results.update({opt:count}) + + conn.close() + return (results, total)","{'deleted': [{'line_no': 3, 'char_start': 53, 'char_end': 148, 'line': ' req = ""SELECT options from {} where name = \'{}\'"".format(CFG(""poll_table_name""), poll_name)\n'}, {'line_no': 4, 'char_start': 148, 'char_end': 183, 'line': ' options_str = queryOne(c, req)\n'}], 'added': [{'line_no': 3, 'char_start': 53, 'char_end': 132, 'line': ' req = ""SELECT options from {} where name=?"".format(CFG(""poll_table_name""))\n'}, {'line_no': 4, 'char_start': 132, 'char_end': 181, 'line': ' options_str = queryOne(c, req, (poll_name,))\n'}]}","{'deleted': [{'char_start': 97, 'char_end': 98, 'chars': ' '}, {'char_start': 99, 'char_end': 104, 'chars': "" '{}'""}, {'char_start': 135, 'char_end': 146, 'chars': ', poll_name'}], 'added': [{'char_start': 98, 'char_end': 99, 'chars': '?'}, {'char_start': 165, 'char_end': 179, 'chars': ', (poll_name,)'}]}",github.com/FAUSheppy/simple-python-poll/commit/186c5ff5cdf58272e253a1bb432419ee50d93109,database.py,cwe-089, +cwe-089,update_sources,"def update_sources(conn, sqlite, k10plus, ai): + """""" + Update the source table. + """""" + current_sources = get_all_current_sources(k10plus, ai) + old_sources = get_all_old_sources(conn, sqlite) + + # Check if the source table is allready filled and this is not the first checkup + source_table_is_filled = len(old_sources) > 100 + + for old_source in old_sources: + if source_table_is_filled and old_source not in current_sources: + message = ""Die SID %s ist im aktuellen Import nicht mehr vorhanden.\nWenn dies beabsichtigt ist, bitte die SID aus der Datenbank loeschen."" % old_source + send_message(message) + + for current_source in current_sources: + if current_source not in old_sources: + message = ""The source %s is new in Solr."" % current_source + if source_table_is_filled: + send_message(message) + else: + logging.info(message) + sql = ""INSERT INTO source (source) VALUES (%s)"" % current_source + sqlite.execute(sql) + conn.commit()","def update_sources(conn, sqlite, k10plus, ai): + """""" + Update the source table. + """""" + current_sources = get_all_current_sources(k10plus, ai) + old_sources = get_all_old_sources(conn, sqlite) + + # Check if the source table is allready filled and this is not the first checkup + source_table_is_filled = len(old_sources) > 100 + + for old_source in old_sources: + if source_table_is_filled and old_source not in current_sources: + message = ""Die SID %s ist im aktuellen Import nicht mehr vorhanden.\nWenn dies beabsichtigt ist, bitte die SID aus der Datenbank loeschen."" % old_source + send_message(message) + + for current_source in current_sources: + if current_source not in old_sources: + message = ""The source %s is new in Solr."" % current_source + if source_table_is_filled: + send_message(message) + else: + logging.info(message) + sql = ""INSERT INTO source (source) VALUES (?)"" + sqlite.execute(sql, (current_source,)) + conn.commit()","{'deleted': [{'line_no': 23, 'char_start': 943, 'char_end': 1020, 'line': ' sql = ""INSERT INTO source (source) VALUES (%s)"" % current_source\n'}, {'line_no': 24, 'char_start': 1020, 'char_end': 1052, 'line': ' sqlite.execute(sql)\n'}], 'added': [{'line_no': 23, 'char_start': 943, 'char_end': 1002, 'line': ' sql = ""INSERT INTO source (source) VALUES (?)""\n'}, {'line_no': 24, 'char_start': 1002, 'char_end': 1053, 'line': ' sqlite.execute(sql, (current_source,))\n'}]}","{'deleted': [{'char_start': 998, 'char_end': 1000, 'chars': '%s'}, {'char_start': 1002, 'char_end': 1019, 'chars': ' % current_source'}], 'added': [{'char_start': 998, 'char_end': 999, 'chars': '?'}, {'char_start': 1032, 'char_end': 1051, 'chars': ', (current_source,)'}]}",github.com/miku/siskin/commit/7fa398d2fea72bf2e8b4808f75df4b3d35ae959a,bin/solrcheckup.py,cwe-089, +cwe-125,search_make_new,"search_make_new(const struct search_state *const state, int n, const char *const base_name) { + const size_t base_len = strlen(base_name); + const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1; + struct search_domain *dom; + + for (dom = state->head; dom; dom = dom->next) { + if (!n--) { + /* this is the postfix we want */ + /* the actual postfix string is kept at the end of the structure */ + const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain); + const int postfix_len = dom->len; + char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1); + if (!newname) return NULL; + memcpy(newname, base_name, base_len); + if (need_to_append_dot) newname[base_len] = '.'; + memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len); + newname[base_len + need_to_append_dot + postfix_len] = 0; + return newname; + } + } + + /* we ran off the end of the list and still didn't find the requested string */ + EVUTIL_ASSERT(0); + return NULL; /* unreachable; stops warnings in some compilers. */ +}","search_make_new(const struct search_state *const state, int n, const char *const base_name) { + const size_t base_len = strlen(base_name); + char need_to_append_dot; + struct search_domain *dom; + + if (!base_len) return NULL; + need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1; + + for (dom = state->head; dom; dom = dom->next) { + if (!n--) { + /* this is the postfix we want */ + /* the actual postfix string is kept at the end of the structure */ + const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain); + const int postfix_len = dom->len; + char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1); + if (!newname) return NULL; + memcpy(newname, base_name, base_len); + if (need_to_append_dot) newname[base_len] = '.'; + memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len); + newname[base_len + need_to_append_dot + postfix_len] = 0; + return newname; + } + } + + /* we ran off the end of the list and still didn't find the requested string */ + EVUTIL_ASSERT(0); + return NULL; /* unreachable; stops warnings in some compilers. */ +}","{'deleted': [{'line_no': 3, 'char_start': 138, 'char_end': 211, 'line': ""\tconst char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;\n""}], 'added': [{'line_no': 3, 'char_start': 138, 'char_end': 164, 'line': '\tchar need_to_append_dot;\n'}, {'line_no': 6, 'char_start': 193, 'char_end': 222, 'line': '\tif (!base_len) return NULL;\n'}, {'line_no': 7, 'char_start': 222, 'char_end': 284, 'line': ""\tneed_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;\n""}, {'line_no': 8, 'char_start': 284, 'char_end': 285, 'line': '\n'}]}","{'deleted': [{'char_start': 209, 'char_end': 237, 'chars': ';\n\tstruct search_domain *dom'}], 'added': [{'char_start': 140, 'char_end': 150, 'chars': 'har need_t'}, {'char_start': 151, 'char_end': 156, 'chars': '_appe'}, {'char_start': 157, 'char_end': 165, 'chars': 'd_dot;\n\t'}, {'char_start': 167, 'char_end': 171, 'chars': 'ruct'}, {'char_start': 172, 'char_end': 176, 'chars': 'sear'}, {'char_start': 178, 'char_end': 182, 'chars': '_dom'}, {'char_start': 183, 'char_end': 209, 'chars': 'in *dom;\n\n\tif (!base_len) '}, {'char_start': 210, 'char_end': 215, 'chars': 'eturn'}, {'char_start': 216, 'char_end': 223, 'chars': 'NULL;\n\t'}]}",github.com/libevent/libevent/commit/ec65c42052d95d2c23d1d837136d1cf1d9ecef9e,evdns.c,cwe-125, +cwe-125,TS_OBJ_print_bio,"int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj) +{ + char obj_txt[128]; + + int len = OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0); + BIO_write(bio, obj_txt, len); + BIO_write(bio, ""\n"", 1); + + return 1; +}","int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj) +{ + char obj_txt[128]; + + OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0); + BIO_printf(bio, ""%s\n"", obj_txt); + + return 1; +}","{'deleted': [{'line_no': 5, 'char_start': 81, 'char_end': 142, 'line': ' int len = OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0);\n'}, {'line_no': 6, 'char_start': 142, 'char_end': 176, 'line': ' BIO_write(bio, obj_txt, len);\n'}, {'line_no': 7, 'char_start': 176, 'char_end': 205, 'line': ' BIO_write(bio, ""\\n"", 1);\n'}], 'added': [{'line_no': 5, 'char_start': 81, 'char_end': 132, 'line': ' OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0);\n'}, {'line_no': 6, 'char_start': 132, 'char_end': 170, 'line': ' BIO_printf(bio, ""%s\\n"", obj_txt);\n'}]}","{'deleted': [{'char_start': 85, 'char_end': 95, 'chars': 'int len = '}, {'char_start': 150, 'char_end': 151, 'chars': 'w'}, {'char_start': 154, 'char_end': 155, 'chars': 'e'}, {'char_start': 168, 'char_end': 202, 'chars': ', len);\n BIO_write(bio, ""\\n"", 1'}], 'added': [{'char_start': 140, 'char_end': 141, 'chars': 'p'}, {'char_start': 145, 'char_end': 146, 'chars': 'f'}, {'char_start': 153, 'char_end': 155, 'chars': '%s'}, {'char_start': 160, 'char_end': 167, 'chars': 'obj_txt'}]}",github.com/openssl/openssl/commit/0ed26acce328ec16a3aa635f1ca37365e8c7403a,crypto/ts/ts_lib.c,cwe-125, +cwe-125,main,"int main(int argc, char *argv[]) +{ + FILE *iplist = NULL; + plist_t root_node = NULL; + char *plist_out = NULL; + uint32_t size = 0; + int read_size = 0; + char *plist_entire = NULL; + struct stat filestats; + options_t *options = parse_arguments(argc, argv); + + if (!options) + { + print_usage(argc, argv); + return 0; + } + + // read input file + iplist = fopen(options->in_file, ""rb""); + if (!iplist) { + free(options); + return 1; + } + + stat(options->in_file, &filestats); + plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1)); + read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist); + fclose(iplist); + + // convert from binary to xml or vice-versa + if (memcmp(plist_entire, ""bplist00"", 8) == 0) + { + plist_from_bin(plist_entire, read_size, &root_node); + plist_to_xml(root_node, &plist_out, &size); + } + else + { + plist_from_xml(plist_entire, read_size, &root_node); + plist_to_bin(root_node, &plist_out, &size); + } + plist_free(root_node); + free(plist_entire); + + if (plist_out) + { + if (options->out_file != NULL) + { + FILE *oplist = fopen(options->out_file, ""wb""); + if (!oplist) { + free(options); + return 1; + } + fwrite(plist_out, size, sizeof(char), oplist); + fclose(oplist); + } + // if no output file specified, write to stdout + else + fwrite(plist_out, size, sizeof(char), stdout); + + free(plist_out); + } + else + printf(""ERROR: Failed to convert input file.\n""); + + free(options); + return 0; +}","int main(int argc, char *argv[]) +{ + FILE *iplist = NULL; + plist_t root_node = NULL; + char *plist_out = NULL; + uint32_t size = 0; + int read_size = 0; + char *plist_entire = NULL; + struct stat filestats; + options_t *options = parse_arguments(argc, argv); + + if (!options) + { + print_usage(argc, argv); + return 0; + } + + // read input file + iplist = fopen(options->in_file, ""rb""); + if (!iplist) { + free(options); + return 1; + } + + stat(options->in_file, &filestats); + + if (filestats.st_size < 8) { + printf(""ERROR: Input file is too small to contain valid plist data.\n""); + return -1; + } + + plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1)); + read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist); + fclose(iplist); + + // convert from binary to xml or vice-versa + if (memcmp(plist_entire, ""bplist00"", 8) == 0) + { + plist_from_bin(plist_entire, read_size, &root_node); + plist_to_xml(root_node, &plist_out, &size); + } + else + { + plist_from_xml(plist_entire, read_size, &root_node); + plist_to_bin(root_node, &plist_out, &size); + } + plist_free(root_node); + free(plist_entire); + + if (plist_out) + { + if (options->out_file != NULL) + { + FILE *oplist = fopen(options->out_file, ""wb""); + if (!oplist) { + free(options); + return 1; + } + fwrite(plist_out, size, sizeof(char), oplist); + fclose(oplist); + } + // if no output file specified, write to stdout + else + fwrite(plist_out, size, sizeof(char), stdout); + + free(plist_out); + } + else + printf(""ERROR: Failed to convert input file.\n""); + + free(options); + return 0; +}","{'deleted': [], 'added': [{'line_no': 26, 'char_start': 533, 'char_end': 534, 'line': '\n'}, {'line_no': 27, 'char_start': 534, 'char_end': 567, 'line': ' if (filestats.st_size < 8) {\n'}, {'line_no': 28, 'char_start': 567, 'char_end': 648, 'line': ' printf(""ERROR: Input file is too small to contain valid plist data.\\n"");\n'}, {'line_no': 29, 'char_start': 648, 'char_end': 667, 'line': ' return -1;\n'}, {'line_no': 30, 'char_start': 667, 'char_end': 673, 'line': ' }\n'}, {'line_no': 31, 'char_start': 673, 'char_end': 674, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 533, 'char_end': 674, 'chars': '\n if (filestats.st_size < 8) {\n printf(""ERROR: Input file is too small to contain valid plist data.\\n"");\n return -1;\n }\n\n'}]}",github.com/libimobiledevice/libplist/commit/7391a506352c009fe044dead7baad9e22dd279ee,tools/plistutil.c,cwe-125, +cwe-125,AirPDcapDecryptWPABroadcastKey,"AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_key, PAIRPDCAP_SEC_ASSOCIATION sa, guint eapol_len) +{ + guint8 key_version; + guint8 *key_data; + guint8 *szEncryptedKey; + guint16 key_bytes_len = 0; /* Length of the total key data field */ + guint16 key_len; /* Actual group key length */ + static AIRPDCAP_KEY_ITEM dummy_key; /* needed in case AirPDcapRsnaMng() wants the key structure */ + AIRPDCAP_SEC_ASSOCIATION *tmp_sa; + + /* We skip verifying the MIC of the key. If we were implementing a WPA supplicant we'd want to verify, but for a sniffer it's not needed. */ + + /* Preparation for decrypting the group key - determine group key data length */ + /* depending on whether the pairwise key is TKIP or AES encryption key */ + key_version = AIRPDCAP_EAP_KEY_DESCR_VER(pEAPKey->key_information[1]); + if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){ + /* TKIP */ + key_bytes_len = pntoh16(pEAPKey->key_length); + }else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){ + /* AES */ + key_bytes_len = pntoh16(pEAPKey->key_data_len); + + /* AES keys must be at least 128 bits = 16 bytes. */ + if (key_bytes_len < 16) { + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + } + + if (key_bytes_len < GROUP_KEY_MIN_LEN || key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY)) { + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* Encrypted key is in the information element field of the EAPOL key packet */ + key_data = (guint8 *)pEAPKey + sizeof(EAPOL_RSN_KEY); + szEncryptedKey = (guint8 *)g_memdup(key_data, key_bytes_len); + + DEBUG_DUMP(""Encrypted Broadcast key:"", szEncryptedKey, key_bytes_len); + DEBUG_DUMP(""KeyIV:"", pEAPKey->key_iv, 16); + DEBUG_DUMP(""decryption_key:"", decryption_key, 16); + + /* We are rekeying, save old sa */ + tmp_sa=(AIRPDCAP_SEC_ASSOCIATION *)g_malloc(sizeof(AIRPDCAP_SEC_ASSOCIATION)); + memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION)); + sa->next=tmp_sa; + + /* As we have no concept of the prior association request at this point, we need to deduce the */ + /* group key cipher from the length of the key bytes. In WPA this is straightforward as the */ + /* keybytes just contain the GTK, and the GTK is only in the group handshake, NOT the M3. */ + /* In WPA2 its a little more tricky as the M3 keybytes contain an RSN_IE, but the group handshake */ + /* does not. Also there are other (variable length) items in the keybytes which we need to account */ + /* for to determine the true key length, and thus the group cipher. */ + + if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){ + guint8 new_key[32]; + guint8 dummy[256]; + /* TKIP key */ + /* Per 802.11i, Draft 3.0 spec, section 8.5.2, p. 97, line 4-8, */ + /* group key is decrypted using RC4. Concatenate the IV with the 16 byte EK (PTK+16) to get the decryption key */ + + rc4_state_struct rc4_state; + + /* The WPA group key just contains the GTK bytes so deducing the type is straightforward */ + /* Note - WPA M3 doesn't contain a group key so we'll only be here for the group handshake */ + sa->wpa.key_ver = (key_bytes_len >=TKIP_GROUP_KEY_LEN)?AIRPDCAP_WPA_KEY_VER_NOT_CCMP:AIRPDCAP_WPA_KEY_VER_AES_CCMP; + + /* Build the full decryption key based on the IV and part of the pairwise key */ + memcpy(new_key, pEAPKey->key_iv, 16); + memcpy(new_key+16, decryption_key, 16); + DEBUG_DUMP(""FullDecrKey:"", new_key, 32); + + crypt_rc4_init(&rc4_state, new_key, sizeof(new_key)); + + /* Do dummy 256 iterations of the RC4 algorithm (per 802.11i, Draft 3.0, p. 97 line 6) */ + crypt_rc4(&rc4_state, dummy, 256); + crypt_rc4(&rc4_state, szEncryptedKey, key_bytes_len); + + } else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){ + /* AES CCMP key */ + + guint8 key_found; + guint8 key_length; + guint16 key_index; + guint8 *decrypted_data; + + /* Unwrap the key; the result is key_bytes_len in length */ + decrypted_data = AES_unwrap(decryption_key, 16, szEncryptedKey, key_bytes_len); + + /* With WPA2 what we get after Broadcast Key decryption is an actual RSN structure. + The key itself is stored as a GTK KDE + WPA2 IE (1 byte) id = 0xdd, length (1 byte), GTK OUI (4 bytes), key index (1 byte) and 1 reserved byte. Thus we have to + pass pointer to the actual key with 8 bytes offset */ + + key_found = FALSE; + key_index = 0; + + /* Parse Key data until we found GTK KDE */ + /* GTK KDE = 00-0F-AC 01 */ + while(key_index < (key_bytes_len - 6) && !key_found){ + guint8 rsn_id; + guint32 type; + + /* Get RSN ID */ + rsn_id = decrypted_data[key_index]; + type = ((decrypted_data[key_index + 2] << 24) + + (decrypted_data[key_index + 3] << 16) + + (decrypted_data[key_index + 4] << 8) + + (decrypted_data[key_index + 5])); + + if (rsn_id == 0xdd && type == 0x000fac01) { + key_found = TRUE; + } else { + key_index += decrypted_data[key_index+1]+2; + } + } + + if (key_found){ + key_length = decrypted_data[key_index+1] - 6; + + if (key_index+8 >= key_bytes_len || + key_length > key_bytes_len - key_index - 8) { + g_free(decrypted_data); + g_free(szEncryptedKey); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* Skip over the GTK header info, and don't copy past the end of the encrypted data */ + memcpy(szEncryptedKey, decrypted_data+key_index+8, key_length); + } else { + g_free(decrypted_data); + g_free(szEncryptedKey); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + if (key_length == TKIP_GROUP_KEY_LEN) + sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_NOT_CCMP; + else + sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP; + + g_free(decrypted_data); + } + + key_len = (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)?TKIP_GROUP_KEY_LEN:CCMP_GROUP_KEY_LEN; + if (key_len > key_bytes_len) { + /* the key required for this protocol is longer than the key that we just calculated */ + g_free(szEncryptedKey); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* Decrypted key is now in szEncryptedKey with len of key_len */ + DEBUG_DUMP(""Broadcast key:"", szEncryptedKey, key_len); + + /* Load the proper key material info into the SA */ + sa->key = &dummy_key; /* we just need key to be not null because it is checked in AirPDcapRsnaMng(). The WPA key materials are actually in the .wpa structure */ + sa->validKey = TRUE; + + /* Since this is a GTK and its size is only 32 bytes (vs. the 64 byte size of a PTK), we fake it and put it in at a 32-byte offset so the */ + /* AirPDcapRsnaMng() function will extract the right piece of the GTK for decryption. (The first 16 bytes of the GTK are used for decryption.) */ + memset(sa->wpa.ptk, 0, sizeof(sa->wpa.ptk)); + memcpy(sa->wpa.ptk+32, szEncryptedKey, key_len); + g_free(szEncryptedKey); + return AIRPDCAP_RET_SUCCESS_HANDSHAKE; +}","AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_key, PAIRPDCAP_SEC_ASSOCIATION sa, guint eapol_len) +{ + guint8 key_version; + guint8 *key_data; + guint8 *szEncryptedKey; + guint16 key_bytes_len = 0; /* Length of the total key data field */ + guint16 key_len; /* Actual group key length */ + static AIRPDCAP_KEY_ITEM dummy_key; /* needed in case AirPDcapRsnaMng() wants the key structure */ + AIRPDCAP_SEC_ASSOCIATION *tmp_sa; + + /* We skip verifying the MIC of the key. If we were implementing a WPA supplicant we'd want to verify, but for a sniffer it's not needed. */ + + /* Preparation for decrypting the group key - determine group key data length */ + /* depending on whether the pairwise key is TKIP or AES encryption key */ + key_version = AIRPDCAP_EAP_KEY_DESCR_VER(pEAPKey->key_information[1]); + if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){ + /* TKIP */ + key_bytes_len = pntoh16(pEAPKey->key_length); + }else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){ + /* AES */ + key_bytes_len = pntoh16(pEAPKey->key_data_len); + + /* AES keys must be at least 128 bits = 16 bytes. */ + if (key_bytes_len < 16) { + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + } + + if ((key_bytes_len < GROUP_KEY_MIN_LEN) || + (eapol_len < sizeof(EAPOL_RSN_KEY)) || + (key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY))) { + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* Encrypted key is in the information element field of the EAPOL key packet */ + key_data = (guint8 *)pEAPKey + sizeof(EAPOL_RSN_KEY); + szEncryptedKey = (guint8 *)g_memdup(key_data, key_bytes_len); + + DEBUG_DUMP(""Encrypted Broadcast key:"", szEncryptedKey, key_bytes_len); + DEBUG_DUMP(""KeyIV:"", pEAPKey->key_iv, 16); + DEBUG_DUMP(""decryption_key:"", decryption_key, 16); + + /* We are rekeying, save old sa */ + tmp_sa=(AIRPDCAP_SEC_ASSOCIATION *)g_malloc(sizeof(AIRPDCAP_SEC_ASSOCIATION)); + memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION)); + sa->next=tmp_sa; + + /* As we have no concept of the prior association request at this point, we need to deduce the */ + /* group key cipher from the length of the key bytes. In WPA this is straightforward as the */ + /* keybytes just contain the GTK, and the GTK is only in the group handshake, NOT the M3. */ + /* In WPA2 its a little more tricky as the M3 keybytes contain an RSN_IE, but the group handshake */ + /* does not. Also there are other (variable length) items in the keybytes which we need to account */ + /* for to determine the true key length, and thus the group cipher. */ + + if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){ + guint8 new_key[32]; + guint8 dummy[256]; + /* TKIP key */ + /* Per 802.11i, Draft 3.0 spec, section 8.5.2, p. 97, line 4-8, */ + /* group key is decrypted using RC4. Concatenate the IV with the 16 byte EK (PTK+16) to get the decryption key */ + + rc4_state_struct rc4_state; + + /* The WPA group key just contains the GTK bytes so deducing the type is straightforward */ + /* Note - WPA M3 doesn't contain a group key so we'll only be here for the group handshake */ + sa->wpa.key_ver = (key_bytes_len >=TKIP_GROUP_KEY_LEN)?AIRPDCAP_WPA_KEY_VER_NOT_CCMP:AIRPDCAP_WPA_KEY_VER_AES_CCMP; + + /* Build the full decryption key based on the IV and part of the pairwise key */ + memcpy(new_key, pEAPKey->key_iv, 16); + memcpy(new_key+16, decryption_key, 16); + DEBUG_DUMP(""FullDecrKey:"", new_key, 32); + + crypt_rc4_init(&rc4_state, new_key, sizeof(new_key)); + + /* Do dummy 256 iterations of the RC4 algorithm (per 802.11i, Draft 3.0, p. 97 line 6) */ + crypt_rc4(&rc4_state, dummy, 256); + crypt_rc4(&rc4_state, szEncryptedKey, key_bytes_len); + + } else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){ + /* AES CCMP key */ + + guint8 key_found; + guint8 key_length; + guint16 key_index; + guint8 *decrypted_data; + + /* Unwrap the key; the result is key_bytes_len in length */ + decrypted_data = AES_unwrap(decryption_key, 16, szEncryptedKey, key_bytes_len); + + /* With WPA2 what we get after Broadcast Key decryption is an actual RSN structure. + The key itself is stored as a GTK KDE + WPA2 IE (1 byte) id = 0xdd, length (1 byte), GTK OUI (4 bytes), key index (1 byte) and 1 reserved byte. Thus we have to + pass pointer to the actual key with 8 bytes offset */ + + key_found = FALSE; + key_index = 0; + + /* Parse Key data until we found GTK KDE */ + /* GTK KDE = 00-0F-AC 01 */ + while(key_index < (key_bytes_len - 6) && !key_found){ + guint8 rsn_id; + guint32 type; + + /* Get RSN ID */ + rsn_id = decrypted_data[key_index]; + type = ((decrypted_data[key_index + 2] << 24) + + (decrypted_data[key_index + 3] << 16) + + (decrypted_data[key_index + 4] << 8) + + (decrypted_data[key_index + 5])); + + if (rsn_id == 0xdd && type == 0x000fac01) { + key_found = TRUE; + } else { + key_index += decrypted_data[key_index+1]+2; + } + } + + if (key_found){ + key_length = decrypted_data[key_index+1] - 6; + + if (key_index+8 >= key_bytes_len || + key_length > key_bytes_len - key_index - 8) { + g_free(decrypted_data); + g_free(szEncryptedKey); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* Skip over the GTK header info, and don't copy past the end of the encrypted data */ + memcpy(szEncryptedKey, decrypted_data+key_index+8, key_length); + } else { + g_free(decrypted_data); + g_free(szEncryptedKey); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + if (key_length == TKIP_GROUP_KEY_LEN) + sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_NOT_CCMP; + else + sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP; + + g_free(decrypted_data); + } + + key_len = (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)?TKIP_GROUP_KEY_LEN:CCMP_GROUP_KEY_LEN; + if (key_len > key_bytes_len) { + /* the key required for this protocol is longer than the key that we just calculated */ + g_free(szEncryptedKey); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* Decrypted key is now in szEncryptedKey with len of key_len */ + DEBUG_DUMP(""Broadcast key:"", szEncryptedKey, key_len); + + /* Load the proper key material info into the SA */ + sa->key = &dummy_key; /* we just need key to be not null because it is checked in AirPDcapRsnaMng(). The WPA key materials are actually in the .wpa structure */ + sa->validKey = TRUE; + + /* Since this is a GTK and its size is only 32 bytes (vs. the 64 byte size of a PTK), we fake it and put it in at a 32-byte offset so the */ + /* AirPDcapRsnaMng() function will extract the right piece of the GTK for decryption. (The first 16 bytes of the GTK are used for decryption.) */ + memset(sa->wpa.ptk, 0, sizeof(sa->wpa.ptk)); + memcpy(sa->wpa.ptk+32, szEncryptedKey, key_len); + g_free(szEncryptedKey); + return AIRPDCAP_RET_SUCCESS_HANDSHAKE; +}","{'deleted': [{'line_no': 29, 'char_start': 1297, 'char_end': 1395, 'line': ' if (key_bytes_len < GROUP_KEY_MIN_LEN || key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY)) {\n'}], 'added': [{'line_no': 29, 'char_start': 1297, 'char_end': 1344, 'line': ' if ((key_bytes_len < GROUP_KEY_MIN_LEN) ||\n'}, {'line_no': 30, 'char_start': 1344, 'char_end': 1391, 'line': ' (eapol_len < sizeof(EAPOL_RSN_KEY)) ||\n'}, {'line_no': 31, 'char_start': 1391, 'char_end': 1454, 'line': ' (key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY))) {\n'}]}","{'deleted': [], 'added': [{'char_start': 1305, 'char_end': 1306, 'chars': '('}, {'char_start': 1339, 'char_end': 1340, 'chars': ')'}, {'char_start': 1343, 'char_end': 1349, 'chars': '\n '}, {'char_start': 1350, 'char_end': 1400, 'chars': ' (eapol_len < sizeof(EAPOL_RSN_KEY)) ||\n ('}, {'char_start': 1448, 'char_end': 1449, 'chars': ')'}]}",github.com/wireshark/wireshark/commit/b6d838eebf4456192360654092e5587c5207f185,epan/crypt/airpdcap.c,cwe-125, +cwe-125,AdaptiveThresholdImage,"MagickExport Image *AdaptiveThresholdImage(const Image *image, + const size_t width,const size_t height,const double bias, + ExceptionInfo *exception) +{ +#define AdaptiveThresholdImageTag ""AdaptiveThreshold/Image"" + + CacheView + *image_view, + *threshold_view; + + Image + *threshold_image; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + MagickSizeType + number_pixels; + + ssize_t + y; + + /* + Initialize threshold image attributes. + */ + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + threshold_image=CloneImage(image,0,0,MagickTrue,exception); + if (threshold_image == (Image *) NULL) + return((Image *) NULL); + status=SetImageStorageClass(threshold_image,DirectClass,exception); + if (status == MagickFalse) + { + threshold_image=DestroyImage(threshold_image); + return((Image *) NULL); + } + /* + Threshold image. + */ + status=MagickTrue; + progress=0; + number_pixels=(MagickSizeType) width*height; + image_view=AcquireVirtualCacheView(image,exception); + threshold_view=AcquireAuthenticCacheView(threshold_image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp parallel for schedule(static) shared(progress,status) \ + magick_number_threads(image,threshold_image,image->rows,1) +#endif + for (y=0; y < (ssize_t) image->rows; y++) + { + double + channel_bias[MaxPixelChannels], + channel_sum[MaxPixelChannels]; + + register const Quantum + *magick_restrict p, + *magick_restrict pixels; + + register Quantum + *magick_restrict q; + + register ssize_t + i, + x; + + ssize_t + center, + u, + v; + + if (status == MagickFalse) + continue; + p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) + (height/2L),image->columns+width,height,exception); + q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, + 1,exception); + if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) + { + status=MagickFalse; + continue; + } + center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ + GetPixelChannels(image)*(width/2); + for (i=0; i < (ssize_t) GetPixelChannels(image); i++) + { + PixelChannel channel = GetPixelChannelChannel(image,i); + PixelTrait traits = GetPixelChannelTraits(image,channel); + PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, + channel); + if ((traits == UndefinedPixelTrait) || + (threshold_traits == UndefinedPixelTrait)) + continue; + if ((threshold_traits & CopyPixelTrait) != 0) + { + SetPixelChannel(threshold_image,channel,p[center+i],q); + continue; + } + pixels=p; + channel_bias[channel]=0.0; + channel_sum[channel]=0.0; + for (v=0; v < (ssize_t) height; v++) + { + for (u=0; u < (ssize_t) width; u++) + { + if (u == (ssize_t) (width-1)) + channel_bias[channel]+=pixels[i]; + channel_sum[channel]+=pixels[i]; + pixels+=GetPixelChannels(image); + } + pixels+=GetPixelChannels(image)*image->columns; + } + } + for (x=0; x < (ssize_t) image->columns; x++) + { + for (i=0; i < (ssize_t) GetPixelChannels(image); i++) + { + double + mean; + + PixelChannel channel = GetPixelChannelChannel(image,i); + PixelTrait traits = GetPixelChannelTraits(image,channel); + PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, + channel); + if ((traits == UndefinedPixelTrait) || + (threshold_traits == UndefinedPixelTrait)) + continue; + if ((threshold_traits & CopyPixelTrait) != 0) + { + SetPixelChannel(threshold_image,channel,p[center+i],q); + continue; + } + channel_sum[channel]-=channel_bias[channel]; + channel_bias[channel]=0.0; + pixels=p; + for (v=0; v < (ssize_t) height; v++) + { + channel_bias[channel]+=pixels[i]; + pixels+=(width-1)*GetPixelChannels(image); + channel_sum[channel]+=pixels[i]; + pixels+=GetPixelChannels(image)*(image->columns+1); + } + mean=(double) (channel_sum[channel]/number_pixels+bias); + SetPixelChannel(threshold_image,channel,(Quantum) ((double) + p[center+i] <= mean ? 0 : QuantumRange),q); + } + p+=GetPixelChannels(image); + q+=GetPixelChannels(threshold_image); + } + if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) + status=MagickFalse; + if (image->progress_monitor != (MagickProgressMonitor) NULL) + { + MagickBooleanType + proceed; + +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp atomic +#endif + progress++; + proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, + image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + threshold_image->type=image->type; + threshold_view=DestroyCacheView(threshold_view); + image_view=DestroyCacheView(image_view); + if (status == MagickFalse) + threshold_image=DestroyImage(threshold_image); + return(threshold_image); +}","MagickExport Image *AdaptiveThresholdImage(const Image *image, + const size_t width,const size_t height,const double bias, + ExceptionInfo *exception) +{ +#define AdaptiveThresholdImageTag ""AdaptiveThreshold/Image"" + + CacheView + *image_view, + *threshold_view; + + Image + *threshold_image; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + MagickSizeType + number_pixels; + + ssize_t + y; + + /* + Initialize threshold image attributes. + */ + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + threshold_image=CloneImage(image,0,0,MagickTrue,exception); + if (threshold_image == (Image *) NULL) + return((Image *) NULL); + if (width == 0) + return(threshold_image); + status=SetImageStorageClass(threshold_image,DirectClass,exception); + if (status == MagickFalse) + { + threshold_image=DestroyImage(threshold_image); + return((Image *) NULL); + } + /* + Threshold image. + */ + status=MagickTrue; + progress=0; + number_pixels=(MagickSizeType) width*height; + image_view=AcquireVirtualCacheView(image,exception); + threshold_view=AcquireAuthenticCacheView(threshold_image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp parallel for schedule(static) shared(progress,status) \ + magick_number_threads(image,threshold_image,image->rows,1) +#endif + for (y=0; y < (ssize_t) image->rows; y++) + { + double + channel_bias[MaxPixelChannels], + channel_sum[MaxPixelChannels]; + + register const Quantum + *magick_restrict p, + *magick_restrict pixels; + + register Quantum + *magick_restrict q; + + register ssize_t + i, + x; + + ssize_t + center, + u, + v; + + if (status == MagickFalse) + continue; + p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) + (height/2L),image->columns+width,height,exception); + q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, + 1,exception); + if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) + { + status=MagickFalse; + continue; + } + center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ + GetPixelChannels(image)*(width/2); + for (i=0; i < (ssize_t) GetPixelChannels(image); i++) + { + PixelChannel channel = GetPixelChannelChannel(image,i); + PixelTrait traits = GetPixelChannelTraits(image,channel); + PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, + channel); + if ((traits == UndefinedPixelTrait) || + (threshold_traits == UndefinedPixelTrait)) + continue; + if ((threshold_traits & CopyPixelTrait) != 0) + { + SetPixelChannel(threshold_image,channel,p[center+i],q); + continue; + } + pixels=p; + channel_bias[channel]=0.0; + channel_sum[channel]=0.0; + for (v=0; v < (ssize_t) height; v++) + { + for (u=0; u < (ssize_t) width; u++) + { + if (u == (ssize_t) (width-1)) + channel_bias[channel]+=pixels[i]; + channel_sum[channel]+=pixels[i]; + pixels+=GetPixelChannels(image); + } + pixels+=GetPixelChannels(image)*image->columns; + } + } + for (x=0; x < (ssize_t) image->columns; x++) + { + for (i=0; i < (ssize_t) GetPixelChannels(image); i++) + { + double + mean; + + PixelChannel channel = GetPixelChannelChannel(image,i); + PixelTrait traits = GetPixelChannelTraits(image,channel); + PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, + channel); + if ((traits == UndefinedPixelTrait) || + (threshold_traits == UndefinedPixelTrait)) + continue; + if ((threshold_traits & CopyPixelTrait) != 0) + { + SetPixelChannel(threshold_image,channel,p[center+i],q); + continue; + } + channel_sum[channel]-=channel_bias[channel]; + channel_bias[channel]=0.0; + pixels=p; + for (v=0; v < (ssize_t) height; v++) + { + channel_bias[channel]+=pixels[i]; + pixels+=(width-1)*GetPixelChannels(image); + channel_sum[channel]+=pixels[i]; + pixels+=GetPixelChannels(image)*(image->columns+1); + } + mean=(double) (channel_sum[channel]/number_pixels+bias); + SetPixelChannel(threshold_image,channel,(Quantum) ((double) + p[center+i] <= mean ? 0 : QuantumRange),q); + } + p+=GetPixelChannels(image); + q+=GetPixelChannels(threshold_image); + } + if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) + status=MagickFalse; + if (image->progress_monitor != (MagickProgressMonitor) NULL) + { + MagickBooleanType + proceed; + +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp atomic +#endif + progress++; + proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, + image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + threshold_image->type=image->type; + threshold_view=DestroyCacheView(threshold_view); + image_view=DestroyCacheView(image_view); + if (status == MagickFalse) + threshold_image=DestroyImage(threshold_image); + return(threshold_image); +}","{'deleted': [], 'added': [{'line_no': 38, 'char_start': 904, 'char_end': 922, 'line': ' if (width == 0)\n'}, {'line_no': 39, 'char_start': 922, 'char_end': 951, 'line': ' return(threshold_image);\n'}]}","{'deleted': [], 'added': [{'char_start': 906, 'char_end': 953, 'chars': 'if (width == 0)\n return(threshold_image);\n '}]}",github.com/ImageMagick/ImageMagick/commit/a7759f410b773a1dd57b0e1fb28112e1cd8b97bc,MagickCore/threshold.c,cwe-125, +cwe-125,INST_HANDLER,"INST_HANDLER (lds) { // LDS Rd, k + int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); + int k = (buf[3] << 8) | buf[2]; + op->ptr = k; + + // load value from RAMPD:k + __generic_ld_st (op, ""ram"", 0, 1, 0, k, 0); + ESIL_A (""r%d,=,"", d); +}","INST_HANDLER (lds) { // LDS Rd, k + if (len < 4) { + return; + } + int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); + int k = (buf[3] << 8) | buf[2]; + op->ptr = k; + + // load value from RAMPD:k + __generic_ld_st (op, ""ram"", 0, 1, 0, k, 0); + ESIL_A (""r%d,=,"", d); +}","{'deleted': [], 'added': [{'line_no': 2, 'char_start': 34, 'char_end': 50, 'line': '\tif (len < 4) {\n'}, {'line_no': 3, 'char_start': 50, 'char_end': 60, 'line': '\t\treturn;\n'}, {'line_no': 4, 'char_start': 60, 'char_end': 63, 'line': '\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 36, 'char_end': 65, 'chars': 'f (len < 4) {\n\t\treturn;\n\t}\n\ti'}]}",github.com/radare/radare2/commit/041e53cab7ca33481ae45ecd65ad596976d78e68,libr/anal/p/anal_avr.c,cwe-125, +cwe-125,jpeg_size,"static int jpeg_size(unsigned char* data, unsigned int data_size, + int *width, int *height) +{ + int i = 0; + if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 && + data[i+2] == 0xFF && data[i+3] == 0xE0) { + i += 4; + if(i + 6 < data_size && + data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' && + data[i+5] == 'F' && data[i+6] == 0x00) { + unsigned short block_length = data[i] * 256 + data[i+1]; + while(i= data_size) + return -1; + if(data[i] != 0xFF) + return -1; + if(data[i+1] == 0xC0) { + *height = data[i+5]*256 + data[i+6]; + *width = data[i+7]*256 + data[i+8]; + return 0; + } + i+=2; + block_length = data[i] * 256 + data[i+1]; + } + } + } + + return -1; +}","static int jpeg_size(unsigned char* data, unsigned int data_size, + int *width, int *height) +{ + int i = 0; + if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 && + data[i+2] == 0xFF && data[i+3] == 0xE0) { + i += 4; + if(i + 6 < data_size && + data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' && + data[i+5] == 'F' && data[i+6] == 0x00) { + unsigned short block_length = data[i] * 256 + data[i+1]; + while(i= data_size) + return -1; + if(data[i] != 0xFF) + return -1; + if(data[i+1] == 0xC0) { + *height = data[i+5]*256 + data[i+6]; + *width = data[i+7]*256 + data[i+8]; + return 0; + } + i+=2; + if (i + 1 < data_size) + block_length = data[i] * 256 + data[i+1]; + } + } + } + + return -1; +}","{'deleted': [{'line_no': 24, 'char_start': 930, 'char_end': 988, 'line': ' block_length = data[i] * 256 + data[i+1];\n'}], 'added': [{'line_no': 24, 'char_start': 930, 'char_end': 969, 'line': ' if (i + 1 < data_size)\n'}, {'line_no': 25, 'char_start': 969, 'char_end': 1031, 'line': ' block_length = data[i] * 256 + data[i+1];\n'}]}","{'deleted': [], 'added': [{'char_start': 946, 'char_end': 989, 'chars': 'if (i + 1 < data_size)\n '}]}",github.com/AndreRenaud/PDFGen/commit/ee58aff6918b8bbc3be29b9e3089485ea46ff956,pdfgen.c,cwe-125, +cwe-125,RLEDECOMPRESS,"static INLINE BOOL RLEDECOMPRESS(const BYTE* pbSrcBuffer, UINT32 cbSrcBuffer, BYTE* pbDestBuffer, + UINT32 rowDelta, UINT32 width, UINT32 height) +{ + const BYTE* pbSrc = pbSrcBuffer; + const BYTE* pbEnd; + const BYTE* pbDestEnd; + BYTE* pbDest = pbDestBuffer; + PIXEL temp; + PIXEL fgPel = WHITE_PIXEL; + BOOL fInsertFgPel = FALSE; + BOOL fFirstLine = TRUE; + BYTE bitmask; + PIXEL pixelA, pixelB; + UINT32 runLength; + UINT32 code; + UINT32 advance; + RLEEXTRA + + if ((rowDelta == 0) || (rowDelta < width)) + return FALSE; + + if (!pbSrcBuffer || !pbDestBuffer) + return FALSE; + + pbEnd = pbSrcBuffer + cbSrcBuffer; + pbDestEnd = pbDestBuffer + rowDelta * height; + + while (pbSrc < pbEnd) + { + /* Watch out for the end of the first scanline. */ + if (fFirstLine) + { + if ((UINT32)(pbDest - pbDestBuffer) >= rowDelta) + { + fFirstLine = FALSE; + fInsertFgPel = FALSE; + } + } + + /* + Extract the compression order code ID from the compression + order header. + */ + code = ExtractCodeId(*pbSrc); + + /* Handle Background Run Orders. */ + if (code == REGULAR_BG_RUN || code == MEGA_MEGA_BG_RUN) + { + runLength = ExtractRunLength(code, pbSrc, &advance); + pbSrc = pbSrc + advance; + + if (fFirstLine) + { + if (fInsertFgPel) + { + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) + return FALSE; + + DESTWRITEPIXEL(pbDest, fgPel); + DESTNEXTPIXEL(pbDest); + runLength = runLength - 1; + } + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) + return FALSE; + + UNROLL(runLength, { + DESTWRITEPIXEL(pbDest, BLACK_PIXEL); + DESTNEXTPIXEL(pbDest); + }); + } + else + { + if (fInsertFgPel) + { + DESTREADPIXEL(temp, pbDest - rowDelta); + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) + return FALSE; + + DESTWRITEPIXEL(pbDest, temp ^ fgPel); + DESTNEXTPIXEL(pbDest); + runLength--; + } + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) + return FALSE; + + UNROLL(runLength, { + DESTREADPIXEL(temp, pbDest - rowDelta); + DESTWRITEPIXEL(pbDest, temp); + DESTNEXTPIXEL(pbDest); + }); + } + + /* A follow-on background run order will need a foreground pel inserted. */ + fInsertFgPel = TRUE; + continue; + } + + /* For any of the other run-types a follow-on background run + order does not need a foreground pel inserted. */ + fInsertFgPel = FALSE; + + switch (code) + { + /* Handle Foreground Run Orders. */ + case REGULAR_FG_RUN: + case MEGA_MEGA_FG_RUN: + case LITE_SET_FG_FG_RUN: + case MEGA_MEGA_SET_FG_RUN: + runLength = ExtractRunLength(code, pbSrc, &advance); + pbSrc = pbSrc + advance; + + if (code == LITE_SET_FG_FG_RUN || code == MEGA_MEGA_SET_FG_RUN) + { + SRCREADPIXEL(fgPel, pbSrc); + SRCNEXTPIXEL(pbSrc); + } + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) + return FALSE; + + if (fFirstLine) + { + UNROLL(runLength, { + DESTWRITEPIXEL(pbDest, fgPel); + DESTNEXTPIXEL(pbDest); + }); + } + else + { + UNROLL(runLength, { + DESTREADPIXEL(temp, pbDest - rowDelta); + DESTWRITEPIXEL(pbDest, temp ^ fgPel); + DESTNEXTPIXEL(pbDest); + }); + } + + break; + + /* Handle Dithered Run Orders. */ + case LITE_DITHERED_RUN: + case MEGA_MEGA_DITHERED_RUN: + runLength = ExtractRunLength(code, pbSrc, &advance); + pbSrc = pbSrc + advance; + SRCREADPIXEL(pixelA, pbSrc); + SRCNEXTPIXEL(pbSrc); + SRCREADPIXEL(pixelB, pbSrc); + SRCNEXTPIXEL(pbSrc); + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength * 2)) + return FALSE; + + UNROLL(runLength, { + DESTWRITEPIXEL(pbDest, pixelA); + DESTNEXTPIXEL(pbDest); + DESTWRITEPIXEL(pbDest, pixelB); + DESTNEXTPIXEL(pbDest); + }); + break; + + /* Handle Color Run Orders. */ + case REGULAR_COLOR_RUN: + case MEGA_MEGA_COLOR_RUN: + runLength = ExtractRunLength(code, pbSrc, &advance); + pbSrc = pbSrc + advance; + SRCREADPIXEL(pixelA, pbSrc); + SRCNEXTPIXEL(pbSrc); + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) + return FALSE; + + UNROLL(runLength, { + DESTWRITEPIXEL(pbDest, pixelA); + DESTNEXTPIXEL(pbDest); + }); + break; + + /* Handle Foreground/Background Image Orders. */ + case REGULAR_FGBG_IMAGE: + case MEGA_MEGA_FGBG_IMAGE: + case LITE_SET_FG_FGBG_IMAGE: + case MEGA_MEGA_SET_FGBG_IMAGE: + runLength = ExtractRunLength(code, pbSrc, &advance); + pbSrc = pbSrc + advance; + + if (code == LITE_SET_FG_FGBG_IMAGE || code == MEGA_MEGA_SET_FGBG_IMAGE) + { + SRCREADPIXEL(fgPel, pbSrc); + SRCNEXTPIXEL(pbSrc); + } + + if (fFirstLine) + { + while (runLength > 8) + { + bitmask = *pbSrc; + pbSrc = pbSrc + 1; + pbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, 8); + + if (!pbDest) + return FALSE; + + runLength = runLength - 8; + } + } + else + { + while (runLength > 8) + { + bitmask = *pbSrc; + pbSrc = pbSrc + 1; + pbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, 8); + + if (!pbDest) + return FALSE; + + runLength = runLength - 8; + } + } + + if (runLength > 0) + { + bitmask = *pbSrc; + pbSrc = pbSrc + 1; + + if (fFirstLine) + { + pbDest = + WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, runLength); + } + else + { + pbDest = + WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, runLength); + } + + if (!pbDest) + return FALSE; + } + + break; + + /* Handle Color Image Orders. */ + case REGULAR_COLOR_IMAGE: + case MEGA_MEGA_COLOR_IMAGE: + runLength = ExtractRunLength(code, pbSrc, &advance); + pbSrc = pbSrc + advance; + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) + return FALSE; + + UNROLL(runLength, { + SRCREADPIXEL(temp, pbSrc); + SRCNEXTPIXEL(pbSrc); + DESTWRITEPIXEL(pbDest, temp); + DESTNEXTPIXEL(pbDest); + }); + break; + + /* Handle Special Order 1. */ + case SPECIAL_FGBG_1: + pbSrc = pbSrc + 1; + + if (fFirstLine) + { + pbDest = + WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg1, fgPel, 8); + } + else + { + pbDest = + WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg1, fgPel, 8); + } + + if (!pbDest) + return FALSE; + + break; + + /* Handle Special Order 2. */ + case SPECIAL_FGBG_2: + pbSrc = pbSrc + 1; + + if (fFirstLine) + { + pbDest = + WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg2, fgPel, 8); + } + else + { + pbDest = + WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg2, fgPel, 8); + } + + if (!pbDest) + return FALSE; + + break; + + /* Handle White Order. */ + case SPECIAL_WHITE: + pbSrc = pbSrc + 1; + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) + return FALSE; + + DESTWRITEPIXEL(pbDest, WHITE_PIXEL); + DESTNEXTPIXEL(pbDest); + break; + + /* Handle Black Order. */ + case SPECIAL_BLACK: + pbSrc = pbSrc + 1; + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) + return FALSE; + + DESTWRITEPIXEL(pbDest, BLACK_PIXEL); + DESTNEXTPIXEL(pbDest); + break; + + default: + return FALSE; + } + } + + return TRUE; +}","static INLINE BOOL RLEDECOMPRESS(const BYTE* pbSrcBuffer, UINT32 cbSrcBuffer, BYTE* pbDestBuffer, + UINT32 rowDelta, UINT32 width, UINT32 height) +{ + const BYTE* pbSrc = pbSrcBuffer; + const BYTE* pbEnd; + const BYTE* pbDestEnd; + BYTE* pbDest = pbDestBuffer; + PIXEL temp; + PIXEL fgPel = WHITE_PIXEL; + BOOL fInsertFgPel = FALSE; + BOOL fFirstLine = TRUE; + BYTE bitmask; + PIXEL pixelA, pixelB; + UINT32 runLength; + UINT32 code; + UINT32 advance; + RLEEXTRA + + if ((rowDelta == 0) || (rowDelta < width)) + return FALSE; + + if (!pbSrcBuffer || !pbDestBuffer) + return FALSE; + + pbEnd = pbSrcBuffer + cbSrcBuffer; + pbDestEnd = pbDestBuffer + rowDelta * height; + + while (pbSrc < pbEnd) + { + /* Watch out for the end of the first scanline. */ + if (fFirstLine) + { + if ((UINT32)(pbDest - pbDestBuffer) >= rowDelta) + { + fFirstLine = FALSE; + fInsertFgPel = FALSE; + } + } + + /* + Extract the compression order code ID from the compression + order header. + */ + code = ExtractCodeId(*pbSrc); + + /* Handle Background Run Orders. */ + if (code == REGULAR_BG_RUN || code == MEGA_MEGA_BG_RUN) + { + runLength = ExtractRunLength(code, pbSrc, &advance); + pbSrc = pbSrc + advance; + + if (fFirstLine) + { + if (fInsertFgPel) + { + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) + return FALSE; + + DESTWRITEPIXEL(pbDest, fgPel); + DESTNEXTPIXEL(pbDest); + runLength = runLength - 1; + } + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) + return FALSE; + + UNROLL(runLength, { + DESTWRITEPIXEL(pbDest, BLACK_PIXEL); + DESTNEXTPIXEL(pbDest); + }); + } + else + { + if (fInsertFgPel) + { + DESTREADPIXEL(temp, pbDest - rowDelta); + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) + return FALSE; + + DESTWRITEPIXEL(pbDest, temp ^ fgPel); + DESTNEXTPIXEL(pbDest); + runLength--; + } + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) + return FALSE; + + UNROLL(runLength, { + DESTREADPIXEL(temp, pbDest - rowDelta); + DESTWRITEPIXEL(pbDest, temp); + DESTNEXTPIXEL(pbDest); + }); + } + + /* A follow-on background run order will need a foreground pel inserted. */ + fInsertFgPel = TRUE; + continue; + } + + /* For any of the other run-types a follow-on background run + order does not need a foreground pel inserted. */ + fInsertFgPel = FALSE; + + switch (code) + { + /* Handle Foreground Run Orders. */ + case REGULAR_FG_RUN: + case MEGA_MEGA_FG_RUN: + case LITE_SET_FG_FG_RUN: + case MEGA_MEGA_SET_FG_RUN: + runLength = ExtractRunLength(code, pbSrc, &advance); + pbSrc = pbSrc + advance; + + if (code == LITE_SET_FG_FG_RUN || code == MEGA_MEGA_SET_FG_RUN) + { + if (pbSrc >= pbEnd) + return FALSE; + SRCREADPIXEL(fgPel, pbSrc); + SRCNEXTPIXEL(pbSrc); + } + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) + return FALSE; + + if (fFirstLine) + { + UNROLL(runLength, { + DESTWRITEPIXEL(pbDest, fgPel); + DESTNEXTPIXEL(pbDest); + }); + } + else + { + UNROLL(runLength, { + DESTREADPIXEL(temp, pbDest - rowDelta); + DESTWRITEPIXEL(pbDest, temp ^ fgPel); + DESTNEXTPIXEL(pbDest); + }); + } + + break; + + /* Handle Dithered Run Orders. */ + case LITE_DITHERED_RUN: + case MEGA_MEGA_DITHERED_RUN: + runLength = ExtractRunLength(code, pbSrc, &advance); + pbSrc = pbSrc + advance; + if (pbSrc >= pbEnd) + return FALSE; + SRCREADPIXEL(pixelA, pbSrc); + SRCNEXTPIXEL(pbSrc); + if (pbSrc >= pbEnd) + return FALSE; + SRCREADPIXEL(pixelB, pbSrc); + SRCNEXTPIXEL(pbSrc); + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength * 2)) + return FALSE; + + UNROLL(runLength, { + DESTWRITEPIXEL(pbDest, pixelA); + DESTNEXTPIXEL(pbDest); + DESTWRITEPIXEL(pbDest, pixelB); + DESTNEXTPIXEL(pbDest); + }); + break; + + /* Handle Color Run Orders. */ + case REGULAR_COLOR_RUN: + case MEGA_MEGA_COLOR_RUN: + runLength = ExtractRunLength(code, pbSrc, &advance); + pbSrc = pbSrc + advance; + if (pbSrc >= pbEnd) + return FALSE; + SRCREADPIXEL(pixelA, pbSrc); + SRCNEXTPIXEL(pbSrc); + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) + return FALSE; + + UNROLL(runLength, { + DESTWRITEPIXEL(pbDest, pixelA); + DESTNEXTPIXEL(pbDest); + }); + break; + + /* Handle Foreground/Background Image Orders. */ + case REGULAR_FGBG_IMAGE: + case MEGA_MEGA_FGBG_IMAGE: + case LITE_SET_FG_FGBG_IMAGE: + case MEGA_MEGA_SET_FGBG_IMAGE: + runLength = ExtractRunLength(code, pbSrc, &advance); + pbSrc = pbSrc + advance; + + if (pbSrc >= pbEnd) + return FALSE; + if (code == LITE_SET_FG_FGBG_IMAGE || code == MEGA_MEGA_SET_FGBG_IMAGE) + { + SRCREADPIXEL(fgPel, pbSrc); + SRCNEXTPIXEL(pbSrc); + } + + if (fFirstLine) + { + while (runLength > 8) + { + bitmask = *pbSrc; + pbSrc = pbSrc + 1; + pbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, 8); + + if (!pbDest) + return FALSE; + + runLength = runLength - 8; + } + } + else + { + while (runLength > 8) + { + bitmask = *pbSrc; + pbSrc = pbSrc + 1; + pbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, 8); + + if (!pbDest) + return FALSE; + + runLength = runLength - 8; + } + } + + if (runLength > 0) + { + bitmask = *pbSrc; + pbSrc = pbSrc + 1; + + if (fFirstLine) + { + pbDest = + WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, runLength); + } + else + { + pbDest = + WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, runLength); + } + + if (!pbDest) + return FALSE; + } + + break; + + /* Handle Color Image Orders. */ + case REGULAR_COLOR_IMAGE: + case MEGA_MEGA_COLOR_IMAGE: + runLength = ExtractRunLength(code, pbSrc, &advance); + pbSrc = pbSrc + advance; + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) + return FALSE; + + UNROLL(runLength, { + if (pbSrc >= pbEnd) + return FALSE; + SRCREADPIXEL(temp, pbSrc); + SRCNEXTPIXEL(pbSrc); + DESTWRITEPIXEL(pbDest, temp); + DESTNEXTPIXEL(pbDest); + }); + break; + + /* Handle Special Order 1. */ + case SPECIAL_FGBG_1: + pbSrc = pbSrc + 1; + + if (fFirstLine) + { + pbDest = + WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg1, fgPel, 8); + } + else + { + pbDest = + WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg1, fgPel, 8); + } + + if (!pbDest) + return FALSE; + + break; + + /* Handle Special Order 2. */ + case SPECIAL_FGBG_2: + pbSrc = pbSrc + 1; + + if (fFirstLine) + { + pbDest = + WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg2, fgPel, 8); + } + else + { + pbDest = + WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg2, fgPel, 8); + } + + if (!pbDest) + return FALSE; + + break; + + /* Handle White Order. */ + case SPECIAL_WHITE: + pbSrc = pbSrc + 1; + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) + return FALSE; + + DESTWRITEPIXEL(pbDest, WHITE_PIXEL); + DESTNEXTPIXEL(pbDest); + break; + + /* Handle Black Order. */ + case SPECIAL_BLACK: + pbSrc = pbSrc + 1; + + if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) + return FALSE; + + DESTWRITEPIXEL(pbDest, BLACK_PIXEL); + DESTNEXTPIXEL(pbDest); + break; + + default: + return FALSE; + } + } + + return TRUE; +}","{'deleted': [], 'added': [{'line_no': 117, 'char_start': 2683, 'char_end': 2708, 'line': '\t\t\t\t\tif (pbSrc >= pbEnd)\n'}, {'line_no': 118, 'char_start': 2708, 'char_end': 2728, 'line': '\t\t\t\t\t\treturn FALSE;\n'}, {'line_no': 149, 'char_start': 3371, 'char_end': 3395, 'line': '\t\t\t\tif (pbSrc >= pbEnd)\n'}, {'line_no': 150, 'char_start': 3395, 'char_end': 3414, 'line': '\t\t\t\t\treturn FALSE;\n'}, {'line_no': 153, 'char_start': 3472, 'char_end': 3496, 'line': '\t\t\t\tif (pbSrc >= pbEnd)\n'}, {'line_no': 154, 'char_start': 3496, 'char_end': 3515, 'line': '\t\t\t\t\treturn FALSE;\n'}, {'line_no': 174, 'char_start': 4004, 'char_end': 4028, 'line': '\t\t\t\tif (pbSrc >= pbEnd)\n'}, {'line_no': 175, 'char_start': 4028, 'char_end': 4047, 'line': '\t\t\t\t\treturn FALSE;\n'}, {'line_no': 196, 'char_start': 4554, 'char_end': 4578, 'line': '\t\t\t\tif (pbSrc >= pbEnd)\n'}, {'line_no': 197, 'char_start': 4578, 'char_end': 4597, 'line': '\t\t\t\t\treturn FALSE;\n'}, {'line_no': 264, 'char_start': 5955, 'char_end': 5980, 'line': '\t\t\t\t\tif (pbSrc >= pbEnd)\n'}, {'line_no': 265, 'char_start': 5980, 'char_end': 6000, 'line': '\t\t\t\t\t\treturn FALSE;\n'}]}","{'deleted': [{'char_start': 2716, 'char_end': 2716, 'chars': ''}, {'char_start': 5714, 'char_end': 5714, 'chars': ''}], 'added': [{'char_start': 2688, 'char_end': 2733, 'chars': 'if (pbSrc >= pbEnd)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t'}, {'char_start': 3371, 'char_end': 3414, 'chars': '\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\treturn FALSE;\n'}, {'char_start': 3472, 'char_end': 3515, 'chars': '\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\treturn FALSE;\n'}, {'char_start': 4004, 'char_end': 4047, 'chars': '\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\treturn FALSE;\n'}, {'char_start': 4554, 'char_end': 4597, 'chars': '\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\treturn FALSE;\n'}, {'char_start': 5954, 'char_end': 5999, 'chars': '\n\t\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\t\treturn FALSE;'}]}",github.com/FreeRDP/FreeRDP/commit/0a98c450c58ec150e44781c89aa6f8e7e0f571f5,libfreerdp/codec/include/bitmap.c,cwe-125, +cwe-125,jp2_decode,"jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr) +{ + jp2_box_t *box; + int found; + jas_image_t *image; + jp2_dec_t *dec; + bool samedtype; + int dtype; + unsigned int i; + jp2_cmap_t *cmapd; + jp2_pclr_t *pclrd; + jp2_cdef_t *cdefd; + unsigned int channo; + int newcmptno; + int_fast32_t *lutents; +#if 0 + jp2_cdefchan_t *cdefent; + int cmptno; +#endif + jp2_cmapent_t *cmapent; + jas_icchdr_t icchdr; + jas_iccprof_t *iccprof; + + dec = 0; + box = 0; + image = 0; + + JAS_DBGLOG(100, (""jp2_decode(%p, \""%s\"")\n"", in, optstr)); + + if (!(dec = jp2_dec_create())) { + goto error; + } + + /* Get the first box. This should be a JP box. */ + if (!(box = jp2_box_get(in))) { + jas_eprintf(""error: cannot get box\n""); + goto error; + } + if (box->type != JP2_BOX_JP) { + jas_eprintf(""error: expecting signature box\n""); + goto error; + } + if (box->data.jp.magic != JP2_JP_MAGIC) { + jas_eprintf(""incorrect magic number\n""); + goto error; + } + jp2_box_destroy(box); + box = 0; + + /* Get the second box. This should be a FTYP box. */ + if (!(box = jp2_box_get(in))) { + goto error; + } + if (box->type != JP2_BOX_FTYP) { + jas_eprintf(""expecting file type box\n""); + goto error; + } + jp2_box_destroy(box); + box = 0; + + /* Get more boxes... */ + found = 0; + while ((box = jp2_box_get(in))) { + if (jas_getdbglevel() >= 1) { + jas_eprintf(""got box type %s\n"", box->info->name); + } + switch (box->type) { + case JP2_BOX_JP2C: + found = 1; + break; + case JP2_BOX_IHDR: + if (!dec->ihdr) { + dec->ihdr = box; + box = 0; + } + break; + case JP2_BOX_BPCC: + if (!dec->bpcc) { + dec->bpcc = box; + box = 0; + } + break; + case JP2_BOX_CDEF: + if (!dec->cdef) { + dec->cdef = box; + box = 0; + } + break; + case JP2_BOX_PCLR: + if (!dec->pclr) { + dec->pclr = box; + box = 0; + } + break; + case JP2_BOX_CMAP: + if (!dec->cmap) { + dec->cmap = box; + box = 0; + } + break; + case JP2_BOX_COLR: + if (!dec->colr) { + dec->colr = box; + box = 0; + } + break; + } + if (box) { + jp2_box_destroy(box); + box = 0; + } + if (found) { + break; + } + } + + if (!found) { + jas_eprintf(""error: no code stream found\n""); + goto error; + } + + if (!(dec->image = jpc_decode(in, optstr))) { + jas_eprintf(""error: cannot decode code stream\n""); + goto error; + } + + /* An IHDR box must be present. */ + if (!dec->ihdr) { + jas_eprintf(""error: missing IHDR box\n""); + goto error; + } + + /* Does the number of components indicated in the IHDR box match + the value specified in the code stream? */ + if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint, + jas_image_numcmpts(dec->image))) { + jas_eprintf(""warning: number of components mismatch\n""); + } + + /* At least one component must be present. */ + if (!jas_image_numcmpts(dec->image)) { + jas_eprintf(""error: no components\n""); + goto error; + } + + /* Determine if all components have the same data type. */ + samedtype = true; + dtype = jas_image_cmptdtype(dec->image, 0); + for (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { + if (jas_image_cmptdtype(dec->image, i) != dtype) { + samedtype = false; + break; + } + } + + /* Is the component data type indicated in the IHDR box consistent + with the data in the code stream? */ + if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) || + (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) { + jas_eprintf(""warning: component data type mismatch (IHDR)\n""); + } + + /* Is the compression type supported? */ + if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) { + jas_eprintf(""error: unsupported compression type\n""); + goto error; + } + + if (dec->bpcc) { + /* Is the number of components indicated in the BPCC box + consistent with the code stream data? */ + if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts( + dec->image))) { + jas_eprintf(""warning: number of components mismatch\n""); + } + /* Is the component data type information indicated in the BPCC + box consistent with the code stream data? */ + if (!samedtype) { + for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); + ++i) { + if (jas_image_cmptdtype(dec->image, i) != + JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) { + jas_eprintf(""warning: component data type mismatch (BPCC)\n""); + } + } + } else { + jas_eprintf(""warning: superfluous BPCC box\n""); + } + } + + /* A COLR box must be present. */ + if (!dec->colr) { + jas_eprintf(""error: no COLR box\n""); + goto error; + } + + switch (dec->colr->data.colr.method) { + case JP2_COLR_ENUM: + jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr)); + break; + case JP2_COLR_ICC: + iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp, + dec->colr->data.colr.iccplen); + if (!iccprof) { + jas_eprintf(""error: failed to parse ICC profile\n""); + goto error; + } + jas_iccprof_gethdr(iccprof, &icchdr); + jas_eprintf(""ICC Profile CS %08x\n"", icchdr.colorspc); + jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc)); + dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof); + if (!dec->image->cmprof_) { + jas_iccprof_destroy(iccprof); + goto error; + } + jas_iccprof_destroy(iccprof); + break; + } + + /* If a CMAP box is present, a PCLR box must also be present. */ + if (dec->cmap && !dec->pclr) { + jas_eprintf(""warning: missing PCLR box or superfluous CMAP box\n""); + jp2_box_destroy(dec->cmap); + dec->cmap = 0; + } + + /* If a CMAP box is not present, a PCLR box must not be present. */ + if (!dec->cmap && dec->pclr) { + jas_eprintf(""warning: missing CMAP box or superfluous PCLR box\n""); + jp2_box_destroy(dec->pclr); + dec->pclr = 0; + } + + /* Determine the number of channels (which is essentially the number + of components after any palette mappings have been applied). */ + dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : + JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); + + /* Perform a basic sanity check on the CMAP box if present. */ + if (dec->cmap) { + for (i = 0; i < dec->numchans; ++i) { + /* Is the component number reasonable? */ + if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint, + jas_image_numcmpts(dec->image))) { + jas_eprintf(""error: invalid component number in CMAP box\n""); + goto error; + } + /* Is the LUT index reasonable? */ + if (dec->cmap->data.cmap.ents[i].pcol >= + dec->pclr->data.pclr.numchans) { + jas_eprintf(""error: invalid CMAP LUT index\n""); + goto error; + } + } + } + + /* Allocate space for the channel-number to component-number LUT. */ + if (!(dec->chantocmptlut = jas_alloc2(dec->numchans, + sizeof(uint_fast16_t)))) { + jas_eprintf(""error: no memory\n""); + goto error; + } + + if (!dec->cmap) { + for (i = 0; i < dec->numchans; ++i) { + dec->chantocmptlut[i] = i; + } + } else { + cmapd = &dec->cmap->data.cmap; + pclrd = &dec->pclr->data.pclr; + cdefd = &dec->cdef->data.cdef; + for (channo = 0; channo < cmapd->numchans; ++channo) { + cmapent = &cmapd->ents[channo]; + if (cmapent->map == JP2_CMAP_DIRECT) { + dec->chantocmptlut[channo] = channo; + } else if (cmapent->map == JP2_CMAP_PALETTE) { + if (!pclrd->numlutents) { + goto error; + } + lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t)); + if (!lutents) { + goto error; + } + for (i = 0; i < pclrd->numlutents; ++i) { + lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans]; + } + newcmptno = jas_image_numcmpts(dec->image); + jas_image_depalettize(dec->image, cmapent->cmptno, + pclrd->numlutents, lutents, + JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno); + dec->chantocmptlut[channo] = newcmptno; + jas_free(lutents); +#if 0 + if (dec->cdef) { + cdefent = jp2_cdef_lookup(cdefd, channo); + if (!cdefent) { + abort(); + } + jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc)); + } else { + jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1)); + } +#else + /* suppress -Wunused-but-set-variable */ + (void)cdefd; +#endif + } else { + jas_eprintf(""error: invalid MTYP in CMAP box\n""); + goto error; + } + } + } + + /* Ensure that the number of channels being used by the decoder + matches the number of image components. */ + if (dec->numchans != jas_image_numcmpts(dec->image)) { + jas_eprintf(""error: mismatch in number of components (%d != %d)\n"", + dec->numchans, jas_image_numcmpts(dec->image)); + goto error; + } + + /* Mark all components as being of unknown type. */ + + for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { + jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN); + } + + /* Determine the type of each component. */ + if (dec->cdef) { + for (i = 0; i < dec->cdef->data.cdef.numchans; ++i) { + /* Is the channel number reasonable? */ + if (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) { + jas_eprintf(""error: invalid channel number in CDEF box\n""); + goto error; + } + jas_image_setcmpttype(dec->image, + dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo], + jp2_getct(jas_image_clrspc(dec->image), + dec->cdef->data.cdef.ents[i].type, + dec->cdef->data.cdef.ents[i].assoc)); + } + } else { + for (i = 0; i < dec->numchans; ++i) { + jas_image_setcmpttype(dec->image, dec->chantocmptlut[i], + jp2_getct(jas_image_clrspc(dec->image), 0, i + 1)); + } + } + + /* Delete any components that are not of interest. */ + for (i = jas_image_numcmpts(dec->image); i > 0; --i) { + if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) { + jas_image_delcmpt(dec->image, i - 1); + } + } + + /* Ensure that some components survived. */ + if (!jas_image_numcmpts(dec->image)) { + jas_eprintf(""error: no components\n""); + goto error; + } +#if 0 +jas_eprintf(""no of components is %d\n"", jas_image_numcmpts(dec->image)); +#endif + + /* Prevent the image from being destroyed later. */ + image = dec->image; + dec->image = 0; + + jp2_dec_destroy(dec); + + return image; + +error: + if (box) { + jp2_box_destroy(box); + } + if (dec) { + jp2_dec_destroy(dec); + } + return 0; +}","jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr) +{ + jp2_box_t *box; + int found; + jas_image_t *image; + jp2_dec_t *dec; + bool samedtype; + int dtype; + unsigned int i; + jp2_cmap_t *cmapd; + jp2_pclr_t *pclrd; + jp2_cdef_t *cdefd; + unsigned int channo; + int newcmptno; + int_fast32_t *lutents; +#if 0 + jp2_cdefchan_t *cdefent; + int cmptno; +#endif + jp2_cmapent_t *cmapent; + jas_icchdr_t icchdr; + jas_iccprof_t *iccprof; + + dec = 0; + box = 0; + image = 0; + + JAS_DBGLOG(100, (""jp2_decode(%p, \""%s\"")\n"", in, optstr)); + + if (!(dec = jp2_dec_create())) { + goto error; + } + + /* Get the first box. This should be a JP box. */ + if (!(box = jp2_box_get(in))) { + jas_eprintf(""error: cannot get box\n""); + goto error; + } + if (box->type != JP2_BOX_JP) { + jas_eprintf(""error: expecting signature box\n""); + goto error; + } + if (box->data.jp.magic != JP2_JP_MAGIC) { + jas_eprintf(""incorrect magic number\n""); + goto error; + } + jp2_box_destroy(box); + box = 0; + + /* Get the second box. This should be a FTYP box. */ + if (!(box = jp2_box_get(in))) { + goto error; + } + if (box->type != JP2_BOX_FTYP) { + jas_eprintf(""expecting file type box\n""); + goto error; + } + jp2_box_destroy(box); + box = 0; + + /* Get more boxes... */ + found = 0; + while ((box = jp2_box_get(in))) { + if (jas_getdbglevel() >= 1) { + jas_eprintf(""got box type %s\n"", box->info->name); + } + switch (box->type) { + case JP2_BOX_JP2C: + found = 1; + break; + case JP2_BOX_IHDR: + if (!dec->ihdr) { + dec->ihdr = box; + box = 0; + } + break; + case JP2_BOX_BPCC: + if (!dec->bpcc) { + dec->bpcc = box; + box = 0; + } + break; + case JP2_BOX_CDEF: + if (!dec->cdef) { + dec->cdef = box; + box = 0; + } + break; + case JP2_BOX_PCLR: + if (!dec->pclr) { + dec->pclr = box; + box = 0; + } + break; + case JP2_BOX_CMAP: + if (!dec->cmap) { + dec->cmap = box; + box = 0; + } + break; + case JP2_BOX_COLR: + if (!dec->colr) { + dec->colr = box; + box = 0; + } + break; + } + if (box) { + jp2_box_destroy(box); + box = 0; + } + if (found) { + break; + } + } + + if (!found) { + jas_eprintf(""error: no code stream found\n""); + goto error; + } + + if (!(dec->image = jpc_decode(in, optstr))) { + jas_eprintf(""error: cannot decode code stream\n""); + goto error; + } + + /* An IHDR box must be present. */ + if (!dec->ihdr) { + jas_eprintf(""error: missing IHDR box\n""); + goto error; + } + + /* Does the number of components indicated in the IHDR box match + the value specified in the code stream? */ + if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint, + jas_image_numcmpts(dec->image))) { + jas_eprintf(""error: number of components mismatch (IHDR)\n""); + goto error; + } + + /* At least one component must be present. */ + if (!jas_image_numcmpts(dec->image)) { + jas_eprintf(""error: no components\n""); + goto error; + } + + /* Determine if all components have the same data type. */ + samedtype = true; + dtype = jas_image_cmptdtype(dec->image, 0); + for (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { + if (jas_image_cmptdtype(dec->image, i) != dtype) { + samedtype = false; + break; + } + } + + /* Is the component data type indicated in the IHDR box consistent + with the data in the code stream? */ + if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) || + (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) { + jas_eprintf(""error: component data type mismatch (IHDR)\n""); + goto error; + } + + /* Is the compression type supported? */ + if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) { + jas_eprintf(""error: unsupported compression type\n""); + goto error; + } + + if (dec->bpcc) { + /* Is the number of components indicated in the BPCC box + consistent with the code stream data? */ + if (dec->bpcc->data.bpcc.numcmpts != + JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) { + jas_eprintf(""error: number of components mismatch (BPCC)\n""); + goto error; + } + /* Is the component data type information indicated in the BPCC + box consistent with the code stream data? */ + if (!samedtype) { + for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); + ++i) { + if (jas_image_cmptdtype(dec->image, i) != + JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) { + jas_eprintf(""error: component data type mismatch (BPCC)\n""); + goto error; + } + } + } else { + jas_eprintf(""warning: superfluous BPCC box\n""); + } + } + + /* A COLR box must be present. */ + if (!dec->colr) { + jas_eprintf(""error: no COLR box\n""); + goto error; + } + + switch (dec->colr->data.colr.method) { + case JP2_COLR_ENUM: + jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr)); + break; + case JP2_COLR_ICC: + iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp, + dec->colr->data.colr.iccplen); + if (!iccprof) { + jas_eprintf(""error: failed to parse ICC profile\n""); + goto error; + } + jas_iccprof_gethdr(iccprof, &icchdr); + jas_eprintf(""ICC Profile CS %08x\n"", icchdr.colorspc); + jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc)); + dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof); + if (!dec->image->cmprof_) { + jas_iccprof_destroy(iccprof); + goto error; + } + jas_iccprof_destroy(iccprof); + break; + } + + /* If a CMAP box is present, a PCLR box must also be present. */ + if (dec->cmap && !dec->pclr) { + jas_eprintf(""warning: missing PCLR box or superfluous CMAP box\n""); + jp2_box_destroy(dec->cmap); + dec->cmap = 0; + } + + /* If a CMAP box is not present, a PCLR box must not be present. */ + if (!dec->cmap && dec->pclr) { + jas_eprintf(""warning: missing CMAP box or superfluous PCLR box\n""); + jp2_box_destroy(dec->pclr); + dec->pclr = 0; + } + + /* Determine the number of channels (which is essentially the number + of components after any palette mappings have been applied). */ + dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : + JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); + + /* Perform a basic sanity check on the CMAP box if present. */ + if (dec->cmap) { + for (i = 0; i < dec->numchans; ++i) { + /* Is the component number reasonable? */ + if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint, + jas_image_numcmpts(dec->image))) { + jas_eprintf(""error: invalid component number in CMAP box\n""); + goto error; + } + /* Is the LUT index reasonable? */ + if (dec->cmap->data.cmap.ents[i].pcol >= + dec->pclr->data.pclr.numchans) { + jas_eprintf(""error: invalid CMAP LUT index\n""); + goto error; + } + } + } + + /* Allocate space for the channel-number to component-number LUT. */ + if (!(dec->chantocmptlut = jas_alloc2(dec->numchans, + sizeof(uint_fast16_t)))) { + jas_eprintf(""error: no memory\n""); + goto error; + } + + if (!dec->cmap) { + for (i = 0; i < dec->numchans; ++i) { + dec->chantocmptlut[i] = i; + } + } else { + cmapd = &dec->cmap->data.cmap; + pclrd = &dec->pclr->data.pclr; + cdefd = &dec->cdef->data.cdef; + for (channo = 0; channo < cmapd->numchans; ++channo) { + cmapent = &cmapd->ents[channo]; + if (cmapent->map == JP2_CMAP_DIRECT) { + dec->chantocmptlut[channo] = channo; + } else if (cmapent->map == JP2_CMAP_PALETTE) { + if (!pclrd->numlutents) { + goto error; + } + lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t)); + if (!lutents) { + goto error; + } + for (i = 0; i < pclrd->numlutents; ++i) { + lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans]; + } + newcmptno = jas_image_numcmpts(dec->image); + jas_image_depalettize(dec->image, cmapent->cmptno, + pclrd->numlutents, lutents, + JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno); + dec->chantocmptlut[channo] = newcmptno; + jas_free(lutents); +#if 0 + if (dec->cdef) { + cdefent = jp2_cdef_lookup(cdefd, channo); + if (!cdefent) { + abort(); + } + jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc)); + } else { + jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1)); + } +#else + /* suppress -Wunused-but-set-variable */ + (void)cdefd; +#endif + } else { + jas_eprintf(""error: invalid MTYP in CMAP box\n""); + goto error; + } + } + } + + /* Ensure that the number of channels being used by the decoder + matches the number of image components. */ + if (dec->numchans != jas_image_numcmpts(dec->image)) { + jas_eprintf(""error: mismatch in number of components (%d != %d)\n"", + dec->numchans, jas_image_numcmpts(dec->image)); + goto error; + } + + /* Mark all components as being of unknown type. */ + + for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { + jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN); + } + + /* Determine the type of each component. */ + if (dec->cdef) { + for (i = 0; i < dec->cdef->data.cdef.numchans; ++i) { + /* Is the channel number reasonable? */ + if (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) { + jas_eprintf(""error: invalid channel number in CDEF box\n""); + goto error; + } + jas_image_setcmpttype(dec->image, + dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo], + jp2_getct(jas_image_clrspc(dec->image), + dec->cdef->data.cdef.ents[i].type, + dec->cdef->data.cdef.ents[i].assoc)); + } + } else { + for (i = 0; i < dec->numchans; ++i) { + jas_image_setcmpttype(dec->image, dec->chantocmptlut[i], + jp2_getct(jas_image_clrspc(dec->image), 0, i + 1)); + } + } + + /* Delete any components that are not of interest. */ + for (i = jas_image_numcmpts(dec->image); i > 0; --i) { + if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) { + jas_image_delcmpt(dec->image, i - 1); + } + } + + /* Ensure that some components survived. */ + if (!jas_image_numcmpts(dec->image)) { + jas_eprintf(""error: no components\n""); + goto error; + } +#if 0 +jas_eprintf(""no of components is %d\n"", jas_image_numcmpts(dec->image)); +#endif + + /* Prevent the image from being destroyed later. */ + image = dec->image; + dec->image = 0; + + jp2_dec_destroy(dec); + + return image; + +error: + if (box) { + jp2_box_destroy(box); + } + if (dec) { + jp2_dec_destroy(dec); + } + return 0; +}","{'deleted': [{'line_no': 137, 'char_start': 2575, 'char_end': 2634, 'line': '\t\tjas_eprintf(""warning: number of components mismatch\\n"");\n'}, {'line_no': 160, 'char_start': 3325, 'char_end': 3390, 'line': '\t\tjas_eprintf(""warning: component data type mismatch (IHDR)\\n"");\n'}, {'line_no': 172, 'char_start': 3691, 'char_end': 3769, 'line': '\t\tif (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts(\n'}, {'line_no': 173, 'char_start': 3769, 'char_end': 3789, 'line': '\t\t dec->image))) {\n'}, {'line_no': 174, 'char_start': 3789, 'char_end': 3849, 'line': '\t\t\tjas_eprintf(""warning: number of components mismatch\\n"");\n'}, {'line_no': 183, 'char_start': 4171, 'char_end': 4239, 'line': '\t\t\t\t\tjas_eprintf(""warning: component data type mismatch (BPCC)\\n"");\n'}], 'added': [{'line_no': 137, 'char_start': 2575, 'char_end': 2639, 'line': '\t\tjas_eprintf(""error: number of components mismatch (IHDR)\\n"");\n'}, {'line_no': 138, 'char_start': 2639, 'char_end': 2653, 'line': '\t\tgoto error;\n'}, {'line_no': 161, 'char_start': 3344, 'char_end': 3407, 'line': '\t\tjas_eprintf(""error: component data type mismatch (IHDR)\\n"");\n'}, {'line_no': 162, 'char_start': 3407, 'char_end': 3421, 'line': '\t\tgoto error;\n'}, {'line_no': 174, 'char_start': 3722, 'char_end': 3761, 'line': '\t\tif (dec->bpcc->data.bpcc.numcmpts !=\n'}, {'line_no': 175, 'char_start': 3761, 'char_end': 3819, 'line': '\t\t JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) {\n'}, {'line_no': 176, 'char_start': 3819, 'char_end': 3884, 'line': '\t\t\tjas_eprintf(""error: number of components mismatch (BPCC)\\n"");\n'}, {'line_no': 177, 'char_start': 3884, 'char_end': 3899, 'line': '\t\t\tgoto error;\n'}, {'line_no': 186, 'char_start': 4221, 'char_end': 4287, 'line': '\t\t\t\t\tjas_eprintf(""error: component data type mismatch (BPCC)\\n"");\n'}, {'line_no': 187, 'char_start': 4287, 'char_end': 4305, 'line': '\t\t\t\t\t\tgoto error;\n'}]}","{'deleted': [{'char_start': 2590, 'char_end': 2592, 'chars': 'wa'}, {'char_start': 2593, 'char_end': 2597, 'chars': 'ning'}, {'char_start': 3340, 'char_end': 3342, 'chars': 'wa'}, {'char_start': 3343, 'char_end': 3347, 'chars': 'ning'}, {'char_start': 3768, 'char_end': 3773, 'chars': '\n\t\t '}, {'char_start': 3805, 'char_end': 3807, 'chars': 'wa'}, {'char_start': 3808, 'char_end': 3812, 'chars': 'ning'}, {'char_start': 4189, 'char_end': 4191, 'chars': 'wa'}, {'char_start': 4192, 'char_end': 4196, 'chars': 'ning'}], 'added': [{'char_start': 2590, 'char_end': 2594, 'chars': 'erro'}, {'char_start': 2626, 'char_end': 2633, 'chars': ' (IHDR)'}, {'char_start': 2639, 'char_end': 2653, 'chars': '\t\tgoto error;\n'}, {'char_start': 3359, 'char_end': 3363, 'chars': 'erro'}, {'char_start': 3407, 'char_end': 3421, 'chars': '\t\tgoto error;\n'}, {'char_start': 3760, 'char_end': 3764, 'chars': '\n\t\t '}, {'char_start': 3835, 'char_end': 3839, 'chars': 'erro'}, {'char_start': 3871, 'char_end': 3878, 'chars': ' (BPCC)'}, {'char_start': 3884, 'char_end': 3899, 'chars': '\t\t\tgoto error;\n'}, {'char_start': 4239, 'char_end': 4243, 'chars': 'erro'}, {'char_start': 4285, 'char_end': 4303, 'chars': ';\n\t\t\t\t\t\tgoto error'}]}",github.com/jasper-software/jasper/commit/41f214b121b837fa30d9ca5f2430212110f5cd9b,src/libjasper/jp2/jp2_dec.c,cwe-125, +cwe-125,get_conn_text,"static inline void get_conn_text(const conn *c, const int af, + char* addr, struct sockaddr *sock_addr) { + char addr_text[MAXPATHLEN]; + addr_text[0] = '\0'; + const char *protoname = ""?""; + unsigned short port = 0; + + switch (af) { + case AF_INET: + (void) inet_ntop(af, + &((struct sockaddr_in *)sock_addr)->sin_addr, + addr_text, + sizeof(addr_text) - 1); + port = ntohs(((struct sockaddr_in *)sock_addr)->sin_port); + protoname = IS_UDP(c->transport) ? ""udp"" : ""tcp""; + break; + + case AF_INET6: + addr_text[0] = '['; + addr_text[1] = '\0'; + if (inet_ntop(af, + &((struct sockaddr_in6 *)sock_addr)->sin6_addr, + addr_text + 1, + sizeof(addr_text) - 2)) { + strcat(addr_text, ""]""); + } + port = ntohs(((struct sockaddr_in6 *)sock_addr)->sin6_port); + protoname = IS_UDP(c->transport) ? ""udp6"" : ""tcp6""; + break; + + case AF_UNIX: + strncpy(addr_text, + ((struct sockaddr_un *)sock_addr)->sun_path, + sizeof(addr_text) - 1); + addr_text[sizeof(addr_text)-1] = '\0'; + protoname = ""unix""; + break; + } + + if (strlen(addr_text) < 2) { + /* Most likely this is a connected UNIX-domain client which + * has no peer socket address, but there's no portable way + * to tell for sure. + */ + sprintf(addr_text, """", af); + } + + if (port) { + sprintf(addr, ""%s:%s:%u"", protoname, addr_text, port); + } else { + sprintf(addr, ""%s:%s"", protoname, addr_text); + } +}","static inline void get_conn_text(const conn *c, const int af, + char* addr, struct sockaddr *sock_addr) { + char addr_text[MAXPATHLEN]; + addr_text[0] = '\0'; + const char *protoname = ""?""; + unsigned short port = 0; + size_t pathlen = 0; + + switch (af) { + case AF_INET: + (void) inet_ntop(af, + &((struct sockaddr_in *)sock_addr)->sin_addr, + addr_text, + sizeof(addr_text) - 1); + port = ntohs(((struct sockaddr_in *)sock_addr)->sin_port); + protoname = IS_UDP(c->transport) ? ""udp"" : ""tcp""; + break; + + case AF_INET6: + addr_text[0] = '['; + addr_text[1] = '\0'; + if (inet_ntop(af, + &((struct sockaddr_in6 *)sock_addr)->sin6_addr, + addr_text + 1, + sizeof(addr_text) - 2)) { + strcat(addr_text, ""]""); + } + port = ntohs(((struct sockaddr_in6 *)sock_addr)->sin6_port); + protoname = IS_UDP(c->transport) ? ""udp6"" : ""tcp6""; + break; + + case AF_UNIX: + // this strncpy call originally could piss off an address + // sanitizer; we supplied the size of the dest buf as a limiter, + // but optimized versions of strncpy could read past the end of + // *src while looking for a null terminator. Since buf and + // sun_path here are both on the stack they could even overlap, + // which is ""undefined"". In all OSS versions of strncpy I could + // find this has no effect; it'll still only copy until the first null + // terminator is found. Thus it's possible to get the OS to + // examine past the end of sun_path but it's unclear to me if this + // can cause any actual problem. + // + // We need a safe_strncpy util function but I'll punt on figuring + // that out for now. + pathlen = sizeof(((struct sockaddr_un *)sock_addr)->sun_path); + if (MAXPATHLEN <= pathlen) { + pathlen = MAXPATHLEN - 1; + } + strncpy(addr_text, + ((struct sockaddr_un *)sock_addr)->sun_path, + pathlen); + addr_text[pathlen] = '\0'; + protoname = ""unix""; + break; + } + + if (strlen(addr_text) < 2) { + /* Most likely this is a connected UNIX-domain client which + * has no peer socket address, but there's no portable way + * to tell for sure. + */ + sprintf(addr_text, """", af); + } + + if (port) { + sprintf(addr, ""%s:%s:%u"", protoname, addr_text, port); + } else { + sprintf(addr, ""%s:%s"", protoname, addr_text); + } +}","{'deleted': [{'line_no': 34, 'char_start': 1203, 'char_end': 1247, 'line': ' sizeof(addr_text) - 1);\n'}, {'line_no': 35, 'char_start': 1247, 'char_end': 1298, 'line': "" addr_text[sizeof(addr_text)-1] = '\\0';\n""}], 'added': [{'line_no': 7, 'char_start': 239, 'char_end': 263, 'line': ' size_t pathlen = 0;\n'}, {'line_no': 46, 'char_start': 1982, 'char_end': 2057, 'line': ' pathlen = sizeof(((struct sockaddr_un *)sock_addr)->sun_path);\n'}, {'line_no': 47, 'char_start': 2057, 'char_end': 2098, 'line': ' if (MAXPATHLEN <= pathlen) {\n'}, {'line_no': 48, 'char_start': 2098, 'char_end': 2140, 'line': ' pathlen = MAXPATHLEN - 1;\n'}, {'line_no': 49, 'char_start': 2140, 'char_end': 2154, 'line': ' }\n'}, {'line_no': 52, 'char_start': 2250, 'char_end': 2280, 'line': ' pathlen);\n'}, {'line_no': 53, 'char_start': 2280, 'char_end': 2319, 'line': "" addr_text[pathlen] = '\\0';\n""}]}","{'deleted': [{'char_start': 1223, 'char_end': 1230, 'chars': 'sizeof('}, {'char_start': 1231, 'char_end': 1235, 'chars': 'ddr_'}, {'char_start': 1237, 'char_end': 1244, 'chars': 'xt) - 1'}, {'char_start': 1269, 'char_end': 1276, 'chars': 'sizeof('}, {'char_start': 1277, 'char_end': 1281, 'chars': 'ddr_'}, {'char_start': 1283, 'char_end': 1288, 'chars': 'xt)-1'}], 'added': [{'char_start': 239, 'char_end': 263, 'chars': ' size_t pathlen = 0;\n'}, {'char_start': 1131, 'char_end': 2154, 'chars': ' // this strncpy call originally could piss off an address\n // sanitizer; we supplied the size of the dest buf as a limiter,\n // but optimized versions of strncpy could read past the end of\n // *src while looking for a null terminator. Since buf and\n // sun_path here are both on the stack they could even overlap,\n // which is ""undefined"". In all OSS versions of strncpy I could\n // find this has no effect; it\'ll still only copy until the first null\n // terminator is found. Thus it\'s possible to get the OS to\n // examine past the end of sun_path but it\'s unclear to me if this\n // can cause any actual problem.\n //\n // We need a safe_strncpy util function but I\'ll punt on figuring\n // that out for now.\n pathlen = sizeof(((struct sockaddr_un *)sock_addr)->sun_path);\n if (MAXPATHLEN <= pathlen) {\n pathlen = MAXPATHLEN - 1;\n }\n'}, {'char_start': 2270, 'char_end': 2271, 'chars': 'p'}, {'char_start': 2273, 'char_end': 2275, 'chars': 'hl'}, {'char_start': 2276, 'char_end': 2277, 'chars': 'n'}, {'char_start': 2302, 'char_end': 2303, 'chars': 'p'}, {'char_start': 2305, 'char_end': 2307, 'chars': 'hl'}, {'char_start': 2308, 'char_end': 2309, 'chars': 'n'}]}",github.com/memcached/memcached/commit/554b56687a19300a75ec24184746b5512580c819,memcached.c,cwe-125, +cwe-125,parse_sec_attr_44,"static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len) +{ + /* OpenSc Operation values for each command operation-type */ + const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/ + SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE, + SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, + SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1}; + const int ef_idx[8] = { + SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, + SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, + -1, SC_AC_OP_ERASE, -1}; + const int efi_idx[8] = { /* internal EF used for RSA keys */ + SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE, + SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, + -1, SC_AC_OP_ERASE, -1}; + + u8 bValue; + int i; + int iKeyRef = 0; + int iMethod; + int iPinCount; + int iOffset = 0; + int iOperation; + const int* p_idx; + + /* Check all sub-AC definitions within the total AC */ + while (len > 1) { /* minimum length = 2 */ + size_t iACLen = buf[iOffset] & 0x0F; + if (iACLen > len) + break; + + iMethod = SC_AC_NONE; /* default no authentication required */ + + if (buf[iOffset] & 0X80) { /* AC in adaptive coding */ + /* Evaluates only the command-byte, not the optional P1/P2/Option bytes */ + size_t iParmLen = 1; /* command-byte is always present */ + size_t iKeyLen = 0; /* Encryption key is optional */ + + if (buf[iOffset] & 0x20) iKeyLen++; + if (buf[iOffset+1] & 0x40) iParmLen++; + if (buf[iOffset+1] & 0x20) iParmLen++; + if (buf[iOffset+1] & 0x10) iParmLen++; + if (buf[iOffset+1] & 0x08) iParmLen++; + + /* Get KeyNumber if available */ + if(iKeyLen) { + int iSC; + if (len < 1+(size_t)iACLen) + break; + iSC = buf[iOffset+iACLen]; + + switch( (iSC>>5) & 0x03 ){ + case 0: + iMethod = SC_AC_TERM; /* key authentication */ + break; + case 1: + iMethod = SC_AC_AUT; /* key authentication */ + break; + case 2: + case 3: + iMethod = SC_AC_PRO; /* secure messaging */ + break; + } + iKeyRef = iSC & 0x1F; /* get key number */ + } + + /* Get PinNumber if available */ + if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */ + if (len < 1+1+1+(size_t)iParmLen) + break; + iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */ + iMethod = SC_AC_CHV; + } + + /* Convert SETCOS command to OpenSC command group */ + if (len < 1+2) + break; + switch(buf[iOffset+2]){ + case 0x2A: /* crypto operation */ + iOperation = SC_AC_OP_CRYPTO; + break; + case 0x46: /* key-generation operation */ + iOperation = SC_AC_OP_UPDATE; + break; + default: + iOperation = SC_AC_OP_SELECT; + break; + } + sc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef); + } + else { /* AC in simple coding */ + /* Initial AC is treated as an operational AC */ + + /* Get specific Cmd groups for specified file-type */ + switch (file->type) { + case SC_FILE_TYPE_DF: /* DF */ + p_idx = df_idx; + break; + case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */ + p_idx = efi_idx; + break; + default: /* EF */ + p_idx = ef_idx; + break; + } + + /* Encryption key present ? */ + iPinCount = iACLen - 1; + + if (buf[iOffset] & 0x20) { + int iSC; + if (len < 1 + (size_t)iACLen) + break; + iSC = buf[iOffset + iACLen]; + + switch( (iSC>>5) & 0x03 ) { + case 0: + iMethod = SC_AC_TERM; /* key authentication */ + break; + case 1: + iMethod = SC_AC_AUT; /* key authentication */ + break; + case 2: + case 3: + iMethod = SC_AC_PRO; /* secure messaging */ + break; + } + iKeyRef = iSC & 0x1F; /* get key number */ + + iPinCount--; /* one byte used for keyReference */ + } + + /* Pin present ? */ + if ( iPinCount > 0 ) { + if (len < 1 + 2) + break; + iKeyRef = buf[iOffset + 2]; /* pin ref */ + iMethod = SC_AC_CHV; + } + + /* Add AC for each command-operationType into OpenSc structure */ + bValue = buf[iOffset + 1]; + for (i = 0; i < 8; i++) { + if((bValue & 1) && (p_idx[i] >= 0)) + sc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef); + bValue >>= 1; + } + } + /* Current field treated, get next AC sub-field */ + iOffset += iACLen +1; /* AC + PTL-byte */ + len -= iACLen +1; + } +}","static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len) +{ + /* OpenSc Operation values for each command operation-type */ + const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/ + SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE, + SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, + SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1}; + const int ef_idx[8] = { + SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, + SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, + -1, SC_AC_OP_ERASE, -1}; + const int efi_idx[8] = { /* internal EF used for RSA keys */ + SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE, + SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, + -1, SC_AC_OP_ERASE, -1}; + + u8 bValue; + int i; + int iKeyRef = 0; + int iMethod; + int iPinCount; + int iOffset = 0; + int iOperation; + const int* p_idx; + + /* Check all sub-AC definitions within the total AC */ + while (len > 1) { /* minimum length = 2 */ + size_t iACLen = buf[iOffset] & 0x0F; + if (iACLen > len) + break; + + iMethod = SC_AC_NONE; /* default no authentication required */ + + if (buf[iOffset] & 0X80) { /* AC in adaptive coding */ + /* Evaluates only the command-byte, not the optional P1/P2/Option bytes */ + size_t iParmLen = 1; /* command-byte is always present */ + size_t iKeyLen = 0; /* Encryption key is optional */ + + if (buf[iOffset] & 0x20) iKeyLen++; + if (buf[iOffset+1] & 0x40) iParmLen++; + if (buf[iOffset+1] & 0x20) iParmLen++; + if (buf[iOffset+1] & 0x10) iParmLen++; + if (buf[iOffset+1] & 0x08) iParmLen++; + + /* Get KeyNumber if available */ + if(iKeyLen) { + int iSC; + if (len < 1+(size_t)iACLen) + break; + iSC = buf[iOffset+iACLen]; + + switch( (iSC>>5) & 0x03 ){ + case 0: + iMethod = SC_AC_TERM; /* key authentication */ + break; + case 1: + iMethod = SC_AC_AUT; /* key authentication */ + break; + case 2: + case 3: + iMethod = SC_AC_PRO; /* secure messaging */ + break; + } + iKeyRef = iSC & 0x1F; /* get key number */ + } + + /* Get PinNumber if available */ + if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */ + if (len < 1+1+1+(size_t)iParmLen) + break; + iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */ + iMethod = SC_AC_CHV; + } + + /* Convert SETCOS command to OpenSC command group */ + if (len < 1+2) + break; + switch(buf[iOffset+2]){ + case 0x2A: /* crypto operation */ + iOperation = SC_AC_OP_CRYPTO; + break; + case 0x46: /* key-generation operation */ + iOperation = SC_AC_OP_UPDATE; + break; + default: + iOperation = SC_AC_OP_SELECT; + break; + } + sc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef); + } + else { /* AC in simple coding */ + /* Initial AC is treated as an operational AC */ + + /* Get specific Cmd groups for specified file-type */ + switch (file->type) { + case SC_FILE_TYPE_DF: /* DF */ + p_idx = df_idx; + break; + case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */ + p_idx = efi_idx; + break; + default: /* EF */ + p_idx = ef_idx; + break; + } + + /* Encryption key present ? */ + iPinCount = iACLen > 0 ? iACLen - 1 : 0; + + if (buf[iOffset] & 0x20) { + int iSC; + if (len < 1 + (size_t)iACLen) + break; + iSC = buf[iOffset + iACLen]; + + switch( (iSC>>5) & 0x03 ) { + case 0: + iMethod = SC_AC_TERM; /* key authentication */ + break; + case 1: + iMethod = SC_AC_AUT; /* key authentication */ + break; + case 2: + case 3: + iMethod = SC_AC_PRO; /* secure messaging */ + break; + } + iKeyRef = iSC & 0x1F; /* get key number */ + + iPinCount--; /* one byte used for keyReference */ + } + + /* Pin present ? */ + if ( iPinCount > 0 ) { + if (len < 1 + 2) + break; + iKeyRef = buf[iOffset + 2]; /* pin ref */ + iMethod = SC_AC_CHV; + } + + /* Add AC for each command-operationType into OpenSc structure */ + bValue = buf[iOffset + 1]; + for (i = 0; i < 8; i++) { + if((bValue & 1) && (p_idx[i] >= 0)) + sc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef); + bValue >>= 1; + } + } + /* Current field treated, get next AC sub-field */ + iOffset += iACLen +1; /* AC + PTL-byte */ + len -= iACLen +1; + } +}","{'deleted': [{'line_no': 108, 'char_start': 3184, 'char_end': 3213, 'line': '\t\t\tiPinCount = iACLen - 1;\t\t\n'}], 'added': [{'line_no': 108, 'char_start': 3184, 'char_end': 3228, 'line': '\t\t\tiPinCount = iACLen > 0 ? iACLen - 1 : 0;\n'}]}","{'deleted': [{'char_start': 3210, 'char_end': 3212, 'chars': '\t\t'}], 'added': [{'char_start': 3206, 'char_end': 3219, 'chars': '> 0 ? iACLen '}, {'char_start': 3222, 'char_end': 3226, 'chars': ' : 0'}]}",github.com/OpenSC/OpenSC/commit/c3f23b836e5a1766c36617fe1da30d22f7b63de2,src/libopensc/card-setcos.c,cwe-125, +cwe-125,do_core_note,"do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, + int swap, uint32_t namesz, uint32_t descsz, + size_t noff, size_t doff, int *flags, size_t size, int clazz) +{ +#ifdef ELFCORE + int os_style = -1; + /* + * Sigh. The 2.0.36 kernel in Debian 2.1, at + * least, doesn't correctly implement name + * sections, in core dumps, as specified by + * the ""Program Linking"" section of ""UNIX(R) System + * V Release 4 Programmer's Guide: ANSI C and + * Programming Support Tools"", because my copy + * clearly says ""The first 'namesz' bytes in 'name' + * contain a *null-terminated* [emphasis mine] + * character representation of the entry's owner + * or originator"", but the 2.0.36 kernel code + * doesn't include the terminating null in the + * name.... + */ + if ((namesz == 4 && strncmp((char *)&nbuf[noff], ""CORE"", 4) == 0) || + (namesz == 5 && strcmp((char *)&nbuf[noff], ""CORE"") == 0)) { + os_style = OS_STYLE_SVR4; + } + + if ((namesz == 8 && strcmp((char *)&nbuf[noff], ""FreeBSD"") == 0)) { + os_style = OS_STYLE_FREEBSD; + } + + if ((namesz >= 11 && strncmp((char *)&nbuf[noff], ""NetBSD-CORE"", 11) + == 0)) { + os_style = OS_STYLE_NETBSD; + } + + if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { + if (file_printf(ms, "", %s-style"", os_style_names[os_style]) + == -1) + return 1; + *flags |= FLAGS_DID_CORE_STYLE; + *flags |= os_style; + } + + switch (os_style) { + case OS_STYLE_NETBSD: + if (type == NT_NETBSD_CORE_PROCINFO) { + char sbuf[512]; + struct NetBSD_elfcore_procinfo pi; + memset(&pi, 0, sizeof(pi)); + memcpy(&pi, nbuf + doff, descsz); + + if (file_printf(ms, "", from '%.31s', pid=%u, uid=%u, "" + ""gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)"", + file_printable(sbuf, sizeof(sbuf), + CAST(char *, pi.cpi_name)), + elf_getu32(swap, (uint32_t)pi.cpi_pid), + elf_getu32(swap, pi.cpi_euid), + elf_getu32(swap, pi.cpi_egid), + elf_getu32(swap, pi.cpi_nlwps), + elf_getu32(swap, (uint32_t)pi.cpi_siglwp), + elf_getu32(swap, pi.cpi_signo), + elf_getu32(swap, pi.cpi_sigcode)) == -1) + return 1; + + *flags |= FLAGS_DID_CORE; + return 1; + } + break; + + default: + if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { + size_t i, j; + unsigned char c; + /* + * Extract the program name. We assume + * it to be 16 characters (that's what it + * is in SunOS 5.x and Linux). + * + * Unfortunately, it's at a different offset + * in various OSes, so try multiple offsets. + * If the characters aren't all printable, + * reject it. + */ + for (i = 0; i < NOFFSETS; i++) { + unsigned char *cname, *cp; + size_t reloffset = prpsoffsets(i); + size_t noffset = doff + reloffset; + size_t k; + for (j = 0; j < 16; j++, noffset++, + reloffset++) { + /* + * Make sure we're not past + * the end of the buffer; if + * we are, just give up. + */ + if (noffset >= size) + goto tryanother; + + /* + * Make sure we're not past + * the end of the contents; + * if we are, this obviously + * isn't the right offset. + */ + if (reloffset >= descsz) + goto tryanother; + + c = nbuf[noffset]; + if (c == '\0') { + /* + * A '\0' at the + * beginning is + * obviously wrong. + * Any other '\0' + * means we're done. + */ + if (j == 0) + goto tryanother; + else + break; + } else { + /* + * A nonprintable + * character is also + * wrong. + */ + if (!isprint(c) || isquote(c)) + goto tryanother; + } + } + /* + * Well, that worked. + */ + + /* + * Try next offsets, in case this match is + * in the middle of a string. + */ + for (k = i + 1 ; k < NOFFSETS; k++) { + size_t no; + int adjust = 1; + if (prpsoffsets(k) >= prpsoffsets(i)) + continue; + for (no = doff + prpsoffsets(k); + no < doff + prpsoffsets(i); no++) + adjust = adjust + && isprint(nbuf[no]); + if (adjust) + i = k; + } + + cname = (unsigned char *) + &nbuf[doff + prpsoffsets(i)]; + for (cp = cname; *cp && isprint(*cp); cp++) + continue; + /* + * Linux apparently appends a space at the end + * of the command line: remove it. + */ + while (cp > cname && isspace(cp[-1])) + cp--; + if (file_printf(ms, "", from '%.*s'"", + (int)(cp - cname), cname) == -1) + return 1; + *flags |= FLAGS_DID_CORE; + return 1; + + tryanother: + ; + } + } + break; + } +#endif + return 0; +}","do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, + int swap, uint32_t namesz, uint32_t descsz, + size_t noff, size_t doff, int *flags, size_t size, int clazz) +{ +#ifdef ELFCORE + int os_style = -1; + /* + * Sigh. The 2.0.36 kernel in Debian 2.1, at + * least, doesn't correctly implement name + * sections, in core dumps, as specified by + * the ""Program Linking"" section of ""UNIX(R) System + * V Release 4 Programmer's Guide: ANSI C and + * Programming Support Tools"", because my copy + * clearly says ""The first 'namesz' bytes in 'name' + * contain a *null-terminated* [emphasis mine] + * character representation of the entry's owner + * or originator"", but the 2.0.36 kernel code + * doesn't include the terminating null in the + * name.... + */ + if ((namesz == 4 && strncmp((char *)&nbuf[noff], ""CORE"", 4) == 0) || + (namesz == 5 && strcmp((char *)&nbuf[noff], ""CORE"") == 0)) { + os_style = OS_STYLE_SVR4; + } + + if ((namesz == 8 && strcmp((char *)&nbuf[noff], ""FreeBSD"") == 0)) { + os_style = OS_STYLE_FREEBSD; + } + + if ((namesz >= 11 && strncmp((char *)&nbuf[noff], ""NetBSD-CORE"", 11) + == 0)) { + os_style = OS_STYLE_NETBSD; + } + + if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { + if (file_printf(ms, "", %s-style"", os_style_names[os_style]) + == -1) + return 1; + *flags |= FLAGS_DID_CORE_STYLE; + *flags |= os_style; + } + + switch (os_style) { + case OS_STYLE_NETBSD: + if (type == NT_NETBSD_CORE_PROCINFO) { + char sbuf[512]; + struct NetBSD_elfcore_procinfo pi; + memset(&pi, 0, sizeof(pi)); + memcpy(&pi, nbuf + doff, descsz); + + if (file_printf(ms, "", from '%.31s', pid=%u, uid=%u, "" + ""gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)"", + file_printable(sbuf, sizeof(sbuf), + CAST(char *, pi.cpi_name)), + elf_getu32(swap, (uint32_t)pi.cpi_pid), + elf_getu32(swap, pi.cpi_euid), + elf_getu32(swap, pi.cpi_egid), + elf_getu32(swap, pi.cpi_nlwps), + elf_getu32(swap, (uint32_t)pi.cpi_siglwp), + elf_getu32(swap, pi.cpi_signo), + elf_getu32(swap, pi.cpi_sigcode)) == -1) + return 1; + + *flags |= FLAGS_DID_CORE; + return 1; + } + break; + + default: + if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { + size_t i, j; + unsigned char c; + /* + * Extract the program name. We assume + * it to be 16 characters (that's what it + * is in SunOS 5.x and Linux). + * + * Unfortunately, it's at a different offset + * in various OSes, so try multiple offsets. + * If the characters aren't all printable, + * reject it. + */ + for (i = 0; i < NOFFSETS; i++) { + unsigned char *cname, *cp; + size_t reloffset = prpsoffsets(i); + size_t noffset = doff + reloffset; + size_t k; + for (j = 0; j < 16; j++, noffset++, + reloffset++) { + /* + * Make sure we're not past + * the end of the buffer; if + * we are, just give up. + */ + if (noffset >= size) + goto tryanother; + + /* + * Make sure we're not past + * the end of the contents; + * if we are, this obviously + * isn't the right offset. + */ + if (reloffset >= descsz) + goto tryanother; + + c = nbuf[noffset]; + if (c == '\0') { + /* + * A '\0' at the + * beginning is + * obviously wrong. + * Any other '\0' + * means we're done. + */ + if (j == 0) + goto tryanother; + else + break; + } else { + /* + * A nonprintable + * character is also + * wrong. + */ + if (!isprint(c) || isquote(c)) + goto tryanother; + } + } + /* + * Well, that worked. + */ + + /* + * Try next offsets, in case this match is + * in the middle of a string. + */ + for (k = i + 1 ; k < NOFFSETS; k++) { + size_t no; + int adjust = 1; + if (prpsoffsets(k) >= prpsoffsets(i)) + continue; + for (no = doff + prpsoffsets(k); + no < doff + prpsoffsets(i); no++) + adjust = adjust + && isprint(nbuf[no]); + if (adjust) + i = k; + } + + cname = (unsigned char *) + &nbuf[doff + prpsoffsets(i)]; + for (cp = cname; cp < nbuf + size && *cp + && isprint(*cp); cp++) + continue; + /* + * Linux apparently appends a space at the end + * of the command line: remove it. + */ + while (cp > cname && isspace(cp[-1])) + cp--; + if (file_printf(ms, "", from '%.*s'"", + (int)(cp - cname), cname) == -1) + return 1; + *flags |= FLAGS_DID_CORE; + return 1; + + tryanother: + ; + } + } + break; + } +#endif + return 0; +}","{'deleted': [{'line_no': 153, 'char_start': 4087, 'char_end': 4135, 'line': '\t\t\t\tfor (cp = cname; *cp && isprint(*cp); cp++)\n'}], 'added': [{'line_no': 153, 'char_start': 4087, 'char_end': 4132, 'line': '\t\t\t\tfor (cp = cname; cp < nbuf + size && *cp\n'}, {'line_no': 154, 'char_start': 4132, 'char_end': 4163, 'line': '\t\t\t\t && isprint(*cp); cp++)\n'}]}","{'deleted': [], 'added': [{'char_start': 4108, 'char_end': 4128, 'chars': 'cp < nbuf + size && '}, {'char_start': 4131, 'char_end': 4139, 'chars': '\n\t\t\t\t '}]}",github.com/file/file/commit/a642587a9c9e2dd7feacdf513c3643ce26ad3c22,src/readelf.c,cwe-125, +cwe-125,gst_asf_demux_process_ext_content_desc,"gst_asf_demux_process_ext_content_desc (GstASFDemux * demux, guint8 * data, + guint64 size) +{ + /* Other known (and unused) 'text/unicode' metadata available : + * + * WM/Lyrics = + * WM/MediaPrimaryClassID = {D1607DBC-E323-4BE2-86A1-48A42A28441E} + * WMFSDKVersion = 9.00.00.2980 + * WMFSDKNeeded = 0.0.0.0000 + * WM/UniqueFileIdentifier = AMGa_id=R 15334;AMGp_id=P 5149;AMGt_id=T 2324984 + * WM/Publisher = 4AD + * WM/Provider = AMG + * WM/ProviderRating = 8 + * WM/ProviderStyle = Rock (similar to WM/Genre) + * WM/GenreID (similar to WM/Genre) + * WM/TrackNumber (same as WM/Track but as a string) + * + * Other known (and unused) 'non-text' metadata available : + * + * WM/EncodingTime + * WM/MCDI + * IsVBR + * + * We might want to read WM/TrackNumber and use atoi() if we don't have + * WM/Track + */ + + GstTagList *taglist; + guint16 blockcount, i; + gboolean content3D = FALSE; + + struct + { + const gchar *interleave_name; + GstASF3DMode interleaving_type; + } stereoscopic_layout_map[] = { + { + ""SideBySideRF"", GST_ASF_3D_SIDE_BY_SIDE_HALF_RL}, { + ""SideBySideLF"", GST_ASF_3D_SIDE_BY_SIDE_HALF_LR}, { + ""OverUnderRT"", GST_ASF_3D_TOP_AND_BOTTOM_HALF_RL}, { + ""OverUnderLT"", GST_ASF_3D_TOP_AND_BOTTOM_HALF_LR}, { + ""DualStream"", GST_ASF_3D_DUAL_STREAM} + }; + GST_INFO_OBJECT (demux, ""object is an extended content description""); + + taglist = gst_tag_list_new_empty (); + + /* Content Descriptor Count */ + if (size < 2) + goto not_enough_data; + + blockcount = gst_asf_demux_get_uint16 (&data, &size); + + for (i = 1; i <= blockcount; ++i) { + const gchar *gst_tag_name; + guint16 datatype; + guint16 value_len; + guint16 name_len; + GValue tag_value = { 0, }; + gsize in, out; + gchar *name; + gchar *name_utf8 = NULL; + gchar *value; + + /* Descriptor */ + if (!gst_asf_demux_get_string (&name, &name_len, &data, &size)) + goto not_enough_data; + + if (size < 2) { + g_free (name); + goto not_enough_data; + } + /* Descriptor Value Data Type */ + datatype = gst_asf_demux_get_uint16 (&data, &size); + + /* Descriptor Value (not really a string, but same thing reading-wise) */ + if (!gst_asf_demux_get_string (&value, &value_len, &data, &size)) { + g_free (name); + goto not_enough_data; + } + + name_utf8 = + g_convert (name, name_len, ""UTF-8"", ""UTF-16LE"", &in, &out, NULL); + + if (name_utf8 != NULL) { + GST_DEBUG (""Found tag/metadata %s"", name_utf8); + + gst_tag_name = gst_asf_demux_get_gst_tag_from_tag_name (name_utf8); + GST_DEBUG (""gst_tag_name %s"", GST_STR_NULL (gst_tag_name)); + + switch (datatype) { + case ASF_DEMUX_DATA_TYPE_UTF16LE_STRING:{ + gchar *value_utf8; + + value_utf8 = g_convert (value, value_len, ""UTF-8"", ""UTF-16LE"", + &in, &out, NULL); + + /* get rid of tags with empty value */ + if (value_utf8 != NULL && *value_utf8 != '\0') { + GST_DEBUG (""string value %s"", value_utf8); + + value_utf8[out] = '\0'; + + if (gst_tag_name != NULL) { + if (strcmp (gst_tag_name, GST_TAG_DATE_TIME) == 0) { + guint year = atoi (value_utf8); + + if (year > 0) { + g_value_init (&tag_value, GST_TYPE_DATE_TIME); + g_value_take_boxed (&tag_value, gst_date_time_new_y (year)); + } + } else if (strcmp (gst_tag_name, GST_TAG_GENRE) == 0) { + guint id3v1_genre_id; + const gchar *genre_str; + + if (sscanf (value_utf8, ""(%u)"", &id3v1_genre_id) == 1 && + ((genre_str = gst_tag_id3_genre_get (id3v1_genre_id)))) { + GST_DEBUG (""Genre: %s -> %s"", value_utf8, genre_str); + g_free (value_utf8); + value_utf8 = g_strdup (genre_str); + } + } else { + GType tag_type; + + /* convert tag from string to other type if required */ + tag_type = gst_tag_get_type (gst_tag_name); + g_value_init (&tag_value, tag_type); + if (!gst_value_deserialize (&tag_value, value_utf8)) { + GValue from_val = { 0, }; + + g_value_init (&from_val, G_TYPE_STRING); + g_value_set_string (&from_val, value_utf8); + if (!g_value_transform (&from_val, &tag_value)) { + GST_WARNING_OBJECT (demux, + ""Could not transform string tag to "" ""%s tag type %s"", + gst_tag_name, g_type_name (tag_type)); + g_value_unset (&tag_value); + } + g_value_unset (&from_val); + } + } + } else { + /* metadata ! */ + GST_DEBUG (""Setting metadata""); + g_value_init (&tag_value, G_TYPE_STRING); + g_value_set_string (&tag_value, value_utf8); + /* If we found a stereoscopic marker, look for StereoscopicLayout + * metadata */ + if (content3D) { + guint i; + if (strncmp (""StereoscopicLayout"", name_utf8, + strlen (name_utf8)) == 0) { + for (i = 0; i < G_N_ELEMENTS (stereoscopic_layout_map); i++) { + if (g_str_equal (stereoscopic_layout_map[i].interleave_name, + value_utf8)) { + demux->asf_3D_mode = + stereoscopic_layout_map[i].interleaving_type; + GST_INFO (""find interleave type %u"", demux->asf_3D_mode); + } + } + } + GST_INFO_OBJECT (demux, ""3d type is %u"", demux->asf_3D_mode); + } else { + demux->asf_3D_mode = GST_ASF_3D_NONE; + GST_INFO_OBJECT (demux, ""None 3d type""); + } + } + } else if (value_utf8 == NULL) { + GST_WARNING (""Failed to convert string value to UTF8, skipping""); + } else { + GST_DEBUG (""Skipping empty string value for %s"", + GST_STR_NULL (gst_tag_name)); + } + g_free (value_utf8); + break; + } + case ASF_DEMUX_DATA_TYPE_BYTE_ARRAY:{ + if (gst_tag_name) { + if (!g_str_equal (gst_tag_name, GST_TAG_IMAGE)) { + GST_FIXME (""Unhandled byte array tag %s"", + GST_STR_NULL (gst_tag_name)); + break; + } else { + asf_demux_parse_picture_tag (taglist, (guint8 *) value, + value_len); + } + } + break; + } + case ASF_DEMUX_DATA_TYPE_DWORD:{ + guint uint_val = GST_READ_UINT32_LE (value); + + /* this is the track number */ + g_value_init (&tag_value, G_TYPE_UINT); + + /* WM/Track counts from 0 */ + if (!strcmp (name_utf8, ""WM/Track"")) + ++uint_val; + + g_value_set_uint (&tag_value, uint_val); + break; + } + /* Detect 3D */ + case ASF_DEMUX_DATA_TYPE_BOOL:{ + gboolean bool_val = GST_READ_UINT32_LE (value); + + if (strncmp (""Stereoscopic"", name_utf8, strlen (name_utf8)) == 0) { + if (bool_val) { + GST_INFO_OBJECT (demux, ""This is 3D contents""); + content3D = TRUE; + } else { + GST_INFO_OBJECT (demux, ""This is not 3D contenst""); + content3D = FALSE; + } + } + + break; + } + default:{ + GST_DEBUG (""Skipping tag %s of type %d"", gst_tag_name, datatype); + break; + } + } + + if (G_IS_VALUE (&tag_value)) { + if (gst_tag_name) { + GstTagMergeMode merge_mode = GST_TAG_MERGE_APPEND; + + /* WM/TrackNumber is more reliable than WM/Track, since the latter + * is supposed to have a 0 base but is often wrongly written to start + * from 1 as well, so prefer WM/TrackNumber when we have it: either + * replace the value added earlier from WM/Track or put it first in + * the list, so that it will get picked up by _get_uint() */ + if (strcmp (name_utf8, ""WM/TrackNumber"") == 0) + merge_mode = GST_TAG_MERGE_REPLACE; + + gst_tag_list_add_values (taglist, merge_mode, gst_tag_name, + &tag_value, NULL); + } else { + GST_DEBUG (""Setting global metadata %s"", name_utf8); + gst_structure_set_value (demux->global_metadata, name_utf8, + &tag_value); + } + + g_value_unset (&tag_value); + } + } + + g_free (name); + g_free (value); + g_free (name_utf8); + } + + gst_asf_demux_add_global_tags (demux, taglist); + + return GST_FLOW_OK; + + /* Errors */ +not_enough_data: + { + GST_WARNING (""Unexpected end of data parsing ext content desc object""); + gst_tag_list_unref (taglist); + return GST_FLOW_OK; /* not really fatal */ + } +}","gst_asf_demux_process_ext_content_desc (GstASFDemux * demux, guint8 * data, + guint64 size) +{ + /* Other known (and unused) 'text/unicode' metadata available : + * + * WM/Lyrics = + * WM/MediaPrimaryClassID = {D1607DBC-E323-4BE2-86A1-48A42A28441E} + * WMFSDKVersion = 9.00.00.2980 + * WMFSDKNeeded = 0.0.0.0000 + * WM/UniqueFileIdentifier = AMGa_id=R 15334;AMGp_id=P 5149;AMGt_id=T 2324984 + * WM/Publisher = 4AD + * WM/Provider = AMG + * WM/ProviderRating = 8 + * WM/ProviderStyle = Rock (similar to WM/Genre) + * WM/GenreID (similar to WM/Genre) + * WM/TrackNumber (same as WM/Track but as a string) + * + * Other known (and unused) 'non-text' metadata available : + * + * WM/EncodingTime + * WM/MCDI + * IsVBR + * + * We might want to read WM/TrackNumber and use atoi() if we don't have + * WM/Track + */ + + GstTagList *taglist; + guint16 blockcount, i; + gboolean content3D = FALSE; + + struct + { + const gchar *interleave_name; + GstASF3DMode interleaving_type; + } stereoscopic_layout_map[] = { + { + ""SideBySideRF"", GST_ASF_3D_SIDE_BY_SIDE_HALF_RL}, { + ""SideBySideLF"", GST_ASF_3D_SIDE_BY_SIDE_HALF_LR}, { + ""OverUnderRT"", GST_ASF_3D_TOP_AND_BOTTOM_HALF_RL}, { + ""OverUnderLT"", GST_ASF_3D_TOP_AND_BOTTOM_HALF_LR}, { + ""DualStream"", GST_ASF_3D_DUAL_STREAM} + }; + GST_INFO_OBJECT (demux, ""object is an extended content description""); + + taglist = gst_tag_list_new_empty (); + + /* Content Descriptor Count */ + if (size < 2) + goto not_enough_data; + + blockcount = gst_asf_demux_get_uint16 (&data, &size); + + for (i = 1; i <= blockcount; ++i) { + const gchar *gst_tag_name; + guint16 datatype; + guint16 value_len; + guint16 name_len; + GValue tag_value = { 0, }; + gsize in, out; + gchar *name; + gchar *name_utf8 = NULL; + gchar *value; + + /* Descriptor */ + if (!gst_asf_demux_get_string (&name, &name_len, &data, &size)) + goto not_enough_data; + + if (size < 2) { + g_free (name); + goto not_enough_data; + } + /* Descriptor Value Data Type */ + datatype = gst_asf_demux_get_uint16 (&data, &size); + + /* Descriptor Value (not really a string, but same thing reading-wise) */ + if (!gst_asf_demux_get_string (&value, &value_len, &data, &size)) { + g_free (name); + goto not_enough_data; + } + + name_utf8 = + g_convert (name, name_len, ""UTF-8"", ""UTF-16LE"", &in, &out, NULL); + + if (name_utf8 != NULL) { + GST_DEBUG (""Found tag/metadata %s"", name_utf8); + + gst_tag_name = gst_asf_demux_get_gst_tag_from_tag_name (name_utf8); + GST_DEBUG (""gst_tag_name %s"", GST_STR_NULL (gst_tag_name)); + + switch (datatype) { + case ASF_DEMUX_DATA_TYPE_UTF16LE_STRING:{ + gchar *value_utf8; + + value_utf8 = g_convert (value, value_len, ""UTF-8"", ""UTF-16LE"", + &in, &out, NULL); + + /* get rid of tags with empty value */ + if (value_utf8 != NULL && *value_utf8 != '\0') { + GST_DEBUG (""string value %s"", value_utf8); + + value_utf8[out] = '\0'; + + if (gst_tag_name != NULL) { + if (strcmp (gst_tag_name, GST_TAG_DATE_TIME) == 0) { + guint year = atoi (value_utf8); + + if (year > 0) { + g_value_init (&tag_value, GST_TYPE_DATE_TIME); + g_value_take_boxed (&tag_value, gst_date_time_new_y (year)); + } + } else if (strcmp (gst_tag_name, GST_TAG_GENRE) == 0) { + guint id3v1_genre_id; + const gchar *genre_str; + + if (sscanf (value_utf8, ""(%u)"", &id3v1_genre_id) == 1 && + ((genre_str = gst_tag_id3_genre_get (id3v1_genre_id)))) { + GST_DEBUG (""Genre: %s -> %s"", value_utf8, genre_str); + g_free (value_utf8); + value_utf8 = g_strdup (genre_str); + } + } else { + GType tag_type; + + /* convert tag from string to other type if required */ + tag_type = gst_tag_get_type (gst_tag_name); + g_value_init (&tag_value, tag_type); + if (!gst_value_deserialize (&tag_value, value_utf8)) { + GValue from_val = { 0, }; + + g_value_init (&from_val, G_TYPE_STRING); + g_value_set_string (&from_val, value_utf8); + if (!g_value_transform (&from_val, &tag_value)) { + GST_WARNING_OBJECT (demux, + ""Could not transform string tag to "" ""%s tag type %s"", + gst_tag_name, g_type_name (tag_type)); + g_value_unset (&tag_value); + } + g_value_unset (&from_val); + } + } + } else { + /* metadata ! */ + GST_DEBUG (""Setting metadata""); + g_value_init (&tag_value, G_TYPE_STRING); + g_value_set_string (&tag_value, value_utf8); + /* If we found a stereoscopic marker, look for StereoscopicLayout + * metadata */ + if (content3D) { + guint i; + if (strncmp (""StereoscopicLayout"", name_utf8, + strlen (name_utf8)) == 0) { + for (i = 0; i < G_N_ELEMENTS (stereoscopic_layout_map); i++) { + if (g_str_equal (stereoscopic_layout_map[i].interleave_name, + value_utf8)) { + demux->asf_3D_mode = + stereoscopic_layout_map[i].interleaving_type; + GST_INFO (""find interleave type %u"", demux->asf_3D_mode); + } + } + } + GST_INFO_OBJECT (demux, ""3d type is %u"", demux->asf_3D_mode); + } else { + demux->asf_3D_mode = GST_ASF_3D_NONE; + GST_INFO_OBJECT (demux, ""None 3d type""); + } + } + } else if (value_utf8 == NULL) { + GST_WARNING (""Failed to convert string value to UTF8, skipping""); + } else { + GST_DEBUG (""Skipping empty string value for %s"", + GST_STR_NULL (gst_tag_name)); + } + g_free (value_utf8); + break; + } + case ASF_DEMUX_DATA_TYPE_BYTE_ARRAY:{ + if (gst_tag_name) { + if (!g_str_equal (gst_tag_name, GST_TAG_IMAGE)) { + GST_FIXME (""Unhandled byte array tag %s"", + GST_STR_NULL (gst_tag_name)); + break; + } else { + asf_demux_parse_picture_tag (taglist, (guint8 *) value, + value_len); + } + } + break; + } + case ASF_DEMUX_DATA_TYPE_DWORD:{ + guint uint_val; + + if (value_len < 4) + break; + + uint_val = GST_READ_UINT32_LE (value); + + /* this is the track number */ + g_value_init (&tag_value, G_TYPE_UINT); + + /* WM/Track counts from 0 */ + if (!strcmp (name_utf8, ""WM/Track"")) + ++uint_val; + + g_value_set_uint (&tag_value, uint_val); + break; + } + /* Detect 3D */ + case ASF_DEMUX_DATA_TYPE_BOOL:{ + gboolean bool_val; + + if (value_len < 4) + break; + + bool_val = GST_READ_UINT32_LE (value); + + if (strncmp (""Stereoscopic"", name_utf8, strlen (name_utf8)) == 0) { + if (bool_val) { + GST_INFO_OBJECT (demux, ""This is 3D contents""); + content3D = TRUE; + } else { + GST_INFO_OBJECT (demux, ""This is not 3D contenst""); + content3D = FALSE; + } + } + + break; + } + default:{ + GST_DEBUG (""Skipping tag %s of type %d"", gst_tag_name, datatype); + break; + } + } + + if (G_IS_VALUE (&tag_value)) { + if (gst_tag_name) { + GstTagMergeMode merge_mode = GST_TAG_MERGE_APPEND; + + /* WM/TrackNumber is more reliable than WM/Track, since the latter + * is supposed to have a 0 base but is often wrongly written to start + * from 1 as well, so prefer WM/TrackNumber when we have it: either + * replace the value added earlier from WM/Track or put it first in + * the list, so that it will get picked up by _get_uint() */ + if (strcmp (name_utf8, ""WM/TrackNumber"") == 0) + merge_mode = GST_TAG_MERGE_REPLACE; + + gst_tag_list_add_values (taglist, merge_mode, gst_tag_name, + &tag_value, NULL); + } else { + GST_DEBUG (""Setting global metadata %s"", name_utf8); + gst_structure_set_value (demux->global_metadata, name_utf8, + &tag_value); + } + + g_value_unset (&tag_value); + } + } + + g_free (name); + g_free (value); + g_free (name_utf8); + } + + gst_asf_demux_add_global_tags (demux, taglist); + + return GST_FLOW_OK; + + /* Errors */ +not_enough_data: + { + GST_WARNING (""Unexpected end of data parsing ext content desc object""); + gst_tag_list_unref (taglist); + return GST_FLOW_OK; /* not really fatal */ + } +}","{'deleted': [{'line_no': 191, 'char_start': 6766, 'char_end': 6821, 'line': ' guint uint_val = GST_READ_UINT32_LE (value);\n'}, {'line_no': 205, 'char_start': 7169, 'char_end': 7227, 'line': ' gboolean bool_val = GST_READ_UINT32_LE (value);\n'}], 'added': [{'line_no': 191, 'char_start': 6766, 'char_end': 6792, 'line': ' guint uint_val;\n'}, {'line_no': 192, 'char_start': 6792, 'char_end': 6793, 'line': '\n'}, {'line_no': 193, 'char_start': 6793, 'char_end': 6822, 'line': ' if (value_len < 4)\n'}, {'line_no': 194, 'char_start': 6822, 'char_end': 6841, 'line': ' break;\n'}, {'line_no': 195, 'char_start': 6841, 'char_end': 6842, 'line': '\n'}, {'line_no': 196, 'char_start': 6842, 'char_end': 6891, 'line': ' uint_val = GST_READ_UINT32_LE (value);\n'}, {'line_no': 210, 'char_start': 7239, 'char_end': 7268, 'line': ' gboolean bool_val;\n'}, {'line_no': 211, 'char_start': 7268, 'char_end': 7269, 'line': '\n'}, {'line_no': 212, 'char_start': 7269, 'char_end': 7298, 'line': ' if (value_len < 4)\n'}, {'line_no': 213, 'char_start': 7298, 'char_end': 7317, 'line': ' break;\n'}, {'line_no': 214, 'char_start': 7317, 'char_end': 7318, 'line': '\n'}, {'line_no': 215, 'char_start': 7318, 'char_end': 7367, 'line': ' bool_val = GST_READ_UINT32_LE (value);\n'}]}","{'deleted': [], 'added': [{'char_start': 6790, 'char_end': 6860, 'chars': ';\n\n if (value_len < 4)\n break;\n\n uint_val'}, {'char_start': 7257, 'char_end': 7327, 'chars': ' bool_val;\n\n if (value_len < 4)\n break;\n\n '}]}",github.com/GStreamer/gst-plugins-ugly/commit/d21017b52a585f145e8d62781bcc1c5fefc7ee37,gst/asfdemux/gstasfdemux.c,cwe-125, +cwe-125,enc_untrusted_recvmsg,"ssize_t enc_untrusted_recvmsg(int sockfd, struct msghdr *msg, int flags) { + size_t total_buffer_size = CalculateTotalMessageSize(msg); + + MessageWriter input; + input.Push(sockfd); + input.Push(msg->msg_namelen); + input.Push(total_buffer_size); + input.Push(msg->msg_controllen); + input.Push(msg->msg_flags); + input.Push(flags); + + MessageReader output; + + const auto status = NonSystemCallDispatcher( + ::asylo::host_call::kRecvMsgHandler, &input, &output); + CheckStatusAndParamCount(status, output, ""enc_untrusted_recvmsg"", 2, + /*match_exact_params=*/false); + + ssize_t result = output.next(); + int klinux_errno = output.next(); + + // recvmsg() returns the number of characters received. On error, -1 is + // returned, with errno set to indicate the cause of the error. + if (result == -1) { + errno = FromkLinuxErrorNumber(klinux_errno); + return result; + } + + auto msg_name_extent = output.next(); + // The returned |msg_namelen| should not exceed the buffer size. + if (msg_name_extent.size() <= msg->msg_namelen) { + msg->msg_namelen = msg_name_extent.size(); + } + memcpy(msg->msg_name, msg_name_extent.As(), msg->msg_namelen); + + // A single buffer is passed from the untrusted side, copy it into the + // scattered buffers inside the enclave. + auto msg_iov_extent = output.next(); + size_t total_bytes = msg_iov_extent.size(); + size_t bytes_copied = 0; + for (int i = 0; i < msg->msg_iovlen && bytes_copied < total_bytes; ++i) { + size_t bytes_to_copy = + std::min(msg->msg_iov[i].iov_len, total_bytes - bytes_copied); + memcpy(msg->msg_iov[i].iov_base, msg_iov_extent.As() + bytes_copied, + bytes_to_copy); + bytes_copied += bytes_to_copy; + } + + auto msg_control_extent = output.next(); + // The returned |msg_controllen| should not exceed the buffer size. + if (msg_control_extent.size() <= msg->msg_controllen) { + msg->msg_controllen = msg_control_extent.size(); + } + memcpy(msg->msg_control, msg_control_extent.As(), msg->msg_controllen); + + return result; +}","ssize_t enc_untrusted_recvmsg(int sockfd, struct msghdr *msg, int flags) { + size_t total_buffer_size = CalculateTotalMessageSize(msg); + + MessageWriter input; + input.Push(sockfd); + input.Push(msg->msg_namelen); + input.Push(total_buffer_size); + input.Push(msg->msg_controllen); + input.Push(msg->msg_flags); + input.Push(flags); + + MessageReader output; + + const auto status = NonSystemCallDispatcher( + ::asylo::host_call::kRecvMsgHandler, &input, &output); + CheckStatusAndParamCount(status, output, ""enc_untrusted_recvmsg"", 2, + /*match_exact_params=*/false); + + ssize_t result = output.next(); + int klinux_errno = output.next(); + + // recvmsg() returns the number of characters received. On error, -1 is + // returned, with errno set to indicate the cause of the error. + if (result == -1) { + errno = FromkLinuxErrorNumber(klinux_errno); + return result; + } + + if (result > total_buffer_size) { + ::asylo::primitives::TrustedPrimitives::BestEffortAbort( + ""enc_untrusted_recvmsg: result exceeds requested""); + } + + auto msg_name_extent = output.next(); + // The returned |msg_namelen| should not exceed the buffer size. + if (msg_name_extent.size() <= msg->msg_namelen) { + msg->msg_namelen = msg_name_extent.size(); + } + memcpy(msg->msg_name, msg_name_extent.As(), msg->msg_namelen); + + // A single buffer is passed from the untrusted side, copy it into the + // scattered buffers inside the enclave. + auto msg_iov_extent = output.next(); + size_t total_bytes = msg_iov_extent.size(); + size_t bytes_copied = 0; + for (int i = 0; i < msg->msg_iovlen && bytes_copied < total_bytes; ++i) { + size_t bytes_to_copy = + std::min(msg->msg_iov[i].iov_len, total_bytes - bytes_copied); + memcpy(msg->msg_iov[i].iov_base, msg_iov_extent.As() + bytes_copied, + bytes_to_copy); + bytes_copied += bytes_to_copy; + } + + auto msg_control_extent = output.next(); + // The returned |msg_controllen| should not exceed the buffer size. + if (msg_control_extent.size() <= msg->msg_controllen) { + msg->msg_controllen = msg_control_extent.size(); + } + memcpy(msg->msg_control, msg_control_extent.As(), msg->msg_controllen); + + return result; +}","{'deleted': [], 'added': [{'line_no': 29, 'char_start': 947, 'char_end': 983, 'line': ' if (result > total_buffer_size) {\n'}, {'line_no': 30, 'char_start': 983, 'char_end': 1044, 'line': ' ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n'}, {'line_no': 31, 'char_start': 1044, 'char_end': 1104, 'line': ' ""enc_untrusted_recvmsg: result exceeds requested"");\n'}, {'line_no': 32, 'char_start': 1104, 'char_end': 1108, 'line': ' }\n'}, {'line_no': 33, 'char_start': 1108, 'char_end': 1109, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 949, 'char_end': 1111, 'chars': 'if (result > total_buffer_size) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n ""enc_untrusted_recvmsg: result exceeds requested"");\n }\n\n '}]}",github.com/google/asylo/commit/fa6485c5d16a7355eab047d4a44345a73bc9131e,asylo/platform/host_call/trusted/host_calls.cc,cwe-125, +cwe-125,HPHP::HHVM_METHOD,"static Array HHVM_METHOD(Memcache, getextendedstats, + const String& /*type*/ /* = null_string */, + int /*slabid*/ /* = 0 */, int /*limit*/ /* = 100 */) { + auto data = Native::data(this_); + memcached_return_t ret; + memcached_stat_st *stats; + + stats = memcached_stat(&data->m_memcache, nullptr, &ret); + if (ret != MEMCACHED_SUCCESS) { + return Array(); + } + + int server_count = memcached_server_count(&data->m_memcache); + + Array return_val; + + for (int server_id = 0; server_id < server_count; server_id++) { + memcached_stat_st *stat; + char stats_key[30] = {0}; + size_t key_len; + + LMCD_SERVER_POSITION_INSTANCE_TYPE instance = + memcached_server_instance_by_position(&data->m_memcache, server_id); + const char *hostname = LMCD_SERVER_HOSTNAME(instance); + in_port_t port = LMCD_SERVER_PORT(instance); + + stat = stats + server_id; + + Array server_stats = memcache_build_stats(&data->m_memcache, stat, &ret); + if (ret != MEMCACHED_SUCCESS) { + continue; + } + + key_len = snprintf(stats_key, sizeof(stats_key), ""%s:%d"", hostname, port); + + return_val.set(String(stats_key, key_len, CopyString), server_stats); + } + + free(stats); + return return_val; +}","static Array HHVM_METHOD(Memcache, getextendedstats, + const String& /*type*/ /* = null_string */, + int /*slabid*/ /* = 0 */, int /*limit*/ /* = 100 */) { + auto data = Native::data(this_); + memcached_return_t ret; + memcached_stat_st *stats; + + stats = memcached_stat(&data->m_memcache, nullptr, &ret); + if (ret != MEMCACHED_SUCCESS) { + return Array(); + } + + int server_count = memcached_server_count(&data->m_memcache); + + Array return_val; + + for (int server_id = 0; server_id < server_count; server_id++) { + memcached_stat_st *stat; + LMCD_SERVER_POSITION_INSTANCE_TYPE instance = + memcached_server_instance_by_position(&data->m_memcache, server_id); + const char *hostname = LMCD_SERVER_HOSTNAME(instance); + in_port_t port = LMCD_SERVER_PORT(instance); + + stat = stats + server_id; + + Array server_stats = memcache_build_stats(&data->m_memcache, stat, &ret); + if (ret != MEMCACHED_SUCCESS) { + continue; + } + + auto const port_str = folly::to(port); + auto const key_len = strlen(hostname) + 1 + port_str.length(); + auto key = String(key_len, ReserveString); + key += hostname; + key += "":""; + key += port_str; + return_val.set(key, server_stats); + } + + free(stats); + return return_val; +}","{'deleted': [{'line_no': 19, 'char_start': 607, 'char_end': 637, 'line': ' char stats_key[30] = {0};\n'}, {'line_no': 20, 'char_start': 637, 'char_end': 657, 'line': ' size_t key_len;\n'}, {'line_no': 21, 'char_start': 657, 'char_end': 658, 'line': '\n'}, {'line_no': 34, 'char_start': 1060, 'char_end': 1139, 'line': ' key_len = snprintf(stats_key, sizeof(stats_key), ""%s:%d"", hostname, port);\n'}, {'line_no': 35, 'char_start': 1139, 'char_end': 1140, 'line': '\n'}, {'line_no': 36, 'char_start': 1140, 'char_end': 1214, 'line': ' return_val.set(String(stats_key, key_len, CopyString), server_stats);\n'}], 'added': [{'line_no': 31, 'char_start': 1009, 'char_end': 1065, 'line': ' auto const port_str = folly::to(port);\n'}, {'line_no': 32, 'char_start': 1065, 'char_end': 1132, 'line': ' auto const key_len = strlen(hostname) + 1 + port_str.length();\n'}, {'line_no': 33, 'char_start': 1132, 'char_end': 1179, 'line': ' auto key = String(key_len, ReserveString);\n'}, {'line_no': 34, 'char_start': 1179, 'char_end': 1200, 'line': ' key += hostname;\n'}, {'line_no': 35, 'char_start': 1200, 'char_end': 1216, 'line': ' key += "":"";\n'}, {'line_no': 36, 'char_start': 1216, 'char_end': 1237, 'line': ' key += port_str;\n'}, {'line_no': 37, 'char_start': 1237, 'char_end': 1276, 'line': ' return_val.set(key, server_stats);\n'}]}","{'deleted': [{'char_start': 611, 'char_end': 662, 'chars': 'char stats_key[30] = {0};\n size_t key_len;\n\n '}, {'char_start': 1064, 'char_end': 1071, 'chars': 'key_len'}, {'char_start': 1072, 'char_end': 1075, 'chars': '= s'}, {'char_start': 1078, 'char_end': 1080, 'chars': 'in'}, {'char_start': 1081, 'char_end': 1083, 'chars': 'f('}, {'char_start': 1085, 'char_end': 1086, 'chars': 'a'}, {'char_start': 1088, 'char_end': 1094, 'chars': '_key, '}, {'char_start': 1096, 'char_end': 1100, 'chars': 'zeof'}, {'char_start': 1101, 'char_end': 1102, 'chars': 's'}, {'char_start': 1106, 'char_end': 1107, 'chars': '_'}, {'char_start': 1110, 'char_end': 1112, 'chars': '),'}, {'char_start': 1113, 'char_end': 1121, 'chars': '""%s:%d"",'}, {'char_start': 1130, 'char_end': 1131, 'chars': ','}, {'char_start': 1139, 'char_end': 1140, 'chars': '\n'}, {'char_start': 1144, 'char_end': 1145, 'chars': 'r'}, {'char_start': 1147, 'char_end': 1148, 'chars': 'u'}, {'char_start': 1151, 'char_end': 1153, 'chars': 'va'}, {'char_start': 1154, 'char_end': 1155, 'chars': '.'}, {'char_start': 1157, 'char_end': 1159, 'chars': 't('}, {'char_start': 1165, 'char_end': 1166, 'chars': '('}, {'char_start': 1169, 'char_end': 1172, 'chars': 'ts_'}, {'char_start': 1175, 'char_end': 1176, 'chars': ','}, {'char_start': 1181, 'char_end': 1185, 'chars': 'len,'}, {'char_start': 1186, 'char_end': 1191, 'chars': 'CopyS'}, {'char_start': 1193, 'char_end': 1194, 'chars': 'i'}, {'char_start': 1195, 'char_end': 1197, 'chars': 'g)'}], 'added': [{'char_start': 1013, 'char_end': 1028, 'chars': 'auto const port'}, {'char_start': 1029, 'char_end': 1032, 'chars': 'str'}, {'char_start': 1035, 'char_end': 1045, 'chars': 'folly::to<'}, {'char_start': 1046, 'char_end': 1052, 'chars': 'td::st'}, {'char_start': 1055, 'char_end': 1057, 'chars': 'g>'}, {'char_start': 1058, 'char_end': 1061, 'chars': 'por'}, {'char_start': 1062, 'char_end': 1069, 'chars': ');\n '}, {'char_start': 1070, 'char_end': 1071, 'chars': 'u'}, {'char_start': 1072, 'char_end': 1073, 'chars': 'o'}, {'char_start': 1074, 'char_end': 1075, 'chars': 'c'}, {'char_start': 1076, 'char_end': 1077, 'chars': 'n'}, {'char_start': 1079, 'char_end': 1080, 'chars': ' '}, {'char_start': 1083, 'char_end': 1087, 'chars': '_len'}, {'char_start': 1088, 'char_end': 1090, 'chars': '= '}, {'char_start': 1091, 'char_end': 1097, 'chars': 'trlen('}, {'char_start': 1105, 'char_end': 1112, 'chars': ') + 1 +'}, {'char_start': 1117, 'char_end': 1129, 'chars': '_str.length('}, {'char_start': 1136, 'char_end': 1142, 'chars': 'auto k'}, {'char_start': 1143, 'char_end': 1148, 'chars': 'y = S'}, {'char_start': 1150, 'char_end': 1151, 'chars': 'i'}, {'char_start': 1152, 'char_end': 1157, 'chars': 'g(key'}, {'char_start': 1159, 'char_end': 1165, 'chars': 'en, Re'}, {'char_start': 1167, 'char_end': 1170, 'chars': 'rve'}, {'char_start': 1176, 'char_end': 1192, 'chars': ');\n key += ho'}, {'char_start': 1194, 'char_end': 1195, 'chars': 'n'}, {'char_start': 1196, 'char_end': 1204, 'chars': 'me;\n '}, {'char_start': 1207, 'char_end': 1219, 'chars': ' += "":"";\n '}, {'char_start': 1224, 'char_end': 1227, 'chars': '+= '}, {'char_start': 1228, 'char_end': 1233, 'chars': 'ort_s'}, {'char_start': 1235, 'char_end': 1246, 'chars': ';\n retur'}, {'char_start': 1247, 'char_end': 1259, 'chars': '_val.set(key'}]}",github.com/facebook/hhvm/commit/4bff3bfbe90d10451e4638c2118d1ad1117bb3e3,hphp/runtime/ext/memcache/ext_memcache.cpp,cwe-125, +cwe-190,opj_get_encoding_parameters,"static void opj_get_encoding_parameters(const opj_image_t *p_image, + const opj_cp_t *p_cp, + OPJ_UINT32 p_tileno, + OPJ_INT32 * p_tx0, + OPJ_INT32 * p_tx1, + OPJ_INT32 * p_ty0, + OPJ_INT32 * p_ty1, + OPJ_UINT32 * p_dx_min, + OPJ_UINT32 * p_dy_min, + OPJ_UINT32 * p_max_prec, + OPJ_UINT32 * p_max_res) +{ + /* loop */ + OPJ_UINT32 compno, resno; + /* pointers */ + const opj_tcp_t *l_tcp = 00; + const opj_tccp_t * l_tccp = 00; + const opj_image_comp_t * l_img_comp = 00; + + /* position in x and y of tile */ + OPJ_UINT32 p, q; + + /* preconditions */ + assert(p_cp != 00); + assert(p_image != 00); + assert(p_tileno < p_cp->tw * p_cp->th); + + /* initializations */ + l_tcp = &p_cp->tcps [p_tileno]; + l_img_comp = p_image->comps; + l_tccp = l_tcp->tccps; + + /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ + p = p_tileno % p_cp->tw; + q = p_tileno / p_cp->tw; + + /* find extent of tile */ + *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), + (OPJ_INT32)p_image->x0); + *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), + (OPJ_INT32)p_image->x1); + *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), + (OPJ_INT32)p_image->y0); + *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), + (OPJ_INT32)p_image->y1); + + /* max precision is 0 (can only grow) */ + *p_max_prec = 0; + *p_max_res = 0; + + /* take the largest value for dx_min and dy_min */ + *p_dx_min = 0x7fffffff; + *p_dy_min = 0x7fffffff; + + for (compno = 0; compno < p_image->numcomps; ++compno) { + /* arithmetic variables to calculate */ + OPJ_UINT32 l_level_no; + OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; + OPJ_INT32 l_px0, l_py0, l_px1, py1; + OPJ_UINT32 l_pdx, l_pdy; + OPJ_UINT32 l_pw, l_ph; + OPJ_UINT32 l_product; + OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; + + l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); + l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); + l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); + l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); + + if (l_tccp->numresolutions > *p_max_res) { + *p_max_res = l_tccp->numresolutions; + } + + /* use custom size for precincts */ + for (resno = 0; resno < l_tccp->numresolutions; ++resno) { + OPJ_UINT32 l_dx, l_dy; + + /* precinct width and height */ + l_pdx = l_tccp->prcw[resno]; + l_pdy = l_tccp->prch[resno]; + + l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); + l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); + + /* take the minimum size for dx for each comp and resolution */ + *p_dx_min = opj_uint_min(*p_dx_min, l_dx); + *p_dy_min = opj_uint_min(*p_dy_min, l_dy); + + /* various calculations of extents */ + l_level_no = l_tccp->numresolutions - 1 - resno; + + l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); + l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); + l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); + l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); + + l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; + l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; + l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; + + py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; + + l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); + l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy); + + l_product = l_pw * l_ph; + + /* update precision */ + if (l_product > *p_max_prec) { + *p_max_prec = l_product; + } + } + ++l_img_comp; + ++l_tccp; + } +}","static void opj_get_encoding_parameters(const opj_image_t *p_image, + const opj_cp_t *p_cp, + OPJ_UINT32 p_tileno, + OPJ_INT32 * p_tx0, + OPJ_INT32 * p_tx1, + OPJ_INT32 * p_ty0, + OPJ_INT32 * p_ty1, + OPJ_UINT32 * p_dx_min, + OPJ_UINT32 * p_dy_min, + OPJ_UINT32 * p_max_prec, + OPJ_UINT32 * p_max_res) +{ + /* loop */ + OPJ_UINT32 compno, resno; + /* pointers */ + const opj_tcp_t *l_tcp = 00; + const opj_tccp_t * l_tccp = 00; + const opj_image_comp_t * l_img_comp = 00; + + /* position in x and y of tile */ + OPJ_UINT32 p, q; + + /* non-corrected (in regard to image offset) tile offset */ + OPJ_UINT32 l_tx0, l_ty0; + + /* preconditions */ + assert(p_cp != 00); + assert(p_image != 00); + assert(p_tileno < p_cp->tw * p_cp->th); + + /* initializations */ + l_tcp = &p_cp->tcps [p_tileno]; + l_img_comp = p_image->comps; + l_tccp = l_tcp->tccps; + + /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ + p = p_tileno % p_cp->tw; + q = p_tileno / p_cp->tw; + + /* find extent of tile */ + l_tx0 = p_cp->tx0 + p * + p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */ + *p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0); + *p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1); + l_ty0 = p_cp->ty0 + q * + p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */ + *p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0); + *p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1); + + /* max precision is 0 (can only grow) */ + *p_max_prec = 0; + *p_max_res = 0; + + /* take the largest value for dx_min and dy_min */ + *p_dx_min = 0x7fffffff; + *p_dy_min = 0x7fffffff; + + for (compno = 0; compno < p_image->numcomps; ++compno) { + /* arithmetic variables to calculate */ + OPJ_UINT32 l_level_no; + OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; + OPJ_INT32 l_px0, l_py0, l_px1, py1; + OPJ_UINT32 l_pdx, l_pdy; + OPJ_UINT32 l_pw, l_ph; + OPJ_UINT32 l_product; + OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; + + l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); + l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); + l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); + l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); + + if (l_tccp->numresolutions > *p_max_res) { + *p_max_res = l_tccp->numresolutions; + } + + /* use custom size for precincts */ + for (resno = 0; resno < l_tccp->numresolutions; ++resno) { + OPJ_UINT32 l_dx, l_dy; + + /* precinct width and height */ + l_pdx = l_tccp->prcw[resno]; + l_pdy = l_tccp->prch[resno]; + + l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); + l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); + + /* take the minimum size for dx for each comp and resolution */ + *p_dx_min = opj_uint_min(*p_dx_min, l_dx); + *p_dy_min = opj_uint_min(*p_dy_min, l_dy); + + /* various calculations of extents */ + l_level_no = l_tccp->numresolutions - 1 - resno; + + l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); + l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); + l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); + l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); + + l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; + l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; + l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; + + py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; + + l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); + l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy); + + l_product = l_pw * l_ph; + + /* update precision */ + if (l_product > *p_max_prec) { + *p_max_prec = l_product; + } + } + ++l_img_comp; + ++l_tccp; + } +}","{'deleted': [{'line_no': 38, 'char_start': 1329, 'char_end': 1394, 'line': ' *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx),\n'}, {'line_no': 39, 'char_start': 1394, 'char_end': 1444, 'line': ' (OPJ_INT32)p_image->x0);\n'}, {'line_no': 40, 'char_start': 1444, 'char_end': 1515, 'line': ' *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx),\n'}, {'line_no': 41, 'char_start': 1515, 'char_end': 1565, 'line': ' (OPJ_INT32)p_image->x1);\n'}, {'line_no': 42, 'char_start': 1565, 'char_end': 1630, 'line': ' *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy),\n'}, {'line_no': 43, 'char_start': 1630, 'char_end': 1680, 'line': ' (OPJ_INT32)p_image->y0);\n'}, {'line_no': 44, 'char_start': 1680, 'char_end': 1751, 'line': ' *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy),\n'}, {'line_no': 45, 'char_start': 1751, 'char_end': 1801, 'line': ' (OPJ_INT32)p_image->y1);\n'}], 'added': [{'line_no': 23, 'char_start': 928, 'char_end': 992, 'line': ' /* non-corrected (in regard to image offset) tile offset */\n'}, {'line_no': 24, 'char_start': 992, 'char_end': 1021, 'line': ' OPJ_UINT32 l_tx0, l_ty0;\n'}, {'line_no': 25, 'char_start': 1021, 'char_end': 1022, 'line': '\n'}, {'line_no': 41, 'char_start': 1423, 'char_end': 1451, 'line': ' l_tx0 = p_cp->tx0 + p *\n'}, {'line_no': 42, 'char_start': 1451, 'char_end': 1532, 'line': "" p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */\n""}, {'line_no': 43, 'char_start': 1532, 'char_end': 1590, 'line': ' *p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0);\n'}, {'line_no': 44, 'char_start': 1590, 'char_end': 1674, 'line': ' *p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1);\n'}, {'line_no': 45, 'char_start': 1674, 'char_end': 1702, 'line': ' l_ty0 = p_cp->ty0 + q *\n'}, {'line_no': 46, 'char_start': 1702, 'char_end': 1783, 'line': "" p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */\n""}, {'line_no': 47, 'char_start': 1783, 'char_end': 1841, 'line': ' *p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0);\n'}, {'line_no': 48, 'char_start': 1841, 'char_end': 1925, 'line': ' *p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1);\n'}]}","{'deleted': [{'char_start': 952, 'char_end': 952, 'chars': ''}, {'char_start': 1333, 'char_end': 1335, 'chars': '*p'}, {'char_start': 1342, 'char_end': 1366, 'chars': 'opj_int_max((OPJ_INT32)('}, {'char_start': 1391, 'char_end': 1394, 'chars': '),\n'}, {'char_start': 1400, 'char_end': 1409, 'chars': ' '}, {'char_start': 1469, 'char_end': 1473, 'chars': '(OPJ'}, {'char_start': 1474, 'char_end': 1480, 'chars': 'INT32)'}, {'char_start': 1481, 'char_end': 1482, 'chars': 'p'}, {'char_start': 1483, 'char_end': 1487, 'chars': 'cp->'}, {'char_start': 1490, 'char_end': 1502, 'chars': ' + (p + 1) *'}, {'char_start': 1514, 'char_end': 1523, 'chars': '\n '}, {'char_start': 1524, 'char_end': 1551, 'chars': ' (OPJ_INT32)'}, {'char_start': 1569, 'char_end': 1571, 'chars': '*p'}, {'char_start': 1578, 'char_end': 1602, 'chars': 'opj_int_max((OPJ_INT32)('}, {'char_start': 1627, 'char_end': 1630, 'chars': '),\n'}, {'char_start': 1636, 'char_end': 1645, 'chars': ' '}, {'char_start': 1705, 'char_end': 1709, 'chars': '(OPJ'}, {'char_start': 1710, 'char_end': 1716, 'chars': 'INT32)'}, {'char_start': 1717, 'char_end': 1718, 'chars': 'p'}, {'char_start': 1719, 'char_end': 1723, 'chars': 'cp->'}, {'char_start': 1726, 'char_end': 1738, 'chars': ' + (q + 1) *'}, {'char_start': 1750, 'char_end': 1759, 'chars': '\n '}, {'char_start': 1760, 'char_end': 1787, 'chars': ' (OPJ_INT32)'}], 'added': [{'char_start': 935, 'char_end': 1029, 'chars': 'non-corrected (in regard to image offset) tile offset */\n OPJ_UINT32 l_tx0, l_ty0;\n\n /* '}, {'char_start': 1427, 'char_end': 1428, 'chars': 'l'}, {'char_start': 1463, 'char_end': 1473, 'chars': 'p_cp->tdx;'}, {'char_start': 1474, 'char_end': 1476, 'chars': '/*'}, {'char_start': 1477, 'char_end': 1482, 'chars': ""can't""}, {'char_start': 1483, 'char_end': 1485, 'chars': 'be'}, {'char_start': 1486, 'char_end': 1493, 'chars': 'greater'}, {'char_start': 1494, 'char_end': 1498, 'chars': 'than'}, {'char_start': 1499, 'char_end': 1510, 'chars': 'p_image->x1'}, {'char_start': 1511, 'char_end': 1513, 'chars': 'so'}, {'char_start': 1514, 'char_end': 1519, 'chars': ""won't""}, {'char_start': 1520, 'char_end': 1528, 'chars': 'overflow'}, {'char_start': 1529, 'char_end': 1532, 'chars': '*/\n'}, {'char_start': 1535, 'char_end': 1545, 'chars': ' *p_tx0 = '}, {'char_start': 1556, 'char_end': 1576, 'chars': 'opj_uint_max(l_tx0, '}, {'char_start': 1603, 'char_end': 1614, 'chars': '(OPJ_INT32)'}, {'char_start': 1618, 'char_end': 1619, 'chars': 'u'}, {'char_start': 1627, 'char_end': 1630, 'chars': 'opj'}, {'char_start': 1631, 'char_end': 1640, 'chars': 'uint_adds'}, {'char_start': 1641, 'char_end': 1642, 'chars': 'l'}, {'char_start': 1646, 'char_end': 1647, 'chars': ','}, {'char_start': 1678, 'char_end': 1679, 'chars': 'l'}, {'char_start': 1714, 'char_end': 1724, 'chars': 'p_cp->tdy;'}, {'char_start': 1725, 'char_end': 1727, 'chars': '/*'}, {'char_start': 1728, 'char_end': 1733, 'chars': ""can't""}, {'char_start': 1734, 'char_end': 1736, 'chars': 'be'}, {'char_start': 1737, 'char_end': 1744, 'chars': 'greater'}, {'char_start': 1745, 'char_end': 1749, 'chars': 'than'}, {'char_start': 1750, 'char_end': 1761, 'chars': 'p_image->y1'}, {'char_start': 1762, 'char_end': 1764, 'chars': 'so'}, {'char_start': 1765, 'char_end': 1770, 'chars': ""won't""}, {'char_start': 1771, 'char_end': 1779, 'chars': 'overflow'}, {'char_start': 1780, 'char_end': 1783, 'chars': '*/\n'}, {'char_start': 1786, 'char_end': 1796, 'chars': ' *p_ty0 = '}, {'char_start': 1807, 'char_end': 1827, 'chars': 'opj_uint_max(l_ty0, '}, {'char_start': 1854, 'char_end': 1865, 'chars': '(OPJ_INT32)'}, {'char_start': 1869, 'char_end': 1870, 'chars': 'u'}, {'char_start': 1878, 'char_end': 1881, 'chars': 'opj'}, {'char_start': 1882, 'char_end': 1891, 'chars': 'uint_adds'}, {'char_start': 1892, 'char_end': 1893, 'chars': 'l'}, {'char_start': 1897, 'char_end': 1898, 'chars': ','}]}",github.com/uclouvain/openjpeg/commit/c58df149900df862806d0e892859b41115875845,src/lib/openjp2/pi.c,cwe-190, +cwe-190,rfbScaledScreenUpdateRect,"void rfbScaledScreenUpdateRect(rfbScreenInfoPtr screen, rfbScreenInfoPtr ptr, int x0, int y0, int w0, int h0) +{ + int x,y,w,v,z; + int x1, y1, w1, h1; + int bitsPerPixel, bytesPerPixel, bytesPerLine, areaX, areaY, area2; + unsigned char *srcptr, *dstptr; + + /* Nothing to do!!! */ + if (screen==ptr) return; + + x1 = x0; + y1 = y0; + w1 = w0; + h1 = h0; + + rfbScaledCorrection(screen, ptr, &x1, &y1, &w1, &h1, ""rfbScaledScreenUpdateRect""); + x0 = ScaleX(ptr, screen, x1); + y0 = ScaleY(ptr, screen, y1); + w0 = ScaleX(ptr, screen, w1); + h0 = ScaleY(ptr, screen, h1); + + bitsPerPixel = screen->bitsPerPixel; + bytesPerPixel = bitsPerPixel / 8; + bytesPerLine = w1 * bytesPerPixel; + srcptr = (unsigned char *)(screen->frameBuffer + + (y0 * screen->paddedWidthInBytes + x0 * bytesPerPixel)); + dstptr = (unsigned char *)(ptr->frameBuffer + + ( y1 * ptr->paddedWidthInBytes + x1 * bytesPerPixel)); + /* The area of the source framebuffer for each destination pixel */ + areaX = ScaleX(ptr,screen,1); + areaY = ScaleY(ptr,screen,1); + area2 = areaX*areaY; + + + /* Ensure that we do not go out of bounds */ + if ((x1+w1) > (ptr->width)) + { + if (x1==0) w1=ptr->width; else x1 = ptr->width - w1; + } + if ((y1+h1) > (ptr->height)) + { + if (y1==0) h1=ptr->height; else y1 = ptr->height - h1; + } + /* + * rfbLog(""rfbScaledScreenUpdateRect(%dXx%dY-%dWx%dH -> %dXx%dY-%dWx%dH <%dx%d>) {%dWx%dH -> %dWx%dH} 0x%p\n"", + * x0, y0, w0, h0, x1, y1, w1, h1, areaX, areaY, + * screen->width, screen->height, ptr->width, ptr->height, ptr->frameBuffer); + */ + + if (screen->serverFormat.trueColour) { /* Blend neighbouring pixels together */ + unsigned char *srcptr2; + unsigned long pixel_value, red, green, blue; + unsigned int redShift = screen->serverFormat.redShift; + unsigned int greenShift = screen->serverFormat.greenShift; + unsigned int blueShift = screen->serverFormat.blueShift; + unsigned long redMax = screen->serverFormat.redMax; + unsigned long greenMax = screen->serverFormat.greenMax; + unsigned long blueMax = screen->serverFormat.blueMax; + + /* for each *destination* pixel... */ + for (y = 0; y < h1; y++) { + for (x = 0; x < w1; x++) { + red = green = blue = 0; + /* Get the totals for rgb from the source grid... */ + for (w = 0; w < areaX; w++) { + for (v = 0; v < areaY; v++) { + srcptr2 = &srcptr[(((x * areaX) + w) * bytesPerPixel) + + (v * screen->paddedWidthInBytes)]; + pixel_value = 0; + + + switch (bytesPerPixel) { + case 4: pixel_value = *((unsigned int *)srcptr2); break; + case 2: pixel_value = *((unsigned short *)srcptr2); break; + case 1: pixel_value = *((unsigned char *)srcptr2); break; + default: + /* fixme: endianness problem? */ + for (z = 0; z < bytesPerPixel; z++) + pixel_value += (srcptr2[z] << (8 * z)); + break; + } + /* + srcptr2 += bytesPerPixel; + */ + + red += ((pixel_value >> redShift) & redMax); + green += ((pixel_value >> greenShift) & greenMax); + blue += ((pixel_value >> blueShift) & blueMax); + + } + } + /* We now have a total for all of the colors, find the average! */ + red /= area2; + green /= area2; + blue /= area2; + /* Stuff the new value back into memory */ + pixel_value = ((red & redMax) << redShift) | ((green & greenMax) << greenShift) | ((blue & blueMax) << blueShift); + + switch (bytesPerPixel) { + case 4: *((unsigned int *)dstptr) = (unsigned int) pixel_value; break; + case 2: *((unsigned short *)dstptr) = (unsigned short) pixel_value; break; + case 1: *((unsigned char *)dstptr) = (unsigned char) pixel_value; break; + default: + /* fixme: endianness problem? */ + for (z = 0; z < bytesPerPixel; z++) + dstptr[z]=(pixel_value >> (8 * z)) & 0xff; + break; + } + dstptr += bytesPerPixel; + } + srcptr += (screen->paddedWidthInBytes * areaY); + dstptr += (ptr->paddedWidthInBytes - bytesPerLine); + } + } else + { /* Not truecolour, so we can't blend. Just use the top-left pixel instead */ + for (y = y1; y < (y1+h1); y++) { + for (x = x1; x < (x1+w1); x++) + memcpy (&ptr->frameBuffer[(y *ptr->paddedWidthInBytes) + (x * bytesPerPixel)], + &screen->frameBuffer[(y * areaY * screen->paddedWidthInBytes) + (x *areaX * bytesPerPixel)], bytesPerPixel); + } + } +}","void rfbScaledScreenUpdateRect(rfbScreenInfoPtr screen, rfbScreenInfoPtr ptr, int x0, int y0, int w0, int h0) +{ + int x,y,w,v,z; + int x1, y1, w1, h1; + int bitsPerPixel, bytesPerPixel, bytesPerLine, areaX, areaY, area2; + unsigned char *srcptr, *dstptr; + + /* Nothing to do!!! */ + if (screen==ptr) return; + + x1 = x0; + y1 = y0; + w1 = w0; + h1 = h0; + + rfbScaledCorrection(screen, ptr, &x1, &y1, &w1, &h1, ""rfbScaledScreenUpdateRect""); + x0 = ScaleX(ptr, screen, x1); + y0 = ScaleY(ptr, screen, y1); + w0 = ScaleX(ptr, screen, w1); + h0 = ScaleY(ptr, screen, h1); + + bitsPerPixel = screen->bitsPerPixel; + bytesPerPixel = bitsPerPixel / 8; + bytesPerLine = w1 * bytesPerPixel; + srcptr = (unsigned char *)(screen->frameBuffer + + (y0 * screen->paddedWidthInBytes + x0 * bytesPerPixel)); + dstptr = (unsigned char *)(ptr->frameBuffer + + ( y1 * ptr->paddedWidthInBytes + x1 * bytesPerPixel)); + /* The area of the source framebuffer for each destination pixel */ + areaX = ScaleX(ptr,screen,1); + areaY = ScaleY(ptr,screen,1); + area2 = areaX*areaY; + + + /* Ensure that we do not go out of bounds */ + if ((x1+w1) > (ptr->width)) + { + if (x1==0) w1=ptr->width; else x1 = ptr->width - w1; + } + if ((y1+h1) > (ptr->height)) + { + if (y1==0) h1=ptr->height; else y1 = ptr->height - h1; + } + /* + * rfbLog(""rfbScaledScreenUpdateRect(%dXx%dY-%dWx%dH -> %dXx%dY-%dWx%dH <%dx%d>) {%dWx%dH -> %dWx%dH} 0x%p\n"", + * x0, y0, w0, h0, x1, y1, w1, h1, areaX, areaY, + * screen->width, screen->height, ptr->width, ptr->height, ptr->frameBuffer); + */ + + if (screen->serverFormat.trueColour) { /* Blend neighbouring pixels together */ + unsigned char *srcptr2; + unsigned long pixel_value, red, green, blue; + unsigned int redShift = screen->serverFormat.redShift; + unsigned int greenShift = screen->serverFormat.greenShift; + unsigned int blueShift = screen->serverFormat.blueShift; + unsigned long redMax = screen->serverFormat.redMax; + unsigned long greenMax = screen->serverFormat.greenMax; + unsigned long blueMax = screen->serverFormat.blueMax; + + /* for each *destination* pixel... */ + for (y = 0; y < h1; y++) { + for (x = 0; x < w1; x++) { + red = green = blue = 0; + /* Get the totals for rgb from the source grid... */ + for (w = 0; w < areaX; w++) { + for (v = 0; v < areaY; v++) { + srcptr2 = &srcptr[(((x * areaX) + w) * bytesPerPixel) + + (v * screen->paddedWidthInBytes)]; + pixel_value = 0; + + + switch (bytesPerPixel) { + case 4: pixel_value = *((unsigned int *)srcptr2); break; + case 2: pixel_value = *((unsigned short *)srcptr2); break; + case 1: pixel_value = *((unsigned char *)srcptr2); break; + default: + /* fixme: endianness problem? */ + for (z = 0; z < bytesPerPixel; z++) + pixel_value += ((unsigned long)srcptr2[z] << (8 * z)); + break; + } + /* + srcptr2 += bytesPerPixel; + */ + + red += ((pixel_value >> redShift) & redMax); + green += ((pixel_value >> greenShift) & greenMax); + blue += ((pixel_value >> blueShift) & blueMax); + + } + } + /* We now have a total for all of the colors, find the average! */ + red /= area2; + green /= area2; + blue /= area2; + /* Stuff the new value back into memory */ + pixel_value = ((red & redMax) << redShift) | ((green & greenMax) << greenShift) | ((blue & blueMax) << blueShift); + + switch (bytesPerPixel) { + case 4: *((unsigned int *)dstptr) = (unsigned int) pixel_value; break; + case 2: *((unsigned short *)dstptr) = (unsigned short) pixel_value; break; + case 1: *((unsigned char *)dstptr) = (unsigned char) pixel_value; break; + default: + /* fixme: endianness problem? */ + for (z = 0; z < bytesPerPixel; z++) + dstptr[z]=(pixel_value >> (8 * z)) & 0xff; + break; + } + dstptr += bytesPerPixel; + } + srcptr += (screen->paddedWidthInBytes * areaY); + dstptr += (ptr->paddedWidthInBytes - bytesPerLine); + } + } else + { /* Not truecolour, so we can't blend. Just use the top-left pixel instead */ + for (y = y1; y < (y1+h1); y++) { + for (x = x1; x < (x1+w1); x++) + memcpy (&ptr->frameBuffer[(y *ptr->paddedWidthInBytes) + (x * bytesPerPixel)], + &screen->frameBuffer[(y * areaY * screen->paddedWidthInBytes) + (x *areaX * bytesPerPixel)], bytesPerPixel); + } + } +}","{'deleted': [{'line_no': 79, 'char_start': 3001, 'char_end': 3058, 'line': ' pixel_value += (srcptr2[z] << (8 * z));\n'}], 'added': [{'line_no': 79, 'char_start': 3001, 'char_end': 3073, 'line': ' pixel_value += ((unsigned long)srcptr2[z] << (8 * z));\n'}]}","{'deleted': [], 'added': [{'char_start': 3034, 'char_end': 3049, 'chars': '(unsigned long)'}]}",github.com/LibVNC/libvncserver/commit/a6788d1da719ae006605b78d22f5a9f170b423af,libvncserver/scale.c,cwe-190, +cwe-190,jsuGetFreeStack,"size_t jsuGetFreeStack() { +#ifdef ARM + void *frame = __builtin_frame_address(0); + size_t stackPos = (size_t)((char*)frame); + size_t stackEnd = (size_t)((char*)&LINKER_END_VAR); + if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow! + return stackPos - stackEnd; +#elif defined(LINUX) + // On linux, we set STACK_BASE from `main`. + char ptr; // this is on the stack + extern void *STACK_BASE; + uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr); + return 1000000 - count; // give it 1 megabyte of stack +#else + // stack depth seems pretty platform-specific :( Default to a value that disables it + return 1000000; // no stack depth check on this platform +#endif +}","size_t jsuGetFreeStack() { +#ifdef ARM + void *frame = __builtin_frame_address(0); + size_t stackPos = (size_t)((char*)frame); + size_t stackEnd = (size_t)((char*)&LINKER_END_VAR); + if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow! + return stackPos - stackEnd; +#elif defined(LINUX) + // On linux, we set STACK_BASE from `main`. + char ptr; // this is on the stack + extern void *STACK_BASE; + uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr); + const uint32_t max_stack = 1000000; // give it 1 megabyte of stack + if (count>max_stack) return 0; + return max_stack - count; +#else + // stack depth seems pretty platform-specific :( Default to a value that disables it + return 1000000; // no stack depth check on this platform +#endif +}","{'deleted': [{'line_no': 13, 'char_start': 499, 'char_end': 556, 'line': ' return 1000000 - count; // give it 1 megabyte of stack\n'}], 'added': [{'line_no': 13, 'char_start': 499, 'char_end': 568, 'line': ' const uint32_t max_stack = 1000000; // give it 1 megabyte of stack\n'}, {'line_no': 14, 'char_start': 568, 'char_end': 601, 'line': ' if (count>max_stack) return 0;\n'}, {'line_no': 15, 'char_start': 601, 'char_end': 629, 'line': ' return max_stack - count;\n'}]}","{'deleted': [{'char_start': 501, 'char_end': 503, 'chars': 're'}, {'char_start': 505, 'char_end': 506, 'chars': 'r'}, {'char_start': 515, 'char_end': 523, 'chars': ' - count'}], 'added': [{'char_start': 501, 'char_end': 505, 'chars': 'cons'}, {'char_start': 506, 'char_end': 507, 'chars': ' '}, {'char_start': 508, 'char_end': 509, 'chars': 'i'}, {'char_start': 510, 'char_end': 527, 'chars': 't32_t max_stack ='}, {'char_start': 567, 'char_end': 628, 'chars': '\n if (count>max_stack) return 0;\n return max_stack - count;'}]}",github.com/espruino/Espruino/commit/a0d7f432abee692402c00e8b615ff5982dde9780,src/jsutils.c,cwe-190, +cwe-190,ssl_parse_client_psk_identity,"static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p, + const unsigned char *end ) +{ + int ret = 0; + size_t n; + + if( ssl->conf->f_psk == NULL && + ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL || + ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""got no pre-shared key"" ) ); + return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); + } + + /* + * Receive client pre-shared key identity name + */ + if( *p + 2 > end ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client key exchange message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); + } + + n = ( (*p)[0] << 8 ) | (*p)[1]; + *p += 2; + + if( n < 1 || n > 65535 || *p + n > end ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client key exchange message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); + } + + if( ssl->conf->f_psk != NULL ) + { + if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 ) + ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; + } + else + { + /* Identity is not a big secret since clients send it in the clear, + * but treat it carefully anyway, just in case */ + if( n != ssl->conf->psk_identity_len || + mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 ) + { + ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; + } + } + + if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ) + { + MBEDTLS_SSL_DEBUG_BUF( 3, ""Unknown PSK identity"", *p, n ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY ); + return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ); + } + + *p += n; + + return( 0 ); +}","static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p, + const unsigned char *end ) +{ + int ret = 0; + size_t n; + + if( ssl->conf->f_psk == NULL && + ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL || + ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""got no pre-shared key"" ) ); + return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); + } + + /* + * Receive client pre-shared key identity name + */ + if( end - *p < 2 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client key exchange message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); + } + + n = ( (*p)[0] << 8 ) | (*p)[1]; + *p += 2; + + if( n < 1 || n > 65535 || n > (size_t) ( end - *p ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client key exchange message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); + } + + if( ssl->conf->f_psk != NULL ) + { + if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 ) + ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; + } + else + { + /* Identity is not a big secret since clients send it in the clear, + * but treat it carefully anyway, just in case */ + if( n != ssl->conf->psk_identity_len || + mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 ) + { + ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; + } + } + + if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ) + { + MBEDTLS_SSL_DEBUG_BUF( 3, ""Unknown PSK identity"", *p, n ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY ); + return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ); + } + + *p += n; + + return( 0 ); +}","{'deleted': [{'line_no': 18, 'char_start': 571, 'char_end': 594, 'line': ' if( *p + 2 > end )\n'}, {'line_no': 27, 'char_start': 794, 'char_end': 839, 'line': ' if( n < 1 || n > 65535 || *p + n > end )\n'}], 'added': [{'line_no': 18, 'char_start': 571, 'char_end': 594, 'line': ' if( end - *p < 2 )\n'}, {'line_no': 27, 'char_start': 794, 'char_end': 852, 'line': ' if( n < 1 || n > 65535 || n > (size_t) ( end - *p ) )\n'}]}","{'deleted': [{'char_start': 582, 'char_end': 583, 'chars': '+'}, {'char_start': 585, 'char_end': 591, 'chars': ' > end'}, {'char_start': 824, 'char_end': 826, 'chars': '*p'}, {'char_start': 827, 'char_end': 828, 'chars': '+'}, {'char_start': 829, 'char_end': 830, 'chars': 'n'}, {'char_start': 831, 'char_end': 832, 'chars': '>'}], 'added': [{'char_start': 579, 'char_end': 585, 'chars': 'end - '}, {'char_start': 588, 'char_end': 589, 'chars': '<'}, {'char_start': 828, 'char_end': 839, 'chars': '(size_t) ( '}, {'char_start': 842, 'char_end': 849, 'chars': ' - *p )'}]}",github.com/ARMmbed/mbedtls/commit/83c9f495ffe70c7dd280b41fdfd4881485a3bc28,library/ssl_srv.c,cwe-190, +cwe-190,read_ujpg,"bool read_ujpg( void ) +{ + using namespace IOUtil; + using namespace Sirikata; +// colldata.start_decoder_worker_thread(std::bind(&simple_decoder, &colldata, str_in)); + unsigned char ujpg_mrk[ 64 ]; + // this is where we will enable seccomp, before reading user data + write_byte_bill(Billing::HEADER, true, 24); // for the fixed header + + str_out->call_size_callback(max_file_size); + uint32_t compressed_header_size = 0; + if (ReadFull(str_in, ujpg_mrk, 4) != 4) { + custom_exit(ExitCode::SHORT_READ); + } + write_byte_bill(Billing::HEADER, true, 4); + + compressed_header_size = LEtoUint32(ujpg_mrk); + if (compressed_header_size > 128 * 1024 * 1024 || max_file_size > 128 * 1024 * 1024) { + always_assert(false && ""Only support images < 128 megs""); + return false; // bool too big + } + bool pending_header_reads = false; + if (header_reader == NULL) { + std::vector > compressed_header_buffer(compressed_header_size); + IOUtil::ReadFull(str_in, compressed_header_buffer.data(), compressed_header_buffer.size()); + header_reader = new MemReadWriter((JpegAllocator())); + { + if (ujgversion == 1) { + JpegAllocator no_free_allocator; +#if !defined(USE_STANDARD_MEMORY_ALLOCATORS) && !defined(_WIN32) && !defined(EMSCRIPTEN) + no_free_allocator.setup_memory_subsystem(32 * 1024 * 1024, + 16, + &mem_init_nop, + &MemMgrAllocatorMalloc, + &mem_nop, + &mem_realloc_nop, + &MemMgrAllocatorMsize); +#endif + std::pair >, + JpegError> uncompressed_header_buffer( + ZlibDecoderDecompressionReader::Decompress(compressed_header_buffer.data(), + compressed_header_buffer.size(), + no_free_allocator, + max_file_size + 2048)); + if (uncompressed_header_buffer.second) { + always_assert(false && ""Data not properly zlib coded""); + return false; + } + zlib_hdrs = compressed_header_buffer.size(); + header_reader->SwapIn(uncompressed_header_buffer.first, 0); + } else { + std::pair >, + JpegError> uncompressed_header_buffer( + Sirikata::BrotliCodec::Decompress(compressed_header_buffer.data(), + compressed_header_buffer.size(), + JpegAllocator(), + max_file_size * 2 + 128 * 1024 * 1024)); + if (uncompressed_header_buffer.second) { + always_assert(false && ""Data not properly zlib coded""); + return false; + } + zlib_hdrs = compressed_header_buffer.size(); + header_reader->SwapIn(uncompressed_header_buffer.first, 0); + } + } + write_byte_bill(Billing::HEADER, + true, + compressed_header_buffer.size()); + } else { + always_assert(compressed_header_size == 0 && ""Special concatenation requires 0 size header""); + } + grbs = sizeof(EOI); + grbgdata = EOI; // if we don't have any garbage, assume FFD9 EOI + // read header from file + ReadFull(header_reader, ujpg_mrk, 3 ) ; + // check marker + if ( memcmp( ujpg_mrk, ""HDR"", 3 ) == 0 ) { + // read size of header, alloc memory + ReadFull(header_reader, ujpg_mrk, 4 ); + hdrs = LEtoUint32(ujpg_mrk); + hdrdata = (unsigned char*) aligned_alloc(hdrs); + memset(hdrdata, 0, hdrs); + if ( hdrdata == NULL ) { + fprintf( stderr, MEM_ERRMSG ); + errorlevel.store(2); + return false; + } + // read hdrdata + ReadFull(header_reader, hdrdata, hdrs ); + } + else { + fprintf( stderr, ""HDR marker not found"" ); + errorlevel.store(2); + return false; + } + bool memory_optimized_image = (filetype != UJG) && !g_allow_progressive; + // parse header for image-info + if ( !setup_imginfo_jpg(memory_optimized_image) ) + return false; + + // beginning here: recovery information (needed for exact JPEG recovery) + + // read padbit information from file + ReadFull(header_reader, ujpg_mrk, 3 ); + // check marker + if ( memcmp( ujpg_mrk, ""P0D"", 3 ) == 0 ) { + // This is a more nuanced pad byte that can have different values per bit + header_reader->Read( reinterpret_cast(&padbit), 1 ); + } + else if ( memcmp( ujpg_mrk, ""PAD"", 3 ) == 0 ) { + // this is a single pad bit that is implied to have all the same values + header_reader->Read( reinterpret_cast(&padbit), 1 ); + if (!(padbit == 0 || padbit == 1 ||padbit == -1)) { + while (write(2, + ""Legacy Padbit must be 0, 1 or -1\n"", + strlen(""Legacy Padbit must be 0, 1 or -1\n"")) < 0 + && errno == EINTR) { + } + custom_exit(ExitCode::STREAM_INCONSISTENT); + } + if (padbit == 1) { + padbit = 0x7f; // all 6 bits set + } + } + else { + fprintf( stderr, ""PAD marker not found"" ); + errorlevel.store(2); + return false; + } + std::vector thread_handoff; + // read further recovery information if any + while ( ReadFull(header_reader, ujpg_mrk, 3 ) == 3 ) { + // check marker + if ( memcmp( ujpg_mrk, ""CRS"", 3 ) == 0 ) { + rst_cnt_set = true; + ReadFull(header_reader, ujpg_mrk, 4); + rst_cnt.resize(LEtoUint32(ujpg_mrk)); + for (size_t i = 0; i < rst_cnt.size(); ++i) { + ReadFull(header_reader, ujpg_mrk, 4); + rst_cnt.at(i) = LEtoUint32(ujpg_mrk); + } + } else if ( memcmp( ujpg_mrk, ""HHX"", 2 ) == 0 ) { // only look at first two bytes + size_t to_alloc = ThreadHandoff::get_remaining_data_size_from_two_bytes(ujpg_mrk + 1) + 2; + if(to_alloc) { + std::vector data(to_alloc); + data[0] = ujpg_mrk[1]; + data[1] = ujpg_mrk[2]; + ReadFull(header_reader, &data[2], to_alloc - 2); + thread_handoff = ThreadHandoff::deserialize(&data[0], to_alloc); + } + } else if ( memcmp( ujpg_mrk, ""FRS"", 3 ) == 0 ) { + // read number of false set RST markers per scan from file + ReadFull(header_reader, ujpg_mrk, 4); + scnc = LEtoUint32(ujpg_mrk); + + rst_err.insert(rst_err.end(), scnc - rst_err.size(), 0); + // read data + ReadFull(header_reader, rst_err.data(), scnc ); + } + else if ( memcmp( ujpg_mrk, ""GRB"", 3 ) == 0 ) { + // read garbage (data after end of JPG) from file + ReadFull(header_reader, ujpg_mrk, 4); + grbs = LEtoUint32(ujpg_mrk); + grbgdata = aligned_alloc(grbs); + memset(grbgdata, 0, sizeof(grbs)); + if ( grbgdata == NULL ) { + fprintf( stderr, MEM_ERRMSG ); + errorlevel.store(2); + return false; + } + // read garbage data + ReadFull(header_reader, grbgdata, grbs ); + } + else if ( memcmp( ujpg_mrk, ""PGR"", 3 ) == 0 || memcmp( ujpg_mrk, ""PGE"", 3 ) == 0 ) { + // read prefix garbage (data before beginning of JPG) from file + if (ujpg_mrk[2] == 'E') { + // embedded jpeg: full header required + embedded_jpeg = true; + } + ReadFull(header_reader, ujpg_mrk, 4); + prefix_grbs = LEtoUint32(ujpg_mrk); + prefix_grbgdata = aligned_alloc(prefix_grbs); + memset(prefix_grbgdata, 0, sizeof(prefix_grbs)); + if ( prefix_grbgdata == NULL ) { + fprintf( stderr, MEM_ERRMSG ); + errorlevel.store(2); + return false; + } + // read garbage data + ReadFull(header_reader, prefix_grbgdata, prefix_grbs ); + } + else if ( memcmp( ujpg_mrk, ""SIZ"", 3 ) == 0 ) { + // full size of the original file + ReadFull(header_reader, ujpg_mrk, 4); + max_file_size = LEtoUint32(ujpg_mrk); + } + else if ( memcmp( ujpg_mrk, ""EEE"", 3) == 0) { + ReadFull(header_reader, ujpg_mrk, 28); + max_cmp = LEtoUint32(ujpg_mrk); + max_bpos = LEtoUint32(ujpg_mrk + 4); + max_sah = LEtoUint32(ujpg_mrk + 8); + max_dpos[0] = LEtoUint32(ujpg_mrk + 12); + max_dpos[1] = LEtoUint32(ujpg_mrk + 16); + max_dpos[2] = LEtoUint32(ujpg_mrk + 20); + max_dpos[3] = LEtoUint32(ujpg_mrk + 24); + early_eof_encountered = true; + colldata.set_truncation_bounds(max_cmp, max_bpos, max_dpos, max_sah); + } + else { + if (memcmp(ujpg_mrk, ""CNT"", 3) == 0 ) { + pending_header_reads = true; + break; + } else if (memcmp(ujpg_mrk, ""CMP"", 3) == 0 ) { + break; + } else { + fprintf( stderr, ""unknown data found"" ); + errorlevel.store(2); + } + return false; + } + } + if (!pending_header_reads) { + delete header_reader; + header_reader = NULL; + } + write_byte_bill(Billing::HEADER, + false, + 2 + hdrs + prefix_grbs + grbs); + + ReadFull(str_in, ujpg_mrk, 3 ) ; + write_byte_bill(Billing::HEADER, true, 3); + + write_byte_bill(Billing::DELIMITERS, true, 4 * NUM_THREADS); // trailing vpx_encode bits + write_byte_bill(Billing::HEADER, true, 4); //trailing size + + if (memcmp(ujpg_mrk, ""CMP"", 3) != 0) { + always_assert(false && ""CMP must be present (uncompressed) in the file or CNT continue marker""); + return false; // not a JPG + } + colldata.signal_worker_should_begin(); + g_decoder->initialize(str_in, thread_handoff); + colldata.start_decoder(g_decoder); + return true; +}","bool read_ujpg( void ) +{ + using namespace IOUtil; + using namespace Sirikata; +// colldata.start_decoder_worker_thread(std::bind(&simple_decoder, &colldata, str_in)); + unsigned char ujpg_mrk[ 64 ]; + // this is where we will enable seccomp, before reading user data + write_byte_bill(Billing::HEADER, true, 24); // for the fixed header + + str_out->call_size_callback(max_file_size); + uint32_t compressed_header_size = 0; + if (ReadFull(str_in, ujpg_mrk, 4) != 4) { + custom_exit(ExitCode::SHORT_READ); + } + write_byte_bill(Billing::HEADER, true, 4); + + compressed_header_size = LEtoUint32(ujpg_mrk); + if (compressed_header_size > 128 * 1024 * 1024 || max_file_size > 128 * 1024 * 1024) { + always_assert(false && ""Only support images < 128 megs""); + return false; // bool too big + } + bool pending_header_reads = false; + if (header_reader == NULL) { + std::vector > compressed_header_buffer(compressed_header_size); + IOUtil::ReadFull(str_in, compressed_header_buffer.data(), compressed_header_buffer.size()); + header_reader = new MemReadWriter((JpegAllocator())); + { + if (ujgversion == 1) { + JpegAllocator no_free_allocator; +#if !defined(USE_STANDARD_MEMORY_ALLOCATORS) && !defined(_WIN32) && !defined(EMSCRIPTEN) + no_free_allocator.setup_memory_subsystem(32 * 1024 * 1024, + 16, + &mem_init_nop, + &MemMgrAllocatorMalloc, + &mem_nop, + &mem_realloc_nop, + &MemMgrAllocatorMsize); +#endif + std::pair >, + JpegError> uncompressed_header_buffer( + ZlibDecoderDecompressionReader::Decompress(compressed_header_buffer.data(), + compressed_header_buffer.size(), + no_free_allocator, + max_file_size + 2048)); + if (uncompressed_header_buffer.second) { + always_assert(false && ""Data not properly zlib coded""); + return false; + } + zlib_hdrs = compressed_header_buffer.size(); + header_reader->SwapIn(uncompressed_header_buffer.first, 0); + } else { + std::pair >, + JpegError> uncompressed_header_buffer( + Sirikata::BrotliCodec::Decompress(compressed_header_buffer.data(), + compressed_header_buffer.size(), + JpegAllocator(), + ((size_t)max_file_size) * 2 + 128 * 1024 * 1024)); + if (uncompressed_header_buffer.second) { + always_assert(false && ""Data not properly zlib coded""); + return false; + } + zlib_hdrs = compressed_header_buffer.size(); + header_reader->SwapIn(uncompressed_header_buffer.first, 0); + } + } + write_byte_bill(Billing::HEADER, + true, + compressed_header_buffer.size()); + } else { + always_assert(compressed_header_size == 0 && ""Special concatenation requires 0 size header""); + } + grbs = sizeof(EOI); + grbgdata = EOI; // if we don't have any garbage, assume FFD9 EOI + // read header from file + ReadFull(header_reader, ujpg_mrk, 3 ) ; + // check marker + if ( memcmp( ujpg_mrk, ""HDR"", 3 ) == 0 ) { + // read size of header, alloc memory + ReadFull(header_reader, ujpg_mrk, 4 ); + hdrs = LEtoUint32(ujpg_mrk); + hdrdata = (unsigned char*) aligned_alloc(hdrs); + memset(hdrdata, 0, hdrs); + if ( hdrdata == NULL ) { + fprintf( stderr, MEM_ERRMSG ); + errorlevel.store(2); + return false; + } + // read hdrdata + ReadFull(header_reader, hdrdata, hdrs ); + } + else { + fprintf( stderr, ""HDR marker not found"" ); + errorlevel.store(2); + return false; + } + bool memory_optimized_image = (filetype != UJG) && !g_allow_progressive; + // parse header for image-info + if ( !setup_imginfo_jpg(memory_optimized_image) ) + return false; + + // beginning here: recovery information (needed for exact JPEG recovery) + + // read padbit information from file + ReadFull(header_reader, ujpg_mrk, 3 ); + // check marker + if ( memcmp( ujpg_mrk, ""P0D"", 3 ) == 0 ) { + // This is a more nuanced pad byte that can have different values per bit + header_reader->Read( reinterpret_cast(&padbit), 1 ); + } + else if ( memcmp( ujpg_mrk, ""PAD"", 3 ) == 0 ) { + // this is a single pad bit that is implied to have all the same values + header_reader->Read( reinterpret_cast(&padbit), 1 ); + if (!(padbit == 0 || padbit == 1 ||padbit == -1)) { + while (write(2, + ""Legacy Padbit must be 0, 1 or -1\n"", + strlen(""Legacy Padbit must be 0, 1 or -1\n"")) < 0 + && errno == EINTR) { + } + custom_exit(ExitCode::STREAM_INCONSISTENT); + } + if (padbit == 1) { + padbit = 0x7f; // all 6 bits set + } + } + else { + fprintf( stderr, ""PAD marker not found"" ); + errorlevel.store(2); + return false; + } + std::vector thread_handoff; + // read further recovery information if any + while ( ReadFull(header_reader, ujpg_mrk, 3 ) == 3 ) { + // check marker + if ( memcmp( ujpg_mrk, ""CRS"", 3 ) == 0 ) { + rst_cnt_set = true; + ReadFull(header_reader, ujpg_mrk, 4); + rst_cnt.resize(LEtoUint32(ujpg_mrk)); + for (size_t i = 0; i < rst_cnt.size(); ++i) { + ReadFull(header_reader, ujpg_mrk, 4); + rst_cnt.at(i) = LEtoUint32(ujpg_mrk); + } + } else if ( memcmp( ujpg_mrk, ""HHX"", 2 ) == 0 ) { // only look at first two bytes + size_t to_alloc = ThreadHandoff::get_remaining_data_size_from_two_bytes(ujpg_mrk + 1) + 2; + if(to_alloc) { + std::vector data(to_alloc); + data[0] = ujpg_mrk[1]; + data[1] = ujpg_mrk[2]; + ReadFull(header_reader, &data[2], to_alloc - 2); + thread_handoff = ThreadHandoff::deserialize(&data[0], to_alloc); + } + } else if ( memcmp( ujpg_mrk, ""FRS"", 3 ) == 0 ) { + // read number of false set RST markers per scan from file + ReadFull(header_reader, ujpg_mrk, 4); + scnc = LEtoUint32(ujpg_mrk); + + rst_err.insert(rst_err.end(), scnc - rst_err.size(), 0); + // read data + ReadFull(header_reader, rst_err.data(), scnc ); + } + else if ( memcmp( ujpg_mrk, ""GRB"", 3 ) == 0 ) { + // read garbage (data after end of JPG) from file + ReadFull(header_reader, ujpg_mrk, 4); + grbs = LEtoUint32(ujpg_mrk); + grbgdata = aligned_alloc(grbs); + memset(grbgdata, 0, sizeof(grbs)); + if ( grbgdata == NULL ) { + fprintf( stderr, MEM_ERRMSG ); + errorlevel.store(2); + return false; + } + // read garbage data + ReadFull(header_reader, grbgdata, grbs ); + } + else if ( memcmp( ujpg_mrk, ""PGR"", 3 ) == 0 || memcmp( ujpg_mrk, ""PGE"", 3 ) == 0 ) { + // read prefix garbage (data before beginning of JPG) from file + if (ujpg_mrk[2] == 'E') { + // embedded jpeg: full header required + embedded_jpeg = true; + } + ReadFull(header_reader, ujpg_mrk, 4); + prefix_grbs = LEtoUint32(ujpg_mrk); + prefix_grbgdata = aligned_alloc(prefix_grbs); + memset(prefix_grbgdata, 0, sizeof(prefix_grbs)); + if ( prefix_grbgdata == NULL ) { + fprintf( stderr, MEM_ERRMSG ); + errorlevel.store(2); + return false; + } + // read garbage data + ReadFull(header_reader, prefix_grbgdata, prefix_grbs ); + } + else if ( memcmp( ujpg_mrk, ""SIZ"", 3 ) == 0 ) { + // full size of the original file + ReadFull(header_reader, ujpg_mrk, 4); + max_file_size = LEtoUint32(ujpg_mrk); + } + else if ( memcmp( ujpg_mrk, ""EEE"", 3) == 0) { + ReadFull(header_reader, ujpg_mrk, 28); + max_cmp = LEtoUint32(ujpg_mrk); + max_bpos = LEtoUint32(ujpg_mrk + 4); + max_sah = LEtoUint32(ujpg_mrk + 8); + max_dpos[0] = LEtoUint32(ujpg_mrk + 12); + max_dpos[1] = LEtoUint32(ujpg_mrk + 16); + max_dpos[2] = LEtoUint32(ujpg_mrk + 20); + max_dpos[3] = LEtoUint32(ujpg_mrk + 24); + early_eof_encountered = true; + colldata.set_truncation_bounds(max_cmp, max_bpos, max_dpos, max_sah); + } + else { + if (memcmp(ujpg_mrk, ""CNT"", 3) == 0 ) { + pending_header_reads = true; + break; + } else if (memcmp(ujpg_mrk, ""CMP"", 3) == 0 ) { + break; + } else { + fprintf( stderr, ""unknown data found"" ); + errorlevel.store(2); + } + return false; + } + } + if (!pending_header_reads) { + delete header_reader; + header_reader = NULL; + } + write_byte_bill(Billing::HEADER, + false, + 2 + hdrs + prefix_grbs + grbs); + + ReadFull(str_in, ujpg_mrk, 3 ) ; + write_byte_bill(Billing::HEADER, true, 3); + + write_byte_bill(Billing::DELIMITERS, true, 4 * NUM_THREADS); // trailing vpx_encode bits + write_byte_bill(Billing::HEADER, true, 4); //trailing size + + if (memcmp(ujpg_mrk, ""CMP"", 3) != 0) { + always_assert(false && ""CMP must be present (uncompressed) in the file or CNT continue marker""); + return false; // not a JPG + } + colldata.signal_worker_should_begin(); + g_decoder->initialize(str_in, thread_handoff); + colldata.start_decoder(g_decoder); + return true; +}","{'deleted': [{'line_no': 59, 'char_start': 3293, 'char_end': 3398, 'line': ' max_file_size * 2 + 128 * 1024 * 1024));\n'}], 'added': [{'line_no': 59, 'char_start': 3293, 'char_end': 3408, 'line': ' ((size_t)max_file_size) * 2 + 128 * 1024 * 1024));\n'}]}","{'deleted': [], 'added': [{'char_start': 3357, 'char_end': 3366, 'chars': '((size_t)'}, {'char_start': 3379, 'char_end': 3380, 'chars': ')'}]}",github.com/dropbox/lepton/commit/6a5ceefac1162783fffd9506a3de39c85c725761,src/lepton/jpgcoder.cc,cwe-190, +cwe-416,__oom_reap_task_mm,"static bool __oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm) +{ + struct mmu_gather tlb; + struct vm_area_struct *vma; + bool ret = true; + + /* + * We have to make sure to not race with the victim exit path + * and cause premature new oom victim selection: + * __oom_reap_task_mm exit_mm + * mmget_not_zero + * mmput + * atomic_dec_and_test + * exit_oom_victim + * [...] + * out_of_memory + * select_bad_process + * # no TIF_MEMDIE task selects new victim + * unmap_page_range # frees some memory + */ + mutex_lock(&oom_lock); + + if (!down_read_trylock(&mm->mmap_sem)) { + ret = false; + trace_skip_task_reaping(tsk->pid); + goto unlock_oom; + } + + /* + * If the mm has notifiers then we would need to invalidate them around + * unmap_page_range and that is risky because notifiers can sleep and + * what they do is basically undeterministic. So let's have a short + * sleep to give the oom victim some more time. + * TODO: we really want to get rid of this ugly hack and make sure that + * notifiers cannot block for unbounded amount of time and add + * mmu_notifier_invalidate_range_{start,end} around unmap_page_range + */ + if (mm_has_notifiers(mm)) { + up_read(&mm->mmap_sem); + schedule_timeout_idle(HZ); + goto unlock_oom; + } + + /* + * MMF_OOM_SKIP is set by exit_mmap when the OOM reaper can't + * work on the mm anymore. The check for MMF_OOM_SKIP must run + * under mmap_sem for reading because it serializes against the + * down_write();up_write() cycle in exit_mmap(). + */ + if (test_bit(MMF_OOM_SKIP, &mm->flags)) { + up_read(&mm->mmap_sem); + trace_skip_task_reaping(tsk->pid); + goto unlock_oom; + } + + trace_start_task_reaping(tsk->pid); + + /* + * Tell all users of get_user/copy_from_user etc... that the content + * is no longer stable. No barriers really needed because unmapping + * should imply barriers already and the reader would hit a page fault + * if it stumbled over a reaped memory. + */ + set_bit(MMF_UNSTABLE, &mm->flags); + + tlb_gather_mmu(&tlb, mm, 0, -1); + for (vma = mm->mmap ; vma; vma = vma->vm_next) { + if (!can_madv_dontneed_vma(vma)) + continue; + + /* + * Only anonymous pages have a good chance to be dropped + * without additional steps which we cannot afford as we + * are OOM already. + * + * We do not even care about fs backed pages because all + * which are reclaimable have already been reclaimed and + * we do not want to block exit_mmap by keeping mm ref + * count elevated without a good reason. + */ + if (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED)) + unmap_page_range(&tlb, vma, vma->vm_start, vma->vm_end, + NULL); + } + tlb_finish_mmu(&tlb, 0, -1); + pr_info(""oom_reaper: reaped process %d (%s), now anon-rss:%lukB, file-rss:%lukB, shmem-rss:%lukB\n"", + task_pid_nr(tsk), tsk->comm, + K(get_mm_counter(mm, MM_ANONPAGES)), + K(get_mm_counter(mm, MM_FILEPAGES)), + K(get_mm_counter(mm, MM_SHMEMPAGES))); + up_read(&mm->mmap_sem); + + trace_finish_task_reaping(tsk->pid); +unlock_oom: + mutex_unlock(&oom_lock); + return ret; +}","static bool __oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm) +{ + struct mmu_gather tlb; + struct vm_area_struct *vma; + bool ret = true; + + /* + * We have to make sure to not race with the victim exit path + * and cause premature new oom victim selection: + * __oom_reap_task_mm exit_mm + * mmget_not_zero + * mmput + * atomic_dec_and_test + * exit_oom_victim + * [...] + * out_of_memory + * select_bad_process + * # no TIF_MEMDIE task selects new victim + * unmap_page_range # frees some memory + */ + mutex_lock(&oom_lock); + + if (!down_read_trylock(&mm->mmap_sem)) { + ret = false; + trace_skip_task_reaping(tsk->pid); + goto unlock_oom; + } + + /* + * If the mm has notifiers then we would need to invalidate them around + * unmap_page_range and that is risky because notifiers can sleep and + * what they do is basically undeterministic. So let's have a short + * sleep to give the oom victim some more time. + * TODO: we really want to get rid of this ugly hack and make sure that + * notifiers cannot block for unbounded amount of time and add + * mmu_notifier_invalidate_range_{start,end} around unmap_page_range + */ + if (mm_has_notifiers(mm)) { + up_read(&mm->mmap_sem); + schedule_timeout_idle(HZ); + goto unlock_oom; + } + + /* + * MMF_OOM_SKIP is set by exit_mmap when the OOM reaper can't + * work on the mm anymore. The check for MMF_OOM_SKIP must run + * under mmap_sem for reading because it serializes against the + * down_write();up_write() cycle in exit_mmap(). + */ + if (test_bit(MMF_OOM_SKIP, &mm->flags)) { + up_read(&mm->mmap_sem); + trace_skip_task_reaping(tsk->pid); + goto unlock_oom; + } + + trace_start_task_reaping(tsk->pid); + + /* + * Tell all users of get_user/copy_from_user etc... that the content + * is no longer stable. No barriers really needed because unmapping + * should imply barriers already and the reader would hit a page fault + * if it stumbled over a reaped memory. + */ + set_bit(MMF_UNSTABLE, &mm->flags); + + for (vma = mm->mmap ; vma; vma = vma->vm_next) { + if (!can_madv_dontneed_vma(vma)) + continue; + + /* + * Only anonymous pages have a good chance to be dropped + * without additional steps which we cannot afford as we + * are OOM already. + * + * We do not even care about fs backed pages because all + * which are reclaimable have already been reclaimed and + * we do not want to block exit_mmap by keeping mm ref + * count elevated without a good reason. + */ + if (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED)) { + tlb_gather_mmu(&tlb, mm, vma->vm_start, vma->vm_end); + unmap_page_range(&tlb, vma, vma->vm_start, vma->vm_end, + NULL); + tlb_finish_mmu(&tlb, vma->vm_start, vma->vm_end); + } + } + pr_info(""oom_reaper: reaped process %d (%s), now anon-rss:%lukB, file-rss:%lukB, shmem-rss:%lukB\n"", + task_pid_nr(tsk), tsk->comm, + K(get_mm_counter(mm, MM_ANONPAGES)), + K(get_mm_counter(mm, MM_FILEPAGES)), + K(get_mm_counter(mm, MM_SHMEMPAGES))); + up_read(&mm->mmap_sem); + + trace_finish_task_reaping(tsk->pid); +unlock_oom: + mutex_unlock(&oom_lock); + return ret; +}","{'deleted': [{'line_no': 66, 'char_start': 1997, 'char_end': 2031, 'line': '\ttlb_gather_mmu(&tlb, mm, 0, -1);\n'}, {'line_no': 81, 'char_start': 2504, 'char_end': 2565, 'line': '\t\tif (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED))\n'}, {'line_no': 85, 'char_start': 2640, 'char_end': 2670, 'line': '\ttlb_finish_mmu(&tlb, 0, -1);\n'}], 'added': [{'line_no': 80, 'char_start': 2470, 'char_end': 2533, 'line': '\t\tif (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED)) {\n'}, {'line_no': 81, 'char_start': 2533, 'char_end': 2590, 'line': '\t\t\ttlb_gather_mmu(&tlb, mm, vma->vm_start, vma->vm_end);\n'}, {'line_no': 84, 'char_start': 2662, 'char_end': 2715, 'line': '\t\t\ttlb_finish_mmu(&tlb, vma->vm_start, vma->vm_end);\n'}, {'line_no': 85, 'char_start': 2715, 'char_end': 2719, 'line': '\t\t}\n'}]}","{'deleted': [{'char_start': 1998, 'char_end': 2032, 'chars': 'tlb_gather_mmu(&tlb, mm, 0, -1);\n\t'}, {'char_start': 2565, 'char_end': 2565, 'chars': ''}, {'char_start': 2638, 'char_end': 2640, 'chars': '}\n'}, {'char_start': 2662, 'char_end': 2663, 'chars': '0'}, {'char_start': 2666, 'char_end': 2667, 'chars': '1'}], 'added': [{'char_start': 2530, 'char_end': 2589, 'chars': ' {\n\t\t\ttlb_gather_mmu(&tlb, mm, vma->vm_start, vma->vm_end);'}, {'char_start': 2663, 'char_end': 2664, 'chars': '\t'}, {'char_start': 2686, 'char_end': 2699, 'chars': 'vma->vm_start'}, {'char_start': 2701, 'char_end': 2704, 'chars': 'vma'}, {'char_start': 2705, 'char_end': 2712, 'chars': '>vm_end'}, {'char_start': 2714, 'char_end': 2721, 'chars': '\n\t\t}\n\t}'}]}",github.com/torvalds/linux/commit/687cb0884a714ff484d038e9190edc874edcf146,mm/oom_kill.c,cwe-416, +cwe-416,gf_m2ts_process_pat,"static void gf_m2ts_process_pat(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status) +{ + GF_M2TS_Program *prog; + GF_M2TS_SECTION_ES *pmt; + u32 i, nb_progs, evt_type; + u32 nb_sections; + u32 data_size; + unsigned char *data; + GF_M2TS_Section *section; + + /*wait for the last section */ + if (!(status&GF_M2TS_TABLE_END)) return; + + /*skip if already received*/ + if (status&GF_M2TS_TABLE_REPEAT) { + if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PAT_REPEAT, NULL); + return; + } + + nb_sections = gf_list_count(sections); + if (nb_sections > 1) { + GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""PAT on multiple sections not supported\n"")); + } + + section = (GF_M2TS_Section *)gf_list_get(sections, 0); + data = section->data; + data_size = section->data_size; + + if (!(status&GF_M2TS_TABLE_UPDATE) && gf_list_count(ts->programs)) { + if (ts->pat->demux_restarted) { + ts->pat->demux_restarted = 0; + } else { + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""Multiple different PAT on single TS found, ignoring new PAT declaration (table id %d - extended table id %d)\n"", table_id, ex_table_id)); + } + return; + } + nb_progs = data_size / 4; + + for (i=0; init) { + ts->nit = gf_m2ts_section_filter_new(gf_m2ts_process_nit, 0); + } + } else { + GF_SAFEALLOC(prog, GF_M2TS_Program); + if (!prog) { + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""Fail to allocate program for pid %d\n"", pid)); + return; + } + prog->streams = gf_list_new(); + prog->pmt_pid = pid; + prog->number = number; + prog->ts = ts; + gf_list_add(ts->programs, prog); + GF_SAFEALLOC(pmt, GF_M2TS_SECTION_ES); + if (!pmt) { + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""Fail to allocate pmt filter for pid %d\n"", pid)); + return; + } + pmt->flags = GF_M2TS_ES_IS_SECTION; + gf_list_add(prog->streams, pmt); + pmt->pid = prog->pmt_pid; + pmt->program = prog; + ts->ess[pmt->pid] = (GF_M2TS_ES *)pmt; + pmt->sec = gf_m2ts_section_filter_new(gf_m2ts_process_pmt, 0); + } + } + + evt_type = (status&GF_M2TS_TABLE_UPDATE) ? GF_M2TS_EVT_PAT_UPDATE : GF_M2TS_EVT_PAT_FOUND; + if (ts->on_event) ts->on_event(ts, evt_type, NULL); +}","static void gf_m2ts_process_pat(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status) +{ + GF_M2TS_Program *prog; + GF_M2TS_SECTION_ES *pmt; + u32 i, nb_progs, evt_type; + u32 nb_sections; + u32 data_size; + unsigned char *data; + GF_M2TS_Section *section; + + /*wait for the last section */ + if (!(status&GF_M2TS_TABLE_END)) return; + + /*skip if already received*/ + if (status&GF_M2TS_TABLE_REPEAT) { + if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PAT_REPEAT, NULL); + return; + } + + nb_sections = gf_list_count(sections); + if (nb_sections > 1) { + GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""PAT on multiple sections not supported\n"")); + } + + section = (GF_M2TS_Section *)gf_list_get(sections, 0); + data = section->data; + data_size = section->data_size; + + if (!(status&GF_M2TS_TABLE_UPDATE) && gf_list_count(ts->programs)) { + if (ts->pat->demux_restarted) { + ts->pat->demux_restarted = 0; + } else { + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""Multiple different PAT on single TS found, ignoring new PAT declaration (table id %d - extended table id %d)\n"", table_id, ex_table_id)); + } + return; + } + nb_progs = data_size / 4; + + for (i=0; init) { + ts->nit = gf_m2ts_section_filter_new(gf_m2ts_process_nit, 0); + } + } else if (!pid) { + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""Broken PAT found reserved PID 0, ignoring\n"", pid)); + } else if (! ts->ess[pid]) { + GF_SAFEALLOC(prog, GF_M2TS_Program); + if (!prog) { + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""Fail to allocate program for pid %d\n"", pid)); + return; + } + prog->streams = gf_list_new(); + prog->pmt_pid = pid; + prog->number = number; + prog->ts = ts; + gf_list_add(ts->programs, prog); + GF_SAFEALLOC(pmt, GF_M2TS_SECTION_ES); + if (!pmt) { + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""Fail to allocate pmt filter for pid %d\n"", pid)); + return; + } + pmt->flags = GF_M2TS_ES_IS_SECTION; + gf_list_add(prog->streams, pmt); + pmt->pid = prog->pmt_pid; + pmt->program = prog; + ts->ess[pmt->pid] = (GF_M2TS_ES *)pmt; + pmt->sec = gf_m2ts_section_filter_new(gf_m2ts_process_pmt, 0); + } + } + + evt_type = (status&GF_M2TS_TABLE_UPDATE) ? GF_M2TS_EVT_PAT_UPDATE : GF_M2TS_EVT_PAT_FOUND; + if (ts->on_event) ts->on_event(ts, evt_type, NULL); +}","{'deleted': [{'line_no': 48, 'char_start': 1458, 'char_end': 1469, 'line': '\t\t} else {\n'}], 'added': [{'line_no': 48, 'char_start': 1458, 'char_end': 1479, 'line': '\t\t} else if (!pid) {\n'}, {'line_no': 49, 'char_start': 1479, 'char_end': 1576, 'line': '\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""Broken PAT found reserved PID 0, ignoring\\n"", pid));\n'}, {'line_no': 50, 'char_start': 1576, 'char_end': 1607, 'line': '\t\t} else if (! ts->ess[pid]) {\n'}]}","{'deleted': [], 'added': [{'char_start': 1467, 'char_end': 1605, 'chars': 'if (!pid) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""Broken PAT found reserved PID 0, ignoring\\n"", pid));\n\t\t} else if (! ts->ess[pid]) '}]}",github.com/gpac/gpac/commit/98b727637e32d1d4824101d8947e2dbd573d4fc8,src/media_tools/mpegts.c,cwe-416, +cwe-416,ReadPWPImage,"static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + FILE + *file; + + Image + *image, + *next_image, + *pwp_image; + + ImageInfo + *read_info; + + int + c, + unique_file; + + MagickBooleanType + status; + + register Image + *p; + + register ssize_t + i; + + size_t + filesize, + length; + + ssize_t + count; + + unsigned char + magick[MaxTextExtent]; + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + if (image_info->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", + image_info->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickSignature); + pwp_image=AcquireImage(image_info); + image=pwp_image; + status=OpenBlob(image_info,pwp_image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + return((Image *) NULL); + count=ReadBlob(pwp_image,5,magick); + if ((count != 5) || (LocaleNCompare((char *) magick,""SFW95"",5) != 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + read_info=CloneImageInfo(image_info); + (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL, + (void *) NULL); + SetImageInfoBlob(read_info,(void *) NULL,0); + unique_file=AcquireUniqueFileResource(read_info->filename); + for ( ; ; ) + { + for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image)) + { + for (i=0; i < 17; i++) + magick[i]=magick[i+1]; + magick[17]=(unsigned char) c; + if (LocaleNCompare((char *) (magick+12),""SFW94A"",6) == 0) + break; + } + if (c == EOF) + break; + if (LocaleNCompare((char *) (magick+12),""SFW94A"",6) != 0) + { + (void) RelinquishUniqueFileResource(read_info->filename); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + /* + Dump SFW image to a temporary file. + */ + file=(FILE *) NULL; + if (unique_file != -1) + file=fdopen(unique_file,""wb""); + if ((unique_file == -1) || (file == (FILE *) NULL)) + { + (void) RelinquishUniqueFileResource(read_info->filename); + ThrowFileException(exception,FileOpenError,""UnableToWriteFile"", + image->filename); + image=DestroyImageList(image); + return((Image *) NULL); + } + length=fwrite(""SFW94A"",1,6,file); + (void) length; + filesize=65535UL*magick[2]+256L*magick[1]+magick[0]; + for (i=0; i < (ssize_t) filesize; i++) + { + c=ReadBlobByte(pwp_image); + (void) fputc(c,file); + } + (void) fclose(file); + next_image=ReadImage(read_info,exception); + if (next_image == (Image *) NULL) + break; + (void) FormatLocaleString(next_image->filename,MaxTextExtent, + ""slide_%02ld.sfw"",(long) next_image->scene); + if (image == (Image *) NULL) + image=next_image; + else + { + /* + Link image into image list. + */ + for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ; + next_image->previous=p; + next_image->scene=p->scene+1; + p->next=next_image; + } + if (image_info->number_scenes != 0) + if (next_image->scene >= (image_info->scene+image_info->number_scenes-1)) + break; + status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image), + GetBlobSize(pwp_image)); + if (status == MagickFalse) + break; + } + if (unique_file != -1) + (void) close(unique_file); + (void) RelinquishUniqueFileResource(read_info->filename); + read_info=DestroyImageInfo(read_info); + (void) CloseBlob(pwp_image); + pwp_image=DestroyImage(pwp_image); + if (EOFBlob(image) != MagickFalse) + { + char + *message; + + message=GetExceptionMessage(errno); + (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, + ""UnexpectedEndOfFile"",""`%s': %s"",image->filename,message); + message=DestroyString(message); + } + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +}","static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + FILE + *file; + + Image + *image, + *next_image, + *pwp_image; + + ImageInfo + *read_info; + + int + c, + unique_file; + + MagickBooleanType + status; + + register Image + *p; + + register ssize_t + i; + + size_t + filesize, + length; + + ssize_t + count; + + unsigned char + magick[MaxTextExtent]; + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + if (image_info->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", + image_info->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickSignature); + pwp_image=AcquireImage(image_info); + image=pwp_image; + status=OpenBlob(image_info,pwp_image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + return((Image *) NULL); + count=ReadBlob(pwp_image,5,magick); + if ((count != 5) || (LocaleNCompare((char *) magick,""SFW95"",5) != 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + read_info=CloneImageInfo(image_info); + (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL, + (void *) NULL); + SetImageInfoBlob(read_info,(void *) NULL,0); + unique_file=AcquireUniqueFileResource(read_info->filename); + for ( ; ; ) + { + for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image)) + { + for (i=0; i < 17; i++) + magick[i]=magick[i+1]; + magick[17]=(unsigned char) c; + if (LocaleNCompare((char *) (magick+12),""SFW94A"",6) == 0) + break; + } + if (c == EOF) + break; + if (LocaleNCompare((char *) (magick+12),""SFW94A"",6) != 0) + { + (void) RelinquishUniqueFileResource(read_info->filename); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + /* + Dump SFW image to a temporary file. + */ + file=(FILE *) NULL; + if (unique_file != -1) + file=fdopen(unique_file,""wb""); + if ((unique_file == -1) || (file == (FILE *) NULL)) + { + (void) RelinquishUniqueFileResource(read_info->filename); + ThrowFileException(exception,FileOpenError,""UnableToWriteFile"", + image->filename); + image=DestroyImageList(image); + return((Image *) NULL); + } + length=fwrite(""SFW94A"",1,6,file); + (void) length; + filesize=65535UL*magick[2]+256L*magick[1]+magick[0]; + for (i=0; i < (ssize_t) filesize; i++) + { + c=ReadBlobByte(pwp_image); + (void) fputc(c,file); + } + (void) fclose(file); + next_image=ReadImage(read_info,exception); + if (next_image == (Image *) NULL) + break; + (void) FormatLocaleString(next_image->filename,MaxTextExtent, + ""slide_%02ld.sfw"",(long) next_image->scene); + if (image == (Image *) NULL) + image=next_image; + else + { + /* + Link image into image list. + */ + for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ; + next_image->previous=p; + next_image->scene=p->scene+1; + p->next=next_image; + } + if (image_info->number_scenes != 0) + if (next_image->scene >= (image_info->scene+image_info->number_scenes-1)) + break; + status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image), + GetBlobSize(pwp_image)); + if (status == MagickFalse) + break; + } + if (unique_file != -1) + (void) close(unique_file); + (void) RelinquishUniqueFileResource(read_info->filename); + read_info=DestroyImageInfo(read_info); + if (EOFBlob(image) != MagickFalse) + { + char + *message; + + message=GetExceptionMessage(errno); + (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, + ""UnexpectedEndOfFile"",""`%s': %s"",image->filename,message); + message=DestroyString(message); + } + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +}","{'deleted': [{'line_no': 129, 'char_start': 3575, 'char_end': 3606, 'line': ' (void) CloseBlob(pwp_image);\n'}, {'line_no': 130, 'char_start': 3606, 'char_end': 3643, 'line': ' pwp_image=DestroyImage(pwp_image);\n'}], 'added': []}","{'deleted': [{'char_start': 3577, 'char_end': 3645, 'chars': '(void) CloseBlob(pwp_image);\n pwp_image=DestroyImage(pwp_image);\n '}], 'added': []}",github.com/ImageMagick/ImageMagick/commit/ecc03a2518c2b7dd375fde3a040fdae0bdf6a521,coders/pwp.c,cwe-416, +cwe-416,skb_segment,"struct sk_buff *skb_segment(struct sk_buff *head_skb, + netdev_features_t features) +{ + struct sk_buff *segs = NULL; + struct sk_buff *tail = NULL; + struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list; + skb_frag_t *frag = skb_shinfo(head_skb)->frags; + unsigned int mss = skb_shinfo(head_skb)->gso_size; + unsigned int doffset = head_skb->data - skb_mac_header(head_skb); + unsigned int offset = doffset; + unsigned int tnl_hlen = skb_tnl_header_len(head_skb); + unsigned int headroom; + unsigned int len; + __be16 proto; + bool csum; + int sg = !!(features & NETIF_F_SG); + int nfrags = skb_shinfo(head_skb)->nr_frags; + int err = -ENOMEM; + int i = 0; + int pos; + + proto = skb_network_protocol(head_skb); + if (unlikely(!proto)) + return ERR_PTR(-EINVAL); + + csum = !!can_checksum_protocol(features, proto); + __skb_push(head_skb, doffset); + headroom = skb_headroom(head_skb); + pos = skb_headlen(head_skb); + + do { + struct sk_buff *nskb; + skb_frag_t *nskb_frag; + int hsize; + int size; + + len = head_skb->len - offset; + if (len > mss) + len = mss; + + hsize = skb_headlen(head_skb) - offset; + if (hsize < 0) + hsize = 0; + if (hsize > len || !sg) + hsize = len; + + if (!hsize && i >= nfrags && skb_headlen(list_skb) && + (skb_headlen(list_skb) == len || sg)) { + BUG_ON(skb_headlen(list_skb) > len); + + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; + pos += skb_headlen(list_skb); + + while (pos < offset + len) { + BUG_ON(i >= nfrags); + + size = skb_frag_size(frag); + if (pos + size > offset + len) + break; + + i++; + pos += size; + frag++; + } + + nskb = skb_clone(list_skb, GFP_ATOMIC); + list_skb = list_skb->next; + + if (unlikely(!nskb)) + goto err; + + if (unlikely(pskb_trim(nskb, len))) { + kfree_skb(nskb); + goto err; + } + + hsize = skb_end_offset(nskb); + if (skb_cow_head(nskb, doffset + headroom)) { + kfree_skb(nskb); + goto err; + } + + nskb->truesize += skb_end_offset(nskb) - hsize; + skb_release_head_state(nskb); + __skb_push(nskb, doffset); + } else { + nskb = __alloc_skb(hsize + doffset + headroom, + GFP_ATOMIC, skb_alloc_rx_flag(head_skb), + NUMA_NO_NODE); + + if (unlikely(!nskb)) + goto err; + + skb_reserve(nskb, headroom); + __skb_put(nskb, doffset); + } + + if (segs) + tail->next = nskb; + else + segs = nskb; + tail = nskb; + + __copy_skb_header(nskb, head_skb); + nskb->mac_len = head_skb->mac_len; + + skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom); + + skb_copy_from_linear_data_offset(head_skb, -tnl_hlen, + nskb->data - tnl_hlen, + doffset + tnl_hlen); + + if (nskb->len == len + doffset) + goto perform_csum_check; + + if (!sg) { + nskb->ip_summed = CHECKSUM_NONE; + nskb->csum = skb_copy_and_csum_bits(head_skb, offset, + skb_put(nskb, len), + len, 0); + continue; + } + + nskb_frag = skb_shinfo(nskb)->frags; + + skb_copy_from_linear_data_offset(head_skb, offset, + skb_put(nskb, hsize), hsize); + + skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags & + SKBTX_SHARED_FRAG; + + while (pos < offset + len) { + if (i >= nfrags) { + BUG_ON(skb_headlen(list_skb)); + + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; + + BUG_ON(!nfrags); + + list_skb = list_skb->next; + } + + if (unlikely(skb_shinfo(nskb)->nr_frags >= + MAX_SKB_FRAGS)) { + net_warn_ratelimited( + ""skb_segment: too many frags: %u %u\n"", + pos, mss); + goto err; + } + + *nskb_frag = *frag; + __skb_frag_ref(nskb_frag); + size = skb_frag_size(nskb_frag); + + if (pos < offset) { + nskb_frag->page_offset += offset - pos; + skb_frag_size_sub(nskb_frag, offset - pos); + } + + skb_shinfo(nskb)->nr_frags++; + + if (pos + size <= offset + len) { + i++; + frag++; + pos += size; + } else { + skb_frag_size_sub(nskb_frag, pos + size - (offset + len)); + goto skip_fraglist; + } + + nskb_frag++; + } + +skip_fraglist: + nskb->data_len = len - hsize; + nskb->len += nskb->data_len; + nskb->truesize += nskb->data_len; + +perform_csum_check: + if (!csum) { + nskb->csum = skb_checksum(nskb, doffset, + nskb->len - doffset, 0); + nskb->ip_summed = CHECKSUM_NONE; + } + } while ((offset += len) < head_skb->len); + + return segs; + +err: + kfree_skb_list(segs); + return ERR_PTR(err); +}","struct sk_buff *skb_segment(struct sk_buff *head_skb, + netdev_features_t features) +{ + struct sk_buff *segs = NULL; + struct sk_buff *tail = NULL; + struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list; + skb_frag_t *frag = skb_shinfo(head_skb)->frags; + unsigned int mss = skb_shinfo(head_skb)->gso_size; + unsigned int doffset = head_skb->data - skb_mac_header(head_skb); + struct sk_buff *frag_skb = head_skb; + unsigned int offset = doffset; + unsigned int tnl_hlen = skb_tnl_header_len(head_skb); + unsigned int headroom; + unsigned int len; + __be16 proto; + bool csum; + int sg = !!(features & NETIF_F_SG); + int nfrags = skb_shinfo(head_skb)->nr_frags; + int err = -ENOMEM; + int i = 0; + int pos; + + proto = skb_network_protocol(head_skb); + if (unlikely(!proto)) + return ERR_PTR(-EINVAL); + + csum = !!can_checksum_protocol(features, proto); + __skb_push(head_skb, doffset); + headroom = skb_headroom(head_skb); + pos = skb_headlen(head_skb); + + do { + struct sk_buff *nskb; + skb_frag_t *nskb_frag; + int hsize; + int size; + + len = head_skb->len - offset; + if (len > mss) + len = mss; + + hsize = skb_headlen(head_skb) - offset; + if (hsize < 0) + hsize = 0; + if (hsize > len || !sg) + hsize = len; + + if (!hsize && i >= nfrags && skb_headlen(list_skb) && + (skb_headlen(list_skb) == len || sg)) { + BUG_ON(skb_headlen(list_skb) > len); + + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; + frag_skb = list_skb; + pos += skb_headlen(list_skb); + + while (pos < offset + len) { + BUG_ON(i >= nfrags); + + size = skb_frag_size(frag); + if (pos + size > offset + len) + break; + + i++; + pos += size; + frag++; + } + + nskb = skb_clone(list_skb, GFP_ATOMIC); + list_skb = list_skb->next; + + if (unlikely(!nskb)) + goto err; + + if (unlikely(pskb_trim(nskb, len))) { + kfree_skb(nskb); + goto err; + } + + hsize = skb_end_offset(nskb); + if (skb_cow_head(nskb, doffset + headroom)) { + kfree_skb(nskb); + goto err; + } + + nskb->truesize += skb_end_offset(nskb) - hsize; + skb_release_head_state(nskb); + __skb_push(nskb, doffset); + } else { + nskb = __alloc_skb(hsize + doffset + headroom, + GFP_ATOMIC, skb_alloc_rx_flag(head_skb), + NUMA_NO_NODE); + + if (unlikely(!nskb)) + goto err; + + skb_reserve(nskb, headroom); + __skb_put(nskb, doffset); + } + + if (segs) + tail->next = nskb; + else + segs = nskb; + tail = nskb; + + __copy_skb_header(nskb, head_skb); + nskb->mac_len = head_skb->mac_len; + + skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom); + + skb_copy_from_linear_data_offset(head_skb, -tnl_hlen, + nskb->data - tnl_hlen, + doffset + tnl_hlen); + + if (nskb->len == len + doffset) + goto perform_csum_check; + + if (!sg) { + nskb->ip_summed = CHECKSUM_NONE; + nskb->csum = skb_copy_and_csum_bits(head_skb, offset, + skb_put(nskb, len), + len, 0); + continue; + } + + nskb_frag = skb_shinfo(nskb)->frags; + + skb_copy_from_linear_data_offset(head_skb, offset, + skb_put(nskb, hsize), hsize); + + skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags & + SKBTX_SHARED_FRAG; + + while (pos < offset + len) { + if (i >= nfrags) { + BUG_ON(skb_headlen(list_skb)); + + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; + frag_skb = list_skb; + + BUG_ON(!nfrags); + + list_skb = list_skb->next; + } + + if (unlikely(skb_shinfo(nskb)->nr_frags >= + MAX_SKB_FRAGS)) { + net_warn_ratelimited( + ""skb_segment: too many frags: %u %u\n"", + pos, mss); + goto err; + } + + if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC))) + goto err; + + *nskb_frag = *frag; + __skb_frag_ref(nskb_frag); + size = skb_frag_size(nskb_frag); + + if (pos < offset) { + nskb_frag->page_offset += offset - pos; + skb_frag_size_sub(nskb_frag, offset - pos); + } + + skb_shinfo(nskb)->nr_frags++; + + if (pos + size <= offset + len) { + i++; + frag++; + pos += size; + } else { + skb_frag_size_sub(nskb_frag, pos + size - (offset + len)); + goto skip_fraglist; + } + + nskb_frag++; + } + +skip_fraglist: + nskb->data_len = len - hsize; + nskb->len += nskb->data_len; + nskb->truesize += nskb->data_len; + +perform_csum_check: + if (!csum) { + nskb->csum = skb_checksum(nskb, doffset, + nskb->len - doffset, 0); + nskb->ip_summed = CHECKSUM_NONE; + } + } while ((offset += len) < head_skb->len); + + return segs; + +err: + kfree_skb_list(segs); + return ERR_PTR(err); +}","{'deleted': [], 'added': [{'line_no': 10, 'char_start': 380, 'char_end': 418, 'line': '\tstruct sk_buff *frag_skb = head_skb;\n'}, {'line_no': 55, 'char_start': 1439, 'char_end': 1463, 'line': '\t\t\tfrag_skb = list_skb;\n'}, {'line_no': 143, 'char_start': 3321, 'char_end': 3346, 'line': '\t\t\t\tfrag_skb = list_skb;\n'}, {'line_no': 158, 'char_start': 3586, 'char_end': 3643, 'line': '\t\t\tif (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC)))\n'}, {'line_no': 159, 'char_start': 3643, 'char_end': 3657, 'line': '\t\t\t\tgoto err;\n'}, {'line_no': 160, 'char_start': 3657, 'char_end': 3658, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 381, 'char_end': 419, 'chars': 'struct sk_buff *frag_skb = head_skb;\n\t'}, {'char_start': 1437, 'char_end': 1461, 'chars': ';\n\t\t\tfrag_skb = list_skb'}, {'char_start': 3321, 'char_end': 3346, 'chars': '\t\t\t\tfrag_skb = list_skb;\n'}, {'char_start': 3584, 'char_end': 3656, 'chars': '\n\n\t\t\tif (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC)))\n\t\t\t\tgoto err;'}]}",github.com/torvalds/linux/commit/1fd819ecb90cc9b822cd84d3056ddba315d3340f,net/core/skbuff.c,cwe-416, +cwe-416,usb_serial_console_disconnect,"void usb_serial_console_disconnect(struct usb_serial *serial) +{ + if (serial->port[0] == usbcons_info.port) { + usb_serial_console_exit(); + usb_serial_put(serial); + } +}","void usb_serial_console_disconnect(struct usb_serial *serial) +{ + if (serial->port[0] && serial->port[0] == usbcons_info.port) { + usb_serial_console_exit(); + usb_serial_put(serial); + } +}","{'deleted': [{'line_no': 3, 'char_start': 64, 'char_end': 109, 'line': '\tif (serial->port[0] == usbcons_info.port) {\n'}], 'added': [{'line_no': 3, 'char_start': 64, 'char_end': 128, 'line': '\tif (serial->port[0] && serial->port[0] == usbcons_info.port) {\n'}]}","{'deleted': [], 'added': [{'char_start': 85, 'char_end': 104, 'chars': '&& serial->port[0] '}]}",github.com/torvalds/linux/commit/bd998c2e0df0469707503023d50d46cf0b10c787,drivers/usb/serial/console.c,cwe-416, +cwe-416,blk_init_allocated_queue,"int blk_init_allocated_queue(struct request_queue *q) +{ + WARN_ON_ONCE(q->mq_ops); + + q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, q->cmd_size); + if (!q->fq) + return -ENOMEM; + + if (q->init_rq_fn && q->init_rq_fn(q, q->fq->flush_rq, GFP_KERNEL)) + goto out_free_flush_queue; + + if (blk_init_rl(&q->root_rl, q, GFP_KERNEL)) + goto out_exit_flush_rq; + + INIT_WORK(&q->timeout_work, blk_timeout_work); + q->queue_flags |= QUEUE_FLAG_DEFAULT; + + /* + * This also sets hw/phys segments, boundary and size + */ + blk_queue_make_request(q, blk_queue_bio); + + q->sg_reserved_size = INT_MAX; + + if (elevator_init(q)) + goto out_exit_flush_rq; + return 0; + +out_exit_flush_rq: + if (q->exit_rq_fn) + q->exit_rq_fn(q, q->fq->flush_rq); +out_free_flush_queue: + blk_free_flush_queue(q->fq); + return -ENOMEM; +}","int blk_init_allocated_queue(struct request_queue *q) +{ + WARN_ON_ONCE(q->mq_ops); + + q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, q->cmd_size); + if (!q->fq) + return -ENOMEM; + + if (q->init_rq_fn && q->init_rq_fn(q, q->fq->flush_rq, GFP_KERNEL)) + goto out_free_flush_queue; + + if (blk_init_rl(&q->root_rl, q, GFP_KERNEL)) + goto out_exit_flush_rq; + + INIT_WORK(&q->timeout_work, blk_timeout_work); + q->queue_flags |= QUEUE_FLAG_DEFAULT; + + /* + * This also sets hw/phys segments, boundary and size + */ + blk_queue_make_request(q, blk_queue_bio); + + q->sg_reserved_size = INT_MAX; + + if (elevator_init(q)) + goto out_exit_flush_rq; + return 0; + +out_exit_flush_rq: + if (q->exit_rq_fn) + q->exit_rq_fn(q, q->fq->flush_rq); +out_free_flush_queue: + blk_free_flush_queue(q->fq); + q->fq = NULL; + return -ENOMEM; +}","{'deleted': [], 'added': [{'line_no': 34, 'char_start': 768, 'char_end': 783, 'line': '\tq->fq = NULL;\n'}]}","{'deleted': [], 'added': [{'char_start': 769, 'char_end': 784, 'chars': 'q->fq = NULL;\n\t'}]}",github.com/torvalds/linux/commit/54648cf1ec2d7f4b6a71767799c45676a138ca24,block/blk-core.c,cwe-416, +cwe-416,snd_timer_open,"int snd_timer_open(struct snd_timer_instance **ti, + char *owner, struct snd_timer_id *tid, + unsigned int slave_id) +{ + struct snd_timer *timer; + struct snd_timer_instance *timeri = NULL; + struct device *card_dev_to_put = NULL; + int err; + + mutex_lock(®ister_mutex); + if (tid->dev_class == SNDRV_TIMER_CLASS_SLAVE) { + /* open a slave instance */ + if (tid->dev_sclass <= SNDRV_TIMER_SCLASS_NONE || + tid->dev_sclass > SNDRV_TIMER_SCLASS_OSS_SEQUENCER) { + pr_debug(""ALSA: timer: invalid slave class %i\n"", + tid->dev_sclass); + err = -EINVAL; + goto unlock; + } + timeri = snd_timer_instance_new(owner, NULL); + if (!timeri) { + err = -ENOMEM; + goto unlock; + } + timeri->slave_class = tid->dev_sclass; + timeri->slave_id = tid->device; + timeri->flags |= SNDRV_TIMER_IFLG_SLAVE; + list_add_tail(&timeri->open_list, &snd_timer_slave_list); + err = snd_timer_check_slave(timeri); + if (err < 0) { + snd_timer_close_locked(timeri, &card_dev_to_put); + timeri = NULL; + } + goto unlock; + } + + /* open a master instance */ + timer = snd_timer_find(tid); +#ifdef CONFIG_MODULES + if (!timer) { + mutex_unlock(®ister_mutex); + snd_timer_request(tid); + mutex_lock(®ister_mutex); + timer = snd_timer_find(tid); + } +#endif + if (!timer) { + err = -ENODEV; + goto unlock; + } + if (!list_empty(&timer->open_list_head)) { + timeri = list_entry(timer->open_list_head.next, + struct snd_timer_instance, open_list); + if (timeri->flags & SNDRV_TIMER_IFLG_EXCLUSIVE) { + err = -EBUSY; + timeri = NULL; + goto unlock; + } + } + if (timer->num_instances >= timer->max_instances) { + err = -EBUSY; + goto unlock; + } + timeri = snd_timer_instance_new(owner, timer); + if (!timeri) { + err = -ENOMEM; + goto unlock; + } + /* take a card refcount for safe disconnection */ + if (timer->card) + get_device(&timer->card->card_dev); + timeri->slave_class = tid->dev_sclass; + timeri->slave_id = slave_id; + + if (list_empty(&timer->open_list_head) && timer->hw.open) { + err = timer->hw.open(timer); + if (err) { + kfree(timeri->owner); + kfree(timeri); + timeri = NULL; + + if (timer->card) + card_dev_to_put = &timer->card->card_dev; + module_put(timer->module); + goto unlock; + } + } + + list_add_tail(&timeri->open_list, &timer->open_list_head); + timer->num_instances++; + err = snd_timer_check_master(timeri); + if (err < 0) { + snd_timer_close_locked(timeri, &card_dev_to_put); + timeri = NULL; + } + + unlock: + mutex_unlock(®ister_mutex); + /* put_device() is called after unlock for avoiding deadlock */ + if (card_dev_to_put) + put_device(card_dev_to_put); + *ti = timeri; + return err; +}","int snd_timer_open(struct snd_timer_instance **ti, + char *owner, struct snd_timer_id *tid, + unsigned int slave_id) +{ + struct snd_timer *timer; + struct snd_timer_instance *timeri = NULL; + struct device *card_dev_to_put = NULL; + int err; + + mutex_lock(®ister_mutex); + if (tid->dev_class == SNDRV_TIMER_CLASS_SLAVE) { + /* open a slave instance */ + if (tid->dev_sclass <= SNDRV_TIMER_SCLASS_NONE || + tid->dev_sclass > SNDRV_TIMER_SCLASS_OSS_SEQUENCER) { + pr_debug(""ALSA: timer: invalid slave class %i\n"", + tid->dev_sclass); + err = -EINVAL; + goto unlock; + } + timeri = snd_timer_instance_new(owner, NULL); + if (!timeri) { + err = -ENOMEM; + goto unlock; + } + timeri->slave_class = tid->dev_sclass; + timeri->slave_id = tid->device; + timeri->flags |= SNDRV_TIMER_IFLG_SLAVE; + list_add_tail(&timeri->open_list, &snd_timer_slave_list); + err = snd_timer_check_slave(timeri); + if (err < 0) { + snd_timer_close_locked(timeri, &card_dev_to_put); + timeri = NULL; + } + goto unlock; + } + + /* open a master instance */ + timer = snd_timer_find(tid); +#ifdef CONFIG_MODULES + if (!timer) { + mutex_unlock(®ister_mutex); + snd_timer_request(tid); + mutex_lock(®ister_mutex); + timer = snd_timer_find(tid); + } +#endif + if (!timer) { + err = -ENODEV; + goto unlock; + } + if (!list_empty(&timer->open_list_head)) { + struct snd_timer_instance *t = + list_entry(timer->open_list_head.next, + struct snd_timer_instance, open_list); + if (t->flags & SNDRV_TIMER_IFLG_EXCLUSIVE) { + err = -EBUSY; + goto unlock; + } + } + if (timer->num_instances >= timer->max_instances) { + err = -EBUSY; + goto unlock; + } + timeri = snd_timer_instance_new(owner, timer); + if (!timeri) { + err = -ENOMEM; + goto unlock; + } + /* take a card refcount for safe disconnection */ + if (timer->card) + get_device(&timer->card->card_dev); + timeri->slave_class = tid->dev_sclass; + timeri->slave_id = slave_id; + + if (list_empty(&timer->open_list_head) && timer->hw.open) { + err = timer->hw.open(timer); + if (err) { + kfree(timeri->owner); + kfree(timeri); + timeri = NULL; + + if (timer->card) + card_dev_to_put = &timer->card->card_dev; + module_put(timer->module); + goto unlock; + } + } + + list_add_tail(&timeri->open_list, &timer->open_list_head); + timer->num_instances++; + err = snd_timer_check_master(timeri); + if (err < 0) { + snd_timer_close_locked(timeri, &card_dev_to_put); + timeri = NULL; + } + + unlock: + mutex_unlock(®ister_mutex); + /* put_device() is called after unlock for avoiding deadlock */ + if (card_dev_to_put) + put_device(card_dev_to_put); + *ti = timeri; + return err; +}","{'deleted': [{'line_no': 52, 'char_start': 1334, 'char_end': 1384, 'line': '\t\ttimeri = list_entry(timer->open_list_head.next,\n'}, {'line_no': 54, 'char_start': 1431, 'char_end': 1483, 'line': '\t\tif (timeri->flags & SNDRV_TIMER_IFLG_EXCLUSIVE) {\n'}, {'line_no': 56, 'char_start': 1500, 'char_end': 1518, 'line': '\t\t\ttimeri = NULL;\n'}], 'added': [{'line_no': 52, 'char_start': 1334, 'char_end': 1367, 'line': '\t\tstruct snd_timer_instance *t =\n'}, {'line_no': 53, 'char_start': 1367, 'char_end': 1409, 'line': '\t\t\tlist_entry(timer->open_list_head.next,\n'}, {'line_no': 55, 'char_start': 1456, 'char_end': 1503, 'line': '\t\tif (t->flags & SNDRV_TIMER_IFLG_EXCLUSIVE) {\n'}]}","{'deleted': [{'char_start': 1344, 'char_end': 1345, 'chars': ' '}, {'char_start': 1438, 'char_end': 1443, 'chars': 'imeri'}, {'char_start': 1498, 'char_end': 1516, 'chars': ';\n\t\t\ttimeri = NULL'}], 'added': [{'char_start': 1336, 'char_end': 1347, 'chars': 'struct snd_'}, {'char_start': 1352, 'char_end': 1353, 'chars': '_'}, {'char_start': 1354, 'char_end': 1361, 'chars': 'nstance'}, {'char_start': 1362, 'char_end': 1364, 'chars': '*t'}, {'char_start': 1365, 'char_end': 1370, 'chars': '=\n\t\t\t'}]}",github.com/torvalds/linux/commit/e7af6307a8a54f0b873960b32b6a644f2d0fbd97,sound/core/timer.c,cwe-416, +cwe-476,tensorflow::KernelAndDeviceOp::Run,"Status KernelAndDeviceOp::Run( + ScopedStepContainer* step_container, const EagerKernelArgs& inputs, + std::vector* outputs, + CancellationManager* cancellation_manager, + const absl::optional& remote_func_params) { + OpKernelContext::Params params; + params.device = device_; + params.frame_iter = FrameAndIter(0, 0); + params.inputs = inputs.GetTensorValues(); + params.op_kernel = kernel_.get(); + params.resource_manager = device_->resource_manager(); + params.input_alloc_attrs = &input_alloc_attrs_; + params.output_attr_array = output_alloc_attrs_.data(); + params.function_library = flr_; + params.slice_reader_cache = &slice_reader_cache_; + params.rendezvous = rendezvous_; + OpExecutionState* op_execution_state = nullptr; + + CancellationManager default_cancellation_manager; + if (cancellation_manager) { + params.cancellation_manager = cancellation_manager; + } else if (kernel_->is_deferred()) { + op_execution_state = new OpExecutionState; + params.cancellation_manager = &op_execution_state->cancellation_manager; + params.inc_num_deferred_ops_function = [op_execution_state]() { + op_execution_state->Ref(); + }; + params.dec_num_deferred_ops_function = [op_execution_state]() { + op_execution_state->Unref(); + }; + } else { + params.cancellation_manager = &default_cancellation_manager; + } + + params.log_memory = log_memory_; + + params.runner = get_runner(); + + params.step_container = + step_container == nullptr ? &step_container_ : step_container; + auto step_container_cleanup = gtl::MakeCleanup([step_container, this] { + if (step_container == nullptr) { + this->step_container_.CleanUp(); + } + }); + + params.collective_executor = + collective_executor_ ? collective_executor_->get() : nullptr; + + OpKernelContext context(¶ms); + + { + port::ScopedFlushDenormal flush; + port::ScopedSetRound round(FE_TONEAREST); + // 'AnnotatedTraceMe' will trace both scheduling time on host and execution + // time on device of the OpKernel. + profiler::AnnotatedTraceMe activity( + [&] { return kernel_->TraceString(context, /*verbose=*/false); }, + profiler::TraceMeLevel::kInfo); + device_->Compute(kernel_.get(), &context); + } + + // Clean up execution op_execution_state if deferred ops aren't running. + if (op_execution_state != nullptr) { + op_execution_state->Unref(); + } + + if (!context.status().ok()) return context.status(); + + if (outputs != nullptr) { + outputs->clear(); + for (int i = 0; i < context.num_outputs(); ++i) { + outputs->push_back(Tensor(*context.mutable_output(i))); + } + } + return Status::OK(); +}","Status KernelAndDeviceOp::Run( + ScopedStepContainer* step_container, const EagerKernelArgs& inputs, + std::vector* outputs, + CancellationManager* cancellation_manager, + const absl::optional& remote_func_params) { + OpKernelContext::Params params; + params.device = device_; + params.frame_iter = FrameAndIter(0, 0); + params.inputs = inputs.GetTensorValues(); + params.op_kernel = kernel_.get(); + params.resource_manager = device_->resource_manager(); + params.input_alloc_attrs = &input_alloc_attrs_; + params.output_attr_array = output_alloc_attrs_.data(); + params.function_library = flr_; + params.slice_reader_cache = &slice_reader_cache_; + params.rendezvous = rendezvous_; + OpExecutionState* op_execution_state = nullptr; + + CancellationManager default_cancellation_manager; + if (cancellation_manager) { + params.cancellation_manager = cancellation_manager; + } else if (kernel_->is_deferred()) { + op_execution_state = new OpExecutionState; + params.cancellation_manager = &op_execution_state->cancellation_manager; + params.inc_num_deferred_ops_function = [op_execution_state]() { + op_execution_state->Ref(); + }; + params.dec_num_deferred_ops_function = [op_execution_state]() { + op_execution_state->Unref(); + }; + } else { + params.cancellation_manager = &default_cancellation_manager; + } + + params.log_memory = log_memory_; + + params.runner = get_runner(); + + params.step_container = + step_container == nullptr ? &step_container_ : step_container; + auto step_container_cleanup = gtl::MakeCleanup([step_container, this] { + if (step_container == nullptr) { + this->step_container_.CleanUp(); + } + }); + + params.collective_executor = + collective_executor_ ? collective_executor_->get() : nullptr; + + OpKernelContext context(¶ms); + + { + port::ScopedFlushDenormal flush; + port::ScopedSetRound round(FE_TONEAREST); + // 'AnnotatedTraceMe' will trace both scheduling time on host and execution + // time on device of the OpKernel. + profiler::AnnotatedTraceMe activity( + [&] { return kernel_->TraceString(context, /*verbose=*/false); }, + profiler::TraceMeLevel::kInfo); + device_->Compute(kernel_.get(), &context); + } + + // Clean up execution op_execution_state if deferred ops aren't running. + if (op_execution_state != nullptr) { + op_execution_state->Unref(); + } + + if (!context.status().ok()) return context.status(); + + if (outputs != nullptr) { + outputs->clear(); + for (int i = 0; i < context.num_outputs(); ++i) { + const auto* output_tensor = context.mutable_output(i); + if (output_tensor != nullptr) { + outputs->push_back(Tensor(*output_tensor)); + } else { + outputs->push_back(Tensor()); + } + } + } + return Status::OK(); +}","{'deleted': [{'line_no': 73, 'char_start': 2575, 'char_end': 2637, 'line': ' outputs->push_back(Tensor(*context.mutable_output(i)));\n'}], 'added': [{'line_no': 73, 'char_start': 2575, 'char_end': 2636, 'line': ' const auto* output_tensor = context.mutable_output(i);\n'}, {'line_no': 74, 'char_start': 2636, 'char_end': 2674, 'line': ' if (output_tensor != nullptr) {\n'}, {'line_no': 75, 'char_start': 2674, 'char_end': 2726, 'line': ' outputs->push_back(Tensor(*output_tensor));\n'}, {'line_no': 76, 'char_start': 2726, 'char_end': 2741, 'line': ' } else {\n'}, {'line_no': 77, 'char_start': 2741, 'char_end': 2779, 'line': ' outputs->push_back(Tensor());\n'}, {'line_no': 78, 'char_start': 2779, 'char_end': 2787, 'line': ' }\n'}]}","{'deleted': [{'char_start': 2608, 'char_end': 2609, 'chars': 'c'}, {'char_start': 2610, 'char_end': 2614, 'chars': 'ntex'}, {'char_start': 2615, 'char_end': 2617, 'chars': '.m'}, {'char_start': 2619, 'char_end': 2621, 'chars': 'ab'}, {'char_start': 2623, 'char_end': 2624, 'chars': '_'}, {'char_start': 2631, 'char_end': 2633, 'chars': 'i)'}], 'added': [{'char_start': 2581, 'char_end': 2682, 'chars': 'const auto* output_tensor = context.mutable_output(i);\n if (output_tensor != nullptr) {\n '}, {'char_start': 2710, 'char_end': 2711, 'chars': 'u'}, {'char_start': 2712, 'char_end': 2714, 'chars': 'pu'}, {'char_start': 2715, 'char_end': 2716, 'chars': '_'}, {'char_start': 2717, 'char_end': 2735, 'chars': 'ensor));\n } e'}, {'char_start': 2736, 'char_end': 2737, 'chars': 's'}, {'char_start': 2738, 'char_end': 2749, 'chars': ' {\n '}, {'char_start': 2755, 'char_end': 2767, 'chars': 's->push_back'}, {'char_start': 2768, 'char_end': 2775, 'chars': 'Tensor('}, {'char_start': 2778, 'char_end': 2786, 'chars': '\n }'}]}",github.com/tensorflow/tensorflow/commit/da8558533d925694483d2c136a9220d6d49d843c,tensorflow/core/common_runtime/eager/kernel_and_device.cc,cwe-476, +cwe-476,check_client_passwd,"static bool check_client_passwd(PgSocket *client, const char *passwd) +{ + char md5[MD5_PASSWD_LEN + 1]; + const char *correct; + PgUser *user = client->auth_user; + + /* disallow empty passwords */ + if (!*passwd || !*user->passwd) + return false; + + switch (cf_auth_type) { + case AUTH_PLAIN: + return strcmp(user->passwd, passwd) == 0; + case AUTH_CRYPT: + correct = crypt(user->passwd, (char *)client->tmp_login_salt); + return correct && strcmp(correct, passwd) == 0; + case AUTH_MD5: + if (strlen(passwd) != MD5_PASSWD_LEN) + return false; + if (!isMD5(user->passwd)) + pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd); + pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5); + return strcmp(md5, passwd) == 0; + } + return false; +}","static bool check_client_passwd(PgSocket *client, const char *passwd) +{ + char md5[MD5_PASSWD_LEN + 1]; + const char *correct; + PgUser *user = client->auth_user; + + /* auth_user may be missing */ + if (!user) { + slog_error(client, ""Password packet before auth packet?""); + return false; + } + + /* disallow empty passwords */ + if (!*passwd || !*user->passwd) + return false; + + switch (cf_auth_type) { + case AUTH_PLAIN: + return strcmp(user->passwd, passwd) == 0; + case AUTH_CRYPT: + correct = crypt(user->passwd, (char *)client->tmp_login_salt); + return correct && strcmp(correct, passwd) == 0; + case AUTH_MD5: + if (strlen(passwd) != MD5_PASSWD_LEN) + return false; + if (!isMD5(user->passwd)) + pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd); + pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5); + return strcmp(md5, passwd) == 0; + } + return false; +}","{'deleted': [], 'added': [{'line_no': 7, 'char_start': 161, 'char_end': 193, 'line': '\t/* auth_user may be missing */\n'}, {'line_no': 8, 'char_start': 193, 'char_end': 207, 'line': '\tif (!user) {\n'}, {'line_no': 9, 'char_start': 207, 'char_end': 268, 'line': '\t\tslog_error(client, ""Password packet before auth packet?"");\n'}, {'line_no': 10, 'char_start': 268, 'char_end': 284, 'line': '\t\treturn false;\n'}, {'line_no': 11, 'char_start': 284, 'char_end': 287, 'line': '\t}\n'}, {'line_no': 12, 'char_start': 287, 'char_end': 288, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 165, 'char_end': 292, 'chars': 'auth_user may be missing */\n\tif (!user) {\n\t\tslog_error(client, ""Password packet before auth packet?"");\n\t\treturn false;\n\t}\n\n\t/* '}]}",github.com/pgbouncer/pgbouncer/commit/edab5be6665b9e8de66c25ba527509b229468573,src/client.c,cwe-476, +cwe-476,rds_tcp_kill_sock,"static void rds_tcp_kill_sock(struct net *net) +{ + struct rds_tcp_connection *tc, *_tc; + struct sock *sk; + LIST_HEAD(tmp_list); + struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid); + + rds_tcp_listen_stop(rtn->rds_tcp_listen_sock); + rtn->rds_tcp_listen_sock = NULL; + flush_work(&rtn->rds_tcp_accept_w); + spin_lock_irq(&rds_tcp_conn_lock); + list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) { + struct net *c_net = read_pnet(&tc->conn->c_net); + + if (net != c_net) + continue; + list_move_tail(&tc->t_tcp_node, &tmp_list); + } + spin_unlock_irq(&rds_tcp_conn_lock); + list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node) { + sk = tc->t_sock->sk; + sk->sk_prot->disconnect(sk, 0); + tcp_done(sk); + if (tc->conn->c_passive) + rds_conn_destroy(tc->conn->c_passive); + rds_conn_destroy(tc->conn); + } +}","static void rds_tcp_kill_sock(struct net *net) +{ + struct rds_tcp_connection *tc, *_tc; + struct sock *sk; + LIST_HEAD(tmp_list); + struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid); + + rds_tcp_listen_stop(rtn->rds_tcp_listen_sock); + rtn->rds_tcp_listen_sock = NULL; + flush_work(&rtn->rds_tcp_accept_w); + spin_lock_irq(&rds_tcp_conn_lock); + list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) { + struct net *c_net = read_pnet(&tc->conn->c_net); + + if (net != c_net) + continue; + list_move_tail(&tc->t_tcp_node, &tmp_list); + } + spin_unlock_irq(&rds_tcp_conn_lock); + list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node) { + if (tc->t_sock) { + sk = tc->t_sock->sk; + sk->sk_prot->disconnect(sk, 0); + tcp_done(sk); + } + if (tc->conn->c_passive) + rds_conn_destroy(tc->conn->c_passive); + rds_conn_destroy(tc->conn); + } +}","{'deleted': [{'line_no': 21, 'char_start': 644, 'char_end': 667, 'line': '\t\tsk = tc->t_sock->sk;\n'}, {'line_no': 22, 'char_start': 667, 'char_end': 701, 'line': '\t\tsk->sk_prot->disconnect(sk, 0);\n'}, {'line_no': 23, 'char_start': 701, 'char_end': 717, 'line': '\t\ttcp_done(sk);\n'}], 'added': [{'line_no': 21, 'char_start': 644, 'char_end': 664, 'line': '\t\tif (tc->t_sock) {\n'}, {'line_no': 22, 'char_start': 664, 'char_end': 688, 'line': '\t\t\tsk = tc->t_sock->sk;\n'}, {'line_no': 23, 'char_start': 688, 'char_end': 723, 'line': '\t\t\tsk->sk_prot->disconnect(sk, 0);\n'}, {'line_no': 24, 'char_start': 723, 'char_end': 740, 'line': '\t\t\ttcp_done(sk);\n'}, {'line_no': 25, 'char_start': 740, 'char_end': 744, 'line': '\t\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 646, 'char_end': 667, 'chars': 'if (tc->t_sock) {\n\t\t\t'}, {'char_start': 690, 'char_end': 691, 'chars': '\t'}, {'char_start': 725, 'char_end': 726, 'chars': '\t'}, {'char_start': 739, 'char_end': 743, 'chars': '\n\t\t}'}]}",github.com/torvalds/linux/commit/91573ae4aed0a49660abdad4d42f2a0db995ee5e,net/rds/tcp.c,cwe-476, +cwe-476,ReadXCFImage,"static Image *ReadXCFImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + char + magick[14]; + + Image + *image; + + int + foundPropEnd = 0; + + MagickBooleanType + status; + + MagickOffsetType + offset; + + register ssize_t + i; + + size_t + image_type, + length; + + ssize_t + count; + + XCFDocInfo + doc_info; + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + if (image_info->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", + image_info->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickSignature); + image=AcquireImage(image_info); + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + count=ReadBlob(image,14,(unsigned char *) magick); + if ((count != 14) || + (LocaleNCompare((char *) magick,""gimp xcf"",8) != 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + (void) ResetMagickMemory(&doc_info,0,sizeof(XCFDocInfo)); + doc_info.exception=exception; + doc_info.width=ReadBlobMSBLong(image); + doc_info.height=ReadBlobMSBLong(image); + if ((doc_info.width > 262144) || (doc_info.height > 262144)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + doc_info.image_type=ReadBlobMSBLong(image); + /* + Initialize image attributes. + */ + image->columns=doc_info.width; + image->rows=doc_info.height; + image_type=doc_info.image_type; + doc_info.file_size=GetBlobSize(image); + image->compression=NoCompression; + image->depth=8; + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + { + InheritException(exception,&image->exception); + return(DestroyImageList(image)); + } + if (image_type == GIMP_RGB) + ; + else + if (image_type == GIMP_GRAY) + image->colorspace=GRAYColorspace; + else + if (image_type == GIMP_INDEXED) + ThrowReaderException(CoderError,""ColormapTypeNotSupported""); + (void) SetImageOpacity(image,OpaqueOpacity); + (void) SetImageBackgroundColor(image); + /* + Read properties. + */ + while ((foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse)) + { + PropType prop_type = (PropType) ReadBlobMSBLong(image); + size_t prop_size = ReadBlobMSBLong(image); + + switch (prop_type) + { + case PROP_END: + foundPropEnd=1; + break; + case PROP_COLORMAP: + { + /* Cannot rely on prop_size here--the value is set incorrectly + by some Gimp versions. + */ + size_t num_colours = ReadBlobMSBLong(image); + if (DiscardBlobBytes(image,3*num_colours) == MagickFalse) + ThrowFileException(&image->exception,CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + /* + if (info->file_version == 0) + { + gint i; + + g_message (_(""XCF warning: version 0 of XCF file format\n"" + ""did not save indexed colormaps correctly.\n"" + ""Substituting grayscale map."")); + info->cp += + xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1); + gimage->cmap = g_new (guchar, gimage->num_cols*3); + xcf_seek_pos (info, info->cp + gimage->num_cols); + for (i = 0; inum_cols; i++) + { + gimage->cmap[i*3+0] = i; + gimage->cmap[i*3+1] = i; + gimage->cmap[i*3+2] = i; + } + } + else + { + info->cp += + xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1); + gimage->cmap = g_new (guchar, gimage->num_cols*3); + info->cp += + xcf_read_int8 (info->fp, + (guint8*) gimage->cmap, gimage->num_cols*3); + } + */ + break; + } + case PROP_COMPRESSION: + { + doc_info.compression = ReadBlobByte(image); + if ((doc_info.compression != COMPRESS_NONE) && + (doc_info.compression != COMPRESS_RLE) && + (doc_info.compression != COMPRESS_ZLIB) && + (doc_info.compression != COMPRESS_FRACTAL)) + ThrowReaderException(CorruptImageError,""UnrecognizedImageCompression""); + } + break; + + case PROP_GUIDES: + { + /* just skip it - we don't care about guides */ + if (DiscardBlobBytes(image,prop_size) == MagickFalse) + ThrowFileException(&image->exception,CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + } + break; + + case PROP_RESOLUTION: + { + /* float xres = (float) */ (void) ReadBlobMSBLong(image); + /* float yres = (float) */ (void) ReadBlobMSBLong(image); + + /* + if (xres < GIMP_MIN_RESOLUTION || xres > GIMP_MAX_RESOLUTION || + yres < GIMP_MIN_RESOLUTION || yres > GIMP_MAX_RESOLUTION) + { + g_message (""Warning, resolution out of range in XCF file""); + xres = gimage->gimp->config->default_xresolution; + yres = gimage->gimp->config->default_yresolution; + } + */ + + + /* BOGUS: we don't write these yet because we aren't + reading them properly yet :( + image->x_resolution = xres; + image->y_resolution = yres; + */ + } + break; + + case PROP_TATTOO: + { + /* we need to read it, even if we ignore it */ + /*size_t tattoo_state = */ (void) ReadBlobMSBLong(image); + } + break; + + case PROP_PARASITES: + { + /* BOGUS: we may need these for IPTC stuff */ + if (DiscardBlobBytes(image,prop_size) == MagickFalse) + ThrowFileException(&image->exception,CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + /* + gssize_t base = info->cp; + GimpParasite *p; + + while (info->cp - base < prop_size) + { + p = xcf_load_parasite (info); + gimp_image_parasite_attach (gimage, p); + gimp_parasite_free (p); + } + if (info->cp - base != prop_size) + g_message (""Error detected while loading an image's parasites""); + */ + } + break; + + case PROP_UNIT: + { + /* BOGUS: ignore for now... */ + /*size_t unit = */ (void) ReadBlobMSBLong(image); + } + break; + + case PROP_PATHS: + { + /* BOGUS: just skip it for now */ + if (DiscardBlobBytes(image,prop_size) == MagickFalse) + ThrowFileException(&image->exception,CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + + /* + PathList *paths = xcf_load_bzpaths (gimage, info); + gimp_image_set_paths (gimage, paths); + */ + } + break; + + case PROP_USER_UNIT: + { + char unit_string[1000]; + /*BOGUS: ignored for now */ + /*float factor = (float) */ (void) ReadBlobMSBLong(image); + /* size_t digits = */ (void) ReadBlobMSBLong(image); + for (i=0; i<5; i++) + (void) ReadBlobStringWithLongSize(image, unit_string, + sizeof(unit_string)); + } + break; + + default: + { + int buf[16]; + ssize_t amount; + + /* read over it... */ + while ((prop_size > 0) && (EOFBlob(image) == MagickFalse)) + { + amount=(ssize_t) MagickMin(16, prop_size); + amount=(ssize_t) ReadBlob(image,(size_t) amount,(unsigned char *) &buf); + if (!amount) + ThrowReaderException(CorruptImageError,""CorruptImage""); + prop_size -= (size_t) MagickMin(16,(size_t) amount); + } + } + break; + } + } + if (foundPropEnd == MagickFalse) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + + if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) + { + ; /* do nothing, were just pinging! */ + } + else + { + int + current_layer = 0, + foundAllLayers = MagickFalse, + number_layers = 0; + + MagickOffsetType + oldPos=TellBlob(image); + + XCFLayerInfo + *layer_info; + + /* + The read pointer. + */ + do + { + ssize_t offset = ReadBlobMSBSignedLong(image); + if (offset == 0) + foundAllLayers=MagickTrue; + else + number_layers++; + if (EOFBlob(image) != MagickFalse) + { + ThrowFileException(exception,CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + break; + } + } while (foundAllLayers == MagickFalse); + doc_info.number_layers=number_layers; + offset=SeekBlob(image,oldPos,SEEK_SET); /* restore the position! */ + if (offset < 0) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + /* allocate our array of layer info blocks */ + length=(size_t) number_layers; + layer_info=(XCFLayerInfo *) AcquireQuantumMemory(length, + sizeof(*layer_info)); + if (layer_info == (XCFLayerInfo *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + (void) ResetMagickMemory(layer_info,0,number_layers*sizeof(XCFLayerInfo)); + for ( ; ; ) + { + MagickBooleanType + layer_ok; + + MagickOffsetType + offset, + saved_pos; + + /* read in the offset of the next layer */ + offset=(MagickOffsetType) ReadBlobMSBLong(image); + /* if the offset is 0 then we are at the end + * of the layer list. + */ + if (offset == 0) + break; + /* save the current position as it is where the + * next layer offset is stored. + */ + saved_pos=TellBlob(image); + /* seek to the layer offset */ + if (SeekBlob(image,offset,SEEK_SET) != offset) + ThrowReaderException(ResourceLimitError,""NotEnoughPixelData""); + /* read in the layer */ + layer_ok=ReadOneLayer(image_info,image,&doc_info, + &layer_info[current_layer],current_layer); + if (layer_ok == MagickFalse) + { + int j; + + for (j=0; j < current_layer; j++) + layer_info[j].image=DestroyImage(layer_info[j].image); + layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + /* restore the saved position so we'll be ready to + * read the next offset. + */ + offset=SeekBlob(image, saved_pos, SEEK_SET); + current_layer++; + } +#if 0 + { + /* NOTE: XCF layers are REVERSED from composite order! */ + signed int j; + for (j=number_layers-1; j>=0; j--) { + /* BOGUS: need to consider layer blending modes!! */ + + if ( layer_info[j].visible ) { /* only visible ones, please! */ + CompositeImage(image, OverCompositeOp, layer_info[j].image, + layer_info[j].offset_x, layer_info[j].offset_y ); + layer_info[j].image =DestroyImage( layer_info[j].image ); + + /* If we do this, we'll get REAL gray images! */ + if ( image_type == GIMP_GRAY ) { + QuantizeInfo qi; + GetQuantizeInfo(&qi); + qi.colorspace = GRAYColorspace; + QuantizeImage( &qi, layer_info[j].image ); + } + } + } + } +#else + { + /* NOTE: XCF layers are REVERSED from composite order! */ + ssize_t j; + + /* now reverse the order of the layers as they are put + into subimages + */ + for (j=(long) number_layers-1; j >= 0; j--) + AppendImageToList(&image,layer_info[j].image); + } +#endif + + layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info); + +#if 0 /* BOGUS: do we need the channels?? */ + while (MagickTrue) + { + /* read in the offset of the next channel */ + info->cp += xcf_read_int32 (info->fp, &offset, 1); + + /* if the offset is 0 then we are at the end + * of the channel list. + */ + if (offset == 0) + break; + + /* save the current position as it is where the + * next channel offset is stored. + */ + saved_pos = info->cp; + + /* seek to the channel offset */ + xcf_seek_pos (info, offset); + + /* read in the layer */ + channel = xcf_load_channel (info, gimage); + if (channel == 0) + goto error; + + num_successful_elements++; + + /* add the channel to the image if its not the selection */ + if (channel != gimage->selection_mask) + gimp_image_add_channel (gimage, channel, -1); + + /* restore the saved position so we'll be ready to + * read the next offset. + */ + xcf_seek_pos (info, saved_pos); + } +#endif + } + + (void) CloseBlob(image); + DestroyImage(RemoveFirstImageFromList(&image)); + if (image_type == GIMP_GRAY) + image->type=GrayscaleType; + return(GetFirstImageInList(image)); +}","static Image *ReadXCFImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + char + magick[14]; + + Image + *image; + + int + foundPropEnd = 0; + + MagickBooleanType + status; + + MagickOffsetType + offset; + + register ssize_t + i; + + size_t + image_type, + length; + + ssize_t + count; + + XCFDocInfo + doc_info; + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + if (image_info->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", + image_info->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickSignature); + image=AcquireImage(image_info); + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + count=ReadBlob(image,14,(unsigned char *) magick); + if ((count != 14) || + (LocaleNCompare((char *) magick,""gimp xcf"",8) != 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + (void) ResetMagickMemory(&doc_info,0,sizeof(XCFDocInfo)); + doc_info.exception=exception; + doc_info.width=ReadBlobMSBLong(image); + doc_info.height=ReadBlobMSBLong(image); + if ((doc_info.width > 262144) || (doc_info.height > 262144)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + doc_info.image_type=ReadBlobMSBLong(image); + /* + Initialize image attributes. + */ + image->columns=doc_info.width; + image->rows=doc_info.height; + image_type=doc_info.image_type; + doc_info.file_size=GetBlobSize(image); + image->compression=NoCompression; + image->depth=8; + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + { + InheritException(exception,&image->exception); + return(DestroyImageList(image)); + } + if (image_type == GIMP_RGB) + ; + else + if (image_type == GIMP_GRAY) + image->colorspace=GRAYColorspace; + else + if (image_type == GIMP_INDEXED) + ThrowReaderException(CoderError,""ColormapTypeNotSupported""); + (void) SetImageOpacity(image,OpaqueOpacity); + (void) SetImageBackgroundColor(image); + /* + Read properties. + */ + while ((foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse)) + { + PropType prop_type = (PropType) ReadBlobMSBLong(image); + size_t prop_size = ReadBlobMSBLong(image); + + switch (prop_type) + { + case PROP_END: + foundPropEnd=1; + break; + case PROP_COLORMAP: + { + /* Cannot rely on prop_size here--the value is set incorrectly + by some Gimp versions. + */ + size_t num_colours = ReadBlobMSBLong(image); + if (DiscardBlobBytes(image,3*num_colours) == MagickFalse) + ThrowFileException(&image->exception,CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + /* + if (info->file_version == 0) + { + gint i; + + g_message (_(""XCF warning: version 0 of XCF file format\n"" + ""did not save indexed colormaps correctly.\n"" + ""Substituting grayscale map."")); + info->cp += + xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1); + gimage->cmap = g_new (guchar, gimage->num_cols*3); + xcf_seek_pos (info, info->cp + gimage->num_cols); + for (i = 0; inum_cols; i++) + { + gimage->cmap[i*3+0] = i; + gimage->cmap[i*3+1] = i; + gimage->cmap[i*3+2] = i; + } + } + else + { + info->cp += + xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1); + gimage->cmap = g_new (guchar, gimage->num_cols*3); + info->cp += + xcf_read_int8 (info->fp, + (guint8*) gimage->cmap, gimage->num_cols*3); + } + */ + break; + } + case PROP_COMPRESSION: + { + doc_info.compression = ReadBlobByte(image); + if ((doc_info.compression != COMPRESS_NONE) && + (doc_info.compression != COMPRESS_RLE) && + (doc_info.compression != COMPRESS_ZLIB) && + (doc_info.compression != COMPRESS_FRACTAL)) + ThrowReaderException(CorruptImageError,""UnrecognizedImageCompression""); + } + break; + + case PROP_GUIDES: + { + /* just skip it - we don't care about guides */ + if (DiscardBlobBytes(image,prop_size) == MagickFalse) + ThrowFileException(&image->exception,CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + } + break; + + case PROP_RESOLUTION: + { + /* float xres = (float) */ (void) ReadBlobMSBLong(image); + /* float yres = (float) */ (void) ReadBlobMSBLong(image); + + /* + if (xres < GIMP_MIN_RESOLUTION || xres > GIMP_MAX_RESOLUTION || + yres < GIMP_MIN_RESOLUTION || yres > GIMP_MAX_RESOLUTION) + { + g_message (""Warning, resolution out of range in XCF file""); + xres = gimage->gimp->config->default_xresolution; + yres = gimage->gimp->config->default_yresolution; + } + */ + + + /* BOGUS: we don't write these yet because we aren't + reading them properly yet :( + image->x_resolution = xres; + image->y_resolution = yres; + */ + } + break; + + case PROP_TATTOO: + { + /* we need to read it, even if we ignore it */ + /*size_t tattoo_state = */ (void) ReadBlobMSBLong(image); + } + break; + + case PROP_PARASITES: + { + /* BOGUS: we may need these for IPTC stuff */ + if (DiscardBlobBytes(image,prop_size) == MagickFalse) + ThrowFileException(&image->exception,CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + /* + gssize_t base = info->cp; + GimpParasite *p; + + while (info->cp - base < prop_size) + { + p = xcf_load_parasite (info); + gimp_image_parasite_attach (gimage, p); + gimp_parasite_free (p); + } + if (info->cp - base != prop_size) + g_message (""Error detected while loading an image's parasites""); + */ + } + break; + + case PROP_UNIT: + { + /* BOGUS: ignore for now... */ + /*size_t unit = */ (void) ReadBlobMSBLong(image); + } + break; + + case PROP_PATHS: + { + /* BOGUS: just skip it for now */ + if (DiscardBlobBytes(image,prop_size) == MagickFalse) + ThrowFileException(&image->exception,CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + + /* + PathList *paths = xcf_load_bzpaths (gimage, info); + gimp_image_set_paths (gimage, paths); + */ + } + break; + + case PROP_USER_UNIT: + { + char unit_string[1000]; + /*BOGUS: ignored for now */ + /*float factor = (float) */ (void) ReadBlobMSBLong(image); + /* size_t digits = */ (void) ReadBlobMSBLong(image); + for (i=0; i<5; i++) + (void) ReadBlobStringWithLongSize(image, unit_string, + sizeof(unit_string)); + } + break; + + default: + { + int buf[16]; + ssize_t amount; + + /* read over it... */ + while ((prop_size > 0) && (EOFBlob(image) == MagickFalse)) + { + amount=(ssize_t) MagickMin(16, prop_size); + amount=(ssize_t) ReadBlob(image,(size_t) amount,(unsigned char *) &buf); + if (!amount) + ThrowReaderException(CorruptImageError,""CorruptImage""); + prop_size -= (size_t) MagickMin(16,(size_t) amount); + } + } + break; + } + } + if (foundPropEnd == MagickFalse) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + + if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) + { + ; /* do nothing, were just pinging! */ + } + else + { + int + current_layer = 0, + foundAllLayers = MagickFalse, + number_layers = 0; + + MagickOffsetType + oldPos=TellBlob(image); + + XCFLayerInfo + *layer_info; + + /* + The read pointer. + */ + do + { + ssize_t offset = ReadBlobMSBSignedLong(image); + if (offset == 0) + foundAllLayers=MagickTrue; + else + number_layers++; + if (EOFBlob(image) != MagickFalse) + { + ThrowFileException(exception,CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + break; + } + } while (foundAllLayers == MagickFalse); + doc_info.number_layers=number_layers; + offset=SeekBlob(image,oldPos,SEEK_SET); /* restore the position! */ + if (offset < 0) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + /* allocate our array of layer info blocks */ + length=(size_t) number_layers; + layer_info=(XCFLayerInfo *) AcquireQuantumMemory(length, + sizeof(*layer_info)); + if (layer_info == (XCFLayerInfo *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + (void) ResetMagickMemory(layer_info,0,number_layers*sizeof(XCFLayerInfo)); + for ( ; ; ) + { + MagickBooleanType + layer_ok; + + MagickOffsetType + offset, + saved_pos; + + /* read in the offset of the next layer */ + offset=(MagickOffsetType) ReadBlobMSBLong(image); + /* if the offset is 0 then we are at the end + * of the layer list. + */ + if (offset == 0) + break; + /* save the current position as it is where the + * next layer offset is stored. + */ + saved_pos=TellBlob(image); + /* seek to the layer offset */ + if (SeekBlob(image,offset,SEEK_SET) != offset) + ThrowReaderException(ResourceLimitError,""NotEnoughPixelData""); + /* read in the layer */ + layer_ok=ReadOneLayer(image_info,image,&doc_info, + &layer_info[current_layer],current_layer); + if (layer_ok == MagickFalse) + { + int j; + + for (j=0; j < current_layer; j++) + layer_info[j].image=DestroyImage(layer_info[j].image); + layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + /* restore the saved position so we'll be ready to + * read the next offset. + */ + offset=SeekBlob(image, saved_pos, SEEK_SET); + current_layer++; + } +#if 0 + { + /* NOTE: XCF layers are REVERSED from composite order! */ + signed int j; + for (j=number_layers-1; j>=0; j--) { + /* BOGUS: need to consider layer blending modes!! */ + + if ( layer_info[j].visible ) { /* only visible ones, please! */ + CompositeImage(image, OverCompositeOp, layer_info[j].image, + layer_info[j].offset_x, layer_info[j].offset_y ); + layer_info[j].image =DestroyImage( layer_info[j].image ); + + /* If we do this, we'll get REAL gray images! */ + if ( image_type == GIMP_GRAY ) { + QuantizeInfo qi; + GetQuantizeInfo(&qi); + qi.colorspace = GRAYColorspace; + QuantizeImage( &qi, layer_info[j].image ); + } + } + } + } +#else + { + /* NOTE: XCF layers are REVERSED from composite order! */ + ssize_t j; + + /* now reverse the order of the layers as they are put + into subimages + */ + for (j=(long) number_layers-1; j >= 0; j--) + AppendImageToList(&image,layer_info[j].image); + } +#endif + + layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info); + +#if 0 /* BOGUS: do we need the channels?? */ + while (MagickTrue) + { + /* read in the offset of the next channel */ + info->cp += xcf_read_int32 (info->fp, &offset, 1); + + /* if the offset is 0 then we are at the end + * of the channel list. + */ + if (offset == 0) + break; + + /* save the current position as it is where the + * next channel offset is stored. + */ + saved_pos = info->cp; + + /* seek to the channel offset */ + xcf_seek_pos (info, offset); + + /* read in the layer */ + channel = xcf_load_channel (info, gimage); + if (channel == 0) + goto error; + + num_successful_elements++; + + /* add the channel to the image if its not the selection */ + if (channel != gimage->selection_mask) + gimp_image_add_channel (gimage, channel, -1); + + /* restore the saved position so we'll be ready to + * read the next offset. + */ + xcf_seek_pos (info, saved_pos); + } +#endif + } + + (void) CloseBlob(image); + if (GetNextImageInList(image) != (Image *) NULL) + DestroyImage(RemoveFirstImageFromList(&image)); + if (image_type == GIMP_GRAY) + image->type=GrayscaleType; + return(GetFirstImageInList(image)); +}","{'deleted': [{'line_no': 427, 'char_start': 12598, 'char_end': 12648, 'line': ' DestroyImage(RemoveFirstImageFromList(&image));\n'}], 'added': [{'line_no': 427, 'char_start': 12598, 'char_end': 12649, 'line': ' if (GetNextImageInList(image) != (Image *) NULL)\n'}, {'line_no': 428, 'char_start': 12649, 'char_end': 12701, 'line': ' DestroyImage(RemoveFirstImageFromList(&image));\n'}]}","{'deleted': [], 'added': [{'char_start': 12600, 'char_end': 12653, 'chars': 'if (GetNextImageInList(image) != (Image *) NULL)\n '}]}",github.com/ImageMagick/ImageMagick/commit/d31fec57e9dfb0516deead2053a856e3c71e9751,coders/xcf.c,cwe-476, +cwe-476,CopyKeyAliasesToKeymap,"CopyKeyAliasesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info) +{ + AliasInfo *alias; + unsigned i, num_key_aliases; + struct xkb_key_alias *key_aliases; + + /* + * Do some sanity checking on the aliases. We can't do it before + * because keys and their aliases may be added out-of-order. + */ + num_key_aliases = 0; + darray_foreach(alias, info->aliases) { + /* Check that ->real is a key. */ + if (!XkbKeyByName(keymap, alias->real, false)) { + log_vrb(info->ctx, 5, + ""Attempt to alias %s to non-existent key %s; Ignored\n"", + KeyNameText(info->ctx, alias->alias), + KeyNameText(info->ctx, alias->real)); + alias->real = XKB_ATOM_NONE; + continue; + } + + /* Check that ->alias is not a key. */ + if (XkbKeyByName(keymap, alias->alias, false)) { + log_vrb(info->ctx, 5, + ""Attempt to create alias with the name of a real key; "" + ""Alias \""%s = %s\"" ignored\n"", + KeyNameText(info->ctx, alias->alias), + KeyNameText(info->ctx, alias->real)); + alias->real = XKB_ATOM_NONE; + continue; + } + + num_key_aliases++; + } + + /* Copy key aliases. */ + key_aliases = NULL; + if (num_key_aliases > 0) { + key_aliases = calloc(num_key_aliases, sizeof(*key_aliases)); + if (!key_aliases) + return false; + } + + i = 0; + darray_foreach(alias, info->aliases) { + if (alias->real != XKB_ATOM_NONE) { + key_aliases[i].alias = alias->alias; + key_aliases[i].real = alias->real; + i++; + } + } + + keymap->num_key_aliases = num_key_aliases; + keymap->key_aliases = key_aliases; + return true; +}","CopyKeyAliasesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info) +{ + AliasInfo *alias; + unsigned i, num_key_aliases; + struct xkb_key_alias *key_aliases; + + /* + * Do some sanity checking on the aliases. We can't do it before + * because keys and their aliases may be added out-of-order. + */ + num_key_aliases = 0; + darray_foreach(alias, info->aliases) { + /* Check that ->real is a key. */ + if (!XkbKeyByName(keymap, alias->real, false)) { + log_vrb(info->ctx, 5, + ""Attempt to alias %s to non-existent key %s; Ignored\n"", + KeyNameText(info->ctx, alias->alias), + KeyNameText(info->ctx, alias->real)); + alias->real = XKB_ATOM_NONE; + continue; + } + + /* Check that ->alias is not a key. */ + if (XkbKeyByName(keymap, alias->alias, false)) { + log_vrb(info->ctx, 5, + ""Attempt to create alias with the name of a real key; "" + ""Alias \""%s = %s\"" ignored\n"", + KeyNameText(info->ctx, alias->alias), + KeyNameText(info->ctx, alias->real)); + alias->real = XKB_ATOM_NONE; + continue; + } + + num_key_aliases++; + } + + /* Copy key aliases. */ + key_aliases = NULL; + if (num_key_aliases > 0) { + key_aliases = calloc(num_key_aliases, sizeof(*key_aliases)); + if (!key_aliases) + return false; + + i = 0; + darray_foreach(alias, info->aliases) { + if (alias->real != XKB_ATOM_NONE) { + key_aliases[i].alias = alias->alias; + key_aliases[i].real = alias->real; + i++; + } + } + } + + keymap->num_key_aliases = num_key_aliases; + keymap->key_aliases = key_aliases; + return true; +}","{'deleted': [{'line_no': 43, 'char_start': 1477, 'char_end': 1483, 'line': ' }\n'}, {'line_no': 45, 'char_start': 1484, 'char_end': 1495, 'line': ' i = 0;\n'}, {'line_no': 46, 'char_start': 1495, 'char_end': 1538, 'line': ' darray_foreach(alias, info->aliases) {\n'}, {'line_no': 47, 'char_start': 1538, 'char_end': 1582, 'line': ' if (alias->real != XKB_ATOM_NONE) {\n'}, {'line_no': 48, 'char_start': 1582, 'char_end': 1631, 'line': ' key_aliases[i].alias = alias->alias;\n'}, {'line_no': 49, 'char_start': 1631, 'char_end': 1678, 'line': ' key_aliases[i].real = alias->real;\n'}, {'line_no': 50, 'char_start': 1678, 'char_end': 1695, 'line': ' i++;\n'}], 'added': [{'line_no': 44, 'char_start': 1478, 'char_end': 1493, 'line': ' i = 0;\n'}, {'line_no': 45, 'char_start': 1493, 'char_end': 1540, 'line': ' darray_foreach(alias, info->aliases) {\n'}, {'line_no': 46, 'char_start': 1540, 'char_end': 1588, 'line': ' if (alias->real != XKB_ATOM_NONE) {\n'}, {'line_no': 47, 'char_start': 1588, 'char_end': 1641, 'line': ' key_aliases[i].alias = alias->alias;\n'}, {'line_no': 48, 'char_start': 1641, 'char_end': 1692, 'line': ' key_aliases[i].real = alias->real;\n'}, {'line_no': 49, 'char_start': 1692, 'char_end': 1713, 'line': ' i++;\n'}, {'line_no': 50, 'char_start': 1713, 'char_end': 1727, 'line': ' }\n'}]}","{'deleted': [{'char_start': 1481, 'char_end': 1484, 'chars': '}\n\n'}], 'added': [{'char_start': 1477, 'char_end': 1478, 'chars': '\n'}, {'char_start': 1493, 'char_end': 1497, 'chars': ' '}, {'char_start': 1540, 'char_end': 1542, 'chars': ' '}, {'char_start': 1550, 'char_end': 1552, 'chars': ' '}, {'char_start': 1588, 'char_end': 1592, 'chars': ' '}, {'char_start': 1641, 'char_end': 1644, 'chars': ' '}, {'char_start': 1656, 'char_end': 1657, 'chars': ' '}, {'char_start': 1704, 'char_end': 1708, 'chars': ' '}, {'char_start': 1712, 'char_end': 1726, 'chars': '\n }'}]}",github.com/xkbcommon/libxkbcommon/commit/badb428e63387140720f22486b3acbd3d738859f,src/xkbcomp/keycodes.c,cwe-476, +cwe-476,tensorflow::GetSessionHandleOp::Compute," void Compute(OpKernelContext* ctx) override { + const Tensor& val = ctx->input(0); + int64 id = ctx->session_state()->GetNewId(); + TensorStore::TensorAndKey tk{val, id, requested_device()}; + OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(name(), tk)); + + Tensor* handle = nullptr; + OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle)); + if (ctx->expected_output_dtype(0) == DT_RESOURCE) { + ResourceHandle resource_handle = MakeResourceHandle( + ctx, SessionState::kTensorHandleResourceTypeName, + tk.GetHandle(name())); + resource_handle.set_maybe_type_name( + SessionState::kTensorHandleResourceTypeName); + handle->scalar()() = resource_handle; + } else { + // Legacy behavior in V1. + handle->flat().setConstant(tk.GetHandle(name())); + } + }"," void Compute(OpKernelContext* ctx) override { + const Tensor& val = ctx->input(0); + auto session_state = ctx->session_state(); + OP_REQUIRES(ctx, session_state != nullptr, + errors::FailedPrecondition( + ""GetSessionHandle called on null session state"")); + int64 id = session_state->GetNewId(); + TensorStore::TensorAndKey tk{val, id, requested_device()}; + OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(name(), tk)); + + Tensor* handle = nullptr; + OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle)); + if (ctx->expected_output_dtype(0) == DT_RESOURCE) { + ResourceHandle resource_handle = MakeResourceHandle( + ctx, SessionState::kTensorHandleResourceTypeName, + tk.GetHandle(name())); + resource_handle.set_maybe_type_name( + SessionState::kTensorHandleResourceTypeName); + handle->scalar()() = resource_handle; + } else { + // Legacy behavior in V1. + handle->flat().setConstant(tk.GetHandle(name())); + } + }","{'deleted': [{'line_no': 3, 'char_start': 87, 'char_end': 136, 'line': ' int64 id = ctx->session_state()->GetNewId();\n'}], 'added': [{'line_no': 3, 'char_start': 87, 'char_end': 134, 'line': ' auto session_state = ctx->session_state();\n'}, {'line_no': 4, 'char_start': 134, 'char_end': 181, 'line': ' OP_REQUIRES(ctx, session_state != nullptr,\n'}, {'line_no': 5, 'char_start': 181, 'char_end': 225, 'line': ' errors::FailedPrecondition(\n'}, {'line_no': 6, 'char_start': 225, 'char_end': 296, 'line': ' ""GetSessionHandle called on null session state""));\n'}, {'line_no': 7, 'char_start': 296, 'char_end': 338, 'line': ' int64 id = session_state->GetNewId();\n'}]}","{'deleted': [{'char_start': 94, 'char_end': 99, 'chars': '64 id'}], 'added': [{'char_start': 91, 'char_end': 93, 'chars': 'au'}, {'char_start': 94, 'char_end': 95, 'chars': 'o'}, {'char_start': 96, 'char_end': 100, 'chars': 'sess'}, {'char_start': 101, 'char_end': 109, 'chars': 'on_state'}, {'char_start': 132, 'char_end': 324, 'chars': ';\n OP_REQUIRES(ctx, session_state != nullptr,\n errors::FailedPrecondition(\n ""GetSessionHandle called on null session state""));\n int64 id = session_state'}]}",github.com/tensorflow/tensorflow/commit/9a133d73ae4b4664d22bd1aa6d654fec13c52ee1,tensorflow/core/kernels/session_ops.cc,cwe-476, +cwe-476,tun_set_iff,"static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) +{ + struct tun_struct *tun; + struct tun_file *tfile = file->private_data; + struct net_device *dev; + int err; + + if (tfile->detached) + return -EINVAL; + + dev = __dev_get_by_name(net, ifr->ifr_name); + if (dev) { + if (ifr->ifr_flags & IFF_TUN_EXCL) + return -EBUSY; + if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) + tun = netdev_priv(dev); + else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) + tun = netdev_priv(dev); + else + return -EINVAL; + + if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != + !!(tun->flags & IFF_MULTI_QUEUE)) + return -EINVAL; + + if (tun_not_capable(tun)) + return -EPERM; + err = security_tun_dev_open(tun->security); + if (err < 0) + return err; + + err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); + if (err < 0) + return err; + + if (tun->flags & IFF_MULTI_QUEUE && + (tun->numqueues + tun->numdisabled > 1)) { + /* One or more queue has already been attached, no need + * to initialize the device again. + */ + return 0; + } + } + else { + char *name; + unsigned long flags = 0; + int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? + MAX_TAP_QUEUES : 1; + + if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) + return -EPERM; + err = security_tun_dev_create(); + if (err < 0) + return err; + + /* Set dev type */ + if (ifr->ifr_flags & IFF_TUN) { + /* TUN device */ + flags |= IFF_TUN; + name = ""tun%d""; + } else if (ifr->ifr_flags & IFF_TAP) { + /* TAP device */ + flags |= IFF_TAP; + name = ""tap%d""; + } else + return -EINVAL; + + if (*ifr->ifr_name) + name = ifr->ifr_name; + + dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, + NET_NAME_UNKNOWN, tun_setup, queues, + queues); + + if (!dev) + return -ENOMEM; + err = dev_get_valid_name(net, dev, name); + if (err) + goto err_free_dev; + + dev_net_set(dev, net); + dev->rtnl_link_ops = &tun_link_ops; + dev->ifindex = tfile->ifindex; + dev->sysfs_groups[0] = &tun_attr_group; + + tun = netdev_priv(dev); + tun->dev = dev; + tun->flags = flags; + tun->txflt.count = 0; + tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); + + tun->align = NET_SKB_PAD; + tun->filter_attached = false; + tun->sndbuf = tfile->socket.sk->sk_sndbuf; + tun->rx_batched = 0; + + tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); + if (!tun->pcpu_stats) { + err = -ENOMEM; + goto err_free_dev; + } + + spin_lock_init(&tun->lock); + + err = security_tun_dev_alloc_security(&tun->security); + if (err < 0) + goto err_free_stat; + + tun_net_init(dev); + tun_flow_init(tun); + + dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | + TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | + NETIF_F_HW_VLAN_STAG_TX; + dev->features = dev->hw_features | NETIF_F_LLTX; + dev->vlan_features = dev->features & + ~(NETIF_F_HW_VLAN_CTAG_TX | + NETIF_F_HW_VLAN_STAG_TX); + + INIT_LIST_HEAD(&tun->disabled); + err = tun_attach(tun, file, false); + if (err < 0) + goto err_free_flow; + + err = register_netdevice(tun->dev); + if (err < 0) + goto err_detach; + } + + netif_carrier_on(tun->dev); + + tun_debug(KERN_INFO, tun, ""tun_set_iff\n""); + + tun->flags = (tun->flags & ~TUN_FEATURES) | + (ifr->ifr_flags & TUN_FEATURES); + + /* Make sure persistent devices do not get stuck in + * xoff state. + */ + if (netif_running(tun->dev)) + netif_tx_wake_all_queues(tun->dev); + + strcpy(ifr->ifr_name, tun->dev->name); + return 0; + +err_detach: + tun_detach_all(dev); + /* register_netdevice() already called tun_free_netdev() */ + goto err_free_dev; + +err_free_flow: + tun_flow_uninit(tun); + security_tun_dev_free_security(tun->security); +err_free_stat: + free_percpu(tun->pcpu_stats); +err_free_dev: + free_netdev(dev); + return err; +}","static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) +{ + struct tun_struct *tun; + struct tun_file *tfile = file->private_data; + struct net_device *dev; + int err; + + if (tfile->detached) + return -EINVAL; + + dev = __dev_get_by_name(net, ifr->ifr_name); + if (dev) { + if (ifr->ifr_flags & IFF_TUN_EXCL) + return -EBUSY; + if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) + tun = netdev_priv(dev); + else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) + tun = netdev_priv(dev); + else + return -EINVAL; + + if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != + !!(tun->flags & IFF_MULTI_QUEUE)) + return -EINVAL; + + if (tun_not_capable(tun)) + return -EPERM; + err = security_tun_dev_open(tun->security); + if (err < 0) + return err; + + err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); + if (err < 0) + return err; + + if (tun->flags & IFF_MULTI_QUEUE && + (tun->numqueues + tun->numdisabled > 1)) { + /* One or more queue has already been attached, no need + * to initialize the device again. + */ + return 0; + } + } + else { + char *name; + unsigned long flags = 0; + int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? + MAX_TAP_QUEUES : 1; + + if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) + return -EPERM; + err = security_tun_dev_create(); + if (err < 0) + return err; + + /* Set dev type */ + if (ifr->ifr_flags & IFF_TUN) { + /* TUN device */ + flags |= IFF_TUN; + name = ""tun%d""; + } else if (ifr->ifr_flags & IFF_TAP) { + /* TAP device */ + flags |= IFF_TAP; + name = ""tap%d""; + } else + return -EINVAL; + + if (*ifr->ifr_name) + name = ifr->ifr_name; + + dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, + NET_NAME_UNKNOWN, tun_setup, queues, + queues); + + if (!dev) + return -ENOMEM; + err = dev_get_valid_name(net, dev, name); + if (err < 0) + goto err_free_dev; + + dev_net_set(dev, net); + dev->rtnl_link_ops = &tun_link_ops; + dev->ifindex = tfile->ifindex; + dev->sysfs_groups[0] = &tun_attr_group; + + tun = netdev_priv(dev); + tun->dev = dev; + tun->flags = flags; + tun->txflt.count = 0; + tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); + + tun->align = NET_SKB_PAD; + tun->filter_attached = false; + tun->sndbuf = tfile->socket.sk->sk_sndbuf; + tun->rx_batched = 0; + + tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); + if (!tun->pcpu_stats) { + err = -ENOMEM; + goto err_free_dev; + } + + spin_lock_init(&tun->lock); + + err = security_tun_dev_alloc_security(&tun->security); + if (err < 0) + goto err_free_stat; + + tun_net_init(dev); + tun_flow_init(tun); + + dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | + TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | + NETIF_F_HW_VLAN_STAG_TX; + dev->features = dev->hw_features | NETIF_F_LLTX; + dev->vlan_features = dev->features & + ~(NETIF_F_HW_VLAN_CTAG_TX | + NETIF_F_HW_VLAN_STAG_TX); + + INIT_LIST_HEAD(&tun->disabled); + err = tun_attach(tun, file, false); + if (err < 0) + goto err_free_flow; + + err = register_netdevice(tun->dev); + if (err < 0) + goto err_detach; + } + + netif_carrier_on(tun->dev); + + tun_debug(KERN_INFO, tun, ""tun_set_iff\n""); + + tun->flags = (tun->flags & ~TUN_FEATURES) | + (ifr->ifr_flags & TUN_FEATURES); + + /* Make sure persistent devices do not get stuck in + * xoff state. + */ + if (netif_running(tun->dev)) + netif_tx_wake_all_queues(tun->dev); + + strcpy(ifr->ifr_name, tun->dev->name); + return 0; + +err_detach: + tun_detach_all(dev); + /* register_netdevice() already called tun_free_netdev() */ + goto err_free_dev; + +err_free_flow: + tun_flow_uninit(tun); + security_tun_dev_free_security(tun->security); +err_free_stat: + free_percpu(tun->pcpu_stats); +err_free_dev: + free_netdev(dev); + return err; +}","{'deleted': [{'line_no': 78, 'char_start': 1859, 'char_end': 1870, 'line': '\t\tif (err)\n'}], 'added': [{'line_no': 78, 'char_start': 1859, 'char_end': 1874, 'line': '\t\tif (err < 0)\n'}]}","{'deleted': [], 'added': [{'char_start': 1868, 'char_end': 1872, 'chars': ' < 0'}]}",github.com/torvalds/linux/commit/5c25f65fd1e42685f7ccd80e0621829c105785d9,drivers/net/tun.c,cwe-476, +cwe-476,WriteImages,"MagickExport MagickBooleanType WriteImages(const ImageInfo *image_info, + Image *images,const char *filename,ExceptionInfo *exception) +{ +#define WriteImageTag ""Write/Image"" + + ExceptionInfo + *sans_exception; + + ImageInfo + *write_info; + + MagickBooleanType + proceed; + + MagickOffsetType + progress; + + MagickProgressMonitor + progress_monitor; + + MagickSizeType + number_images; + + MagickStatusType + status; + + register Image + *p; + + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + assert(images != (Image *) NULL); + assert(images->signature == MagickCoreSignature); + if (images->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",images->filename); + assert(exception != (ExceptionInfo *) NULL); + write_info=CloneImageInfo(image_info); + *write_info->magick='\0'; + images=GetFirstImageInList(images); + if (filename != (const char *) NULL) + for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) + (void) CopyMagickString(p->filename,filename,MagickPathExtent); + (void) CopyMagickString(write_info->filename,images->filename,MagickPathExtent); + sans_exception=AcquireExceptionInfo(); + (void) SetImageInfo(write_info,(unsigned int) GetImageListLength(images), + sans_exception); + sans_exception=DestroyExceptionInfo(sans_exception); + if (*write_info->magick == '\0') + (void) CopyMagickString(write_info->magick,images->magick,MagickPathExtent); + p=images; + for ( ; GetNextImageInList(p) != (Image *) NULL; p=GetNextImageInList(p)) + if (p->scene >= GetNextImageInList(p)->scene) + { + register ssize_t + i; + + /* + Generate consistent scene numbers. + */ + i=(ssize_t) images->scene; + for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) + p->scene=(size_t) i++; + break; + } + /* + Write images. + */ + status=MagickTrue; + progress_monitor=(MagickProgressMonitor) NULL; + progress=0; + number_images=GetImageListLength(images); + for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) + { + if (number_images != 1) + progress_monitor=SetImageProgressMonitor(p,(MagickProgressMonitor) NULL, + p->client_data); + status&=WriteImage(write_info,p,exception); + if (number_images != 1) + (void) SetImageProgressMonitor(p,progress_monitor,p->client_data); + if (write_info->adjoin != MagickFalse) + break; + if (number_images != 1) + { + proceed=SetImageProgress(p,WriteImageTag,progress++,number_images); + if (proceed == MagickFalse) + break; + } + } + write_info=DestroyImageInfo(write_info); + return(status != 0 ? MagickTrue : MagickFalse); +}","MagickExport MagickBooleanType WriteImages(const ImageInfo *image_info, + Image *images,const char *filename,ExceptionInfo *exception) +{ +#define WriteImageTag ""Write/Image"" + + ExceptionInfo + *sans_exception; + + ImageInfo + *write_info; + + MagickBooleanType + proceed; + + MagickOffsetType + progress; + + MagickProgressMonitor + progress_monitor; + + MagickSizeType + number_images; + + MagickStatusType + status; + + register Image + *p; + + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + assert(images != (Image *) NULL); + assert(images->signature == MagickCoreSignature); + if (images->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",images->filename); + assert(exception != (ExceptionInfo *) NULL); + write_info=CloneImageInfo(image_info); + *write_info->magick='\0'; + images=GetFirstImageInList(images); + if (filename != (const char *) NULL) + for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) + (void) CopyMagickString(p->filename,filename,MagickPathExtent); + (void) CopyMagickString(write_info->filename,images->filename,MagickPathExtent); + sans_exception=AcquireExceptionInfo(); + (void) SetImageInfo(write_info,(unsigned int) GetImageListLength(images), + sans_exception); + sans_exception=DestroyExceptionInfo(sans_exception); + if (*write_info->magick == '\0') + (void) CopyMagickString(write_info->magick,images->magick,MagickPathExtent); + p=images; + for ( ; GetNextImageInList(p) != (Image *) NULL; p=GetNextImageInList(p)) + { + register Image + *next; + + next=GetNextImageInList(p); + if (next == (Image *) NULL) + break; + if (p->scene >= next->scene) + { + register ssize_t + i; + + /* + Generate consistent scene numbers. + */ + i=(ssize_t) images->scene; + for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) + p->scene=(size_t) i++; + break; + } + } + /* + Write images. + */ + status=MagickTrue; + progress_monitor=(MagickProgressMonitor) NULL; + progress=0; + number_images=GetImageListLength(images); + for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) + { + if (number_images != 1) + progress_monitor=SetImageProgressMonitor(p,(MagickProgressMonitor) NULL, + p->client_data); + status&=WriteImage(write_info,p,exception); + if (number_images != 1) + (void) SetImageProgressMonitor(p,progress_monitor,p->client_data); + if (write_info->adjoin != MagickFalse) + break; + if (number_images != 1) + { + proceed=SetImageProgress(p,WriteImageTag,progress++,number_images); + if (proceed == MagickFalse) + break; + } + } + write_info=DestroyImageInfo(write_info); + return(status != 0 ? MagickTrue : MagickFalse); +}","{'deleted': [{'line_no': 52, 'char_start': 1570, 'char_end': 1620, 'line': ' if (p->scene >= GetNextImageInList(p)->scene)\n'}], 'added': [{'line_no': 52, 'char_start': 1570, 'char_end': 1574, 'line': ' {\n'}, {'line_no': 53, 'char_start': 1574, 'char_end': 1593, 'line': ' register Image\n'}, {'line_no': 54, 'char_start': 1593, 'char_end': 1606, 'line': ' *next;\n'}, {'line_no': 55, 'char_start': 1606, 'char_end': 1611, 'line': ' \n'}, {'line_no': 56, 'char_start': 1611, 'char_end': 1643, 'line': ' next=GetNextImageInList(p);\n'}, {'line_no': 57, 'char_start': 1643, 'char_end': 1675, 'line': ' if (next == (Image *) NULL)\n'}, {'line_no': 58, 'char_start': 1675, 'char_end': 1688, 'line': ' break;\n'}, {'line_no': 59, 'char_start': 1688, 'char_end': 1721, 'line': ' if (p->scene >= next->scene)\n'}, {'line_no': 72, 'char_start': 1995, 'char_end': 1999, 'line': ' }\n'}]}","{'deleted': [{'char_start': 1575, 'char_end': 1581, 'chars': 'f (p->'}, {'char_start': 1582, 'char_end': 1583, 'chars': 'c'}, {'char_start': 1587, 'char_end': 1589, 'chars': '>='}], 'added': [{'char_start': 1572, 'char_end': 1576, 'chars': '{\n '}, {'char_start': 1578, 'char_end': 1581, 'chars': 'reg'}, {'char_start': 1582, 'char_end': 1586, 'chars': 'ster'}, {'char_start': 1587, 'char_end': 1591, 'chars': 'Imag'}, {'char_start': 1592, 'char_end': 1600, 'chars': '\n *'}, {'char_start': 1602, 'char_end': 1606, 'chars': 'xt;\n'}, {'char_start': 1607, 'char_end': 1619, 'chars': ' \n next'}, {'char_start': 1641, 'char_end': 1712, 'chars': ';\n if (next == (Image *) NULL)\n break;\n if (p->scene >= next'}, {'char_start': 1991, 'char_end': 1995, 'chars': ' }\n'}]}",github.com/ImageMagick/ImageMagick/commit/5b4bebaa91849c592a8448bc353ab25a54ff8c44,MagickCore/constitute.c,cwe-476, +cwe-787,WritePSDChannels,"static ssize_t WritePSDChannels(const PSDInfo *psd_info, + const ImageInfo *image_info,Image *image,Image *next_image, + MagickOffsetType size_offset,const MagickBooleanType separate) +{ + Image + *mask; + + MagickOffsetType + rows_offset; + + size_t + channels, + count, + length, + offset_length; + + unsigned char + *compact_pixels; + + count=0; + offset_length=0; + rows_offset=0; + compact_pixels=(unsigned char *) NULL; + if (next_image->compression == RLECompression) + { + compact_pixels=AcquireCompactPixels(image); + if (compact_pixels == (unsigned char *) NULL) + return(0); + } + channels=1; + if (separate == MagickFalse) + { + if (next_image->storage_class != PseudoClass) + { + if (IsGrayImage(next_image,&next_image->exception) == MagickFalse) + channels=next_image->colorspace == CMYKColorspace ? 4 : 3; + if (next_image->matte != MagickFalse) + channels++; + } + rows_offset=TellBlob(image)+2; + count+=WriteCompressionStart(psd_info,image,next_image,channels); + offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); + } + size_offset+=2; + if (next_image->storage_class == PseudoClass) + { + length=WritePSDChannel(psd_info,image_info,image,next_image, + IndexQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + } + else + { + if (IsGrayImage(next_image,&next_image->exception) != MagickFalse) + { + length=WritePSDChannel(psd_info,image_info,image,next_image, + GrayQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + } + else + { + if (next_image->colorspace == CMYKColorspace) + (void) NegateImage(next_image,MagickFalse); + + length=WritePSDChannel(psd_info,image_info,image,next_image, + RedQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + + length=WritePSDChannel(psd_info,image_info,image,next_image, + GreenQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + + length=WritePSDChannel(psd_info,image_info,image,next_image, + BlueQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + + if (next_image->colorspace == CMYKColorspace) + { + length=WritePSDChannel(psd_info,image_info,image,next_image, + BlackQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + } + } + if (next_image->matte != MagickFalse) + { + length=WritePSDChannel(psd_info,image_info,image,next_image, + AlphaQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + } + } + compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); + if (next_image->colorspace == CMYKColorspace) + (void) NegateImage(next_image,MagickFalse); + if (separate != MagickFalse) + { + const char + *property; + + property=GetImageArtifact(next_image,""psd:opacity-mask""); + if (property != (const char *) NULL) + { + mask=(Image *) GetImageRegistry(ImageRegistryType,property, + &image->exception); + if (mask != (Image *) NULL) + { + if (mask->compression == RLECompression) + { + compact_pixels=AcquireCompactPixels(mask); + if (compact_pixels == (unsigned char *) NULL) + return(0); + } + length=WritePSDChannel(psd_info,image_info,image,mask, + RedQuantum,compact_pixels,rows_offset,MagickTrue); + (void) WritePSDSize(psd_info,image,length,size_offset); + count+=length; + compact_pixels=(unsigned char *) RelinquishMagickMemory( + compact_pixels); + } + } + } + return(count); +}","static ssize_t WritePSDChannels(const PSDInfo *psd_info, + const ImageInfo *image_info,Image *image,Image *next_image, + MagickOffsetType size_offset,const MagickBooleanType separate) +{ + Image + *mask; + + MagickOffsetType + rows_offset; + + size_t + channels, + count, + length, + offset_length; + + unsigned char + *compact_pixels; + + count=0; + offset_length=0; + rows_offset=0; + compact_pixels=(unsigned char *) NULL; + if (next_image->compression == RLECompression) + { + compact_pixels=AcquireCompactPixels(next_image); + if (compact_pixels == (unsigned char *) NULL) + return(0); + } + channels=1; + if (separate == MagickFalse) + { + if (next_image->storage_class != PseudoClass) + { + if (IsGrayImage(next_image,&next_image->exception) == MagickFalse) + channels=next_image->colorspace == CMYKColorspace ? 4 : 3; + if (next_image->matte != MagickFalse) + channels++; + } + rows_offset=TellBlob(image)+2; + count+=WriteCompressionStart(psd_info,image,next_image,channels); + offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); + } + size_offset+=2; + if (next_image->storage_class == PseudoClass) + { + length=WritePSDChannel(psd_info,image_info,image,next_image, + IndexQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + } + else + { + if (IsGrayImage(next_image,&next_image->exception) != MagickFalse) + { + length=WritePSDChannel(psd_info,image_info,image,next_image, + GrayQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + } + else + { + if (next_image->colorspace == CMYKColorspace) + (void) NegateImage(next_image,MagickFalse); + + length=WritePSDChannel(psd_info,image_info,image,next_image, + RedQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + + length=WritePSDChannel(psd_info,image_info,image,next_image, + GreenQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + + length=WritePSDChannel(psd_info,image_info,image,next_image, + BlueQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + + if (next_image->colorspace == CMYKColorspace) + { + length=WritePSDChannel(psd_info,image_info,image,next_image, + BlackQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + } + } + if (next_image->matte != MagickFalse) + { + length=WritePSDChannel(psd_info,image_info,image,next_image, + AlphaQuantum,compact_pixels,rows_offset,separate); + if (separate != MagickFalse) + size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; + else + rows_offset+=offset_length; + count+=length; + } + } + compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); + if (next_image->colorspace == CMYKColorspace) + (void) NegateImage(next_image,MagickFalse); + if (separate != MagickFalse) + { + const char + *property; + + property=GetImageArtifact(next_image,""psd:opacity-mask""); + if (property != (const char *) NULL) + { + mask=(Image *) GetImageRegistry(ImageRegistryType,property, + &image->exception); + if (mask != (Image *) NULL) + { + if (mask->compression == RLECompression) + { + compact_pixels=AcquireCompactPixels(mask); + if (compact_pixels == (unsigned char *) NULL) + return(0); + } + length=WritePSDChannel(psd_info,image_info,image,mask, + RedQuantum,compact_pixels,rows_offset,MagickTrue); + (void) WritePSDSize(psd_info,image,length,size_offset); + count+=length; + compact_pixels=(unsigned char *) RelinquishMagickMemory( + compact_pixels); + } + } + } + return(count); +}","{'deleted': [{'line_no': 26, 'char_start': 490, 'char_end': 540, 'line': ' compact_pixels=AcquireCompactPixels(image);\n'}], 'added': [{'line_no': 26, 'char_start': 490, 'char_end': 545, 'line': ' compact_pixels=AcquireCompactPixels(next_image);\n'}]}","{'deleted': [], 'added': [{'char_start': 532, 'char_end': 537, 'chars': 'next_'}]}",github.com/ImageMagick/ImageMagick/commit/37a1710e2dab6ed91128ea648d654a22fbe2a6af,coders/psd.c,cwe-787, +cwe-787,InitialiseRFBConnection,"InitialiseRFBConnection(rfbClient* client) +{ + rfbProtocolVersionMsg pv; + int major,minor; + uint32_t authScheme; + uint32_t subAuthScheme; + rfbClientInitMsg ci; + + /* if the connection is immediately closed, don't report anything, so + that pmw's monitor can make test connections */ + + if (client->listenSpecified) + errorMessageOnReadFailure = FALSE; + + if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; + pv[sz_rfbProtocolVersionMsg]=0; + + errorMessageOnReadFailure = TRUE; + + pv[sz_rfbProtocolVersionMsg] = 0; + + if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) { + rfbClientLog(""Not a valid VNC server (%s)\n"",pv); + return FALSE; + } + + + DefaultSupportedMessages(client); + client->major = major; + client->minor = minor; + + /* fall back to viewer supported version */ + if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion)) + client->minor = rfbProtocolMinorVersion; + + /* UltraVNC uses minor codes 4 and 6 for the server */ + if (major==3 && (minor==4 || minor==6)) { + rfbClientLog(""UltraVNC server detected, enabling UltraVNC specific messages\n"",pv); + DefaultSupportedMessagesUltraVNC(client); + } + + /* UltraVNC Single Click uses minor codes 14 and 16 for the server */ + if (major==3 && (minor==14 || minor==16)) { + minor = minor - 10; + client->minor = minor; + rfbClientLog(""UltraVNC Single Click server detected, enabling UltraVNC specific messages\n"",pv); + DefaultSupportedMessagesUltraVNC(client); + } + + /* TightVNC uses minor codes 5 for the server */ + if (major==3 && minor==5) { + rfbClientLog(""TightVNC server detected, enabling TightVNC specific messages\n"",pv); + DefaultSupportedMessagesTightVNC(client); + } + + /* we do not support > RFB3.8 */ + if ((major==3 && minor>8) || major>3) + { + client->major=3; + client->minor=8; + } + + rfbClientLog(""VNC server supports protocol version %d.%d (viewer %d.%d)\n"", + major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion); + + sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor); + + if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; + + + /* 3.7 and onwards sends a # of security types first */ + if (client->major==3 && client->minor > 6) + { + if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE; + } + else + { + if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE; + authScheme = rfbClientSwap32IfLE(authScheme); + } + + rfbClientLog(""Selected Security Scheme %d\n"", authScheme); + client->authScheme = authScheme; + + switch (authScheme) { + + case rfbConnFailed: + ReadReason(client); + return FALSE; + + case rfbNoAuth: + rfbClientLog(""No authentication needed\n""); + + /* 3.8 and upwards sends a Security Result for rfbNoAuth */ + if ((client->major==3 && client->minor > 7) || client->major>3) + if (!rfbHandleAuthResult(client)) return FALSE; + + break; + + case rfbVncAuth: + if (!HandleVncAuth(client)) return FALSE; + break; + +#ifdef LIBVNCSERVER_HAVE_SASL + case rfbSASL: + if (!HandleSASLAuth(client)) return FALSE; + break; +#endif /* LIBVNCSERVER_HAVE_SASL */ + + case rfbMSLogon: + if (!HandleMSLogonAuth(client)) return FALSE; + break; + + case rfbARD: +#ifndef LIBVNCSERVER_WITH_CLIENT_GCRYPT + rfbClientLog(""GCrypt support was not compiled in\n""); + return FALSE; +#else + if (!HandleARDAuth(client)) return FALSE; +#endif + break; + + case rfbTLS: + if (!HandleAnonTLSAuth(client)) return FALSE; + /* After the TLS session is established, sub auth types are expected. + * Note that all following reading/writing are through the TLS session from here. + */ + if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE; + client->subAuthScheme = subAuthScheme; + + switch (subAuthScheme) { + + case rfbConnFailed: + ReadReason(client); + return FALSE; + + case rfbNoAuth: + rfbClientLog(""No sub authentication needed\n""); + /* 3.8 and upwards sends a Security Result for rfbNoAuth */ + if ((client->major==3 && client->minor > 7) || client->major>3) + if (!rfbHandleAuthResult(client)) return FALSE; + break; + + case rfbVncAuth: + if (!HandleVncAuth(client)) return FALSE; + break; + +#ifdef LIBVNCSERVER_HAVE_SASL + case rfbSASL: + if (!HandleSASLAuth(client)) return FALSE; + break; +#endif /* LIBVNCSERVER_HAVE_SASL */ + + default: + rfbClientLog(""Unknown sub authentication scheme from VNC server: %d\n"", + (int)subAuthScheme); + return FALSE; + } + + break; + + case rfbVeNCrypt: + if (!HandleVeNCryptAuth(client)) return FALSE; + + switch (client->subAuthScheme) { + + case rfbVeNCryptTLSNone: + case rfbVeNCryptX509None: + rfbClientLog(""No sub authentication needed\n""); + if (!rfbHandleAuthResult(client)) return FALSE; + break; + + case rfbVeNCryptTLSVNC: + case rfbVeNCryptX509VNC: + if (!HandleVncAuth(client)) return FALSE; + break; + + case rfbVeNCryptTLSPlain: + case rfbVeNCryptX509Plain: + if (!HandlePlainAuth(client)) return FALSE; + break; + +#ifdef LIBVNCSERVER_HAVE_SASL + case rfbVeNCryptX509SASL: + case rfbVeNCryptTLSSASL: + if (!HandleSASLAuth(client)) return FALSE; + break; +#endif /* LIBVNCSERVER_HAVE_SASL */ + + default: + rfbClientLog(""Unknown sub authentication scheme from VNC server: %d\n"", + client->subAuthScheme); + return FALSE; + } + + break; + + default: + { + rfbBool authHandled=FALSE; + rfbClientProtocolExtension* e; + for (e = rfbClientExtensions; e; e = e->next) { + uint32_t const* secType; + if (!e->handleAuthentication) continue; + for (secType = e->securityTypes; secType && *secType; secType++) { + if (authScheme==*secType) { + if (!e->handleAuthentication(client, authScheme)) return FALSE; + if (!rfbHandleAuthResult(client)) return FALSE; + authHandled=TRUE; + } + } + } + if (authHandled) break; + } + rfbClientLog(""Unknown authentication scheme from VNC server: %d\n"", + (int)authScheme); + return FALSE; + } + + ci.shared = (client->appData.shareDesktop ? 1 : 0); + + if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE; + + if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE; + + client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth); + client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight); + client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax); + client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax); + client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax); + client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength); + + /* To guard against integer wrap-around, si.nameLength is cast to 64 bit */ + client->desktopName = malloc((uint64_t)client->si.nameLength + 1); + if (!client->desktopName) { + rfbClientLog(""Error allocating memory for desktop name, %lu bytes\n"", + (unsigned long)client->si.nameLength); + return FALSE; + } + + if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE; + + client->desktopName[client->si.nameLength] = 0; + + rfbClientLog(""Desktop name \""%s\""\n"",client->desktopName); + + rfbClientLog(""Connected to VNC server, using protocol version %d.%d\n"", + client->major, client->minor); + + rfbClientLog(""VNC server default format:\n""); + PrintPixelFormat(&client->si.format); + + return TRUE; +}","InitialiseRFBConnection(rfbClient* client) +{ + rfbProtocolVersionMsg pv; + int major,minor; + uint32_t authScheme; + uint32_t subAuthScheme; + rfbClientInitMsg ci; + + /* if the connection is immediately closed, don't report anything, so + that pmw's monitor can make test connections */ + + if (client->listenSpecified) + errorMessageOnReadFailure = FALSE; + + if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; + pv[sz_rfbProtocolVersionMsg]=0; + + errorMessageOnReadFailure = TRUE; + + pv[sz_rfbProtocolVersionMsg] = 0; + + if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) { + rfbClientLog(""Not a valid VNC server (%s)\n"",pv); + return FALSE; + } + + + DefaultSupportedMessages(client); + client->major = major; + client->minor = minor; + + /* fall back to viewer supported version */ + if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion)) + client->minor = rfbProtocolMinorVersion; + + /* UltraVNC uses minor codes 4 and 6 for the server */ + if (major==3 && (minor==4 || minor==6)) { + rfbClientLog(""UltraVNC server detected, enabling UltraVNC specific messages\n"",pv); + DefaultSupportedMessagesUltraVNC(client); + } + + /* UltraVNC Single Click uses minor codes 14 and 16 for the server */ + if (major==3 && (minor==14 || minor==16)) { + minor = minor - 10; + client->minor = minor; + rfbClientLog(""UltraVNC Single Click server detected, enabling UltraVNC specific messages\n"",pv); + DefaultSupportedMessagesUltraVNC(client); + } + + /* TightVNC uses minor codes 5 for the server */ + if (major==3 && minor==5) { + rfbClientLog(""TightVNC server detected, enabling TightVNC specific messages\n"",pv); + DefaultSupportedMessagesTightVNC(client); + } + + /* we do not support > RFB3.8 */ + if ((major==3 && minor>8) || major>3) + { + client->major=3; + client->minor=8; + } + + rfbClientLog(""VNC server supports protocol version %d.%d (viewer %d.%d)\n"", + major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion); + + sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor); + + if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; + + + /* 3.7 and onwards sends a # of security types first */ + if (client->major==3 && client->minor > 6) + { + if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE; + } + else + { + if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE; + authScheme = rfbClientSwap32IfLE(authScheme); + } + + rfbClientLog(""Selected Security Scheme %d\n"", authScheme); + client->authScheme = authScheme; + + switch (authScheme) { + + case rfbConnFailed: + ReadReason(client); + return FALSE; + + case rfbNoAuth: + rfbClientLog(""No authentication needed\n""); + + /* 3.8 and upwards sends a Security Result for rfbNoAuth */ + if ((client->major==3 && client->minor > 7) || client->major>3) + if (!rfbHandleAuthResult(client)) return FALSE; + + break; + + case rfbVncAuth: + if (!HandleVncAuth(client)) return FALSE; + break; + +#ifdef LIBVNCSERVER_HAVE_SASL + case rfbSASL: + if (!HandleSASLAuth(client)) return FALSE; + break; +#endif /* LIBVNCSERVER_HAVE_SASL */ + + case rfbMSLogon: + if (!HandleMSLogonAuth(client)) return FALSE; + break; + + case rfbARD: +#ifndef LIBVNCSERVER_WITH_CLIENT_GCRYPT + rfbClientLog(""GCrypt support was not compiled in\n""); + return FALSE; +#else + if (!HandleARDAuth(client)) return FALSE; +#endif + break; + + case rfbTLS: + if (!HandleAnonTLSAuth(client)) return FALSE; + /* After the TLS session is established, sub auth types are expected. + * Note that all following reading/writing are through the TLS session from here. + */ + if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE; + client->subAuthScheme = subAuthScheme; + + switch (subAuthScheme) { + + case rfbConnFailed: + ReadReason(client); + return FALSE; + + case rfbNoAuth: + rfbClientLog(""No sub authentication needed\n""); + /* 3.8 and upwards sends a Security Result for rfbNoAuth */ + if ((client->major==3 && client->minor > 7) || client->major>3) + if (!rfbHandleAuthResult(client)) return FALSE; + break; + + case rfbVncAuth: + if (!HandleVncAuth(client)) return FALSE; + break; + +#ifdef LIBVNCSERVER_HAVE_SASL + case rfbSASL: + if (!HandleSASLAuth(client)) return FALSE; + break; +#endif /* LIBVNCSERVER_HAVE_SASL */ + + default: + rfbClientLog(""Unknown sub authentication scheme from VNC server: %d\n"", + (int)subAuthScheme); + return FALSE; + } + + break; + + case rfbVeNCrypt: + if (!HandleVeNCryptAuth(client)) return FALSE; + + switch (client->subAuthScheme) { + + case rfbVeNCryptTLSNone: + case rfbVeNCryptX509None: + rfbClientLog(""No sub authentication needed\n""); + if (!rfbHandleAuthResult(client)) return FALSE; + break; + + case rfbVeNCryptTLSVNC: + case rfbVeNCryptX509VNC: + if (!HandleVncAuth(client)) return FALSE; + break; + + case rfbVeNCryptTLSPlain: + case rfbVeNCryptX509Plain: + if (!HandlePlainAuth(client)) return FALSE; + break; + +#ifdef LIBVNCSERVER_HAVE_SASL + case rfbVeNCryptX509SASL: + case rfbVeNCryptTLSSASL: + if (!HandleSASLAuth(client)) return FALSE; + break; +#endif /* LIBVNCSERVER_HAVE_SASL */ + + default: + rfbClientLog(""Unknown sub authentication scheme from VNC server: %d\n"", + client->subAuthScheme); + return FALSE; + } + + break; + + default: + { + rfbBool authHandled=FALSE; + rfbClientProtocolExtension* e; + for (e = rfbClientExtensions; e; e = e->next) { + uint32_t const* secType; + if (!e->handleAuthentication) continue; + for (secType = e->securityTypes; secType && *secType; secType++) { + if (authScheme==*secType) { + if (!e->handleAuthentication(client, authScheme)) return FALSE; + if (!rfbHandleAuthResult(client)) return FALSE; + authHandled=TRUE; + } + } + } + if (authHandled) break; + } + rfbClientLog(""Unknown authentication scheme from VNC server: %d\n"", + (int)authScheme); + return FALSE; + } + + ci.shared = (client->appData.shareDesktop ? 1 : 0); + + if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE; + + if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE; + + client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth); + client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight); + client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax); + client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax); + client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax); + client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength); + + if (client->si.nameLength > 1<<20) { + rfbClientErr(""Too big desktop name length sent by server: %u B > 1 MB\n"", (unsigned int)client->si.nameLength); + return FALSE; + } + + client->desktopName = malloc(client->si.nameLength + 1); + if (!client->desktopName) { + rfbClientLog(""Error allocating memory for desktop name, %lu bytes\n"", + (unsigned long)client->si.nameLength); + return FALSE; + } + + if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE; + + client->desktopName[client->si.nameLength] = 0; + + rfbClientLog(""Desktop name \""%s\""\n"",client->desktopName); + + rfbClientLog(""Connected to VNC server, using protocol version %d.%d\n"", + client->major, client->minor); + + rfbClientLog(""VNC server default format:\n""); + PrintPixelFormat(&client->si.format); + + return TRUE; +}","{'deleted': [{'line_no': 233, 'char_start': 6941, 'char_end': 7019, 'line': ' /* To guard against integer wrap-around, si.nameLength is cast to 64 bit */\n'}, {'line_no': 234, 'char_start': 7019, 'char_end': 7088, 'line': ' client->desktopName = malloc((uint64_t)client->si.nameLength + 1);\n'}], 'added': [{'line_no': 233, 'char_start': 6941, 'char_end': 6980, 'line': ' if (client->si.nameLength > 1<<20) {\n'}, {'line_no': 234, 'char_start': 6980, 'char_end': 7098, 'line': ' rfbClientErr(""Too big desktop name length sent by server: %u B > 1 MB\\n"", (unsigned int)client->si.nameLength);\n'}, {'line_no': 235, 'char_start': 7098, 'char_end': 7118, 'line': ' return FALSE;\n'}, {'line_no': 236, 'char_start': 7118, 'char_end': 7122, 'line': ' }\n'}, {'line_no': 237, 'char_start': 7122, 'char_end': 7123, 'line': '\n'}, {'line_no': 238, 'char_start': 7123, 'char_end': 7182, 'line': ' client->desktopName = malloc(client->si.nameLength + 1);\n'}]}","{'deleted': [{'char_start': 6943, 'char_end': 6945, 'chars': '/*'}, {'char_start': 6950, 'char_end': 6953, 'chars': 'uar'}, {'char_start': 6956, 'char_end': 6959, 'chars': 'gai'}, {'char_start': 6960, 'char_end': 6961, 'chars': 's'}, {'char_start': 6963, 'char_end': 6964, 'chars': 'i'}, {'char_start': 6967, 'char_end': 6968, 'chars': 'g'}, {'char_start': 6971, 'char_end': 6979, 'chars': 'wrap-aro'}, {'char_start': 6981, 'char_end': 6982, 'chars': 'd'}, {'char_start': 6998, 'char_end': 7000, 'chars': 'is'}, {'char_start': 7001, 'char_end': 7005, 'chars': 'cast'}, {'char_start': 7007, 'char_end': 7008, 'chars': 'o'}, {'char_start': 7009, 'char_end': 7011, 'chars': '64'}, {'char_start': 7012, 'char_end': 7015, 'chars': 'bit'}, {'char_start': 7016, 'char_end': 7018, 'chars': '*/'}, {'char_start': 7050, 'char_end': 7060, 'chars': '(uint64_t)'}], 'added': [{'char_start': 6943, 'char_end': 6970, 'chars': 'if (client->si.nameLength >'}, {'char_start': 6971, 'char_end': 7000, 'chars': '1<<20) {\n rfbClientErr(""'}, {'char_start': 7002, 'char_end': 7003, 'chars': 'o'}, {'char_start': 7004, 'char_end': 7006, 'chars': 'bi'}, {'char_start': 7007, 'char_end': 7008, 'chars': ' '}, {'char_start': 7009, 'char_end': 7015, 'chars': 'esktop'}, {'char_start': 7016, 'char_end': 7017, 'chars': 'n'}, {'char_start': 7018, 'char_end': 7024, 'chars': 'me len'}, {'char_start': 7026, 'char_end': 7027, 'chars': 'h'}, {'char_start': 7028, 'char_end': 7030, 'chars': 'se'}, {'char_start': 7032, 'char_end': 7037, 'chars': ' by s'}, {'char_start': 7038, 'char_end': 7040, 'chars': 'rv'}, {'char_start': 7042, 'char_end': 7043, 'chars': ':'}, {'char_start': 7044, 'char_end': 7045, 'chars': '%'}, {'char_start': 7046, 'char_end': 7056, 'chars': ' B > 1 MB\\'}, {'char_start': 7057, 'char_end': 7058, 'chars': '""'}, {'char_start': 7060, 'char_end': 7082, 'chars': '(unsigned int)client->'}, {'char_start': 7095, 'char_end': 7098, 'chars': ');\n'}, {'char_start': 7102, 'char_end': 7103, 'chars': ' '}, {'char_start': 7104, 'char_end': 7106, 'chars': 're'}, {'char_start': 7107, 'char_end': 7110, 'chars': 'urn'}, {'char_start': 7111, 'char_end': 7122, 'chars': 'FALSE;\n }\n'}]}",github.com/LibVNC/libvncserver/commit/c2c4b81e6cb3b485fb1ec7ba9e7defeb889f6ba7,libvncclient/rfbproto.c,cwe-787, +cwe-787,cdf_read_property_info,"cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, + uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) +{ + const cdf_section_header_t *shp; + cdf_section_header_t sh; + const uint8_t *p, *q, *e; + size_t i, o4, nelements, j, slen, left; + cdf_property_info_t *inp; + + if (offs > UINT32_MAX / 4) { + errno = EFTYPE; + goto out; + } + shp = CAST(const cdf_section_header_t *, + cdf_offset(sst->sst_tab, offs)); + if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) + goto out; + sh.sh_len = CDF_TOLE4(shp->sh_len); + if (sh.sh_len > CDF_SHLEN_LIMIT) { + errno = EFTYPE; + goto out; + } + + if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1) + goto out; + + sh.sh_properties = CDF_TOLE4(shp->sh_properties); + DPRINTF((""section len: %u properties %u\n"", sh.sh_len, + sh.sh_properties)); + if (sh.sh_properties > CDF_PROP_LIMIT) + goto out; + inp = cdf_grow_info(info, maxcount, sh.sh_properties); + if (inp == NULL) + goto out; + inp += *count; + *count += sh.sh_properties; + p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh))); + e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len)); + if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) + goto out; + + for (i = 0; i < sh.sh_properties; i++) { + if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL) + goto out; + inp[i].pi_id = CDF_GETUINT32(p, i << 1); + left = CAST(size_t, e - q); + if (left < sizeof(uint32_t)) { + DPRINTF((""short info (no type)_\n"")); + goto out; + } + inp[i].pi_type = CDF_GETUINT32(q, 0); + DPRINTF((""%"" SIZE_T_FORMAT ""u) id=%#x type=%#x offs=%#tx,%#x\n"", + i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); + if (inp[i].pi_type & CDF_VECTOR) { + if (left < sizeof(uint32_t) * 2) { + DPRINTF((""missing CDF_VECTOR length\n"")); + goto out; + } + nelements = CDF_GETUINT32(q, 1); + if (nelements == 0) { + DPRINTF((""CDF_VECTOR with nelements == 0\n"")); + goto out; + } + slen = 2; + } else { + nelements = 1; + slen = 1; + } + o4 = slen * sizeof(uint32_t); + if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) + goto unknown; + switch (inp[i].pi_type & CDF_TYPEMASK) { + case CDF_NULL: + case CDF_EMPTY: + break; + case CDF_SIGNED16: + if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t))) + goto unknown; + break; + case CDF_SIGNED32: + case CDF_BOOL: + case CDF_UNSIGNED32: + case CDF_FLOAT: + if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t))) + goto unknown; + break; + case CDF_SIGNED64: + case CDF_UNSIGNED64: + case CDF_DOUBLE: + case CDF_FILETIME: + if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t))) + goto unknown; + break; + case CDF_LENGTH32_STRING: + case CDF_LENGTH32_WSTRING: + if (nelements > 1) { + size_t nelem = inp - *info; + inp = cdf_grow_info(info, maxcount, nelements); + if (inp == NULL) + goto out; + inp += nelem; + } + DPRINTF((""nelements = %"" SIZE_T_FORMAT ""u\n"", + nelements)); + for (j = 0; j < nelements && i < sh.sh_properties; + j++, i++) + { + uint32_t l; + + if (o4 + sizeof(uint32_t) > left) + goto out; + + l = CDF_GETUINT32(q, slen); + o4 += sizeof(uint32_t); + if (o4 + l > left) + goto out; + + inp[i].pi_str.s_len = l; + inp[i].pi_str.s_buf = CAST(const char *, + CAST(const void *, &q[o4])); + + DPRINTF((""o=%"" SIZE_T_FORMAT ""u l=%d(%"" + SIZE_T_FORMAT ""u), t=%"" SIZE_T_FORMAT + ""u s=%s\n"", o4, l, CDF_ROUND(l, sizeof(l)), + left, inp[i].pi_str.s_buf)); + + if (l & 1) + l++; + + slen += l >> 1; + o4 = slen * sizeof(uint32_t); + } + i--; + break; + case CDF_CLIPBOARD: + if (inp[i].pi_type & CDF_VECTOR) + goto unknown; + break; + default: + unknown: + memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val)); + DPRINTF((""Don't know how to deal with %#x\n"", + inp[i].pi_type)); + break; + } + } + return 0; +out: + free(*info); + *info = NULL; + *count = 0; + *maxcount = 0; + errno = EFTYPE; + return -1; +}","cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, + uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) +{ + const cdf_section_header_t *shp; + cdf_section_header_t sh; + const uint8_t *p, *q, *e; + size_t i, o4, nelements, j, slen, left; + cdf_property_info_t *inp; + + if (offs > UINT32_MAX / 4) { + errno = EFTYPE; + goto out; + } + shp = CAST(const cdf_section_header_t *, + cdf_offset(sst->sst_tab, offs)); + if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) + goto out; + sh.sh_len = CDF_TOLE4(shp->sh_len); + if (sh.sh_len > CDF_SHLEN_LIMIT) { + errno = EFTYPE; + goto out; + } + + if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1) + goto out; + + sh.sh_properties = CDF_TOLE4(shp->sh_properties); + DPRINTF((""section len: %u properties %u\n"", sh.sh_len, + sh.sh_properties)); + if (sh.sh_properties > CDF_PROP_LIMIT) + goto out; + inp = cdf_grow_info(info, maxcount, sh.sh_properties); + if (inp == NULL) + goto out; + inp += *count; + *count += sh.sh_properties; + p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh))); + e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len)); + if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) + goto out; + + for (i = 0; i < sh.sh_properties; i++) { + if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL) + goto out; + inp[i].pi_id = CDF_GETUINT32(p, i << 1); + left = CAST(size_t, e - q); + if (left < sizeof(uint32_t)) { + DPRINTF((""short info (no type)_\n"")); + goto out; + } + inp[i].pi_type = CDF_GETUINT32(q, 0); + DPRINTF((""%"" SIZE_T_FORMAT ""u) id=%#x type=%#x offs=%#tx,%#x\n"", + i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); + if (inp[i].pi_type & CDF_VECTOR) { + if (left < sizeof(uint32_t) * 2) { + DPRINTF((""missing CDF_VECTOR length\n"")); + goto out; + } + nelements = CDF_GETUINT32(q, 1); + if (nelements > CDF_ELEMENT_LIMIT || nelements == 0) { + DPRINTF((""CDF_VECTOR with nelements == %"" + SIZE_T_FORMAT ""u\n"", nelements)); + goto out; + } + slen = 2; + } else { + nelements = 1; + slen = 1; + } + o4 = slen * sizeof(uint32_t); + if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) + goto unknown; + switch (inp[i].pi_type & CDF_TYPEMASK) { + case CDF_NULL: + case CDF_EMPTY: + break; + case CDF_SIGNED16: + if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t))) + goto unknown; + break; + case CDF_SIGNED32: + case CDF_BOOL: + case CDF_UNSIGNED32: + case CDF_FLOAT: + if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t))) + goto unknown; + break; + case CDF_SIGNED64: + case CDF_UNSIGNED64: + case CDF_DOUBLE: + case CDF_FILETIME: + if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t))) + goto unknown; + break; + case CDF_LENGTH32_STRING: + case CDF_LENGTH32_WSTRING: + if (nelements > 1) { + size_t nelem = inp - *info; + inp = cdf_grow_info(info, maxcount, nelements); + if (inp == NULL) + goto out; + inp += nelem; + } + for (j = 0; j < nelements && i < sh.sh_properties; + j++, i++) + { + uint32_t l; + + if (o4 + sizeof(uint32_t) > left) + goto out; + + l = CDF_GETUINT32(q, slen); + o4 += sizeof(uint32_t); + if (o4 + l > left) + goto out; + + inp[i].pi_str.s_len = l; + inp[i].pi_str.s_buf = CAST(const char *, + CAST(const void *, &q[o4])); + + DPRINTF((""o=%"" SIZE_T_FORMAT ""u l=%d(%"" + SIZE_T_FORMAT ""u), t=%"" SIZE_T_FORMAT + ""u s=%s\n"", o4, l, CDF_ROUND(l, sizeof(l)), + left, inp[i].pi_str.s_buf)); + + if (l & 1) + l++; + + slen += l >> 1; + o4 = slen * sizeof(uint32_t); + } + i--; + break; + case CDF_CLIPBOARD: + if (inp[i].pi_type & CDF_VECTOR) + goto unknown; + break; + default: + unknown: + memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val)); + DPRINTF((""Don't know how to deal with %#x\n"", + inp[i].pi_type)); + break; + } + } + return 0; +out: + free(*info); + *info = NULL; + *count = 0; + *maxcount = 0; + errno = EFTYPE; + return -1; +}","{'deleted': [{'line_no': 60, 'char_start': 1874, 'char_end': 1899, 'line': '\t\t\tif (nelements == 0) {\n'}, {'line_no': 61, 'char_start': 1899, 'char_end': 1950, 'line': '\t\t\t\tDPRINTF((""CDF_VECTOR with nelements == 0\\n""));\n'}, {'line_no': 103, 'char_start': 2896, 'char_end': 2945, 'line': '\t\t\tDPRINTF((""nelements = %"" SIZE_T_FORMAT ""u\\n"",\n'}, {'line_no': 104, 'char_start': 2945, 'char_end': 2965, 'line': '\t\t\t nelements));\n'}], 'added': [{'line_no': 60, 'char_start': 1874, 'char_end': 1932, 'line': '\t\t\tif (nelements > CDF_ELEMENT_LIMIT || nelements == 0) {\n'}, {'line_no': 61, 'char_start': 1932, 'char_end': 1978, 'line': '\t\t\t\tDPRINTF((""CDF_VECTOR with nelements == %""\n'}, {'line_no': 62, 'char_start': 1978, 'char_end': 2020, 'line': '\t\t\t\t SIZE_T_FORMAT ""u\\n"", nelements));\n'}]}","{'deleted': [{'char_start': 1942, 'char_end': 1943, 'chars': '0'}, {'char_start': 2895, 'char_end': 2964, 'chars': '\n\t\t\tDPRINTF((""nelements = %"" SIZE_T_FORMAT ""u\\n"",\n\t\t\t nelements));'}], 'added': [{'char_start': 1891, 'char_end': 1924, 'chars': '> CDF_ELEMENT_LIMIT || nelements '}, {'char_start': 1975, 'char_end': 2002, 'chars': '%""\n\t\t\t\t SIZE_T_FORMAT ""u'}, {'char_start': 2005, 'char_end': 2016, 'chars': ', nelements'}]}",github.com/file/file/commit/46a8443f76cec4b41ec736eca396984c74664f84,src/cdf.c,cwe-787, +cwe-787,pgxtoimage,"opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) +{ + FILE *f = NULL; + int w, h, prec; + int i, numcomps, max; + OPJ_COLOR_SPACE color_space; + opj_image_cmptparm_t cmptparm; /* maximum of 1 component */ + opj_image_t * image = NULL; + int adjustS, ushift, dshift, force8; + + char endian1, endian2, sign; + char signtmp[32]; + + char temp[32]; + int bigendian; + opj_image_comp_t *comp = NULL; + + numcomps = 1; + color_space = OPJ_CLRSPC_GRAY; + + memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t)); + + max = 0; + + f = fopen(filename, ""rb""); + if (!f) { + fprintf(stderr, ""Failed to open %s for reading !\n"", filename); + return NULL; + } + + fseek(f, 0, SEEK_SET); + if (fscanf(f, ""PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d"", temp, &endian1, + &endian2, signtmp, &prec, temp, &w, temp, &h) != 9) { + fclose(f); + fprintf(stderr, + ""ERROR: Failed to read the right number of element from the fscanf() function!\n""); + return NULL; + } + + i = 0; + sign = '+'; + while (signtmp[i] != '\0') { + if (signtmp[i] == '-') { + sign = '-'; + } + i++; + } + + fgetc(f); + if (endian1 == 'M' && endian2 == 'L') { + bigendian = 1; + } else if (endian2 == 'M' && endian1 == 'L') { + bigendian = 0; + } else { + fclose(f); + fprintf(stderr, ""Bad pgx header, please check input file\n""); + return NULL; + } + + /* initialize image component */ + + cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0; + cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0; + cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + + 1; + cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + + 1; + + if (sign == '-') { + cmptparm.sgnd = 1; + } else { + cmptparm.sgnd = 0; + } + if (prec < 8) { + force8 = 1; + ushift = 8 - prec; + dshift = prec - ushift; + if (cmptparm.sgnd) { + adjustS = (1 << (prec - 1)); + } else { + adjustS = 0; + } + cmptparm.sgnd = 0; + prec = 8; + } else { + ushift = dshift = force8 = adjustS = 0; + } + + cmptparm.prec = (OPJ_UINT32)prec; + cmptparm.bpp = (OPJ_UINT32)prec; + cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx; + cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy; + + /* create the image */ + image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space); + if (!image) { + fclose(f); + return NULL; + } + /* set image offset and reference grid */ + image->x0 = cmptparm.x0; + image->y0 = cmptparm.x0; + image->x1 = cmptparm.w; + image->y1 = cmptparm.h; + + /* set image data */ + + comp = &image->comps[0]; + + for (i = 0; i < w * h; i++) { + int v; + if (force8) { + v = readuchar(f) + adjustS; + v = (v << ushift) + (v >> dshift); + comp->data[i] = (unsigned char)v; + + if (v > max) { + max = v; + } + + continue; + } + if (comp->prec == 8) { + if (!comp->sgnd) { + v = readuchar(f); + } else { + v = (char) readuchar(f); + } + } else if (comp->prec <= 16) { + if (!comp->sgnd) { + v = readushort(f, bigendian); + } else { + v = (short) readushort(f, bigendian); + } + } else { + if (!comp->sgnd) { + v = (int)readuint(f, bigendian); + } else { + v = (int) readuint(f, bigendian); + } + } + if (v > max) { + max = v; + } + comp->data[i] = v; + } + fclose(f); + comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1; + + return image; +}","opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) +{ + FILE *f = NULL; + int w, h, prec; + int i, numcomps, max; + OPJ_COLOR_SPACE color_space; + opj_image_cmptparm_t cmptparm; /* maximum of 1 component */ + opj_image_t * image = NULL; + int adjustS, ushift, dshift, force8; + + char endian1, endian2, sign; + char signtmp[32]; + + char temp[32]; + int bigendian; + opj_image_comp_t *comp = NULL; + + numcomps = 1; + color_space = OPJ_CLRSPC_GRAY; + + memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t)); + + max = 0; + + f = fopen(filename, ""rb""); + if (!f) { + fprintf(stderr, ""Failed to open %s for reading !\n"", filename); + return NULL; + } + + fseek(f, 0, SEEK_SET); + if (fscanf(f, ""PG%31[ \t]%c%c%31[ \t+-]%d%31[ \t]%d%31[ \t]%d"", temp, &endian1, + &endian2, signtmp, &prec, temp, &w, temp, &h) != 9) { + fclose(f); + fprintf(stderr, + ""ERROR: Failed to read the right number of element from the fscanf() function!\n""); + return NULL; + } + + i = 0; + sign = '+'; + while (signtmp[i] != '\0') { + if (signtmp[i] == '-') { + sign = '-'; + } + i++; + } + + fgetc(f); + if (endian1 == 'M' && endian2 == 'L') { + bigendian = 1; + } else if (endian2 == 'M' && endian1 == 'L') { + bigendian = 0; + } else { + fclose(f); + fprintf(stderr, ""Bad pgx header, please check input file\n""); + return NULL; + } + + /* initialize image component */ + + cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0; + cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0; + cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + + 1; + cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + + 1; + + if (sign == '-') { + cmptparm.sgnd = 1; + } else { + cmptparm.sgnd = 0; + } + if (prec < 8) { + force8 = 1; + ushift = 8 - prec; + dshift = prec - ushift; + if (cmptparm.sgnd) { + adjustS = (1 << (prec - 1)); + } else { + adjustS = 0; + } + cmptparm.sgnd = 0; + prec = 8; + } else { + ushift = dshift = force8 = adjustS = 0; + } + + cmptparm.prec = (OPJ_UINT32)prec; + cmptparm.bpp = (OPJ_UINT32)prec; + cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx; + cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy; + + /* create the image */ + image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space); + if (!image) { + fclose(f); + return NULL; + } + /* set image offset and reference grid */ + image->x0 = cmptparm.x0; + image->y0 = cmptparm.x0; + image->x1 = cmptparm.w; + image->y1 = cmptparm.h; + + /* set image data */ + + comp = &image->comps[0]; + + for (i = 0; i < w * h; i++) { + int v; + if (force8) { + v = readuchar(f) + adjustS; + v = (v << ushift) + (v >> dshift); + comp->data[i] = (unsigned char)v; + + if (v > max) { + max = v; + } + + continue; + } + if (comp->prec == 8) { + if (!comp->sgnd) { + v = readuchar(f); + } else { + v = (char) readuchar(f); + } + } else if (comp->prec <= 16) { + if (!comp->sgnd) { + v = readushort(f, bigendian); + } else { + v = (short) readushort(f, bigendian); + } + } else { + if (!comp->sgnd) { + v = (int)readuint(f, bigendian); + } else { + v = (int) readuint(f, bigendian); + } + } + if (v > max) { + max = v; + } + comp->data[i] = v; + } + fclose(f); + comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1; + + return image; +}","{'deleted': [{'line_no': 32, 'char_start': 745, 'char_end': 821, 'line': ' if (fscanf(f, ""PG%[ \\t]%c%c%[ \\t+-]%d%[ \\t]%d%[ \\t]%d"", temp, &endian1,\n'}], 'added': [{'line_no': 32, 'char_start': 745, 'char_end': 829, 'line': ' if (fscanf(f, ""PG%31[ \\t]%c%c%31[ \\t+-]%d%31[ \\t]%d%31[ \\t]%d"", temp, &endian1,\n'}]}","{'deleted': [], 'added': [{'char_start': 767, 'char_end': 769, 'chars': '31'}, {'char_start': 779, 'char_end': 781, 'chars': '31'}, {'char_start': 791, 'char_end': 793, 'chars': '31'}, {'char_start': 801, 'char_end': 803, 'chars': '31'}]}",github.com/uclouvain/openjpeg/commit/e5285319229a5d77bf316bb0d3a6cbd3cb8666d9,src/bin/jp2/convert.c,cwe-787, +cwe-787,S_study_chunk,"STATIC SSize_t +S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp, + SSize_t *minlenp, SSize_t *deltap, + regnode *last, + scan_data_t *data, + I32 stopparen, + U32 recursed_depth, + regnode_ssc *and_withp, + U32 flags, U32 depth) + /* scanp: Start here (read-write). */ + /* deltap: Write maxlen-minlen here. */ + /* last: Stop before this one. */ + /* data: string data about the pattern */ + /* stopparen: treat close N as END */ + /* recursed: which subroutines have we recursed into */ + /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */ +{ + dVAR; + /* There must be at least this number of characters to match */ + SSize_t min = 0; + I32 pars = 0, code; + regnode *scan = *scanp, *next; + SSize_t delta = 0; + int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF); + int is_inf_internal = 0; /* The studied chunk is infinite */ + I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0; + scan_data_t data_fake; + SV *re_trie_maxbuff = NULL; + regnode *first_non_open = scan; + SSize_t stopmin = SSize_t_MAX; + scan_frame *frame = NULL; + GET_RE_DEBUG_FLAGS_DECL; + + PERL_ARGS_ASSERT_STUDY_CHUNK; + RExC_study_started= 1; + + Zero(&data_fake, 1, scan_data_t); + + if ( depth == 0 ) { + while (first_non_open && OP(first_non_open) == OPEN) + first_non_open=regnext(first_non_open); + } + + + fake_study_recurse: + DEBUG_r( + RExC_study_chunk_recursed_count++; + ); + DEBUG_OPTIMISE_MORE_r( + { + Perl_re_indentf( aTHX_ ""study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p"", + depth, (long)stopparen, + (unsigned long)RExC_study_chunk_recursed_count, + (unsigned long)depth, (unsigned long)recursed_depth, + scan, + last); + if (recursed_depth) { + U32 i; + U32 j; + for ( j = 0 ; j < recursed_depth ; j++ ) { + for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) { + if ( + PAREN_TEST(RExC_study_chunk_recursed + + ( j * RExC_study_chunk_recursed_bytes), i ) + && ( + !j || + !PAREN_TEST(RExC_study_chunk_recursed + + (( j - 1 ) * RExC_study_chunk_recursed_bytes), i) + ) + ) { + Perl_re_printf( aTHX_ "" %d"",(int)i); + break; + } + } + if ( j + 1 < recursed_depth ) { + Perl_re_printf( aTHX_ "",""); + } + } + } + Perl_re_printf( aTHX_ ""\n""); + } + ); + while ( scan && OP(scan) != END && scan < last ){ + UV min_subtract = 0; /* How mmany chars to subtract from the minimum + node length to get a real minimum (because + the folded version may be shorter) */ + bool unfolded_multi_char = FALSE; + /* Peephole optimizer: */ + DEBUG_STUDYDATA(""Peep"", data, depth, is_inf); + DEBUG_PEEP(""Peep"", scan, depth, flags); + + + /* The reason we do this here is that we need to deal with things like + * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT + * parsing code, as each (?:..) is handled by a different invocation of + * reg() -- Yves + */ + JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0); + + /* Follow the next-chain of the current node and optimize + away all the NOTHINGs from it. */ + if (OP(scan) != CURLYX) { + const int max = (reg_off_by_arg[OP(scan)] + ? I32_MAX + /* I32 may be smaller than U16 on CRAYs! */ + : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX)); + int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan)); + int noff; + regnode *n = scan; + + /* Skip NOTHING and LONGJMP. */ + while ((n = regnext(n)) + && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n))) + || ((OP(n) == LONGJMP) && (noff = ARG(n)))) + && off + noff < max) + off += noff; + if (reg_off_by_arg[OP(scan)]) + ARG(scan) = off; + else + NEXT_OFF(scan) = off; + } + + /* The principal pseudo-switch. Cannot be a switch, since we + look into several different things. */ + if ( OP(scan) == DEFINEP ) { + SSize_t minlen = 0; + SSize_t deltanext = 0; + SSize_t fake_last_close = 0; + I32 f = SCF_IN_DEFINE; + + StructCopy(&zero_scan_data, &data_fake, scan_data_t); + scan = regnext(scan); + assert( OP(scan) == IFTHEN ); + DEBUG_PEEP(""expect IFTHEN"", scan, depth, flags); + + data_fake.last_closep= &fake_last_close; + minlen = *minlenp; + next = regnext(scan); + scan = NEXTOPER(NEXTOPER(scan)); + DEBUG_PEEP(""scan"", scan, depth, flags); + DEBUG_PEEP(""next"", next, depth, flags); + + /* we suppose the run is continuous, last=next... + * NOTE we dont use the return here! */ + /* DEFINEP study_chunk() recursion */ + (void)study_chunk(pRExC_state, &scan, &minlen, + &deltanext, next, &data_fake, stopparen, + recursed_depth, NULL, f, depth+1); + + scan = next; + } else + if ( + OP(scan) == BRANCH || + OP(scan) == BRANCHJ || + OP(scan) == IFTHEN + ) { + next = regnext(scan); + code = OP(scan); + + /* The op(next)==code check below is to see if we + * have ""BRANCH-BRANCH"", ""BRANCHJ-BRANCHJ"", ""IFTHEN-IFTHEN"" + * IFTHEN is special as it might not appear in pairs. + * Not sure whether BRANCH-BRANCHJ is possible, regardless + * we dont handle it cleanly. */ + if (OP(next) == code || code == IFTHEN) { + /* NOTE - There is similar code to this block below for + * handling TRIE nodes on a re-study. If you change stuff here + * check there too. */ + SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0; + regnode_ssc accum; + regnode * const startbranch=scan; + + if (flags & SCF_DO_SUBSTR) { + /* Cannot merge strings after this. */ + scan_commit(pRExC_state, data, minlenp, is_inf); + } + + if (flags & SCF_DO_STCLASS) + ssc_init_zero(pRExC_state, &accum); + + while (OP(scan) == code) { + SSize_t deltanext, minnext, fake; + I32 f = 0; + regnode_ssc this_class; + + DEBUG_PEEP(""Branch"", scan, depth, flags); + + num++; + StructCopy(&zero_scan_data, &data_fake, scan_data_t); + if (data) { + data_fake.whilem_c = data->whilem_c; + data_fake.last_closep = data->last_closep; + } + else + data_fake.last_closep = &fake; + + data_fake.pos_delta = delta; + next = regnext(scan); + + scan = NEXTOPER(scan); /* everything */ + if (code != BRANCH) /* everything but BRANCH */ + scan = NEXTOPER(scan); + + if (flags & SCF_DO_STCLASS) { + ssc_init(pRExC_state, &this_class); + data_fake.start_class = &this_class; + f = SCF_DO_STCLASS_AND; + } + if (flags & SCF_WHILEM_VISITED_POS) + f |= SCF_WHILEM_VISITED_POS; + + /* we suppose the run is continuous, last=next...*/ + /* recurse study_chunk() for each BRANCH in an alternation */ + minnext = study_chunk(pRExC_state, &scan, minlenp, + &deltanext, next, &data_fake, stopparen, + recursed_depth, NULL, f, depth+1); + + if (min1 > minnext) + min1 = minnext; + if (deltanext == SSize_t_MAX) { + is_inf = is_inf_internal = 1; + max1 = SSize_t_MAX; + } else if (max1 < minnext + deltanext) + max1 = minnext + deltanext; + scan = next; + if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) + pars++; + if (data_fake.flags & SCF_SEEN_ACCEPT) { + if ( stopmin > minnext) + stopmin = min + min1; + flags &= ~SCF_DO_SUBSTR; + if (data) + data->flags |= SCF_SEEN_ACCEPT; + } + if (data) { + if (data_fake.flags & SF_HAS_EVAL) + data->flags |= SF_HAS_EVAL; + data->whilem_c = data_fake.whilem_c; + } + if (flags & SCF_DO_STCLASS) + ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class); + } + if (code == IFTHEN && num < 2) /* Empty ELSE branch */ + min1 = 0; + if (flags & SCF_DO_SUBSTR) { + data->pos_min += min1; + if (data->pos_delta >= SSize_t_MAX - (max1 - min1)) + data->pos_delta = SSize_t_MAX; + else + data->pos_delta += max1 - min1; + if (max1 != min1 || is_inf) + data->cur_is_floating = 1; + } + min += min1; + if (delta == SSize_t_MAX + || SSize_t_MAX - delta - (max1 - min1) < 0) + delta = SSize_t_MAX; + else + delta += max1 - min1; + if (flags & SCF_DO_STCLASS_OR) { + ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum); + if (min1) { + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + flags &= ~SCF_DO_STCLASS; + } + } + else if (flags & SCF_DO_STCLASS_AND) { + if (min1) { + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum); + flags &= ~SCF_DO_STCLASS; + } + else { + /* Switch to OR mode: cache the old value of + * data->start_class */ + INIT_AND_WITHP; + StructCopy(data->start_class, and_withp, regnode_ssc); + flags &= ~SCF_DO_STCLASS_AND; + StructCopy(&accum, data->start_class, regnode_ssc); + flags |= SCF_DO_STCLASS_OR; + } + } + + if (PERL_ENABLE_TRIE_OPTIMISATION && + OP( startbranch ) == BRANCH ) + { + /* demq. + + Assuming this was/is a branch we are dealing with: 'scan' + now points at the item that follows the branch sequence, + whatever it is. We now start at the beginning of the + sequence and look for subsequences of + + BRANCH->EXACT=>x1 + BRANCH->EXACT=>x2 + tail + + which would be constructed from a pattern like + /A|LIST|OF|WORDS/ + + If we can find such a subsequence we need to turn the first + element into a trie and then add the subsequent branch exact + strings to the trie. + + We have two cases + + 1. patterns where the whole set of branches can be + converted. + + 2. patterns where only a subset can be converted. + + In case 1 we can replace the whole set with a single regop + for the trie. In case 2 we need to keep the start and end + branches so + + 'BRANCH EXACT; BRANCH EXACT; BRANCH X' + becomes BRANCH TRIE; BRANCH X; + + There is an additional case, that being where there is a + common prefix, which gets split out into an EXACT like node + preceding the TRIE node. + + If x(1..n)==tail then we can do a simple trie, if not we make + a ""jump"" trie, such that when we match the appropriate word + we ""jump"" to the appropriate tail node. Essentially we turn + a nested if into a case structure of sorts. + + */ + + int made=0; + if (!re_trie_maxbuff) { + re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1); + if (!SvIOK(re_trie_maxbuff)) + sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT); + } + if ( SvIV(re_trie_maxbuff)>=0 ) { + regnode *cur; + regnode *first = (regnode *)NULL; + regnode *last = (regnode *)NULL; + regnode *tail = scan; + U8 trietype = 0; + U32 count=0; + + /* var tail is used because there may be a TAIL + regop in the way. Ie, the exacts will point to the + thing following the TAIL, but the last branch will + point at the TAIL. So we advance tail. If we + have nested (?:) we may have to move through several + tails. + */ + + while ( OP( tail ) == TAIL ) { + /* this is the TAIL generated by (?:) */ + tail = regnext( tail ); + } + + + DEBUG_TRIE_COMPILE_r({ + regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state); + Perl_re_indentf( aTHX_ ""%s %"" UVuf "":%s\n"", + depth+1, + ""Looking for TRIE'able sequences. Tail node is "", + (UV) REGNODE_OFFSET(tail), + SvPV_nolen_const( RExC_mysv ) + ); + }); + + /* + + Step through the branches + cur represents each branch, + noper is the first thing to be matched as part + of that branch + noper_next is the regnext() of that node. + + We normally handle a case like this + /FOO[xyz]|BAR[pqr]/ via a ""jump trie"" but we also + support building with NOJUMPTRIE, which restricts + the trie logic to structures like /FOO|BAR/. + + If noper is a trieable nodetype then the branch is + a possible optimization target. If we are building + under NOJUMPTRIE then we require that noper_next is + the same as scan (our current position in the regex + program). + + Once we have two or more consecutive such branches + we can create a trie of the EXACT's contents and + stitch it in place into the program. + + If the sequence represents all of the branches in + the alternation we replace the entire thing with a + single TRIE node. + + Otherwise when it is a subsequence we need to + stitch it in place and replace only the relevant + branches. This means the first branch has to remain + as it is used by the alternation logic, and its + next pointer, and needs to be repointed at the item + on the branch chain following the last branch we + have optimized away. + + This could be either a BRANCH, in which case the + subsequence is internal, or it could be the item + following the branch sequence in which case the + subsequence is at the end (which does not + necessarily mean the first node is the start of the + alternation). + + TRIE_TYPE(X) is a define which maps the optype to a + trietype. + + optype | trietype + ----------------+----------- + NOTHING | NOTHING + EXACT | EXACT + EXACT_ONLY8 | EXACT + EXACTFU | EXACTFU + EXACTFU_ONLY8 | EXACTFU + EXACTFUP | EXACTFU + EXACTFAA | EXACTFAA + EXACTL | EXACTL + EXACTFLU8 | EXACTFLU8 + + + */ +#define TRIE_TYPE(X) ( ( NOTHING == (X) ) \ + ? NOTHING \ + : ( EXACT == (X) || EXACT_ONLY8 == (X) ) \ + ? EXACT \ + : ( EXACTFU == (X) \ + || EXACTFU_ONLY8 == (X) \ + || EXACTFUP == (X) ) \ + ? EXACTFU \ + : ( EXACTFAA == (X) ) \ + ? EXACTFAA \ + : ( EXACTL == (X) ) \ + ? EXACTL \ + : ( EXACTFLU8 == (X) ) \ + ? EXACTFLU8 \ + : 0 ) + + /* dont use tail as the end marker for this traverse */ + for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) { + regnode * const noper = NEXTOPER( cur ); + U8 noper_type = OP( noper ); + U8 noper_trietype = TRIE_TYPE( noper_type ); +#if defined(DEBUGGING) || defined(NOJUMPTRIE) + regnode * const noper_next = regnext( noper ); + U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0; + U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0; +#endif + + DEBUG_TRIE_COMPILE_r({ + regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); + Perl_re_indentf( aTHX_ ""- %d:%s (%d)"", + depth+1, + REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) ); + + regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state); + Perl_re_printf( aTHX_ "" -> %d:%s"", + REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv)); + + if ( noper_next ) { + regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state); + Perl_re_printf( aTHX_ ""\t=> %d:%s\t"", + REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv)); + } + Perl_re_printf( aTHX_ ""(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n"", + REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur), + PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype] + ); + }); + + /* Is noper a trieable nodetype that can be merged + * with the current trie (if there is one)? */ + if ( noper_trietype + && + ( + ( noper_trietype == NOTHING ) + || ( trietype == NOTHING ) + || ( trietype == noper_trietype ) + ) +#ifdef NOJUMPTRIE + && noper_next >= tail +#endif + && count < U16_MAX) + { + /* Handle mergable triable node Either we are + * the first node in a new trieable sequence, + * in which case we do some bookkeeping, + * otherwise we update the end pointer. */ + if ( !first ) { + first = cur; + if ( noper_trietype == NOTHING ) { +#if !defined(DEBUGGING) && !defined(NOJUMPTRIE) + regnode * const noper_next = regnext( noper ); + U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0; + U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0; +#endif + + if ( noper_next_trietype ) { + trietype = noper_next_trietype; + } else if (noper_next_type) { + /* a NOTHING regop is 1 regop wide. + * We need at least two for a trie + * so we can't merge this in */ + first = NULL; + } + } else { + trietype = noper_trietype; + } + } else { + if ( trietype == NOTHING ) + trietype = noper_trietype; + last = cur; + } + if (first) + count++; + } /* end handle mergable triable node */ + else { + /* handle unmergable node - + * noper may either be a triable node which can + * not be tried together with the current trie, + * or a non triable node */ + if ( last ) { + /* If last is set and trietype is not + * NOTHING then we have found at least two + * triable branch sequences in a row of a + * similar trietype so we can turn them + * into a trie. If/when we allow NOTHING to + * start a trie sequence this condition + * will be required, and it isn't expensive + * so we leave it in for now. */ + if ( trietype && trietype != NOTHING ) + make_trie( pRExC_state, + startbranch, first, cur, tail, + count, trietype, depth+1 ); + last = NULL; /* note: we clear/update + first, trietype etc below, + so we dont do it here */ + } + if ( noper_trietype +#ifdef NOJUMPTRIE + && noper_next >= tail +#endif + ){ + /* noper is triable, so we can start a new + * trie sequence */ + count = 1; + first = cur; + trietype = noper_trietype; + } else if (first) { + /* if we already saw a first but the + * current node is not triable then we have + * to reset the first information. */ + count = 0; + first = NULL; + trietype = 0; + } + } /* end handle unmergable node */ + } /* loop over branches */ + DEBUG_TRIE_COMPILE_r({ + regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); + Perl_re_indentf( aTHX_ ""- %s (%d) "", + depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur)); + Perl_re_printf( aTHX_ ""(First==%d, Last==%d, Cur==%d, tt==%s)\n"", + REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur), + PL_reg_name[trietype] + ); + + }); + if ( last && trietype ) { + if ( trietype != NOTHING ) { + /* the last branch of the sequence was part of + * a trie, so we have to construct it here + * outside of the loop */ + made= make_trie( pRExC_state, startbranch, + first, scan, tail, count, + trietype, depth+1 ); +#ifdef TRIE_STUDY_OPT + if ( ((made == MADE_EXACT_TRIE && + startbranch == first) + || ( first_non_open == first )) && + depth==0 ) { + flags |= SCF_TRIE_RESTUDY; + if ( startbranch == first + && scan >= tail ) + { + RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN; + } + } +#endif + } else { + /* at this point we know whatever we have is a + * NOTHING sequence/branch AND if 'startbranch' + * is 'first' then we can turn the whole thing + * into a NOTHING + */ + if ( startbranch == first ) { + regnode *opt; + /* the entire thing is a NOTHING sequence, + * something like this: (?:|) So we can + * turn it into a plain NOTHING op. */ + DEBUG_TRIE_COMPILE_r({ + regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); + Perl_re_indentf( aTHX_ ""- %s (%d) \n"", + depth+1, + SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur)); + + }); + OP(startbranch)= NOTHING; + NEXT_OFF(startbranch)= tail - startbranch; + for ( opt= startbranch + 1; opt < tail ; opt++ ) + OP(opt)= OPTIMIZED; + } + } + } /* end if ( last) */ + } /* TRIE_MAXBUF is non zero */ + + } /* do trie */ + + } + else if ( code == BRANCHJ ) { /* single branch is optimized. */ + scan = NEXTOPER(NEXTOPER(scan)); + } else /* single branch is optimized. */ + scan = NEXTOPER(scan); + continue; + } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) { + I32 paren = 0; + regnode *start = NULL; + regnode *end = NULL; + U32 my_recursed_depth= recursed_depth; + + if (OP(scan) != SUSPEND) { /* GOSUB */ + /* Do setup, note this code has side effects beyond + * the rest of this block. Specifically setting + * RExC_recurse[] must happen at least once during + * study_chunk(). */ + paren = ARG(scan); + RExC_recurse[ARG2L(scan)] = scan; + start = REGNODE_p(RExC_open_parens[paren]); + end = REGNODE_p(RExC_close_parens[paren]); + + /* NOTE we MUST always execute the above code, even + * if we do nothing with a GOSUB */ + if ( + ( flags & SCF_IN_DEFINE ) + || + ( + (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF)) + && + ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 ) + ) + ) { + /* no need to do anything here if we are in a define. */ + /* or we are after some kind of infinite construct + * so we can skip recursing into this item. + * Since it is infinite we will not change the maxlen + * or delta, and if we miss something that might raise + * the minlen it will merely pessimise a little. + * + * Iow /(?(DEFINE)(?foo|food))a+(?&foo)/ + * might result in a minlen of 1 and not of 4, + * but this doesn't make us mismatch, just try a bit + * harder than we should. + * */ + scan= regnext(scan); + continue; + } + + if ( + !recursed_depth + || + !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren) + ) { + /* it is quite possible that there are more efficient ways + * to do this. We maintain a bitmap per level of recursion + * of which patterns we have entered so we can detect if a + * pattern creates a possible infinite loop. When we + * recurse down a level we copy the previous levels bitmap + * down. When we are at recursion level 0 we zero the top + * level bitmap. It would be nice to implement a different + * more efficient way of doing this. In particular the top + * level bitmap may be unnecessary. + */ + if (!recursed_depth) { + Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8); + } else { + Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), + RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), + RExC_study_chunk_recursed_bytes, U8); + } + /* we havent recursed into this paren yet, so recurse into it */ + DEBUG_STUDYDATA(""gosub-set"", data, depth, is_inf); + PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren); + my_recursed_depth= recursed_depth + 1; + } else { + DEBUG_STUDYDATA(""gosub-inf"", data, depth, is_inf); + /* some form of infinite recursion, assume infinite length + * */ + if (flags & SCF_DO_SUBSTR) { + scan_commit(pRExC_state, data, minlenp, is_inf); + data->cur_is_floating = 1; + } + is_inf = is_inf_internal = 1; + if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ + ssc_anything(data->start_class); + flags &= ~SCF_DO_STCLASS; + + start= NULL; /* reset start so we dont recurse later on. */ + } + } else { + paren = stopparen; + start = scan + 2; + end = regnext(scan); + } + if (start) { + scan_frame *newframe; + assert(end); + if (!RExC_frame_last) { + Newxz(newframe, 1, scan_frame); + SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe); + RExC_frame_head= newframe; + RExC_frame_count++; + } else if (!RExC_frame_last->next_frame) { + Newxz(newframe, 1, scan_frame); + RExC_frame_last->next_frame= newframe; + newframe->prev_frame= RExC_frame_last; + RExC_frame_count++; + } else { + newframe= RExC_frame_last->next_frame; + } + RExC_frame_last= newframe; + + newframe->next_regnode = regnext(scan); + newframe->last_regnode = last; + newframe->stopparen = stopparen; + newframe->prev_recursed_depth = recursed_depth; + newframe->this_prev_frame= frame; + + DEBUG_STUDYDATA(""frame-new"", data, depth, is_inf); + DEBUG_PEEP(""fnew"", scan, depth, flags); + + frame = newframe; + scan = start; + stopparen = paren; + last = end; + depth = depth + 1; + recursed_depth= my_recursed_depth; + + continue; + } + } + else if ( OP(scan) == EXACT + || OP(scan) == EXACT_ONLY8 + || OP(scan) == EXACTL) + { + SSize_t l = STR_LEN(scan); + UV uc; + assert(l); + if (UTF) { + const U8 * const s = (U8*)STRING(scan); + uc = utf8_to_uvchr_buf(s, s + l, NULL); + l = utf8_length(s, s + l); + } else { + uc = *((U8*)STRING(scan)); + } + min += l; + if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */ + /* The code below prefers earlier match for fixed + offset, later match for variable offset. */ + if (data->last_end == -1) { /* Update the start info. */ + data->last_start_min = data->pos_min; + data->last_start_max = is_inf + ? SSize_t_MAX : data->pos_min + data->pos_delta; + } + sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan)); + if (UTF) + SvUTF8_on(data->last_found); + { + SV * const sv = data->last_found; + MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? + mg_find(sv, PERL_MAGIC_utf8) : NULL; + if (mg && mg->mg_len >= 0) + mg->mg_len += utf8_length((U8*)STRING(scan), + (U8*)STRING(scan)+STR_LEN(scan)); + } + data->last_end = data->pos_min + l; + data->pos_min += l; /* As in the first entry. */ + data->flags &= ~SF_BEFORE_EOL; + } + + /* ANDing the code point leaves at most it, and not in locale, and + * can't match null string */ + if (flags & SCF_DO_STCLASS_AND) { + ssc_cp_and(data->start_class, uc); + ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; + ssc_clear_locale(data->start_class); + } + else if (flags & SCF_DO_STCLASS_OR) { + ssc_add_cp(data->start_class, uc); + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + + /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ + ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; + } + flags &= ~SCF_DO_STCLASS; + } + else if (PL_regkind[OP(scan)] == EXACT) { + /* But OP != EXACT!, so is EXACTFish */ + SSize_t l = STR_LEN(scan); + const U8 * s = (U8*)STRING(scan); + + /* Search for fixed substrings supports EXACT only. */ + if (flags & SCF_DO_SUBSTR) { + assert(data); + scan_commit(pRExC_state, data, minlenp, is_inf); + } + if (UTF) { + l = utf8_length(s, s + l); + } + if (unfolded_multi_char) { + RExC_seen |= REG_UNFOLDED_MULTI_SEEN; + } + min += l - min_subtract; + assert (min >= 0); + delta += min_subtract; + if (flags & SCF_DO_SUBSTR) { + data->pos_min += l - min_subtract; + if (data->pos_min < 0) { + data->pos_min = 0; + } + data->pos_delta += min_subtract; + if (min_subtract) { + data->cur_is_floating = 1; /* float */ + } + } + + if (flags & SCF_DO_STCLASS) { + SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan); + + assert(EXACTF_invlist); + if (flags & SCF_DO_STCLASS_AND) { + if (OP(scan) != EXACTFL) + ssc_clear_locale(data->start_class); + ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; + ANYOF_POSIXL_ZERO(data->start_class); + ssc_intersection(data->start_class, EXACTF_invlist, FALSE); + } + else { /* SCF_DO_STCLASS_OR */ + ssc_union(data->start_class, EXACTF_invlist, FALSE); + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + + /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ + ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; + } + flags &= ~SCF_DO_STCLASS; + SvREFCNT_dec(EXACTF_invlist); + } + } + else if (REGNODE_VARIES(OP(scan))) { + SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0; + I32 fl = 0, f = flags; + regnode * const oscan = scan; + regnode_ssc this_class; + regnode_ssc *oclass = NULL; + I32 next_is_eval = 0; + + switch (PL_regkind[OP(scan)]) { + case WHILEM: /* End of (?:...)* . */ + scan = NEXTOPER(scan); + goto finish; + case PLUS: + if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) { + next = NEXTOPER(scan); + if ( OP(next) == EXACT + || OP(next) == EXACT_ONLY8 + || OP(next) == EXACTL + || (flags & SCF_DO_STCLASS)) + { + mincount = 1; + maxcount = REG_INFTY; + next = regnext(scan); + scan = NEXTOPER(scan); + goto do_curly; + } + } + if (flags & SCF_DO_SUBSTR) + data->pos_min++; + min++; + /* FALLTHROUGH */ + case STAR: + next = NEXTOPER(scan); + + /* This temporary node can now be turned into EXACTFU, and + * must, as regexec.c doesn't handle it */ + if (OP(next) == EXACTFU_S_EDGE) { + OP(next) = EXACTFU; + } + + if ( STR_LEN(next) == 1 + && isALPHA_A(* STRING(next)) + && ( OP(next) == EXACTFAA + || ( OP(next) == EXACTFU + && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next))))) + { + /* These differ in just one bit */ + U8 mask = ~ ('A' ^ 'a'); + + assert(isALPHA_A(* STRING(next))); + + /* Then replace it by an ANYOFM node, with + * the mask set to the complement of the + * bit that differs between upper and lower + * case, and the lowest code point of the + * pair (which the '&' forces) */ + OP(next) = ANYOFM; + ARG_SET(next, *STRING(next) & mask); + FLAGS(next) = mask; + } + + if (flags & SCF_DO_STCLASS) { + mincount = 0; + maxcount = REG_INFTY; + next = regnext(scan); + scan = NEXTOPER(scan); + goto do_curly; + } + if (flags & SCF_DO_SUBSTR) { + scan_commit(pRExC_state, data, minlenp, is_inf); + /* Cannot extend fixed substrings */ + data->cur_is_floating = 1; /* float */ + } + is_inf = is_inf_internal = 1; + scan = regnext(scan); + goto optimize_curly_tail; + case CURLY: + if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM) + && (scan->flags == stopparen)) + { + mincount = 1; + maxcount = 1; + } else { + mincount = ARG1(scan); + maxcount = ARG2(scan); + } + next = regnext(scan); + if (OP(scan) == CURLYX) { + I32 lp = (data ? *(data->last_closep) : 0); + scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX); + } + scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS; + next_is_eval = (OP(scan) == EVAL); + do_curly: + if (flags & SCF_DO_SUBSTR) { + if (mincount == 0) + scan_commit(pRExC_state, data, minlenp, is_inf); + /* Cannot extend fixed substrings */ + pos_before = data->pos_min; + } + if (data) { + fl = data->flags; + data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL); + if (is_inf) + data->flags |= SF_IS_INF; + } + if (flags & SCF_DO_STCLASS) { + ssc_init(pRExC_state, &this_class); + oclass = data->start_class; + data->start_class = &this_class; + f |= SCF_DO_STCLASS_AND; + f &= ~SCF_DO_STCLASS_OR; + } + /* Exclude from super-linear cache processing any {n,m} + regops for which the combination of input pos and regex + pos is not enough information to determine if a match + will be possible. + + For example, in the regex /foo(bar\s*){4,8}baz/ with the + regex pos at the \s*, the prospects for a match depend not + only on the input position but also on how many (bar\s*) + repeats into the {4,8} we are. */ + if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY)) + f &= ~SCF_WHILEM_VISITED_POS; + + /* This will finish on WHILEM, setting scan, or on NULL: */ + /* recurse study_chunk() on loop bodies */ + minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, + last, data, stopparen, recursed_depth, NULL, + (mincount == 0 + ? (f & ~SCF_DO_SUBSTR) + : f) + ,depth+1); + + if (flags & SCF_DO_STCLASS) + data->start_class = oclass; + if (mincount == 0 || minnext == 0) { + if (flags & SCF_DO_STCLASS_OR) { + ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class); + } + else if (flags & SCF_DO_STCLASS_AND) { + /* Switch to OR mode: cache the old value of + * data->start_class */ + INIT_AND_WITHP; + StructCopy(data->start_class, and_withp, regnode_ssc); + flags &= ~SCF_DO_STCLASS_AND; + StructCopy(&this_class, data->start_class, regnode_ssc); + flags |= SCF_DO_STCLASS_OR; + ANYOF_FLAGS(data->start_class) + |= SSC_MATCHES_EMPTY_STRING; + } + } else { /* Non-zero len */ + if (flags & SCF_DO_STCLASS_OR) { + ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class); + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + } + else if (flags & SCF_DO_STCLASS_AND) + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class); + flags &= ~SCF_DO_STCLASS; + } + if (!scan) /* It was not CURLYX, but CURLY. */ + scan = next; + if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR) + /* ? quantifier ok, except for (?{ ... }) */ + && (next_is_eval || !(mincount == 0 && maxcount == 1)) + && (minnext == 0) && (deltanext == 0) + && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR)) + && maxcount <= REG_INFTY/3) /* Complement check for big + count */ + { + _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP), + Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), + ""Quantifier unexpected on zero-length expression "" + ""in regex m/%"" UTF8f ""/"", + UTF8fARG(UTF, RExC_precomp_end - RExC_precomp, + RExC_precomp))); + } + + min += minnext * mincount; + is_inf_internal |= deltanext == SSize_t_MAX + || (maxcount == REG_INFTY && minnext + deltanext > 0); + is_inf |= is_inf_internal; + if (is_inf) { + delta = SSize_t_MAX; + } else { + delta += (minnext + deltanext) * maxcount + - minnext * mincount; + } + /* Try powerful optimization CURLYX => CURLYN. */ + if ( OP(oscan) == CURLYX && data + && data->flags & SF_IN_PAR + && !(data->flags & SF_HAS_EVAL) + && !deltanext && minnext == 1 ) { + /* Try to optimize to CURLYN. */ + regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; + regnode * const nxt1 = nxt; +#ifdef DEBUGGING + regnode *nxt2; +#endif + + /* Skip open. */ + nxt = regnext(nxt); + if (!REGNODE_SIMPLE(OP(nxt)) + && !(PL_regkind[OP(nxt)] == EXACT + && STR_LEN(nxt) == 1)) + goto nogo; +#ifdef DEBUGGING + nxt2 = nxt; +#endif + nxt = regnext(nxt); + if (OP(nxt) != CLOSE) + goto nogo; + if (RExC_open_parens) { + + /*open->CURLYM*/ + RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan); + + /*close->while*/ + RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2; + } + /* Now we know that nxt2 is the only contents: */ + oscan->flags = (U8)ARG(nxt); + OP(oscan) = CURLYN; + OP(nxt1) = NOTHING; /* was OPEN. */ + +#ifdef DEBUGGING + OP(nxt1 + 1) = OPTIMIZED; /* was count. */ + NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */ + NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */ + OP(nxt) = OPTIMIZED; /* was CLOSE. */ + OP(nxt + 1) = OPTIMIZED; /* was count. */ + NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */ +#endif + } + nogo: + + /* Try optimization CURLYX => CURLYM. */ + if ( OP(oscan) == CURLYX && data + && !(data->flags & SF_HAS_PAR) + && !(data->flags & SF_HAS_EVAL) + && !deltanext /* atom is fixed width */ + && minnext != 0 /* CURLYM can't handle zero width */ + + /* Nor characters whose fold at run-time may be + * multi-character */ + && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN) + ) { + /* XXXX How to optimize if data == 0? */ + /* Optimize to a simpler form. */ + regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */ + regnode *nxt2; + + OP(oscan) = CURLYM; + while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/ + && (OP(nxt2) != WHILEM)) + nxt = nxt2; + OP(nxt2) = SUCCEED; /* Whas WHILEM */ + /* Need to optimize away parenths. */ + if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) { + /* Set the parenth number. */ + regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/ + + oscan->flags = (U8)ARG(nxt); + if (RExC_open_parens) { + /*open->CURLYM*/ + RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan); + + /*close->NOTHING*/ + RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2) + + 1; + } + OP(nxt1) = OPTIMIZED; /* was OPEN. */ + OP(nxt) = OPTIMIZED; /* was CLOSE. */ + +#ifdef DEBUGGING + OP(nxt1 + 1) = OPTIMIZED; /* was count. */ + OP(nxt + 1) = OPTIMIZED; /* was count. */ + NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */ + NEXT_OFF(nxt + 1) = 0; /* just for consistency. */ +#endif +#if 0 + while ( nxt1 && (OP(nxt1) != WHILEM)) { + regnode *nnxt = regnext(nxt1); + if (nnxt == nxt) { + if (reg_off_by_arg[OP(nxt1)]) + ARG_SET(nxt1, nxt2 - nxt1); + else if (nxt2 - nxt1 < U16_MAX) + NEXT_OFF(nxt1) = nxt2 - nxt1; + else + OP(nxt) = NOTHING; /* Cannot beautify */ + } + nxt1 = nnxt; + } +#endif + /* Optimize again: */ + /* recurse study_chunk() on optimised CURLYX => CURLYM */ + study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt, + NULL, stopparen, recursed_depth, NULL, 0, + depth+1); + } + else + oscan->flags = 0; + } + else if ((OP(oscan) == CURLYX) + && (flags & SCF_WHILEM_VISITED_POS) + /* See the comment on a similar expression above. + However, this time it's not a subexpression + we care about, but the expression itself. */ + && (maxcount == REG_INFTY) + && data) { + /* This stays as CURLYX, we can put the count/of pair. */ + /* Find WHILEM (as in regexec.c) */ + regnode *nxt = oscan + NEXT_OFF(oscan); + + if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */ + nxt += ARG(nxt); + nxt = PREVOPER(nxt); + if (nxt->flags & 0xf) { + /* we've already set whilem count on this node */ + } else if (++data->whilem_c < 16) { + assert(data->whilem_c <= RExC_whilem_seen); + nxt->flags = (U8)(data->whilem_c + | (RExC_whilem_seen << 4)); /* On WHILEM */ + } + } + if (data && fl & (SF_HAS_PAR|SF_IN_PAR)) + pars++; + if (flags & SCF_DO_SUBSTR) { + SV *last_str = NULL; + STRLEN last_chrs = 0; + int counted = mincount != 0; + + if (data->last_end > 0 && mincount != 0) { /* Ends with a + string. */ + SSize_t b = pos_before >= data->last_start_min + ? pos_before : data->last_start_min; + STRLEN l; + const char * const s = SvPV_const(data->last_found, l); + SSize_t old = b - data->last_start_min; + assert(old >= 0); + + if (UTF) + old = utf8_hop_forward((U8*)s, old, + (U8 *) SvEND(data->last_found)) + - (U8*)s; + l -= old; + /* Get the added string: */ + last_str = newSVpvn_utf8(s + old, l, UTF); + last_chrs = UTF ? utf8_length((U8*)(s + old), + (U8*)(s + old + l)) : l; + if (deltanext == 0 && pos_before == b) { + /* What was added is a constant string */ + if (mincount > 1) { + + SvGROW(last_str, (mincount * l) + 1); + repeatcpy(SvPVX(last_str) + l, + SvPVX_const(last_str), l, + mincount - 1); + SvCUR_set(last_str, SvCUR(last_str) * mincount); + /* Add additional parts. */ + SvCUR_set(data->last_found, + SvCUR(data->last_found) - l); + sv_catsv(data->last_found, last_str); + { + SV * sv = data->last_found; + MAGIC *mg = + SvUTF8(sv) && SvMAGICAL(sv) ? + mg_find(sv, PERL_MAGIC_utf8) : NULL; + if (mg && mg->mg_len >= 0) + mg->mg_len += last_chrs * (mincount-1); + } + last_chrs *= mincount; + data->last_end += l * (mincount - 1); + } + } else { + /* start offset must point into the last copy */ + data->last_start_min += minnext * (mincount - 1); + data->last_start_max = + is_inf + ? SSize_t_MAX + : data->last_start_max + + (maxcount - 1) * (minnext + data->pos_delta); + } + } + /* It is counted once already... */ + data->pos_min += minnext * (mincount - counted); +#if 0 +Perl_re_printf( aTHX_ ""counted=%"" UVuf "" deltanext=%"" UVuf + "" SSize_t_MAX=%"" UVuf "" minnext=%"" UVuf + "" maxcount=%"" UVuf "" mincount=%"" UVuf ""\n"", + (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount, + (UV)mincount); +if (deltanext != SSize_t_MAX) +Perl_re_printf( aTHX_ ""LHS=%"" UVuf "" RHS=%"" UVuf ""\n"", + (UV)(-counted * deltanext + (minnext + deltanext) * maxcount + - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta)); +#endif + if (deltanext == SSize_t_MAX + || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta) + data->pos_delta = SSize_t_MAX; + else + data->pos_delta += - counted * deltanext + + (minnext + deltanext) * maxcount - minnext * mincount; + if (mincount != maxcount) { + /* Cannot extend fixed substrings found inside + the group. */ + scan_commit(pRExC_state, data, minlenp, is_inf); + if (mincount && last_str) { + SV * const sv = data->last_found; + MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? + mg_find(sv, PERL_MAGIC_utf8) : NULL; + + if (mg) + mg->mg_len = -1; + sv_setsv(sv, last_str); + data->last_end = data->pos_min; + data->last_start_min = data->pos_min - last_chrs; + data->last_start_max = is_inf + ? SSize_t_MAX + : data->pos_min + data->pos_delta - last_chrs; + } + data->cur_is_floating = 1; /* float */ + } + SvREFCNT_dec(last_str); + } + if (data && (fl & SF_HAS_EVAL)) + data->flags |= SF_HAS_EVAL; + optimize_curly_tail: + if (OP(oscan) != CURLYX) { + while (PL_regkind[OP(next = regnext(oscan))] == NOTHING + && NEXT_OFF(next)) + NEXT_OFF(oscan) += NEXT_OFF(next); + } + continue; + + default: +#ifdef DEBUGGING + Perl_croak(aTHX_ ""panic: unexpected varying REx opcode %d"", + OP(scan)); +#endif + case REF: + case CLUMP: + if (flags & SCF_DO_SUBSTR) { + /* Cannot expect anything... */ + scan_commit(pRExC_state, data, minlenp, is_inf); + data->cur_is_floating = 1; /* float */ + } + is_inf = is_inf_internal = 1; + if (flags & SCF_DO_STCLASS_OR) { + if (OP(scan) == CLUMP) { + /* Actually is any start char, but very few code points + * aren't start characters */ + ssc_match_all_cp(data->start_class); + } + else { + ssc_anything(data->start_class); + } + } + flags &= ~SCF_DO_STCLASS; + break; + } + } + else if (OP(scan) == LNBREAK) { + if (flags & SCF_DO_STCLASS) { + if (flags & SCF_DO_STCLASS_AND) { + ssc_intersection(data->start_class, + PL_XPosix_ptrs[_CC_VERTSPACE], FALSE); + ssc_clear_locale(data->start_class); + ANYOF_FLAGS(data->start_class) + &= ~SSC_MATCHES_EMPTY_STRING; + } + else if (flags & SCF_DO_STCLASS_OR) { + ssc_union(data->start_class, + PL_XPosix_ptrs[_CC_VERTSPACE], + FALSE); + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + + /* See commit msg for + * 749e076fceedeb708a624933726e7989f2302f6a */ + ANYOF_FLAGS(data->start_class) + &= ~SSC_MATCHES_EMPTY_STRING; + } + flags &= ~SCF_DO_STCLASS; + } + min++; + if (delta != SSize_t_MAX) + delta++; /* Because of the 2 char string cr-lf */ + if (flags & SCF_DO_SUBSTR) { + /* Cannot expect anything... */ + scan_commit(pRExC_state, data, minlenp, is_inf); + data->pos_min += 1; + if (data->pos_delta != SSize_t_MAX) { + data->pos_delta += 1; + } + data->cur_is_floating = 1; /* float */ + } + } + else if (REGNODE_SIMPLE(OP(scan))) { + + if (flags & SCF_DO_SUBSTR) { + scan_commit(pRExC_state, data, minlenp, is_inf); + data->pos_min++; + } + min++; + if (flags & SCF_DO_STCLASS) { + bool invert = 0; + SV* my_invlist = NULL; + U8 namedclass; + + /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ + ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; + + /* Some of the logic below assumes that switching + locale on will only add false positives. */ + switch (OP(scan)) { + + default: +#ifdef DEBUGGING + Perl_croak(aTHX_ ""panic: unexpected simple REx opcode %d"", + OP(scan)); +#endif + case SANY: + if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ + ssc_match_all_cp(data->start_class); + break; + + case REG_ANY: + { + SV* REG_ANY_invlist = _new_invlist(2); + REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist, + '\n'); + if (flags & SCF_DO_STCLASS_OR) { + ssc_union(data->start_class, + REG_ANY_invlist, + TRUE /* TRUE => invert, hence all but \n + */ + ); + } + else if (flags & SCF_DO_STCLASS_AND) { + ssc_intersection(data->start_class, + REG_ANY_invlist, + TRUE /* TRUE => invert */ + ); + ssc_clear_locale(data->start_class); + } + SvREFCNT_dec_NN(REG_ANY_invlist); + } + break; + + case ANYOFD: + case ANYOFL: + case ANYOFPOSIXL: + case ANYOFH: + case ANYOF: + if (flags & SCF_DO_STCLASS_AND) + ssc_and(pRExC_state, data->start_class, + (regnode_charclass *) scan); + else + ssc_or(pRExC_state, data->start_class, + (regnode_charclass *) scan); + break; + + case NANYOFM: + case ANYOFM: + { + SV* cp_list = get_ANYOFM_contents(scan); + + if (flags & SCF_DO_STCLASS_OR) { + ssc_union(data->start_class, cp_list, invert); + } + else if (flags & SCF_DO_STCLASS_AND) { + ssc_intersection(data->start_class, cp_list, invert); + } + + SvREFCNT_dec_NN(cp_list); + break; + } + + case NPOSIXL: + invert = 1; + /* FALLTHROUGH */ + + case POSIXL: + namedclass = classnum_to_namedclass(FLAGS(scan)) + invert; + if (flags & SCF_DO_STCLASS_AND) { + bool was_there = cBOOL( + ANYOF_POSIXL_TEST(data->start_class, + namedclass)); + ANYOF_POSIXL_ZERO(data->start_class); + if (was_there) { /* Do an AND */ + ANYOF_POSIXL_SET(data->start_class, namedclass); + } + /* No individual code points can now match */ + data->start_class->invlist + = sv_2mortal(_new_invlist(0)); + } + else { + int complement = namedclass + ((invert) ? -1 : 1); + + assert(flags & SCF_DO_STCLASS_OR); + + /* If the complement of this class was already there, + * the result is that they match all code points, + * (\d + \D == everything). Remove the classes from + * future consideration. Locale is not relevant in + * this case */ + if (ANYOF_POSIXL_TEST(data->start_class, complement)) { + ssc_match_all_cp(data->start_class); + ANYOF_POSIXL_CLEAR(data->start_class, namedclass); + ANYOF_POSIXL_CLEAR(data->start_class, complement); + } + else { /* The usual case; just add this class to the + existing set */ + ANYOF_POSIXL_SET(data->start_class, namedclass); + } + } + break; + + case NPOSIXA: /* For these, we always know the exact set of + what's matched */ + invert = 1; + /* FALLTHROUGH */ + case POSIXA: + my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL); + goto join_posix_and_ascii; + + case NPOSIXD: + case NPOSIXU: + invert = 1; + /* FALLTHROUGH */ + case POSIXD: + case POSIXU: + my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL); + + /* NPOSIXD matches all upper Latin1 code points unless the + * target string being matched is UTF-8, which is + * unknowable until match time. Since we are going to + * invert, we want to get rid of all of them so that the + * inversion will match all */ + if (OP(scan) == NPOSIXD) { + _invlist_subtract(my_invlist, PL_UpperLatin1, + &my_invlist); + } + + join_posix_and_ascii: + + if (flags & SCF_DO_STCLASS_AND) { + ssc_intersection(data->start_class, my_invlist, invert); + ssc_clear_locale(data->start_class); + } + else { + assert(flags & SCF_DO_STCLASS_OR); + ssc_union(data->start_class, my_invlist, invert); + } + SvREFCNT_dec(my_invlist); + } + if (flags & SCF_DO_STCLASS_OR) + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + flags &= ~SCF_DO_STCLASS; + } + } + else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) { + data->flags |= (OP(scan) == MEOL + ? SF_BEFORE_MEOL + : SF_BEFORE_SEOL); + scan_commit(pRExC_state, data, minlenp, is_inf); + + } + else if ( PL_regkind[OP(scan)] == BRANCHJ + /* Lookbehind, or need to calculate parens/evals/stclass: */ + && (scan->flags || data || (flags & SCF_DO_STCLASS)) + && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) + { + if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY + || OP(scan) == UNLESSM ) + { + /* Negative Lookahead/lookbehind + In this case we can't do fixed string optimisation. + */ + + SSize_t deltanext, minnext, fake = 0; + regnode *nscan; + regnode_ssc intrnl; + int f = 0; + + StructCopy(&zero_scan_data, &data_fake, scan_data_t); + if (data) { + data_fake.whilem_c = data->whilem_c; + data_fake.last_closep = data->last_closep; + } + else + data_fake.last_closep = &fake; + data_fake.pos_delta = delta; + if ( flags & SCF_DO_STCLASS && !scan->flags + && OP(scan) == IFMATCH ) { /* Lookahead */ + ssc_init(pRExC_state, &intrnl); + data_fake.start_class = &intrnl; + f |= SCF_DO_STCLASS_AND; + } + if (flags & SCF_WHILEM_VISITED_POS) + f |= SCF_WHILEM_VISITED_POS; + next = regnext(scan); + nscan = NEXTOPER(NEXTOPER(scan)); + + /* recurse study_chunk() for lookahead body */ + minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, + last, &data_fake, stopparen, + recursed_depth, NULL, f, depth+1); + if (scan->flags) { + if ( deltanext < 0 + || deltanext > (I32) U8_MAX + || minnext > (I32)U8_MAX + || minnext + deltanext > (I32)U8_MAX) + { + FAIL2(""Lookbehind longer than %"" UVuf "" not implemented"", + (UV)U8_MAX); + } + + /* The 'next_off' field has been repurposed to count the + * additional starting positions to try beyond the initial + * one. (This leaves it at 0 for non-variable length + * matches to avoid breakage for those not using this + * extension) */ + if (deltanext) { + scan->next_off = deltanext; + ckWARNexperimental(RExC_parse, + WARN_EXPERIMENTAL__VLB, + ""Variable length lookbehind is experimental""); + } + scan->flags = (U8)minnext + deltanext; + } + if (data) { + if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) + pars++; + if (data_fake.flags & SF_HAS_EVAL) + data->flags |= SF_HAS_EVAL; + data->whilem_c = data_fake.whilem_c; + } + if (f & SCF_DO_STCLASS_AND) { + if (flags & SCF_DO_STCLASS_OR) { + /* OR before, AND after: ideally we would recurse with + * data_fake to get the AND applied by study of the + * remainder of the pattern, and then derecurse; + * *** HACK *** for now just treat as ""no information"". + * See [perl #56690]. + */ + ssc_init(pRExC_state, data->start_class); + } else { + /* AND before and after: combine and continue. These + * assertions are zero-length, so can match an EMPTY + * string */ + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl); + ANYOF_FLAGS(data->start_class) + |= SSC_MATCHES_EMPTY_STRING; + } + } + } +#if PERL_ENABLE_POSITIVE_ASSERTION_STUDY + else { + /* Positive Lookahead/lookbehind + In this case we can do fixed string optimisation, + but we must be careful about it. Note in the case of + lookbehind the positions will be offset by the minimum + length of the pattern, something we won't know about + until after the recurse. + */ + SSize_t deltanext, fake = 0; + regnode *nscan; + regnode_ssc intrnl; + int f = 0; + /* We use SAVEFREEPV so that when the full compile + is finished perl will clean up the allocated + minlens when it's all done. This way we don't + have to worry about freeing them when we know + they wont be used, which would be a pain. + */ + SSize_t *minnextp; + Newx( minnextp, 1, SSize_t ); + SAVEFREEPV(minnextp); + + if (data) { + StructCopy(data, &data_fake, scan_data_t); + if ((flags & SCF_DO_SUBSTR) && data->last_found) { + f |= SCF_DO_SUBSTR; + if (scan->flags) + scan_commit(pRExC_state, &data_fake, minlenp, is_inf); + data_fake.last_found=newSVsv(data->last_found); + } + } + else + data_fake.last_closep = &fake; + data_fake.flags = 0; + data_fake.substrs[0].flags = 0; + data_fake.substrs[1].flags = 0; + data_fake.pos_delta = delta; + if (is_inf) + data_fake.flags |= SF_IS_INF; + if ( flags & SCF_DO_STCLASS && !scan->flags + && OP(scan) == IFMATCH ) { /* Lookahead */ + ssc_init(pRExC_state, &intrnl); + data_fake.start_class = &intrnl; + f |= SCF_DO_STCLASS_AND; + } + if (flags & SCF_WHILEM_VISITED_POS) + f |= SCF_WHILEM_VISITED_POS; + next = regnext(scan); + nscan = NEXTOPER(NEXTOPER(scan)); + + /* positive lookahead study_chunk() recursion */ + *minnextp = study_chunk(pRExC_state, &nscan, minnextp, + &deltanext, last, &data_fake, + stopparen, recursed_depth, NULL, + f, depth+1); + if (scan->flags) { + assert(0); /* This code has never been tested since this + is normally not compiled */ + if ( deltanext < 0 + || deltanext > (I32) U8_MAX + || *minnextp > (I32)U8_MAX + || *minnextp + deltanext > (I32)U8_MAX) + { + FAIL2(""Lookbehind longer than %"" UVuf "" not implemented"", + (UV)U8_MAX); + } + + if (deltanext) { + scan->next_off = deltanext; + } + scan->flags = (U8)*minnextp + deltanext; + } + + *minnextp += min; + + if (f & SCF_DO_STCLASS_AND) { + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl); + ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; + } + if (data) { + if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) + pars++; + if (data_fake.flags & SF_HAS_EVAL) + data->flags |= SF_HAS_EVAL; + data->whilem_c = data_fake.whilem_c; + if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) { + int i; + if (RExC_rx->minlen<*minnextp) + RExC_rx->minlen=*minnextp; + scan_commit(pRExC_state, &data_fake, minnextp, is_inf); + SvREFCNT_dec_NN(data_fake.last_found); + + for (i = 0; i < 2; i++) { + if (data_fake.substrs[i].minlenp != minlenp) { + data->substrs[i].min_offset = + data_fake.substrs[i].min_offset; + data->substrs[i].max_offset = + data_fake.substrs[i].max_offset; + data->substrs[i].minlenp = + data_fake.substrs[i].minlenp; + data->substrs[i].lookbehind += scan->flags; + } + } + } + } + } +#endif + } + + else if (OP(scan) == OPEN) { + if (stopparen != (I32)ARG(scan)) + pars++; + } + else if (OP(scan) == CLOSE) { + if (stopparen == (I32)ARG(scan)) { + break; + } + if ((I32)ARG(scan) == is_par) { + next = regnext(scan); + + if ( next && (OP(next) != WHILEM) && next < last) + is_par = 0; /* Disable optimization */ + } + if (data) + *(data->last_closep) = ARG(scan); + } + else if (OP(scan) == EVAL) { + if (data) + data->flags |= SF_HAS_EVAL; + } + else if ( PL_regkind[OP(scan)] == ENDLIKE ) { + if (flags & SCF_DO_SUBSTR) { + scan_commit(pRExC_state, data, minlenp, is_inf); + flags &= ~SCF_DO_SUBSTR; + } + if (data && OP(scan)==ACCEPT) { + data->flags |= SCF_SEEN_ACCEPT; + if (stopmin > min) + stopmin = min; + } + } + else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */ + { + if (flags & SCF_DO_SUBSTR) { + scan_commit(pRExC_state, data, minlenp, is_inf); + data->cur_is_floating = 1; /* float */ + } + is_inf = is_inf_internal = 1; + if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ + ssc_anything(data->start_class); + flags &= ~SCF_DO_STCLASS; + } + else if (OP(scan) == GPOS) { + if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) && + !(delta || is_inf || (data && data->pos_delta))) + { + if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR)) + RExC_rx->intflags |= PREGf_ANCH_GPOS; + if (RExC_rx->gofs < (STRLEN)min) + RExC_rx->gofs = min; + } else { + RExC_rx->intflags |= PREGf_GPOS_FLOAT; + RExC_rx->gofs = 0; + } + } +#ifdef TRIE_STUDY_OPT +#ifdef FULL_TRIE_STUDY + else if (PL_regkind[OP(scan)] == TRIE) { + /* NOTE - There is similar code to this block above for handling + BRANCH nodes on the initial study. If you change stuff here + check there too. */ + regnode *trie_node= scan; + regnode *tail= regnext(scan); + reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ]; + SSize_t max1 = 0, min1 = SSize_t_MAX; + regnode_ssc accum; + + if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */ + /* Cannot merge strings after this. */ + scan_commit(pRExC_state, data, minlenp, is_inf); + } + if (flags & SCF_DO_STCLASS) + ssc_init_zero(pRExC_state, &accum); + + if (!trie->jump) { + min1= trie->minlen; + max1= trie->maxlen; + } else { + const regnode *nextbranch= NULL; + U32 word; + + for ( word=1 ; word <= trie->wordcount ; word++) + { + SSize_t deltanext=0, minnext=0, f = 0, fake; + regnode_ssc this_class; + + StructCopy(&zero_scan_data, &data_fake, scan_data_t); + if (data) { + data_fake.whilem_c = data->whilem_c; + data_fake.last_closep = data->last_closep; + } + else + data_fake.last_closep = &fake; + data_fake.pos_delta = delta; + if (flags & SCF_DO_STCLASS) { + ssc_init(pRExC_state, &this_class); + data_fake.start_class = &this_class; + f = SCF_DO_STCLASS_AND; + } + if (flags & SCF_WHILEM_VISITED_POS) + f |= SCF_WHILEM_VISITED_POS; + + if (trie->jump[word]) { + if (!nextbranch) + nextbranch = trie_node + trie->jump[0]; + scan= trie_node + trie->jump[word]; + /* We go from the jump point to the branch that follows + it. Note this means we need the vestigal unused + branches even though they arent otherwise used. */ + /* optimise study_chunk() for TRIE */ + minnext = study_chunk(pRExC_state, &scan, minlenp, + &deltanext, (regnode *)nextbranch, &data_fake, + stopparen, recursed_depth, NULL, f, depth+1); + } + if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH) + nextbranch= regnext((regnode*)nextbranch); + + if (min1 > (SSize_t)(minnext + trie->minlen)) + min1 = minnext + trie->minlen; + if (deltanext == SSize_t_MAX) { + is_inf = is_inf_internal = 1; + max1 = SSize_t_MAX; + } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen)) + max1 = minnext + deltanext + trie->maxlen; + + if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) + pars++; + if (data_fake.flags & SCF_SEEN_ACCEPT) { + if ( stopmin > min + min1) + stopmin = min + min1; + flags &= ~SCF_DO_SUBSTR; + if (data) + data->flags |= SCF_SEEN_ACCEPT; + } + if (data) { + if (data_fake.flags & SF_HAS_EVAL) + data->flags |= SF_HAS_EVAL; + data->whilem_c = data_fake.whilem_c; + } + if (flags & SCF_DO_STCLASS) + ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class); + } + } + if (flags & SCF_DO_SUBSTR) { + data->pos_min += min1; + data->pos_delta += max1 - min1; + if (max1 != min1 || is_inf) + data->cur_is_floating = 1; /* float */ + } + min += min1; + if (delta != SSize_t_MAX) { + if (SSize_t_MAX - (max1 - min1) >= delta) + delta += max1 - min1; + else + delta = SSize_t_MAX; + } + if (flags & SCF_DO_STCLASS_OR) { + ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum); + if (min1) { + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + flags &= ~SCF_DO_STCLASS; + } + } + else if (flags & SCF_DO_STCLASS_AND) { + if (min1) { + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum); + flags &= ~SCF_DO_STCLASS; + } + else { + /* Switch to OR mode: cache the old value of + * data->start_class */ + INIT_AND_WITHP; + StructCopy(data->start_class, and_withp, regnode_ssc); + flags &= ~SCF_DO_STCLASS_AND; + StructCopy(&accum, data->start_class, regnode_ssc); + flags |= SCF_DO_STCLASS_OR; + } + } + scan= tail; + continue; + } +#else + else if (PL_regkind[OP(scan)] == TRIE) { + reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ]; + U8*bang=NULL; + + min += trie->minlen; + delta += (trie->maxlen - trie->minlen); + flags &= ~SCF_DO_STCLASS; /* xxx */ + if (flags & SCF_DO_SUBSTR) { + /* Cannot expect anything... */ + scan_commit(pRExC_state, data, minlenp, is_inf); + data->pos_min += trie->minlen; + data->pos_delta += (trie->maxlen - trie->minlen); + if (trie->maxlen != trie->minlen) + data->cur_is_floating = 1; /* float */ + } + if (trie->jump) /* no more substrings -- for now /grr*/ + flags &= ~SCF_DO_SUBSTR; + } +#endif /* old or new */ +#endif /* TRIE_STUDY_OPT */ + + /* Else: zero-length, ignore. */ + scan = regnext(scan); + } + + finish: + if (frame) { + /* we need to unwind recursion. */ + depth = depth - 1; + + DEBUG_STUDYDATA(""frame-end"", data, depth, is_inf); + DEBUG_PEEP(""fend"", scan, depth, flags); + + /* restore previous context */ + last = frame->last_regnode; + scan = frame->next_regnode; + stopparen = frame->stopparen; + recursed_depth = frame->prev_recursed_depth; + + RExC_frame_last = frame->prev_frame; + frame = frame->this_prev_frame; + goto fake_study_recurse; + } + + assert(!frame); + DEBUG_STUDYDATA(""pre-fin"", data, depth, is_inf); + + *scanp = scan; + *deltap = is_inf_internal ? SSize_t_MAX : delta; + + if (flags & SCF_DO_SUBSTR && is_inf) + data->pos_delta = SSize_t_MAX - data->pos_min; + if (is_par > (I32)U8_MAX) + is_par = 0; + if (is_par && pars==1 && data) { + data->flags |= SF_IN_PAR; + data->flags &= ~SF_HAS_PAR; + } + else if (pars && data) { + data->flags |= SF_HAS_PAR; + data->flags &= ~SF_IN_PAR; + } + if (flags & SCF_DO_STCLASS_OR) + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + if (flags & SCF_TRIE_RESTUDY) + data->flags |= SCF_TRIE_RESTUDY; + + DEBUG_STUDYDATA(""post-fin"", data, depth, is_inf); + + { + SSize_t final_minlen= min < stopmin ? min : stopmin; + + if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) { + if (final_minlen > SSize_t_MAX - delta) + RExC_maxlen = SSize_t_MAX; + else if (RExC_maxlen < final_minlen + delta) + RExC_maxlen = final_minlen + delta; + } + return final_minlen; + } + NOT_REACHED; /* NOTREACHED */","STATIC SSize_t +S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp, + SSize_t *minlenp, SSize_t *deltap, + regnode *last, + scan_data_t *data, + I32 stopparen, + U32 recursed_depth, + regnode_ssc *and_withp, + U32 flags, U32 depth) + /* scanp: Start here (read-write). */ + /* deltap: Write maxlen-minlen here. */ + /* last: Stop before this one. */ + /* data: string data about the pattern */ + /* stopparen: treat close N as END */ + /* recursed: which subroutines have we recursed into */ + /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */ +{ + dVAR; + /* There must be at least this number of characters to match */ + SSize_t min = 0; + I32 pars = 0, code; + regnode *scan = *scanp, *next; + SSize_t delta = 0; + int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF); + int is_inf_internal = 0; /* The studied chunk is infinite */ + I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0; + scan_data_t data_fake; + SV *re_trie_maxbuff = NULL; + regnode *first_non_open = scan; + SSize_t stopmin = SSize_t_MAX; + scan_frame *frame = NULL; + GET_RE_DEBUG_FLAGS_DECL; + + PERL_ARGS_ASSERT_STUDY_CHUNK; + RExC_study_started= 1; + + Zero(&data_fake, 1, scan_data_t); + + if ( depth == 0 ) { + while (first_non_open && OP(first_non_open) == OPEN) + first_non_open=regnext(first_non_open); + } + + + fake_study_recurse: + DEBUG_r( + RExC_study_chunk_recursed_count++; + ); + DEBUG_OPTIMISE_MORE_r( + { + Perl_re_indentf( aTHX_ ""study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p"", + depth, (long)stopparen, + (unsigned long)RExC_study_chunk_recursed_count, + (unsigned long)depth, (unsigned long)recursed_depth, + scan, + last); + if (recursed_depth) { + U32 i; + U32 j; + for ( j = 0 ; j < recursed_depth ; j++ ) { + for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) { + if ( + PAREN_TEST(RExC_study_chunk_recursed + + ( j * RExC_study_chunk_recursed_bytes), i ) + && ( + !j || + !PAREN_TEST(RExC_study_chunk_recursed + + (( j - 1 ) * RExC_study_chunk_recursed_bytes), i) + ) + ) { + Perl_re_printf( aTHX_ "" %d"",(int)i); + break; + } + } + if ( j + 1 < recursed_depth ) { + Perl_re_printf( aTHX_ "",""); + } + } + } + Perl_re_printf( aTHX_ ""\n""); + } + ); + while ( scan && OP(scan) != END && scan < last ){ + UV min_subtract = 0; /* How mmany chars to subtract from the minimum + node length to get a real minimum (because + the folded version may be shorter) */ + bool unfolded_multi_char = FALSE; + /* Peephole optimizer: */ + DEBUG_STUDYDATA(""Peep"", data, depth, is_inf); + DEBUG_PEEP(""Peep"", scan, depth, flags); + + + /* The reason we do this here is that we need to deal with things like + * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT + * parsing code, as each (?:..) is handled by a different invocation of + * reg() -- Yves + */ + JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0); + + /* Follow the next-chain of the current node and optimize + away all the NOTHINGs from it. */ + if (OP(scan) != CURLYX) { + const int max = (reg_off_by_arg[OP(scan)] + ? I32_MAX + /* I32 may be smaller than U16 on CRAYs! */ + : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX)); + int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan)); + int noff; + regnode *n = scan; + + /* Skip NOTHING and LONGJMP. */ + while ((n = regnext(n)) + && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n))) + || ((OP(n) == LONGJMP) && (noff = ARG(n)))) + && off + noff < max) + off += noff; + if (reg_off_by_arg[OP(scan)]) + ARG(scan) = off; + else + NEXT_OFF(scan) = off; + } + + /* The principal pseudo-switch. Cannot be a switch, since we + look into several different things. */ + if ( OP(scan) == DEFINEP ) { + SSize_t minlen = 0; + SSize_t deltanext = 0; + SSize_t fake_last_close = 0; + I32 f = SCF_IN_DEFINE; + + StructCopy(&zero_scan_data, &data_fake, scan_data_t); + scan = regnext(scan); + assert( OP(scan) == IFTHEN ); + DEBUG_PEEP(""expect IFTHEN"", scan, depth, flags); + + data_fake.last_closep= &fake_last_close; + minlen = *minlenp; + next = regnext(scan); + scan = NEXTOPER(NEXTOPER(scan)); + DEBUG_PEEP(""scan"", scan, depth, flags); + DEBUG_PEEP(""next"", next, depth, flags); + + /* we suppose the run is continuous, last=next... + * NOTE we dont use the return here! */ + /* DEFINEP study_chunk() recursion */ + (void)study_chunk(pRExC_state, &scan, &minlen, + &deltanext, next, &data_fake, stopparen, + recursed_depth, NULL, f, depth+1); + + scan = next; + } else + if ( + OP(scan) == BRANCH || + OP(scan) == BRANCHJ || + OP(scan) == IFTHEN + ) { + next = regnext(scan); + code = OP(scan); + + /* The op(next)==code check below is to see if we + * have ""BRANCH-BRANCH"", ""BRANCHJ-BRANCHJ"", ""IFTHEN-IFTHEN"" + * IFTHEN is special as it might not appear in pairs. + * Not sure whether BRANCH-BRANCHJ is possible, regardless + * we dont handle it cleanly. */ + if (OP(next) == code || code == IFTHEN) { + /* NOTE - There is similar code to this block below for + * handling TRIE nodes on a re-study. If you change stuff here + * check there too. */ + SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0; + regnode_ssc accum; + regnode * const startbranch=scan; + + if (flags & SCF_DO_SUBSTR) { + /* Cannot merge strings after this. */ + scan_commit(pRExC_state, data, minlenp, is_inf); + } + + if (flags & SCF_DO_STCLASS) + ssc_init_zero(pRExC_state, &accum); + + while (OP(scan) == code) { + SSize_t deltanext, minnext, fake; + I32 f = 0; + regnode_ssc this_class; + + DEBUG_PEEP(""Branch"", scan, depth, flags); + + num++; + StructCopy(&zero_scan_data, &data_fake, scan_data_t); + if (data) { + data_fake.whilem_c = data->whilem_c; + data_fake.last_closep = data->last_closep; + } + else + data_fake.last_closep = &fake; + + data_fake.pos_delta = delta; + next = regnext(scan); + + scan = NEXTOPER(scan); /* everything */ + if (code != BRANCH) /* everything but BRANCH */ + scan = NEXTOPER(scan); + + if (flags & SCF_DO_STCLASS) { + ssc_init(pRExC_state, &this_class); + data_fake.start_class = &this_class; + f = SCF_DO_STCLASS_AND; + } + if (flags & SCF_WHILEM_VISITED_POS) + f |= SCF_WHILEM_VISITED_POS; + + /* we suppose the run is continuous, last=next...*/ + /* recurse study_chunk() for each BRANCH in an alternation */ + minnext = study_chunk(pRExC_state, &scan, minlenp, + &deltanext, next, &data_fake, stopparen, + recursed_depth, NULL, f, depth+1); + + if (min1 > minnext) + min1 = minnext; + if (deltanext == SSize_t_MAX) { + is_inf = is_inf_internal = 1; + max1 = SSize_t_MAX; + } else if (max1 < minnext + deltanext) + max1 = minnext + deltanext; + scan = next; + if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) + pars++; + if (data_fake.flags & SCF_SEEN_ACCEPT) { + if ( stopmin > minnext) + stopmin = min + min1; + flags &= ~SCF_DO_SUBSTR; + if (data) + data->flags |= SCF_SEEN_ACCEPT; + } + if (data) { + if (data_fake.flags & SF_HAS_EVAL) + data->flags |= SF_HAS_EVAL; + data->whilem_c = data_fake.whilem_c; + } + if (flags & SCF_DO_STCLASS) + ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class); + } + if (code == IFTHEN && num < 2) /* Empty ELSE branch */ + min1 = 0; + if (flags & SCF_DO_SUBSTR) { + data->pos_min += min1; + if (data->pos_delta >= SSize_t_MAX - (max1 - min1)) + data->pos_delta = SSize_t_MAX; + else + data->pos_delta += max1 - min1; + if (max1 != min1 || is_inf) + data->cur_is_floating = 1; + } + min += min1; + if (delta == SSize_t_MAX + || SSize_t_MAX - delta - (max1 - min1) < 0) + delta = SSize_t_MAX; + else + delta += max1 - min1; + if (flags & SCF_DO_STCLASS_OR) { + ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum); + if (min1) { + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + flags &= ~SCF_DO_STCLASS; + } + } + else if (flags & SCF_DO_STCLASS_AND) { + if (min1) { + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum); + flags &= ~SCF_DO_STCLASS; + } + else { + /* Switch to OR mode: cache the old value of + * data->start_class */ + INIT_AND_WITHP; + StructCopy(data->start_class, and_withp, regnode_ssc); + flags &= ~SCF_DO_STCLASS_AND; + StructCopy(&accum, data->start_class, regnode_ssc); + flags |= SCF_DO_STCLASS_OR; + } + } + + if (PERL_ENABLE_TRIE_OPTIMISATION && + OP( startbranch ) == BRANCH ) + { + /* demq. + + Assuming this was/is a branch we are dealing with: 'scan' + now points at the item that follows the branch sequence, + whatever it is. We now start at the beginning of the + sequence and look for subsequences of + + BRANCH->EXACT=>x1 + BRANCH->EXACT=>x2 + tail + + which would be constructed from a pattern like + /A|LIST|OF|WORDS/ + + If we can find such a subsequence we need to turn the first + element into a trie and then add the subsequent branch exact + strings to the trie. + + We have two cases + + 1. patterns where the whole set of branches can be + converted. + + 2. patterns where only a subset can be converted. + + In case 1 we can replace the whole set with a single regop + for the trie. In case 2 we need to keep the start and end + branches so + + 'BRANCH EXACT; BRANCH EXACT; BRANCH X' + becomes BRANCH TRIE; BRANCH X; + + There is an additional case, that being where there is a + common prefix, which gets split out into an EXACT like node + preceding the TRIE node. + + If x(1..n)==tail then we can do a simple trie, if not we make + a ""jump"" trie, such that when we match the appropriate word + we ""jump"" to the appropriate tail node. Essentially we turn + a nested if into a case structure of sorts. + + */ + + int made=0; + if (!re_trie_maxbuff) { + re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1); + if (!SvIOK(re_trie_maxbuff)) + sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT); + } + if ( SvIV(re_trie_maxbuff)>=0 ) { + regnode *cur; + regnode *first = (regnode *)NULL; + regnode *last = (regnode *)NULL; + regnode *tail = scan; + U8 trietype = 0; + U32 count=0; + + /* var tail is used because there may be a TAIL + regop in the way. Ie, the exacts will point to the + thing following the TAIL, but the last branch will + point at the TAIL. So we advance tail. If we + have nested (?:) we may have to move through several + tails. + */ + + while ( OP( tail ) == TAIL ) { + /* this is the TAIL generated by (?:) */ + tail = regnext( tail ); + } + + + DEBUG_TRIE_COMPILE_r({ + regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state); + Perl_re_indentf( aTHX_ ""%s %"" UVuf "":%s\n"", + depth+1, + ""Looking for TRIE'able sequences. Tail node is "", + (UV) REGNODE_OFFSET(tail), + SvPV_nolen_const( RExC_mysv ) + ); + }); + + /* + + Step through the branches + cur represents each branch, + noper is the first thing to be matched as part + of that branch + noper_next is the regnext() of that node. + + We normally handle a case like this + /FOO[xyz]|BAR[pqr]/ via a ""jump trie"" but we also + support building with NOJUMPTRIE, which restricts + the trie logic to structures like /FOO|BAR/. + + If noper is a trieable nodetype then the branch is + a possible optimization target. If we are building + under NOJUMPTRIE then we require that noper_next is + the same as scan (our current position in the regex + program). + + Once we have two or more consecutive such branches + we can create a trie of the EXACT's contents and + stitch it in place into the program. + + If the sequence represents all of the branches in + the alternation we replace the entire thing with a + single TRIE node. + + Otherwise when it is a subsequence we need to + stitch it in place and replace only the relevant + branches. This means the first branch has to remain + as it is used by the alternation logic, and its + next pointer, and needs to be repointed at the item + on the branch chain following the last branch we + have optimized away. + + This could be either a BRANCH, in which case the + subsequence is internal, or it could be the item + following the branch sequence in which case the + subsequence is at the end (which does not + necessarily mean the first node is the start of the + alternation). + + TRIE_TYPE(X) is a define which maps the optype to a + trietype. + + optype | trietype + ----------------+----------- + NOTHING | NOTHING + EXACT | EXACT + EXACT_ONLY8 | EXACT + EXACTFU | EXACTFU + EXACTFU_ONLY8 | EXACTFU + EXACTFUP | EXACTFU + EXACTFAA | EXACTFAA + EXACTL | EXACTL + EXACTFLU8 | EXACTFLU8 + + + */ +#define TRIE_TYPE(X) ( ( NOTHING == (X) ) \ + ? NOTHING \ + : ( EXACT == (X) || EXACT_ONLY8 == (X) ) \ + ? EXACT \ + : ( EXACTFU == (X) \ + || EXACTFU_ONLY8 == (X) \ + || EXACTFUP == (X) ) \ + ? EXACTFU \ + : ( EXACTFAA == (X) ) \ + ? EXACTFAA \ + : ( EXACTL == (X) ) \ + ? EXACTL \ + : ( EXACTFLU8 == (X) ) \ + ? EXACTFLU8 \ + : 0 ) + + /* dont use tail as the end marker for this traverse */ + for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) { + regnode * const noper = NEXTOPER( cur ); + U8 noper_type = OP( noper ); + U8 noper_trietype = TRIE_TYPE( noper_type ); +#if defined(DEBUGGING) || defined(NOJUMPTRIE) + regnode * const noper_next = regnext( noper ); + U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0; + U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0; +#endif + + DEBUG_TRIE_COMPILE_r({ + regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); + Perl_re_indentf( aTHX_ ""- %d:%s (%d)"", + depth+1, + REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) ); + + regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state); + Perl_re_printf( aTHX_ "" -> %d:%s"", + REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv)); + + if ( noper_next ) { + regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state); + Perl_re_printf( aTHX_ ""\t=> %d:%s\t"", + REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv)); + } + Perl_re_printf( aTHX_ ""(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n"", + REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur), + PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype] + ); + }); + + /* Is noper a trieable nodetype that can be merged + * with the current trie (if there is one)? */ + if ( noper_trietype + && + ( + ( noper_trietype == NOTHING ) + || ( trietype == NOTHING ) + || ( trietype == noper_trietype ) + ) +#ifdef NOJUMPTRIE + && noper_next >= tail +#endif + && count < U16_MAX) + { + /* Handle mergable triable node Either we are + * the first node in a new trieable sequence, + * in which case we do some bookkeeping, + * otherwise we update the end pointer. */ + if ( !first ) { + first = cur; + if ( noper_trietype == NOTHING ) { +#if !defined(DEBUGGING) && !defined(NOJUMPTRIE) + regnode * const noper_next = regnext( noper ); + U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0; + U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0; +#endif + + if ( noper_next_trietype ) { + trietype = noper_next_trietype; + } else if (noper_next_type) { + /* a NOTHING regop is 1 regop wide. + * We need at least two for a trie + * so we can't merge this in */ + first = NULL; + } + } else { + trietype = noper_trietype; + } + } else { + if ( trietype == NOTHING ) + trietype = noper_trietype; + last = cur; + } + if (first) + count++; + } /* end handle mergable triable node */ + else { + /* handle unmergable node - + * noper may either be a triable node which can + * not be tried together with the current trie, + * or a non triable node */ + if ( last ) { + /* If last is set and trietype is not + * NOTHING then we have found at least two + * triable branch sequences in a row of a + * similar trietype so we can turn them + * into a trie. If/when we allow NOTHING to + * start a trie sequence this condition + * will be required, and it isn't expensive + * so we leave it in for now. */ + if ( trietype && trietype != NOTHING ) + make_trie( pRExC_state, + startbranch, first, cur, tail, + count, trietype, depth+1 ); + last = NULL; /* note: we clear/update + first, trietype etc below, + so we dont do it here */ + } + if ( noper_trietype +#ifdef NOJUMPTRIE + && noper_next >= tail +#endif + ){ + /* noper is triable, so we can start a new + * trie sequence */ + count = 1; + first = cur; + trietype = noper_trietype; + } else if (first) { + /* if we already saw a first but the + * current node is not triable then we have + * to reset the first information. */ + count = 0; + first = NULL; + trietype = 0; + } + } /* end handle unmergable node */ + } /* loop over branches */ + DEBUG_TRIE_COMPILE_r({ + regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); + Perl_re_indentf( aTHX_ ""- %s (%d) "", + depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur)); + Perl_re_printf( aTHX_ ""(First==%d, Last==%d, Cur==%d, tt==%s)\n"", + REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur), + PL_reg_name[trietype] + ); + + }); + if ( last && trietype ) { + if ( trietype != NOTHING ) { + /* the last branch of the sequence was part of + * a trie, so we have to construct it here + * outside of the loop */ + made= make_trie( pRExC_state, startbranch, + first, scan, tail, count, + trietype, depth+1 ); +#ifdef TRIE_STUDY_OPT + if ( ((made == MADE_EXACT_TRIE && + startbranch == first) + || ( first_non_open == first )) && + depth==0 ) { + flags |= SCF_TRIE_RESTUDY; + if ( startbranch == first + && scan >= tail ) + { + RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN; + } + } +#endif + } else { + /* at this point we know whatever we have is a + * NOTHING sequence/branch AND if 'startbranch' + * is 'first' then we can turn the whole thing + * into a NOTHING + */ + if ( startbranch == first ) { + regnode *opt; + /* the entire thing is a NOTHING sequence, + * something like this: (?:|) So we can + * turn it into a plain NOTHING op. */ + DEBUG_TRIE_COMPILE_r({ + regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); + Perl_re_indentf( aTHX_ ""- %s (%d) \n"", + depth+1, + SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur)); + + }); + OP(startbranch)= NOTHING; + NEXT_OFF(startbranch)= tail - startbranch; + for ( opt= startbranch + 1; opt < tail ; opt++ ) + OP(opt)= OPTIMIZED; + } + } + } /* end if ( last) */ + } /* TRIE_MAXBUF is non zero */ + + } /* do trie */ + + } + else if ( code == BRANCHJ ) { /* single branch is optimized. */ + scan = NEXTOPER(NEXTOPER(scan)); + } else /* single branch is optimized. */ + scan = NEXTOPER(scan); + continue; + } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) { + I32 paren = 0; + regnode *start = NULL; + regnode *end = NULL; + U32 my_recursed_depth= recursed_depth; + + if (OP(scan) != SUSPEND) { /* GOSUB */ + /* Do setup, note this code has side effects beyond + * the rest of this block. Specifically setting + * RExC_recurse[] must happen at least once during + * study_chunk(). */ + paren = ARG(scan); + RExC_recurse[ARG2L(scan)] = scan; + start = REGNODE_p(RExC_open_parens[paren]); + end = REGNODE_p(RExC_close_parens[paren]); + + /* NOTE we MUST always execute the above code, even + * if we do nothing with a GOSUB */ + if ( + ( flags & SCF_IN_DEFINE ) + || + ( + (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF)) + && + ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 ) + ) + ) { + /* no need to do anything here if we are in a define. */ + /* or we are after some kind of infinite construct + * so we can skip recursing into this item. + * Since it is infinite we will not change the maxlen + * or delta, and if we miss something that might raise + * the minlen it will merely pessimise a little. + * + * Iow /(?(DEFINE)(?foo|food))a+(?&foo)/ + * might result in a minlen of 1 and not of 4, + * but this doesn't make us mismatch, just try a bit + * harder than we should. + * */ + scan= regnext(scan); + continue; + } + + if ( + !recursed_depth + || + !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren) + ) { + /* it is quite possible that there are more efficient ways + * to do this. We maintain a bitmap per level of recursion + * of which patterns we have entered so we can detect if a + * pattern creates a possible infinite loop. When we + * recurse down a level we copy the previous levels bitmap + * down. When we are at recursion level 0 we zero the top + * level bitmap. It would be nice to implement a different + * more efficient way of doing this. In particular the top + * level bitmap may be unnecessary. + */ + if (!recursed_depth) { + Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8); + } else { + Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), + RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), + RExC_study_chunk_recursed_bytes, U8); + } + /* we havent recursed into this paren yet, so recurse into it */ + DEBUG_STUDYDATA(""gosub-set"", data, depth, is_inf); + PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren); + my_recursed_depth= recursed_depth + 1; + } else { + DEBUG_STUDYDATA(""gosub-inf"", data, depth, is_inf); + /* some form of infinite recursion, assume infinite length + * */ + if (flags & SCF_DO_SUBSTR) { + scan_commit(pRExC_state, data, minlenp, is_inf); + data->cur_is_floating = 1; + } + is_inf = is_inf_internal = 1; + if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ + ssc_anything(data->start_class); + flags &= ~SCF_DO_STCLASS; + + start= NULL; /* reset start so we dont recurse later on. */ + } + } else { + paren = stopparen; + start = scan + 2; + end = regnext(scan); + } + if (start) { + scan_frame *newframe; + assert(end); + if (!RExC_frame_last) { + Newxz(newframe, 1, scan_frame); + SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe); + RExC_frame_head= newframe; + RExC_frame_count++; + } else if (!RExC_frame_last->next_frame) { + Newxz(newframe, 1, scan_frame); + RExC_frame_last->next_frame= newframe; + newframe->prev_frame= RExC_frame_last; + RExC_frame_count++; + } else { + newframe= RExC_frame_last->next_frame; + } + RExC_frame_last= newframe; + + newframe->next_regnode = regnext(scan); + newframe->last_regnode = last; + newframe->stopparen = stopparen; + newframe->prev_recursed_depth = recursed_depth; + newframe->this_prev_frame= frame; + + DEBUG_STUDYDATA(""frame-new"", data, depth, is_inf); + DEBUG_PEEP(""fnew"", scan, depth, flags); + + frame = newframe; + scan = start; + stopparen = paren; + last = end; + depth = depth + 1; + recursed_depth= my_recursed_depth; + + continue; + } + } + else if ( OP(scan) == EXACT + || OP(scan) == EXACT_ONLY8 + || OP(scan) == EXACTL) + { + SSize_t l = STR_LEN(scan); + UV uc; + assert(l); + if (UTF) { + const U8 * const s = (U8*)STRING(scan); + uc = utf8_to_uvchr_buf(s, s + l, NULL); + l = utf8_length(s, s + l); + } else { + uc = *((U8*)STRING(scan)); + } + min += l; + if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */ + /* The code below prefers earlier match for fixed + offset, later match for variable offset. */ + if (data->last_end == -1) { /* Update the start info. */ + data->last_start_min = data->pos_min; + data->last_start_max = is_inf + ? SSize_t_MAX : data->pos_min + data->pos_delta; + } + sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan)); + if (UTF) + SvUTF8_on(data->last_found); + { + SV * const sv = data->last_found; + MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? + mg_find(sv, PERL_MAGIC_utf8) : NULL; + if (mg && mg->mg_len >= 0) + mg->mg_len += utf8_length((U8*)STRING(scan), + (U8*)STRING(scan)+STR_LEN(scan)); + } + data->last_end = data->pos_min + l; + data->pos_min += l; /* As in the first entry. */ + data->flags &= ~SF_BEFORE_EOL; + } + + /* ANDing the code point leaves at most it, and not in locale, and + * can't match null string */ + if (flags & SCF_DO_STCLASS_AND) { + ssc_cp_and(data->start_class, uc); + ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; + ssc_clear_locale(data->start_class); + } + else if (flags & SCF_DO_STCLASS_OR) { + ssc_add_cp(data->start_class, uc); + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + + /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ + ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; + } + flags &= ~SCF_DO_STCLASS; + } + else if (PL_regkind[OP(scan)] == EXACT) { + /* But OP != EXACT!, so is EXACTFish */ + SSize_t l = STR_LEN(scan); + const U8 * s = (U8*)STRING(scan); + + /* Search for fixed substrings supports EXACT only. */ + if (flags & SCF_DO_SUBSTR) { + assert(data); + scan_commit(pRExC_state, data, minlenp, is_inf); + } + if (UTF) { + l = utf8_length(s, s + l); + } + if (unfolded_multi_char) { + RExC_seen |= REG_UNFOLDED_MULTI_SEEN; + } + min += l - min_subtract; + assert (min >= 0); + delta += min_subtract; + if (flags & SCF_DO_SUBSTR) { + data->pos_min += l - min_subtract; + if (data->pos_min < 0) { + data->pos_min = 0; + } + data->pos_delta += min_subtract; + if (min_subtract) { + data->cur_is_floating = 1; /* float */ + } + } + + if (flags & SCF_DO_STCLASS) { + SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan); + + assert(EXACTF_invlist); + if (flags & SCF_DO_STCLASS_AND) { + if (OP(scan) != EXACTFL) + ssc_clear_locale(data->start_class); + ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; + ANYOF_POSIXL_ZERO(data->start_class); + ssc_intersection(data->start_class, EXACTF_invlist, FALSE); + } + else { /* SCF_DO_STCLASS_OR */ + ssc_union(data->start_class, EXACTF_invlist, FALSE); + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + + /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ + ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; + } + flags &= ~SCF_DO_STCLASS; + SvREFCNT_dec(EXACTF_invlist); + } + } + else if (REGNODE_VARIES(OP(scan))) { + SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0; + I32 fl = 0, f = flags; + regnode * const oscan = scan; + regnode_ssc this_class; + regnode_ssc *oclass = NULL; + I32 next_is_eval = 0; + + switch (PL_regkind[OP(scan)]) { + case WHILEM: /* End of (?:...)* . */ + scan = NEXTOPER(scan); + goto finish; + case PLUS: + if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) { + next = NEXTOPER(scan); + if ( OP(next) == EXACT + || OP(next) == EXACT_ONLY8 + || OP(next) == EXACTL + || (flags & SCF_DO_STCLASS)) + { + mincount = 1; + maxcount = REG_INFTY; + next = regnext(scan); + scan = NEXTOPER(scan); + goto do_curly; + } + } + if (flags & SCF_DO_SUBSTR) + data->pos_min++; + min++; + /* FALLTHROUGH */ + case STAR: + next = NEXTOPER(scan); + + /* This temporary node can now be turned into EXACTFU, and + * must, as regexec.c doesn't handle it */ + if (OP(next) == EXACTFU_S_EDGE) { + OP(next) = EXACTFU; + } + + if ( STR_LEN(next) == 1 + && isALPHA_A(* STRING(next)) + && ( OP(next) == EXACTFAA + || ( OP(next) == EXACTFU + && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next))))) + { + /* These differ in just one bit */ + U8 mask = ~ ('A' ^ 'a'); + + assert(isALPHA_A(* STRING(next))); + + /* Then replace it by an ANYOFM node, with + * the mask set to the complement of the + * bit that differs between upper and lower + * case, and the lowest code point of the + * pair (which the '&' forces) */ + OP(next) = ANYOFM; + ARG_SET(next, *STRING(next) & mask); + FLAGS(next) = mask; + } + + if (flags & SCF_DO_STCLASS) { + mincount = 0; + maxcount = REG_INFTY; + next = regnext(scan); + scan = NEXTOPER(scan); + goto do_curly; + } + if (flags & SCF_DO_SUBSTR) { + scan_commit(pRExC_state, data, minlenp, is_inf); + /* Cannot extend fixed substrings */ + data->cur_is_floating = 1; /* float */ + } + is_inf = is_inf_internal = 1; + scan = regnext(scan); + goto optimize_curly_tail; + case CURLY: + if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM) + && (scan->flags == stopparen)) + { + mincount = 1; + maxcount = 1; + } else { + mincount = ARG1(scan); + maxcount = ARG2(scan); + } + next = regnext(scan); + if (OP(scan) == CURLYX) { + I32 lp = (data ? *(data->last_closep) : 0); + scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX); + } + scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS; + next_is_eval = (OP(scan) == EVAL); + do_curly: + if (flags & SCF_DO_SUBSTR) { + if (mincount == 0) + scan_commit(pRExC_state, data, minlenp, is_inf); + /* Cannot extend fixed substrings */ + pos_before = data->pos_min; + } + if (data) { + fl = data->flags; + data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL); + if (is_inf) + data->flags |= SF_IS_INF; + } + if (flags & SCF_DO_STCLASS) { + ssc_init(pRExC_state, &this_class); + oclass = data->start_class; + data->start_class = &this_class; + f |= SCF_DO_STCLASS_AND; + f &= ~SCF_DO_STCLASS_OR; + } + /* Exclude from super-linear cache processing any {n,m} + regops for which the combination of input pos and regex + pos is not enough information to determine if a match + will be possible. + + For example, in the regex /foo(bar\s*){4,8}baz/ with the + regex pos at the \s*, the prospects for a match depend not + only on the input position but also on how many (bar\s*) + repeats into the {4,8} we are. */ + if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY)) + f &= ~SCF_WHILEM_VISITED_POS; + + /* This will finish on WHILEM, setting scan, or on NULL: */ + /* recurse study_chunk() on loop bodies */ + minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, + last, data, stopparen, recursed_depth, NULL, + (mincount == 0 + ? (f & ~SCF_DO_SUBSTR) + : f) + ,depth+1); + + if (flags & SCF_DO_STCLASS) + data->start_class = oclass; + if (mincount == 0 || minnext == 0) { + if (flags & SCF_DO_STCLASS_OR) { + ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class); + } + else if (flags & SCF_DO_STCLASS_AND) { + /* Switch to OR mode: cache the old value of + * data->start_class */ + INIT_AND_WITHP; + StructCopy(data->start_class, and_withp, regnode_ssc); + flags &= ~SCF_DO_STCLASS_AND; + StructCopy(&this_class, data->start_class, regnode_ssc); + flags |= SCF_DO_STCLASS_OR; + ANYOF_FLAGS(data->start_class) + |= SSC_MATCHES_EMPTY_STRING; + } + } else { /* Non-zero len */ + if (flags & SCF_DO_STCLASS_OR) { + ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class); + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + } + else if (flags & SCF_DO_STCLASS_AND) + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class); + flags &= ~SCF_DO_STCLASS; + } + if (!scan) /* It was not CURLYX, but CURLY. */ + scan = next; + if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR) + /* ? quantifier ok, except for (?{ ... }) */ + && (next_is_eval || !(mincount == 0 && maxcount == 1)) + && (minnext == 0) && (deltanext == 0) + && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR)) + && maxcount <= REG_INFTY/3) /* Complement check for big + count */ + { + _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP), + Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), + ""Quantifier unexpected on zero-length expression "" + ""in regex m/%"" UTF8f ""/"", + UTF8fARG(UTF, RExC_precomp_end - RExC_precomp, + RExC_precomp))); + } + + if ( ( minnext > 0 && mincount >= SSize_t_MAX / minnext ) + || min >= SSize_t_MAX - minnext * mincount ) + { + FAIL(""Regexp out of space""); + } + + min += minnext * mincount; + is_inf_internal |= deltanext == SSize_t_MAX + || (maxcount == REG_INFTY && minnext + deltanext > 0); + is_inf |= is_inf_internal; + if (is_inf) { + delta = SSize_t_MAX; + } else { + delta += (minnext + deltanext) * maxcount + - minnext * mincount; + } + /* Try powerful optimization CURLYX => CURLYN. */ + if ( OP(oscan) == CURLYX && data + && data->flags & SF_IN_PAR + && !(data->flags & SF_HAS_EVAL) + && !deltanext && minnext == 1 ) { + /* Try to optimize to CURLYN. */ + regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; + regnode * const nxt1 = nxt; +#ifdef DEBUGGING + regnode *nxt2; +#endif + + /* Skip open. */ + nxt = regnext(nxt); + if (!REGNODE_SIMPLE(OP(nxt)) + && !(PL_regkind[OP(nxt)] == EXACT + && STR_LEN(nxt) == 1)) + goto nogo; +#ifdef DEBUGGING + nxt2 = nxt; +#endif + nxt = regnext(nxt); + if (OP(nxt) != CLOSE) + goto nogo; + if (RExC_open_parens) { + + /*open->CURLYM*/ + RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan); + + /*close->while*/ + RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2; + } + /* Now we know that nxt2 is the only contents: */ + oscan->flags = (U8)ARG(nxt); + OP(oscan) = CURLYN; + OP(nxt1) = NOTHING; /* was OPEN. */ + +#ifdef DEBUGGING + OP(nxt1 + 1) = OPTIMIZED; /* was count. */ + NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */ + NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */ + OP(nxt) = OPTIMIZED; /* was CLOSE. */ + OP(nxt + 1) = OPTIMIZED; /* was count. */ + NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */ +#endif + } + nogo: + + /* Try optimization CURLYX => CURLYM. */ + if ( OP(oscan) == CURLYX && data + && !(data->flags & SF_HAS_PAR) + && !(data->flags & SF_HAS_EVAL) + && !deltanext /* atom is fixed width */ + && minnext != 0 /* CURLYM can't handle zero width */ + + /* Nor characters whose fold at run-time may be + * multi-character */ + && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN) + ) { + /* XXXX How to optimize if data == 0? */ + /* Optimize to a simpler form. */ + regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */ + regnode *nxt2; + + OP(oscan) = CURLYM; + while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/ + && (OP(nxt2) != WHILEM)) + nxt = nxt2; + OP(nxt2) = SUCCEED; /* Whas WHILEM */ + /* Need to optimize away parenths. */ + if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) { + /* Set the parenth number. */ + regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/ + + oscan->flags = (U8)ARG(nxt); + if (RExC_open_parens) { + /*open->CURLYM*/ + RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan); + + /*close->NOTHING*/ + RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2) + + 1; + } + OP(nxt1) = OPTIMIZED; /* was OPEN. */ + OP(nxt) = OPTIMIZED; /* was CLOSE. */ + +#ifdef DEBUGGING + OP(nxt1 + 1) = OPTIMIZED; /* was count. */ + OP(nxt + 1) = OPTIMIZED; /* was count. */ + NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */ + NEXT_OFF(nxt + 1) = 0; /* just for consistency. */ +#endif +#if 0 + while ( nxt1 && (OP(nxt1) != WHILEM)) { + regnode *nnxt = regnext(nxt1); + if (nnxt == nxt) { + if (reg_off_by_arg[OP(nxt1)]) + ARG_SET(nxt1, nxt2 - nxt1); + else if (nxt2 - nxt1 < U16_MAX) + NEXT_OFF(nxt1) = nxt2 - nxt1; + else + OP(nxt) = NOTHING; /* Cannot beautify */ + } + nxt1 = nnxt; + } +#endif + /* Optimize again: */ + /* recurse study_chunk() on optimised CURLYX => CURLYM */ + study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt, + NULL, stopparen, recursed_depth, NULL, 0, + depth+1); + } + else + oscan->flags = 0; + } + else if ((OP(oscan) == CURLYX) + && (flags & SCF_WHILEM_VISITED_POS) + /* See the comment on a similar expression above. + However, this time it's not a subexpression + we care about, but the expression itself. */ + && (maxcount == REG_INFTY) + && data) { + /* This stays as CURLYX, we can put the count/of pair. */ + /* Find WHILEM (as in regexec.c) */ + regnode *nxt = oscan + NEXT_OFF(oscan); + + if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */ + nxt += ARG(nxt); + nxt = PREVOPER(nxt); + if (nxt->flags & 0xf) { + /* we've already set whilem count on this node */ + } else if (++data->whilem_c < 16) { + assert(data->whilem_c <= RExC_whilem_seen); + nxt->flags = (U8)(data->whilem_c + | (RExC_whilem_seen << 4)); /* On WHILEM */ + } + } + if (data && fl & (SF_HAS_PAR|SF_IN_PAR)) + pars++; + if (flags & SCF_DO_SUBSTR) { + SV *last_str = NULL; + STRLEN last_chrs = 0; + int counted = mincount != 0; + + if (data->last_end > 0 && mincount != 0) { /* Ends with a + string. */ + SSize_t b = pos_before >= data->last_start_min + ? pos_before : data->last_start_min; + STRLEN l; + const char * const s = SvPV_const(data->last_found, l); + SSize_t old = b - data->last_start_min; + assert(old >= 0); + + if (UTF) + old = utf8_hop_forward((U8*)s, old, + (U8 *) SvEND(data->last_found)) + - (U8*)s; + l -= old; + /* Get the added string: */ + last_str = newSVpvn_utf8(s + old, l, UTF); + last_chrs = UTF ? utf8_length((U8*)(s + old), + (U8*)(s + old + l)) : l; + if (deltanext == 0 && pos_before == b) { + /* What was added is a constant string */ + if (mincount > 1) { + + SvGROW(last_str, (mincount * l) + 1); + repeatcpy(SvPVX(last_str) + l, + SvPVX_const(last_str), l, + mincount - 1); + SvCUR_set(last_str, SvCUR(last_str) * mincount); + /* Add additional parts. */ + SvCUR_set(data->last_found, + SvCUR(data->last_found) - l); + sv_catsv(data->last_found, last_str); + { + SV * sv = data->last_found; + MAGIC *mg = + SvUTF8(sv) && SvMAGICAL(sv) ? + mg_find(sv, PERL_MAGIC_utf8) : NULL; + if (mg && mg->mg_len >= 0) + mg->mg_len += last_chrs * (mincount-1); + } + last_chrs *= mincount; + data->last_end += l * (mincount - 1); + } + } else { + /* start offset must point into the last copy */ + data->last_start_min += minnext * (mincount - 1); + data->last_start_max = + is_inf + ? SSize_t_MAX + : data->last_start_max + + (maxcount - 1) * (minnext + data->pos_delta); + } + } + /* It is counted once already... */ + data->pos_min += minnext * (mincount - counted); +#if 0 +Perl_re_printf( aTHX_ ""counted=%"" UVuf "" deltanext=%"" UVuf + "" SSize_t_MAX=%"" UVuf "" minnext=%"" UVuf + "" maxcount=%"" UVuf "" mincount=%"" UVuf ""\n"", + (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount, + (UV)mincount); +if (deltanext != SSize_t_MAX) +Perl_re_printf( aTHX_ ""LHS=%"" UVuf "" RHS=%"" UVuf ""\n"", + (UV)(-counted * deltanext + (minnext + deltanext) * maxcount + - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta)); +#endif + if (deltanext == SSize_t_MAX + || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta) + data->pos_delta = SSize_t_MAX; + else + data->pos_delta += - counted * deltanext + + (minnext + deltanext) * maxcount - minnext * mincount; + if (mincount != maxcount) { + /* Cannot extend fixed substrings found inside + the group. */ + scan_commit(pRExC_state, data, minlenp, is_inf); + if (mincount && last_str) { + SV * const sv = data->last_found; + MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? + mg_find(sv, PERL_MAGIC_utf8) : NULL; + + if (mg) + mg->mg_len = -1; + sv_setsv(sv, last_str); + data->last_end = data->pos_min; + data->last_start_min = data->pos_min - last_chrs; + data->last_start_max = is_inf + ? SSize_t_MAX + : data->pos_min + data->pos_delta - last_chrs; + } + data->cur_is_floating = 1; /* float */ + } + SvREFCNT_dec(last_str); + } + if (data && (fl & SF_HAS_EVAL)) + data->flags |= SF_HAS_EVAL; + optimize_curly_tail: + if (OP(oscan) != CURLYX) { + while (PL_regkind[OP(next = regnext(oscan))] == NOTHING + && NEXT_OFF(next)) + NEXT_OFF(oscan) += NEXT_OFF(next); + } + continue; + + default: +#ifdef DEBUGGING + Perl_croak(aTHX_ ""panic: unexpected varying REx opcode %d"", + OP(scan)); +#endif + case REF: + case CLUMP: + if (flags & SCF_DO_SUBSTR) { + /* Cannot expect anything... */ + scan_commit(pRExC_state, data, minlenp, is_inf); + data->cur_is_floating = 1; /* float */ + } + is_inf = is_inf_internal = 1; + if (flags & SCF_DO_STCLASS_OR) { + if (OP(scan) == CLUMP) { + /* Actually is any start char, but very few code points + * aren't start characters */ + ssc_match_all_cp(data->start_class); + } + else { + ssc_anything(data->start_class); + } + } + flags &= ~SCF_DO_STCLASS; + break; + } + } + else if (OP(scan) == LNBREAK) { + if (flags & SCF_DO_STCLASS) { + if (flags & SCF_DO_STCLASS_AND) { + ssc_intersection(data->start_class, + PL_XPosix_ptrs[_CC_VERTSPACE], FALSE); + ssc_clear_locale(data->start_class); + ANYOF_FLAGS(data->start_class) + &= ~SSC_MATCHES_EMPTY_STRING; + } + else if (flags & SCF_DO_STCLASS_OR) { + ssc_union(data->start_class, + PL_XPosix_ptrs[_CC_VERTSPACE], + FALSE); + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + + /* See commit msg for + * 749e076fceedeb708a624933726e7989f2302f6a */ + ANYOF_FLAGS(data->start_class) + &= ~SSC_MATCHES_EMPTY_STRING; + } + flags &= ~SCF_DO_STCLASS; + } + min++; + if (delta != SSize_t_MAX) + delta++; /* Because of the 2 char string cr-lf */ + if (flags & SCF_DO_SUBSTR) { + /* Cannot expect anything... */ + scan_commit(pRExC_state, data, minlenp, is_inf); + data->pos_min += 1; + if (data->pos_delta != SSize_t_MAX) { + data->pos_delta += 1; + } + data->cur_is_floating = 1; /* float */ + } + } + else if (REGNODE_SIMPLE(OP(scan))) { + + if (flags & SCF_DO_SUBSTR) { + scan_commit(pRExC_state, data, minlenp, is_inf); + data->pos_min++; + } + min++; + if (flags & SCF_DO_STCLASS) { + bool invert = 0; + SV* my_invlist = NULL; + U8 namedclass; + + /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ + ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; + + /* Some of the logic below assumes that switching + locale on will only add false positives. */ + switch (OP(scan)) { + + default: +#ifdef DEBUGGING + Perl_croak(aTHX_ ""panic: unexpected simple REx opcode %d"", + OP(scan)); +#endif + case SANY: + if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ + ssc_match_all_cp(data->start_class); + break; + + case REG_ANY: + { + SV* REG_ANY_invlist = _new_invlist(2); + REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist, + '\n'); + if (flags & SCF_DO_STCLASS_OR) { + ssc_union(data->start_class, + REG_ANY_invlist, + TRUE /* TRUE => invert, hence all but \n + */ + ); + } + else if (flags & SCF_DO_STCLASS_AND) { + ssc_intersection(data->start_class, + REG_ANY_invlist, + TRUE /* TRUE => invert */ + ); + ssc_clear_locale(data->start_class); + } + SvREFCNT_dec_NN(REG_ANY_invlist); + } + break; + + case ANYOFD: + case ANYOFL: + case ANYOFPOSIXL: + case ANYOFH: + case ANYOF: + if (flags & SCF_DO_STCLASS_AND) + ssc_and(pRExC_state, data->start_class, + (regnode_charclass *) scan); + else + ssc_or(pRExC_state, data->start_class, + (regnode_charclass *) scan); + break; + + case NANYOFM: + case ANYOFM: + { + SV* cp_list = get_ANYOFM_contents(scan); + + if (flags & SCF_DO_STCLASS_OR) { + ssc_union(data->start_class, cp_list, invert); + } + else if (flags & SCF_DO_STCLASS_AND) { + ssc_intersection(data->start_class, cp_list, invert); + } + + SvREFCNT_dec_NN(cp_list); + break; + } + + case NPOSIXL: + invert = 1; + /* FALLTHROUGH */ + + case POSIXL: + namedclass = classnum_to_namedclass(FLAGS(scan)) + invert; + if (flags & SCF_DO_STCLASS_AND) { + bool was_there = cBOOL( + ANYOF_POSIXL_TEST(data->start_class, + namedclass)); + ANYOF_POSIXL_ZERO(data->start_class); + if (was_there) { /* Do an AND */ + ANYOF_POSIXL_SET(data->start_class, namedclass); + } + /* No individual code points can now match */ + data->start_class->invlist + = sv_2mortal(_new_invlist(0)); + } + else { + int complement = namedclass + ((invert) ? -1 : 1); + + assert(flags & SCF_DO_STCLASS_OR); + + /* If the complement of this class was already there, + * the result is that they match all code points, + * (\d + \D == everything). Remove the classes from + * future consideration. Locale is not relevant in + * this case */ + if (ANYOF_POSIXL_TEST(data->start_class, complement)) { + ssc_match_all_cp(data->start_class); + ANYOF_POSIXL_CLEAR(data->start_class, namedclass); + ANYOF_POSIXL_CLEAR(data->start_class, complement); + } + else { /* The usual case; just add this class to the + existing set */ + ANYOF_POSIXL_SET(data->start_class, namedclass); + } + } + break; + + case NPOSIXA: /* For these, we always know the exact set of + what's matched */ + invert = 1; + /* FALLTHROUGH */ + case POSIXA: + my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL); + goto join_posix_and_ascii; + + case NPOSIXD: + case NPOSIXU: + invert = 1; + /* FALLTHROUGH */ + case POSIXD: + case POSIXU: + my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL); + + /* NPOSIXD matches all upper Latin1 code points unless the + * target string being matched is UTF-8, which is + * unknowable until match time. Since we are going to + * invert, we want to get rid of all of them so that the + * inversion will match all */ + if (OP(scan) == NPOSIXD) { + _invlist_subtract(my_invlist, PL_UpperLatin1, + &my_invlist); + } + + join_posix_and_ascii: + + if (flags & SCF_DO_STCLASS_AND) { + ssc_intersection(data->start_class, my_invlist, invert); + ssc_clear_locale(data->start_class); + } + else { + assert(flags & SCF_DO_STCLASS_OR); + ssc_union(data->start_class, my_invlist, invert); + } + SvREFCNT_dec(my_invlist); + } + if (flags & SCF_DO_STCLASS_OR) + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + flags &= ~SCF_DO_STCLASS; + } + } + else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) { + data->flags |= (OP(scan) == MEOL + ? SF_BEFORE_MEOL + : SF_BEFORE_SEOL); + scan_commit(pRExC_state, data, minlenp, is_inf); + + } + else if ( PL_regkind[OP(scan)] == BRANCHJ + /* Lookbehind, or need to calculate parens/evals/stclass: */ + && (scan->flags || data || (flags & SCF_DO_STCLASS)) + && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) + { + if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY + || OP(scan) == UNLESSM ) + { + /* Negative Lookahead/lookbehind + In this case we can't do fixed string optimisation. + */ + + SSize_t deltanext, minnext, fake = 0; + regnode *nscan; + regnode_ssc intrnl; + int f = 0; + + StructCopy(&zero_scan_data, &data_fake, scan_data_t); + if (data) { + data_fake.whilem_c = data->whilem_c; + data_fake.last_closep = data->last_closep; + } + else + data_fake.last_closep = &fake; + data_fake.pos_delta = delta; + if ( flags & SCF_DO_STCLASS && !scan->flags + && OP(scan) == IFMATCH ) { /* Lookahead */ + ssc_init(pRExC_state, &intrnl); + data_fake.start_class = &intrnl; + f |= SCF_DO_STCLASS_AND; + } + if (flags & SCF_WHILEM_VISITED_POS) + f |= SCF_WHILEM_VISITED_POS; + next = regnext(scan); + nscan = NEXTOPER(NEXTOPER(scan)); + + /* recurse study_chunk() for lookahead body */ + minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, + last, &data_fake, stopparen, + recursed_depth, NULL, f, depth+1); + if (scan->flags) { + if ( deltanext < 0 + || deltanext > (I32) U8_MAX + || minnext > (I32)U8_MAX + || minnext + deltanext > (I32)U8_MAX) + { + FAIL2(""Lookbehind longer than %"" UVuf "" not implemented"", + (UV)U8_MAX); + } + + /* The 'next_off' field has been repurposed to count the + * additional starting positions to try beyond the initial + * one. (This leaves it at 0 for non-variable length + * matches to avoid breakage for those not using this + * extension) */ + if (deltanext) { + scan->next_off = deltanext; + ckWARNexperimental(RExC_parse, + WARN_EXPERIMENTAL__VLB, + ""Variable length lookbehind is experimental""); + } + scan->flags = (U8)minnext + deltanext; + } + if (data) { + if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) + pars++; + if (data_fake.flags & SF_HAS_EVAL) + data->flags |= SF_HAS_EVAL; + data->whilem_c = data_fake.whilem_c; + } + if (f & SCF_DO_STCLASS_AND) { + if (flags & SCF_DO_STCLASS_OR) { + /* OR before, AND after: ideally we would recurse with + * data_fake to get the AND applied by study of the + * remainder of the pattern, and then derecurse; + * *** HACK *** for now just treat as ""no information"". + * See [perl #56690]. + */ + ssc_init(pRExC_state, data->start_class); + } else { + /* AND before and after: combine and continue. These + * assertions are zero-length, so can match an EMPTY + * string */ + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl); + ANYOF_FLAGS(data->start_class) + |= SSC_MATCHES_EMPTY_STRING; + } + } + } +#if PERL_ENABLE_POSITIVE_ASSERTION_STUDY + else { + /* Positive Lookahead/lookbehind + In this case we can do fixed string optimisation, + but we must be careful about it. Note in the case of + lookbehind the positions will be offset by the minimum + length of the pattern, something we won't know about + until after the recurse. + */ + SSize_t deltanext, fake = 0; + regnode *nscan; + regnode_ssc intrnl; + int f = 0; + /* We use SAVEFREEPV so that when the full compile + is finished perl will clean up the allocated + minlens when it's all done. This way we don't + have to worry about freeing them when we know + they wont be used, which would be a pain. + */ + SSize_t *minnextp; + Newx( minnextp, 1, SSize_t ); + SAVEFREEPV(minnextp); + + if (data) { + StructCopy(data, &data_fake, scan_data_t); + if ((flags & SCF_DO_SUBSTR) && data->last_found) { + f |= SCF_DO_SUBSTR; + if (scan->flags) + scan_commit(pRExC_state, &data_fake, minlenp, is_inf); + data_fake.last_found=newSVsv(data->last_found); + } + } + else + data_fake.last_closep = &fake; + data_fake.flags = 0; + data_fake.substrs[0].flags = 0; + data_fake.substrs[1].flags = 0; + data_fake.pos_delta = delta; + if (is_inf) + data_fake.flags |= SF_IS_INF; + if ( flags & SCF_DO_STCLASS && !scan->flags + && OP(scan) == IFMATCH ) { /* Lookahead */ + ssc_init(pRExC_state, &intrnl); + data_fake.start_class = &intrnl; + f |= SCF_DO_STCLASS_AND; + } + if (flags & SCF_WHILEM_VISITED_POS) + f |= SCF_WHILEM_VISITED_POS; + next = regnext(scan); + nscan = NEXTOPER(NEXTOPER(scan)); + + /* positive lookahead study_chunk() recursion */ + *minnextp = study_chunk(pRExC_state, &nscan, minnextp, + &deltanext, last, &data_fake, + stopparen, recursed_depth, NULL, + f, depth+1); + if (scan->flags) { + assert(0); /* This code has never been tested since this + is normally not compiled */ + if ( deltanext < 0 + || deltanext > (I32) U8_MAX + || *minnextp > (I32)U8_MAX + || *minnextp + deltanext > (I32)U8_MAX) + { + FAIL2(""Lookbehind longer than %"" UVuf "" not implemented"", + (UV)U8_MAX); + } + + if (deltanext) { + scan->next_off = deltanext; + } + scan->flags = (U8)*minnextp + deltanext; + } + + *minnextp += min; + + if (f & SCF_DO_STCLASS_AND) { + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl); + ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; + } + if (data) { + if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) + pars++; + if (data_fake.flags & SF_HAS_EVAL) + data->flags |= SF_HAS_EVAL; + data->whilem_c = data_fake.whilem_c; + if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) { + int i; + if (RExC_rx->minlen<*minnextp) + RExC_rx->minlen=*minnextp; + scan_commit(pRExC_state, &data_fake, minnextp, is_inf); + SvREFCNT_dec_NN(data_fake.last_found); + + for (i = 0; i < 2; i++) { + if (data_fake.substrs[i].minlenp != minlenp) { + data->substrs[i].min_offset = + data_fake.substrs[i].min_offset; + data->substrs[i].max_offset = + data_fake.substrs[i].max_offset; + data->substrs[i].minlenp = + data_fake.substrs[i].minlenp; + data->substrs[i].lookbehind += scan->flags; + } + } + } + } + } +#endif + } + + else if (OP(scan) == OPEN) { + if (stopparen != (I32)ARG(scan)) + pars++; + } + else if (OP(scan) == CLOSE) { + if (stopparen == (I32)ARG(scan)) { + break; + } + if ((I32)ARG(scan) == is_par) { + next = regnext(scan); + + if ( next && (OP(next) != WHILEM) && next < last) + is_par = 0; /* Disable optimization */ + } + if (data) + *(data->last_closep) = ARG(scan); + } + else if (OP(scan) == EVAL) { + if (data) + data->flags |= SF_HAS_EVAL; + } + else if ( PL_regkind[OP(scan)] == ENDLIKE ) { + if (flags & SCF_DO_SUBSTR) { + scan_commit(pRExC_state, data, minlenp, is_inf); + flags &= ~SCF_DO_SUBSTR; + } + if (data && OP(scan)==ACCEPT) { + data->flags |= SCF_SEEN_ACCEPT; + if (stopmin > min) + stopmin = min; + } + } + else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */ + { + if (flags & SCF_DO_SUBSTR) { + scan_commit(pRExC_state, data, minlenp, is_inf); + data->cur_is_floating = 1; /* float */ + } + is_inf = is_inf_internal = 1; + if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ + ssc_anything(data->start_class); + flags &= ~SCF_DO_STCLASS; + } + else if (OP(scan) == GPOS) { + if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) && + !(delta || is_inf || (data && data->pos_delta))) + { + if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR)) + RExC_rx->intflags |= PREGf_ANCH_GPOS; + if (RExC_rx->gofs < (STRLEN)min) + RExC_rx->gofs = min; + } else { + RExC_rx->intflags |= PREGf_GPOS_FLOAT; + RExC_rx->gofs = 0; + } + } +#ifdef TRIE_STUDY_OPT +#ifdef FULL_TRIE_STUDY + else if (PL_regkind[OP(scan)] == TRIE) { + /* NOTE - There is similar code to this block above for handling + BRANCH nodes on the initial study. If you change stuff here + check there too. */ + regnode *trie_node= scan; + regnode *tail= regnext(scan); + reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ]; + SSize_t max1 = 0, min1 = SSize_t_MAX; + regnode_ssc accum; + + if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */ + /* Cannot merge strings after this. */ + scan_commit(pRExC_state, data, minlenp, is_inf); + } + if (flags & SCF_DO_STCLASS) + ssc_init_zero(pRExC_state, &accum); + + if (!trie->jump) { + min1= trie->minlen; + max1= trie->maxlen; + } else { + const regnode *nextbranch= NULL; + U32 word; + + for ( word=1 ; word <= trie->wordcount ; word++) + { + SSize_t deltanext=0, minnext=0, f = 0, fake; + regnode_ssc this_class; + + StructCopy(&zero_scan_data, &data_fake, scan_data_t); + if (data) { + data_fake.whilem_c = data->whilem_c; + data_fake.last_closep = data->last_closep; + } + else + data_fake.last_closep = &fake; + data_fake.pos_delta = delta; + if (flags & SCF_DO_STCLASS) { + ssc_init(pRExC_state, &this_class); + data_fake.start_class = &this_class; + f = SCF_DO_STCLASS_AND; + } + if (flags & SCF_WHILEM_VISITED_POS) + f |= SCF_WHILEM_VISITED_POS; + + if (trie->jump[word]) { + if (!nextbranch) + nextbranch = trie_node + trie->jump[0]; + scan= trie_node + trie->jump[word]; + /* We go from the jump point to the branch that follows + it. Note this means we need the vestigal unused + branches even though they arent otherwise used. */ + /* optimise study_chunk() for TRIE */ + minnext = study_chunk(pRExC_state, &scan, minlenp, + &deltanext, (regnode *)nextbranch, &data_fake, + stopparen, recursed_depth, NULL, f, depth+1); + } + if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH) + nextbranch= regnext((regnode*)nextbranch); + + if (min1 > (SSize_t)(minnext + trie->minlen)) + min1 = minnext + trie->minlen; + if (deltanext == SSize_t_MAX) { + is_inf = is_inf_internal = 1; + max1 = SSize_t_MAX; + } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen)) + max1 = minnext + deltanext + trie->maxlen; + + if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) + pars++; + if (data_fake.flags & SCF_SEEN_ACCEPT) { + if ( stopmin > min + min1) + stopmin = min + min1; + flags &= ~SCF_DO_SUBSTR; + if (data) + data->flags |= SCF_SEEN_ACCEPT; + } + if (data) { + if (data_fake.flags & SF_HAS_EVAL) + data->flags |= SF_HAS_EVAL; + data->whilem_c = data_fake.whilem_c; + } + if (flags & SCF_DO_STCLASS) + ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class); + } + } + if (flags & SCF_DO_SUBSTR) { + data->pos_min += min1; + data->pos_delta += max1 - min1; + if (max1 != min1 || is_inf) + data->cur_is_floating = 1; /* float */ + } + min += min1; + if (delta != SSize_t_MAX) { + if (SSize_t_MAX - (max1 - min1) >= delta) + delta += max1 - min1; + else + delta = SSize_t_MAX; + } + if (flags & SCF_DO_STCLASS_OR) { + ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum); + if (min1) { + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + flags &= ~SCF_DO_STCLASS; + } + } + else if (flags & SCF_DO_STCLASS_AND) { + if (min1) { + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum); + flags &= ~SCF_DO_STCLASS; + } + else { + /* Switch to OR mode: cache the old value of + * data->start_class */ + INIT_AND_WITHP; + StructCopy(data->start_class, and_withp, regnode_ssc); + flags &= ~SCF_DO_STCLASS_AND; + StructCopy(&accum, data->start_class, regnode_ssc); + flags |= SCF_DO_STCLASS_OR; + } + } + scan= tail; + continue; + } +#else + else if (PL_regkind[OP(scan)] == TRIE) { + reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ]; + U8*bang=NULL; + + min += trie->minlen; + delta += (trie->maxlen - trie->minlen); + flags &= ~SCF_DO_STCLASS; /* xxx */ + if (flags & SCF_DO_SUBSTR) { + /* Cannot expect anything... */ + scan_commit(pRExC_state, data, minlenp, is_inf); + data->pos_min += trie->minlen; + data->pos_delta += (trie->maxlen - trie->minlen); + if (trie->maxlen != trie->minlen) + data->cur_is_floating = 1; /* float */ + } + if (trie->jump) /* no more substrings -- for now /grr*/ + flags &= ~SCF_DO_SUBSTR; + } +#endif /* old or new */ +#endif /* TRIE_STUDY_OPT */ + + /* Else: zero-length, ignore. */ + scan = regnext(scan); + } + + finish: + if (frame) { + /* we need to unwind recursion. */ + depth = depth - 1; + + DEBUG_STUDYDATA(""frame-end"", data, depth, is_inf); + DEBUG_PEEP(""fend"", scan, depth, flags); + + /* restore previous context */ + last = frame->last_regnode; + scan = frame->next_regnode; + stopparen = frame->stopparen; + recursed_depth = frame->prev_recursed_depth; + + RExC_frame_last = frame->prev_frame; + frame = frame->this_prev_frame; + goto fake_study_recurse; + } + + assert(!frame); + DEBUG_STUDYDATA(""pre-fin"", data, depth, is_inf); + + *scanp = scan; + *deltap = is_inf_internal ? SSize_t_MAX : delta; + + if (flags & SCF_DO_SUBSTR && is_inf) + data->pos_delta = SSize_t_MAX - data->pos_min; + if (is_par > (I32)U8_MAX) + is_par = 0; + if (is_par && pars==1 && data) { + data->flags |= SF_IN_PAR; + data->flags &= ~SF_HAS_PAR; + } + else if (pars && data) { + data->flags |= SF_HAS_PAR; + data->flags &= ~SF_IN_PAR; + } + if (flags & SCF_DO_STCLASS_OR) + ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); + if (flags & SCF_TRIE_RESTUDY) + data->flags |= SCF_TRIE_RESTUDY; + + DEBUG_STUDYDATA(""post-fin"", data, depth, is_inf); + + { + SSize_t final_minlen= min < stopmin ? min : stopmin; + + if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) { + if (final_minlen > SSize_t_MAX - delta) + RExC_maxlen = SSize_t_MAX; + else if (RExC_maxlen < final_minlen + delta) + RExC_maxlen = final_minlen + delta; + } + return final_minlen; + } + NOT_REACHED; /* NOTREACHED */","{'deleted': [], 'added': [{'line_no': 1039, 'char_start': 44524, 'char_end': 44598, 'line': ' if ( ( minnext > 0 && mincount >= SSize_t_MAX / minnext )\n'}, {'line_no': 1040, 'char_start': 44598, 'char_end': 44663, 'line': ' || min >= SSize_t_MAX - minnext * mincount )\n'}, {'line_no': 1041, 'char_start': 44663, 'char_end': 44681, 'line': ' {\n'}, {'line_no': 1042, 'char_start': 44681, 'char_end': 44730, 'line': ' FAIL(""Regexp out of space"");\n'}, {'line_no': 1043, 'char_start': 44730, 'char_end': 44748, 'line': ' }\n'}, {'line_no': 1044, 'char_start': 44748, 'char_end': 44749, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 44524, 'char_end': 44749, 'chars': ' 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'}]}",github.com/perl/perl5/commit/897d1f7fd515b828e4b198d8b8bef76c6faf03ed,regcomp.c,cwe-787, +cwe-787,RemoveICCProfileFromResourceBlock,"static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) +{ + register const unsigned char + *p; + + size_t + length; + + unsigned char + *datum; + + unsigned int + count, + long_sans; + + unsigned short + id, + short_sans; + + length=GetStringInfoLength(bim_profile); + if (length < 16) + return; + datum=GetStringInfoDatum(bim_profile); + for (p=datum; (p >= datum) && (p < (datum+length-16)); ) + { + register unsigned char + *q; + + q=(unsigned char *) p; + if (LocaleNCompare((const char *) p,""8BIM"",4) != 0) + break; + p=PushLongPixel(MSBEndian,p,&long_sans); + p=PushShortPixel(MSBEndian,p,&id); + p=PushShortPixel(MSBEndian,p,&short_sans); + p=PushLongPixel(MSBEndian,p,&count); + if (id == 0x0000040f) + { + (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- + (PSDQuantum(count)+12)-(q-datum)); + SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); + break; + } + p+=count; + if ((count & 0x01) != 0) + p++; + } +}","static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) +{ + register const unsigned char + *p; + + size_t + length; + + unsigned char + *datum; + + unsigned int + count, + long_sans; + + unsigned short + id, + short_sans; + + length=GetStringInfoLength(bim_profile); + if (length < 16) + return; + datum=GetStringInfoDatum(bim_profile); + for (p=datum; (p >= datum) && (p < (datum+length-16)); ) + { + register unsigned char + *q; + + q=(unsigned char *) p; + if (LocaleNCompare((const char *) p,""8BIM"",4) != 0) + break; + p=PushLongPixel(MSBEndian,p,&long_sans); + p=PushShortPixel(MSBEndian,p,&id); + p=PushShortPixel(MSBEndian,p,&short_sans); + p=PushLongPixel(MSBEndian,p,&count); + if (id == 0x0000040f) + { + if ((q+PSDQuantum(count)+12) < (datum+length-16)) + { + (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- + (PSDQuantum(count)+12)-(q-datum)); + SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); + } + break; + } + p+=count; + if ((count & 0x01) != 0) + p++; + } +}","{'deleted': [{'line_no': 38, 'char_start': 766, 'char_end': 831, 'line': ' (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-\n'}, {'line_no': 39, 'char_start': 831, 'char_end': 876, 'line': ' (PSDQuantum(count)+12)-(q-datum));\n'}, {'line_no': 40, 'char_start': 876, 'char_end': 948, 'line': ' SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));\n'}], 'added': [{'line_no': 38, 'char_start': 766, 'char_end': 824, 'line': ' if ((q+PSDQuantum(count)+12) < (datum+length-16))\n'}, {'line_no': 39, 'char_start': 824, 'char_end': 836, 'line': ' {\n'}, {'line_no': 40, 'char_start': 836, 'char_end': 905, 'line': ' (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-\n'}, {'line_no': 41, 'char_start': 905, 'char_end': 954, 'line': ' (PSDQuantum(count)+12)-(q-datum));\n'}, {'line_no': 42, 'char_start': 954, 'char_end': 1030, 'line': ' SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));\n'}, {'line_no': 43, 'char_start': 1030, 'char_end': 1042, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 774, 'char_end': 848, 'chars': 'if ((q+PSDQuantum(count)+12) < (datum+length-16))\n {\n '}, {'char_start': 905, 'char_end': 908, 'chars': ' '}, {'char_start': 918, 'char_end': 919, 'chars': ' '}, {'char_start': 954, 'char_end': 958, 'chars': ' '}, {'char_start': 1029, 'char_end': 1041, 'chars': '\n }'}]}",github.com/ImageMagick/ImageMagick/commit/53c1dcd34bed85181b901bfce1a2322f85a59472,coders/psd.c,cwe-787,